@tier0/sdk-v2 0.9.9 → 0.9.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 (34) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +6 -4
  3. package/dist/cjs/connection-diagnostics.d.ts +2 -0
  4. package/dist/cjs/connection-diagnostics.js +20 -0
  5. package/dist/cjs/connection-diagnostics.js.map +1 -0
  6. package/dist/cjs/data/error.d.ts +1 -1
  7. package/dist/cjs/data/error.js +2 -2
  8. package/dist/cjs/data/error.js.map +1 -1
  9. package/dist/cjs/openapi/client.js +3 -2
  10. package/dist/cjs/openapi/client.js.map +1 -1
  11. package/dist/cjs/uns-v2/client.js +3 -2
  12. package/dist/cjs/uns-v2/client.js.map +1 -1
  13. package/dist/esm/connection-diagnostics.d.ts +2 -0
  14. package/dist/esm/connection-diagnostics.js +17 -0
  15. package/dist/esm/connection-diagnostics.js.map +1 -0
  16. package/dist/esm/data/error.d.ts +1 -1
  17. package/dist/esm/data/error.js +2 -2
  18. package/dist/esm/data/error.js.map +1 -1
  19. package/dist/esm/openapi/client.js +3 -2
  20. package/dist/esm/openapi/client.js.map +1 -1
  21. package/dist/esm/uns-v2/client.js +3 -2
  22. package/dist/esm/uns-v2/client.js.map +1 -1
  23. package/package.json +1 -1
  24. package/skills/tier0-sdk-v2/SKILL.md +2 -0
  25. package/skills/tier0-sdk-v2/references/local-connection.md +61 -0
  26. package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/consistency.md +2 -2
  27. package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/errors.md +4 -2
  28. package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/modeling.md +3 -1
  29. package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/schema-evolution.md +2 -0
  30. package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/SKILL.md +1 -1
  31. package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/delete.md +25 -19
  32. package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/namespace.md +3 -3
  33. package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/read.md +7 -1
  34. package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/restore.md +12 -13
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.9.10 (2026-11-04)
4
+
5
+ - Add a local connection guide for Personal keys, explicit OpenAPI gateway configuration and reading existing collections without a platform App.
6
+ - Explain non-JSON route, authentication, permission and service errors without exposing credentials or changing error types, execution/retry semantics or request destinations.
7
+ - Align Namespace trash, delete and restore guidance: retained data remains readable, archived targets reject writes, and the legacy record restoration limit does not apply to current collection archive / restore.
8
+
3
9
  ## 0.9.9 (2026-11-04)
4
10
 
5
11
  - Clarify workspace Agent/Personal versus App credential query permissions. Keep `namespace()` on OpenAPI; document `dataAppContext` followed by `recordFind` for App keys, with a typed example and 403 troubleshooting. No runtime authorization changes.
package/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  Tier0 云端统一 TypeScript / JavaScript SDK,数据管理与 App Stream 交互均使用 `@tier0/sdk-v2`。旧 SDK 不再作为依赖。
4
4
 
5
+ `0.9.10` 补齐个人 Key 本地接入指南与非 JSON 网关错误提示,并同步 Namespace 回收、删除和恢复说明;保留现有权限、请求地址和重试规则。
6
+
5
7
  `0.9.9` 新增 `client.uns.metadataPurge`,通过明确的已归档 Collection ID 提交永久删除,返回 `accepted` / `jobId` 并通过现有 `jobs` 查询逐项完成结果;`dryRun` 可选。集合删除保留 Record/Sample,支持恢复或继续永久清理。
6
8
 
7
9
  本版同时补齐 Agent / App 凭证的查询说明及 App 读取示例:`namespace()` 仍走 OpenAPI,App Key 使用 `dataAppContext` 和集合数据接口,服务端授权规则保持不变。
@@ -29,18 +31,18 @@ Collection 声明必须同时提供业务名称 `name`(例如「生产工单
29
31
  安装正式版本:
30
32
 
31
33
  ```sh
32
- npm install @tier0/sdk-v2@0.9.9
34
+ npm install @tier0/sdk-v2@0.9.10
33
35
  ```
34
36
 
35
37
  维护者发布前在本仓库运行 `npm ci`、`npm run check`,并验证生成的 `.tgz`。
36
38
 
39
+ 个人 Key 可直接读取已有集合,无需创建平台 App;网关配置、运行示例与排错见[本地连接指南](skills/tier0-sdk-v2/references/local-connection.md)。
40
+
37
41
  ```ts
38
42
  import { createClient } from '@tier0/sdk-v2';
39
43
 
40
44
  // 服务端环境注入 TIER0_API_HOST 和 TIER0_API_KEY。
41
45
  const tier0 = createClient();
42
- // 首次接入时确认身份与 Workspace;不需要在每次业务操作前重复调用。
43
- const user = await tier0.system.whoami();
44
46
  ```
45
47
 
46
48
  也可显式配置 `{ apiHost, apiKey, transportTimeoutMs, fetch }`,或提供 `getApiHost` / `getApiKey` 回调。裸域名默认使用 HTTPS;本地 HTTP 测试请显式写 `http://127.0.0.1:端口`。不自动向浏览器注入或读取 `VITE_` API Key。
@@ -80,7 +82,7 @@ const user = await tier0.system.whoami();
80
82
 
81
83
  ## SDK 方法与凭证权限
82
84
 
83
- 同一 SDK 支持工作空间集成和 App 运行时,方法存在不代表当前凭证可调用。`client.uns.namespace()` 调用的是 `POST /openapi/v2/uns/namespace/query`,属于 OpenAPI;有相应权限且未绑定 App 的 Agent / Personal Key 可以使用,App Key 当前不能使用。App 应通过 `client.uns.dataAppContext({})` 获取可访问集合及结构,再用 `recordFind` 读取记录。`appCollectionsList` 也是管理接口,不能作为 App Key 的替代入口。
85
+ 同一 SDK 支持工作空间集成和 App 运行时,方法存在不代表当前凭证可调用。`client.uns.namespace()` 调用的是 `POST /openapi/v2/uns/namespace/query`,属于 OpenAPI;有相应权限且未绑定 App 的 Agent / Personal Key 可以使用,App Key 当前不能使用。App 已知集合 ID 时可直接用 `recordFind` 读取记录;需要发现可访问集合及结构时使用 `client.uns.dataAppContext({})`。`appCollectionsList` 也是管理接口,不能作为 App Key 的替代入口。
84
86
 
85
87
  SDK 不从 Key 前缀推断权限,也不在 403 后换凭证或回退内部接口。Agent 程序、SDK、MCP 都不能扩大所持凭证的权限。身份区别和排错见[命名空间查询与凭证](skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/namespace.md),App 读取示例见[查询集合与记录](skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/read.md)。
86
88
 
@@ -0,0 +1,2 @@
1
+ /** Static advice only: never include credentials, response bodies or configured URLs. */
2
+ export declare function invalidResponseHint(status: number): string;
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.invalidResponseHint = invalidResponseHint;
4
+ /** Static advice only: never include credentials, response bodies or configured URLs. */
5
+ function invalidResponseHint(status) {
6
+ if (status === 404 || status === 405) {
7
+ return 'Check apiHost / TIER0_API_HOST: use this environment\'s OpenAPI gateway base URL, not its platform webpage or MCP URL. Confirm that the gateway exposes /openapi/v2 routes; obtain the address from the environment deployment guide or administrator.';
8
+ }
9
+ if (status === 401) {
10
+ return 'Check that apiHost / TIER0_API_HOST targets the intended OpenAPI gateway, then check that the API key is present, valid and belongs to that environment. An intermediary may also require authentication.';
11
+ }
12
+ if (status === 403) {
13
+ return 'Check the credential\'s permissions for this operation and any gateway access restrictions. A non-JSON response alone does not prove the API key is invalid.';
14
+ }
15
+ if (status === 502 || status === 503 || status === 504) {
16
+ return 'The gateway or upstream service may be temporarily unavailable. Check service health; do not replace the API key based on this response. Before repeating a write, check whether it committed.';
17
+ }
18
+ return 'Check apiHost / TIER0_API_HOST and the gateway response format against the environment deployment guide; OpenAPI JSON responses are required.';
19
+ }
20
+ //# sourceMappingURL=connection-diagnostics.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connection-diagnostics.js","sourceRoot":"","sources":["../../src/connection-diagnostics.ts"],"names":[],"mappings":";;AACA,kDAcC;AAfD,yFAAyF;AACzF,SAAgB,mBAAmB,CAAC,MAAc;IAChD,IAAI,MAAM,KAAK,GAAG,IAAI,MAAM,KAAK,GAAG,EAAE,CAAC;QACrC,OAAO,wPAAwP,CAAC;IAClQ,CAAC;IACD,IAAI,MAAM,KAAK,GAAG,EAAE,CAAC;QACnB,OAAO,2MAA2M,CAAC;IACrN,CAAC;IACD,IAAI,MAAM,KAAK,GAAG,EAAE,CAAC;QACnB,OAAO,8JAA8J,CAAC;IACxK,CAAC;IACD,IAAI,MAAM,KAAK,GAAG,IAAI,MAAM,KAAK,GAAG,IAAI,MAAM,KAAK,GAAG,EAAE,CAAC;QACvD,OAAO,gMAAgM,CAAC;IAC1M,CAAC;IACD,OAAO,+IAA+I,CAAC;AACzJ,CAAC","sourcesContent":["/** Static advice only: never include credentials, response bodies or configured URLs. */\nexport function invalidResponseHint(status: number): string {\n if (status === 404 || status === 405) {\n return 'Check apiHost / TIER0_API_HOST: use this environment\\'s OpenAPI gateway base URL, not its platform webpage or MCP URL. Confirm that the gateway exposes /openapi/v2 routes; obtain the address from the environment deployment guide or administrator.';\n }\n if (status === 401) {\n return 'Check that apiHost / TIER0_API_HOST targets the intended OpenAPI gateway, then check that the API key is present, valid and belongs to that environment. An intermediary may also require authentication.';\n }\n if (status === 403) {\n return 'Check the credential\\'s permissions for this operation and any gateway access restrictions. A non-JSON response alone does not prove the API key is invalid.';\n }\n if (status === 502 || status === 503 || status === 504) {\n return 'The gateway or upstream service may be temporarily unavailable. Check service health; do not replace the API key based on this response. Before repeating a write, check whether it committed.';\n }\n return 'Check apiHost / TIER0_API_HOST and the gateway response format against the environment deployment guide; OpenAPI JSON responses are required.';\n}\n"]}
@@ -16,7 +16,7 @@ import type { UnsV2Error, UnsV2Execution, UnsV2Retry } from '../uns-v2/client.js
16
16
  export declare const ACCESS_REASONS: {
17
17
  /** 403: the collection exists, but this App's grant does not cover it or the operation. */
18
18
  readonly notGranted: "COLLECTION_NOT_GRANTED";
19
- /** 403 or 404: the collection is gone (hard-deleted or archived). */
19
+ /** 403 or 404: the collection is missing, or the write target is archived. */
20
20
  readonly notFound: "COLLECTION_NOT_FOUND";
21
21
  /** 403: the grant covers the operation, the App key lacks `data.missingPermission`. */
22
22
  readonly permissionMissing: "APP_PERMISSION_MISSING";
@@ -11,7 +11,7 @@ exports.toDataError = toDataError;
11
11
  exports.ACCESS_REASONS = {
12
12
  /** 403: the collection exists, but this App's grant does not cover it or the operation. */
13
13
  notGranted: 'COLLECTION_NOT_GRANTED',
14
- /** 403 or 404: the collection is gone (hard-deleted or archived). */
14
+ /** 403 or 404: the collection is missing, or the write target is archived. */
15
15
  notFound: 'COLLECTION_NOT_FOUND',
16
16
  /** 403: the grant covers the operation, the App key lacks `data.missingPermission`. */
17
17
  permissionMissing: 'APP_PERMISSION_MISSING',
@@ -92,7 +92,7 @@ const CODE_HINTS = {
92
92
  VERSION_CONFLICT: 'The record changed since it was read; reload it and retry with the new revision.',
93
93
  APP_GRANT_REVOKED: "A workspace admin revoked this App's access to the collection; it is not re-granted automatically. Ask the admin to restore the grant.",
94
94
  INDEX_QUOTA_EXCEEDED: 'The workspace index quota (200, counting every index that physically exists) is exhausted. Remove unused indexes through the tier0 MCP.',
95
- COLLECTION_TOO_LARGE: 'archive / restore handle at most 2000 records; stop using a large collection in code instead of archiving it.',
95
+ COLLECTION_TOO_LARGE: 'Legacy recordsArchivedAt restoration handles at most 2000 records; current collection archive / restore retains records without that limit.',
96
96
  OVERLOADED: "This workspace's data requests are over their concurrency share; the data layer already waited and retried. Batch page reads with data.queryBatch and avoid per-record loops.",
97
97
  APP_NOT_READY: 'The platform is still preparing this App (e.g. right after an import); retry shortly.',
98
98
  QUERY_TIMEOUT: 'Narrow the query: add an indexed condition, a smaller limit or maxCount.',
@@ -1 +1 @@
1
- {"version":3,"file":"error.js","sourceRoot":"","sources":["../../../src/data/error.ts"],"names":[],"mappings":";;;AAgGA,8BASC;AAmDD,kCAqDC;AAtMD;;;;GAIG;AACU,QAAA,cAAc,GAAG;IAC5B,2FAA2F;IAC3F,UAAU,EAAE,wBAAwB;IACpC,qEAAqE;IACrE,QAAQ,EAAE,sBAAsB;IAChC,uFAAuF;IACvF,iBA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,CAAC;QAChB,OAAO,GAAG,GAAG,OAAO,IAAI,IAAI,EAAE,CAAC;IACjC,CAAC;IAED,OAAO,IAAI,SAAS,CAAC,EAAE,GAAG,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,SAAS,CAAC,UAAU,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,cAAc,EAAE,UAAU,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;AAC7I,CAAC","sourcesContent":["/**\n * Runtime failures of a data call, missing credentials included, are a\n * `DataError`. The SDK's UNS client does the HTTP exchange; its `UnsV2Error`\n * (kept as `cause`) is translated here, and the data layer raises its own codes\n * (BATCH_LIMIT_EXCEEDED, WRITE_ERRORS, ...). `status` is the HTTP status the App\n * should answer its own caller with. Writes that fail validation throw\n * `ZodError`; programming or platform errors, such as invalid client options or\n * a malformed data subject from the gateway, throw `TypeError`.\n */\nimport type { UnsV2Error, UnsV2Execution, UnsV2Retry } from '../uns-v2/client.js';\n\n/**\n * Stable `data.reason` codes UNS adds when it refuses App data access; the\n * top-level code stays FORBIDDEN / NOT_FOUND. Only whole-request errors carry\n * them, never per-item results of a batch or transaction.\n */\nexport const ACCESS_REASONS = {\n /** 403: the collection exists, but this App's grant does not cover it or the operation. */\n notGranted: 'COLLECTION_NOT_GRANTED',\n /** 403 or 404: the collection is gone (hard-deleted or archived). */\n notFound: 'COLLECTION_NOT_FOUND',\n /** 403: the grant covers the operation, the App key lacks `data.missingPermission`. */\n permissionMissing: 'APP_PERMISSION_MISSING',\n} as const;\n\nexport class DataError extends Error {\n /** HTTP status the App should answer with (see `appStatus`). */\n readonly status: number;\n /** UNS error code, e.g. `DUPLICATE_KEY`, or a data-layer code. */\n readonly code: string;\n /** Stable `data.reason` code, e.g. `COLLECTION_NOT_FOUND` (see ACCESS_REASONS). */\n readonly reason?: string;\n /** HTTP status UNS answered with; 0 when no response arrived. */\n readonly upstreamStatus: number;\n readonly requestId?: string;\n /**\n * How far the failed request got: `notStarted` / `rolledBack` changed\n * nothing, `committed` took effect, `unknown` (writes only) may have.\n * Data-layer refusals raised before sending are `notStarted`.\n */\n readonly execution: UnsV2Execution;\n /** Whether the same call may be repeated later, and after how long. The data layer already retried it. */\n readonly retry: UnsV2Retry;\n /** `execution === \"unknown\"`: a write may have landed. Read back before writing again. */\n readonly outcomeUnknown: boolean;\n /** Requests sent for this call, retries included; 0 when nothing was sent. */\n readonly attempts: number;\n /**\n * The idempotency key the write was sent with (generated unless the caller\n * gave one). After `outcomeUnknown`, sending the same write with this key\n * again cannot apply it twice.\n */\n readonly idempotencyKey?: string;\n /** The `data` object of the UNS error envelope, or data-layer details. */\n readonly details: Record<string, unknown>;\n\n constructor(init: {\n message: string;\n status: number;\n code: string;\n reason?: string;\n upstreamStatus?: number;\n requestId?: string;\n execution?: UnsV2Execution;\n retry?: UnsV2Retry;\n attempts?: number;\n idempotencyKey?: string;\n details?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super(init.message, init.cause === undefined ? undefined : { cause: init.cause });\n this.name = 'DataError';\n this.status = init.status;\n this.code = init.code;\n this.reason = init.reason;\n this.upstreamStatus = init.upstreamStatus ?? 0;\n this.requestId = init.requestId;\n this.execution = init.execution ?? 'notStarted';\n this.retry = init.retry ?? { safe: false };\n this.outcomeUnknown = this.execution === 'unknown';\n this.attempts = init.attempts ?? 0;\n this.idempotencyKey = init.idempotencyKey;\n this.details = init.details ?? {};\n }\n}\n\n/** Platform states the App's caller cannot fix: they answer 503 whatever UNS answered. */\nconst PLATFORM_CODES = new Set(['APP_NOT_READY', 'DEPENDENCY_UNAVAILABLE', 'CREDENTIAL_CHANGED', 'OUTCOME_UNKNOWN', 'TEMPORARILY_UNAVAILABLE']);\n\n/**\n * Maps an upstream UNS status and code to the status the App answers its own\n * caller with. Credential failures are the platform's problem, not the user's\n * session, so a 401 from UNS becomes 502 instead of looking like a logout;\n * platform states (App not ready yet, a dependency down, the App key changed\n * mid-request) become 503 instead of looking like a denied action or a conflict.\n */\nexport function appStatus(upstream: number, code = ''): number {\n if (upstream === 401) return 502;\n if (PLATFORM_CODES.has(code)) return 503;\n if (upstream === 400 || upstream === 403 || upstream === 404 || upstream === 409 || upstream === 413 || upstream === 422 || upstream === 429) {\n return upstream;\n }\n if (upstream === 502 || upstream === 503 || upstream === 504) return 503;\n if (upstream >= 500) return 502;\n return upstream >= 400 ? 400 : 502;\n}\n\nconst CODE_HINTS: Record<string, string> = {\n UPSERT_REQUIRES_UNIQUE_INDEX:\n 'An upsert filter must contain `_id` or every field of a unique index that is already ready; a newly declared unique index may still be building.',\n DUPLICATE_KEY:\n 'A unique index already holds this value. (From restore: an active record took the value meanwhile; nothing was restored.)',\n VERSION_CONFLICT: 'The record changed since it was read; reload it and retry with the new revision.',\n APP_GRANT_REVOKED:\n \"A workspace admin revoked this App's access to the collection; it is not re-granted automatically. Ask the admin to restore the grant.\",\n INDEX_QUOTA_EXCEEDED:\n 'The workspace index quota (200, counting every index that physically exists) is exhausted. Remove unused indexes through the tier0 MCP.',\n COLLECTION_TOO_LARGE:\n 'archive / restore handle at most 2000 records; stop using a large collection in code instead of archiving it.',\n OVERLOADED:\n \"This workspace's data requests are over their concurrency share; the data layer already waited and retried. Batch page reads with data.queryBatch and avoid per-record loops.\",\n APP_NOT_READY: 'The platform is still preparing this App (e.g. right after an import); retry shortly.',\n QUERY_TIMEOUT: 'Narrow the query: add an indexed condition, a smaller limit or maxCount.',\n OUTCOME_UNKNOWN: 'The write may have committed; read the record back before writing again.',\n};\n\n/** `APP_QUOTA_EXCEEDED` per `data.resource`; each per-App limit is 64. */\nconst QUOTA_HINTS: Record<string, string> = {\n collections: 'This App owns 64 active collections. Archive unused ones through the tier0 MCP.',\n indexes: \"This App's collections hold 64 indexes. Drop unused indexes from the declarations, then apply that with schema:replace through the tier0 MCP.\",\n archivedCollections:\n 'This App keeps 64 archived collections. Restore one, or ask a workspace admin to clean up archived collections.',\n};\n\n/** SDK transport failures: no UNS answer to map, so the data layer names them. */\nconst TRANSPORT_FAILURES: Record<string, { code: string; status: number; message: string }> = {\n UNS_V2_TRANSPORT_TIMEOUT: { code: 'DATA_TIMEOUT', status: 503, message: 'UNS did not answer in time' },\n UNS_V2_TRANSPORT_ERROR: { code: 'DATA_UNREACHABLE', status: 503, message: 'Cannot reach the Tier0 data service' },\n // The business request was aborted while the call was in flight (499: client closed request).\n UNS_V2_TRANSPORT_ABORTED: { code: 'DATA_ABORTED', status: 499, message: 'The data call was aborted' },\n UNS_V2_PROTOCOL_ERROR: { code: 'DATA_BAD_RESPONSE', status: 502, message: 'UNS answered with an invalid response' },\n};\n\nfunction codeHint(code: string, details: Record<string, unknown>): string | undefined {\n if (code === 'APP_QUOTA_EXCEEDED') {\n const resource = typeof details.resource === 'string' ? details.resource : '';\n return QUOTA_HINTS[resource] ?? 'This App reached a collection/index quota. Remove unused collections or indexes through the tier0 MCP.';\n }\n return CODE_HINTS[code];\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Translates a failed UNS call of the SDK client after `attempts` requests, sent with `idempotencyKey`. */\nexport function toDataError(error: UnsV2Error, attempts = 1, idempotencyKey?: string): DataError {\n const common = {\n upstreamStatus: error.status,\n requestId: error.requestId,\n execution: error.execution,\n retry: error.retry,\n attempts,\n idempotencyKey,\n cause: error,\n };\n const unknown = error.outcomeUnknown ? '; the write outcome is unknown' : '';\n // An ingress or load balancer answers 502/503/504 without the UNS envelope during\n // rolling releases and pod restarts, like any unavailable upstream. UNS v2 routes\n // answer every other error with the envelope (401/403/429 included), so other\n // unenveloped responses stay DATA_BAD_RESPONSE.\n if (error.code === 'UNS_V2_PROTOCOL_ERROR' && (error.status === 502 || error.status === 503 || error.status === 504)) {\n return new DataError({\n ...common,\n message: `The Tier0 data gateway answered ${error.operation} with HTTP ${error.status}${unknown}.`,\n status: 503,\n code: `HTTP_${error.status}`,\n });\n }\n const transport = TRANSPORT_FAILURES[error.code];\n if (transport) {\n return new DataError({ ...common, message: `${transport.message} (${error.operation})${unknown}.`, status: transport.status, code: transport.code });\n }\n\n const httpStatus = error.status ?? 0;\n const data = isObject(error.data) ? error.data : {};\n // Only `data.reason` is a code; `error.reason` repeats the message text.\n const reason = typeof data.reason === 'string' ? data.reason : undefined;\n const code = error.code;\n const msg = error.message;\n const hint = codeHint(code, data) ?? error.repair;\n let message = `${msg} (${code})`;\n if (reason === ACCESS_REASONS.permissionMissing) {\n message =\n data.missingPermission === 'uns.delete'\n ? `Deleting records requires the App key to hold uns.delete, and this App's key does not (${code}). ` +\n 'Model removal as a status change such as `archived`, or ask a workspace admin to grant uns.delete.'\n : `The App key lacks ${typeof data.missingPermission === 'string' ? data.missingPermission : 'a permission'} for this operation (${code}); ask a workspace admin.`;\n } else if (reason === ACCESS_REASONS.notGranted) {\n message = `${message} This App's grant does not cover the collection or operation; ask a workspace admin to restore the grant.`;\n } else if (reason === ACCESS_REASONS.notFound) {\n message = `${message} The collection was archived or deleted; the data layer ensures the declared collections again.`;\n } else if (httpStatus === 401) {\n message = `Tier0 rejected the App credential for ${error.operation} (${code}). The platform injects TIER0_API_KEY; do not replace it.`;\n } else if (hint) {\n message = `${message} ${hint}`;\n }\n\n return new DataError({ ...common, message, status: appStatus(httpStatus, code), code, reason, upstreamStatus: httpStatus, details: data });\n}\n"]}
1
+ {"version":3,"file":"error.js","sourceRoot":"","sources":["../../../src/data/error.ts"],"names":[],"mappings":";;;AAgGA,8BASC;AAmDD,kCAqDC;AAtMD;;;;GAIG;AACU,QAAA,cAAc,GAAG;IAC5B,2FAA2F;IAC3F,UAAU,EAAE,wBAAwB;IACpC,8EAA8E;IAC9E,QAAQ,EAAE,sBAAsB;IAChC,uFAAuF;IACvF,iBAAiB,EAAE,wBAAwB;CACnC,CAAC;AAEX,MAAa,SAAU,SAAQ,KAAK;IAClC,gEAAgE;IACvD,MAAM,CAAS;IACxB,kEAAkE;IACzD,IAAI,CAAS;IACtB,mFAAmF;IAC1E,MAAM,CAAU;IAC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UAAU,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,cAAc,EAAE,UAAU,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;AAC7I,CAAC","sourcesContent":["/**\n * Runtime failures of a data call, missing credentials included, are a\n * `DataError`. The SDK's UNS client does the HTTP exchange; its `UnsV2Error`\n * (kept as `cause`) is translated here, and the data layer raises its own codes\n * (BATCH_LIMIT_EXCEEDED, WRITE_ERRORS, ...). `status` is the HTTP status the App\n * should answer its own caller with. Writes that fail validation throw\n * `ZodError`; programming or platform errors, such as invalid client options or\n * a malformed data subject from the gateway, throw `TypeError`.\n */\nimport type { UnsV2Error, UnsV2Execution, UnsV2Retry } from '../uns-v2/client.js';\n\n/**\n * Stable `data.reason` codes UNS adds when it refuses App data access; the\n * top-level code stays FORBIDDEN / NOT_FOUND. Only whole-request errors carry\n * them, never per-item results of a batch or transaction.\n */\nexport const ACCESS_REASONS = {\n /** 403: the collection exists, but this App's grant does not cover it or the operation. */\n notGranted: 'COLLECTION_NOT_GRANTED',\n /** 403 or 404: the collection is missing, or the write target is archived. */\n notFound: 'COLLECTION_NOT_FOUND',\n /** 403: the grant covers the operation, the App key lacks `data.missingPermission`. */\n permissionMissing: 'APP_PERMISSION_MISSING',\n} as const;\n\nexport class DataError extends Error {\n /** HTTP status the App should answer with (see `appStatus`). */\n readonly status: number;\n /** UNS error code, e.g. `DUPLICATE_KEY`, or a data-layer code. */\n readonly code: string;\n /** Stable `data.reason` code, e.g. `COLLECTION_NOT_FOUND` (see ACCESS_REASONS). */\n readonly reason?: string;\n /** HTTP status UNS answered with; 0 when no response arrived. */\n readonly upstreamStatus: number;\n readonly requestId?: string;\n /**\n * How far the failed request got: `notStarted` / `rolledBack` changed\n * nothing, `committed` took effect, `unknown` (writes only) may have.\n * Data-layer refusals raised before sending are `notStarted`.\n */\n readonly execution: UnsV2Execution;\n /** Whether the same call may be repeated later, and after how long. The data layer already retried it. */\n readonly retry: UnsV2Retry;\n /** `execution === \"unknown\"`: a write may have landed. Read back before writing again. */\n readonly outcomeUnknown: boolean;\n /** Requests sent for this call, retries included; 0 when nothing was sent. */\n readonly attempts: number;\n /**\n * The idempotency key the write was sent with (generated unless the caller\n * gave one). After `outcomeUnknown`, sending the same write with this key\n * again cannot apply it twice.\n */\n readonly idempotencyKey?: string;\n /** The `data` object of the UNS error envelope, or data-layer details. */\n readonly details: Record<string, unknown>;\n\n constructor(init: {\n message: string;\n status: number;\n code: string;\n reason?: string;\n upstreamStatus?: number;\n requestId?: string;\n execution?: UnsV2Execution;\n retry?: UnsV2Retry;\n attempts?: number;\n idempotencyKey?: string;\n details?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super(init.message, init.cause === undefined ? undefined : { cause: init.cause });\n this.name = 'DataError';\n this.status = init.status;\n this.code = init.code;\n this.reason = init.reason;\n this.upstreamStatus = init.upstreamStatus ?? 0;\n this.requestId = init.requestId;\n this.execution = init.execution ?? 'notStarted';\n this.retry = init.retry ?? { safe: false };\n this.outcomeUnknown = this.execution === 'unknown';\n this.attempts = init.attempts ?? 0;\n this.idempotencyKey = init.idempotencyKey;\n this.details = init.details ?? {};\n }\n}\n\n/** Platform states the App's caller cannot fix: they answer 503 whatever UNS answered. */\nconst PLATFORM_CODES = new Set(['APP_NOT_READY', 'DEPENDENCY_UNAVAILABLE', 'CREDENTIAL_CHANGED', 'OUTCOME_UNKNOWN', 'TEMPORARILY_UNAVAILABLE']);\n\n/**\n * Maps an upstream UNS status and code to the status the App answers its own\n * caller with. Credential failures are the platform's problem, not the user's\n * session, so a 401 from UNS becomes 502 instead of looking like a logout;\n * platform states (App not ready yet, a dependency down, the App key changed\n * mid-request) become 503 instead of looking like a denied action or a conflict.\n */\nexport function appStatus(upstream: number, code = ''): number {\n if (upstream === 401) return 502;\n if (PLATFORM_CODES.has(code)) return 503;\n if (upstream === 400 || upstream === 403 || upstream === 404 || upstream === 409 || upstream === 413 || upstream === 422 || upstream === 429) {\n return upstream;\n }\n if (upstream === 502 || upstream === 503 || upstream === 504) return 503;\n if (upstream >= 500) return 502;\n return upstream >= 400 ? 400 : 502;\n}\n\nconst CODE_HINTS: Record<string, string> = {\n UPSERT_REQUIRES_UNIQUE_INDEX:\n 'An upsert filter must contain `_id` or every field of a unique index that is already ready; a newly declared unique index may still be building.',\n DUPLICATE_KEY:\n 'A unique index already holds this value. (From restore: an active record took the value meanwhile; nothing was restored.)',\n VERSION_CONFLICT: 'The record changed since it was read; reload it and retry with the new revision.',\n APP_GRANT_REVOKED:\n \"A workspace admin revoked this App's access to the collection; it is not re-granted automatically. Ask the admin to restore the grant.\",\n INDEX_QUOTA_EXCEEDED:\n 'The workspace index quota (200, counting every index that physically exists) is exhausted. Remove unused indexes through the tier0 MCP.',\n COLLECTION_TOO_LARGE:\n 'Legacy recordsArchivedAt restoration handles at most 2000 records; current collection archive / restore retains records without that limit.',\n OVERLOADED:\n \"This workspace's data requests are over their concurrency share; the data layer already waited and retried. Batch page reads with data.queryBatch and avoid per-record loops.\",\n APP_NOT_READY: 'The platform is still preparing this App (e.g. right after an import); retry shortly.',\n QUERY_TIMEOUT: 'Narrow the query: add an indexed condition, a smaller limit or maxCount.',\n OUTCOME_UNKNOWN: 'The write may have committed; read the record back before writing again.',\n};\n\n/** `APP_QUOTA_EXCEEDED` per `data.resource`; each per-App limit is 64. */\nconst QUOTA_HINTS: Record<string, string> = {\n collections: 'This App owns 64 active collections. Archive unused ones through the tier0 MCP.',\n indexes: \"This App's collections hold 64 indexes. Drop unused indexes from the declarations, then apply that with schema:replace through the tier0 MCP.\",\n archivedCollections:\n 'This App keeps 64 archived collections. Restore one, or ask a workspace admin to clean up archived collections.',\n};\n\n/** SDK transport failures: no UNS answer to map, so the data layer names them. */\nconst TRANSPORT_FAILURES: Record<string, { code: string; status: number; message: string }> = {\n UNS_V2_TRANSPORT_TIMEOUT: { code: 'DATA_TIMEOUT', status: 503, message: 'UNS did not answer in time' },\n UNS_V2_TRANSPORT_ERROR: { code: 'DATA_UNREACHABLE', status: 503, message: 'Cannot reach the Tier0 data service' },\n // The business request was aborted while the call was in flight (499: client closed request).\n UNS_V2_TRANSPORT_ABORTED: { code: 'DATA_ABORTED', status: 499, message: 'The data call was aborted' },\n UNS_V2_PROTOCOL_ERROR: { code: 'DATA_BAD_RESPONSE', status: 502, message: 'UNS answered with an invalid response' },\n};\n\nfunction codeHint(code: string, details: Record<string, unknown>): string | undefined {\n if (code === 'APP_QUOTA_EXCEEDED') {\n const resource = typeof details.resource === 'string' ? details.resource : '';\n return QUOTA_HINTS[resource] ?? 'This App reached a collection/index quota. Remove unused collections or indexes through the tier0 MCP.';\n }\n return CODE_HINTS[code];\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Translates a failed UNS call of the SDK client after `attempts` requests, sent with `idempotencyKey`. */\nexport function toDataError(error: UnsV2Error, attempts = 1, idempotencyKey?: string): DataError {\n const common = {\n upstreamStatus: error.status,\n requestId: error.requestId,\n execution: error.execution,\n retry: error.retry,\n attempts,\n idempotencyKey,\n cause: error,\n };\n const unknown = error.outcomeUnknown ? '; the write outcome is unknown' : '';\n // An ingress or load balancer answers 502/503/504 without the UNS envelope during\n // rolling releases and pod restarts, like any unavailable upstream. UNS v2 routes\n // answer every other error with the envelope (401/403/429 included), so other\n // unenveloped responses stay DATA_BAD_RESPONSE.\n if (error.code === 'UNS_V2_PROTOCOL_ERROR' && (error.status === 502 || error.status === 503 || error.status === 504)) {\n return new DataError({\n ...common,\n message: `The Tier0 data gateway answered ${error.operation} with HTTP ${error.status}${unknown}.`,\n status: 503,\n code: `HTTP_${error.status}`,\n });\n }\n const transport = TRANSPORT_FAILURES[error.code];\n if (transport) {\n return new DataError({ ...common, message: `${transport.message} (${error.operation})${unknown}.`, status: transport.status, code: transport.code });\n }\n\n const httpStatus = error.status ?? 0;\n const data = isObject(error.data) ? error.data : {};\n // Only `data.reason` is a code; `error.reason` repeats the message text.\n const reason = typeof data.reason === 'string' ? data.reason : undefined;\n const code = error.code;\n const msg = error.message;\n const hint = codeHint(code, data) ?? error.repair;\n let message = `${msg} (${code})`;\n if (reason === ACCESS_REASONS.permissionMissing) {\n message =\n data.missingPermission === 'uns.delete'\n ? `Deleting records requires the App key to hold uns.delete, and this App's key does not (${code}). ` +\n 'Model removal as a status change such as `archived`, or ask a workspace admin to grant uns.delete.'\n : `The App key lacks ${typeof data.missingPermission === 'string' ? data.missingPermission : 'a permission'} for this operation (${code}); ask a workspace admin.`;\n } else if (reason === ACCESS_REASONS.notGranted) {\n message = `${message} This App's grant does not cover the collection or operation; ask a workspace admin to restore the grant.`;\n } else if (reason === ACCESS_REASONS.notFound) {\n message = `${message} The collection was archived or deleted; the data layer ensures the declared collections again.`;\n } else if (httpStatus === 401) {\n message = `Tier0 rejected the App credential for ${error.operation} (${code}). The platform injects TIER0_API_KEY; do not replace it.`;\n } else if (hint) {\n message = `${message} ${hint}`;\n }\n\n return new DataError({ ...common, message, status: appStatus(httpStatus, code), code, reason, upstreamStatus: httpStatus, details: data });\n}\n"]}
@@ -5,6 +5,7 @@ exports.responseError = responseError;
5
5
  exports.configureClient = configureClient;
6
6
  exports.getClient = getClient;
7
7
  const runtime_env_js_1 = require("../runtime-env.js");
8
+ const connection_diagnostics_js_1 = require("../connection-diagnostics.js");
8
9
  const codec_js_1 = require("../uns-v2/codec.js");
9
10
  class ApiError extends Error {
10
11
  status;
@@ -186,7 +187,7 @@ class HttpClient {
186
187
  }
187
188
  catch {
188
189
  if (!response.ok)
189
- throw new ApiError(response.status, 0, 'Non-JSON API error');
190
+ throw new ApiError(response.status, 0, `Non-JSON API error. ${(0, connection_diagnostics_js_1.invalidResponseHint)(response.status)}`);
190
191
  throw new TransportError('PROTOCOL', !operation.readonly, response.status);
191
192
  }
192
193
  if (!response.ok)
@@ -209,7 +210,7 @@ class HttpClient {
209
210
  value = (0, codec_js_1.decodeUnsV2JSON)(response.text, 'V1_Empty');
210
211
  }
211
212
  catch {
212
- throw new ApiError(response.status, 0, 'Invalid API response');
213
+ throw new ApiError(response.status, 0, `Invalid API response. ${(0, connection_diagnostics_js_1.invalidResponseHint)(response.status)}`);
213
214
  }
214
215
  if (!response.ok || (record(value) && typeof value.code === 'number' && value.code !== 200))
215
216
  throw responseError(response.status, value);
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/openapi/client.ts"],"names":[],"mappings":";;;AA4CA,sCAIC;AA6ID,0CAAuG;AACvG,8BAAiE;AA9LjE,sDAA8C;AAC9C,iDAAsE;AAyBtE,MAAa,QAAS,SAAQ,KAAK;IAGZ;IAAyB;IAAuB;IAF5D,SAAS,CAAU;IACnB,cAAc,CAAU;IACjC,YAAqB,MAAc,EAAW,IAAY,EAAW,GAAW,EAC9E,UAA4D,EAAE;QAC9D,KAAK,CAAC,QAAQ,MAAM,KAAK,GAAG,EAAE,CAAC,CAAC;QAFb,WAAM,GAAN,MAAM,CAAQ;QAAW,SAAI,GAAJ,IAAI,CAAQ;QAAW,QAAG,GAAH,GAAG,CAAQ;QAG9E,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;QACnC,IAAI,CAAC,cAAc,GAAG,OAAO,CAAC,cAAc,IAAI,KAAK,CAAC;IACxD,CAAC;CACF;AAVD,4BAUC;AACD,MAAa,cAAe,SAAQ,QAAQ;IAC1C,YAAY,IAAoD,EAAE,cAAuB,EAAE,MAAM,GAAG,CAAC;QACnG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,gBAAgB,IAAI,CAAC,WAAW,EAAE,QAAQ,EAAE,EAAE,SAAS,EAAE,OAAO,IAAI,EAAE,EAAE,cAAc,EAAE,CAAC,CAAC;QAC3G,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;IAC/B,CAAC;CACF;AALD,wCAKC;AACD,MAAM,MAAM,GAAG,CAAC,CAAU,EAAgC,EAAE,CAAC,CAA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Aa,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACvG,SAAgB,SAAS,KAAiB,OAAO,aAAa,CAAC,CAAC,CAAC","sourcesContent":["import { getEnvVar } from '../runtime-env.js';\nimport { decodeUnsV2JSON, encodeUnsV2JSON } from '../uns-v2/codec.js';\n\nexport interface ClientConfig {\n apiHost?: string;\n apiKey?: string;\n getApiHost?: () => string | undefined;\n getApiKey?: () => string | undefined;\n fetch?: typeof globalThis.fetch;\n transportTimeoutMs?: number;\n}\nexport interface RequestOptions { signal?: AbortSignal }\nexport interface Operation {\n method: string;\n path: string;\n readonly pathParams: readonly string[];\n mode: 'envelope' | 'direct' | 'download';\n readonly: boolean;\n requestSchema?: string;\n responseSchema: string;\n}\nexport interface OperationInput {\n params?: Record<string, string>;\n query?: object;\n body?: unknown;\n}\nexport class ApiError extends Error {\n readonly errorCode?: string;\n readonly outcomeUnknown: boolean;\n constructor(readonly status: number, readonly code: number, readonly msg: string,\n details: { errorCode?: string; outcomeUnknown?: boolean } = {}) {\n super(`HTTP ${status}: ${msg}`);\n this.name = 'ApiError';\n this.errorCode = details.errorCode;\n this.outcomeUnknown = details.outcomeUnknown ?? false;\n }\n}\nexport class TransportError extends ApiError {\n constructor(kind: 'TIMEOUT' | 'ABORTED' | 'NETWORK' | 'PROTOCOL', outcomeUnknown: boolean, status = 0) {\n super(status, 0, `Tier0 SDK v2 ${kind.toLowerCase()} error`, { errorCode: `SDK_${kind}`, outcomeUnknown });\n this.name = 'TransportError';\n }\n}\nconst record = (v: unknown): v is Record<string, unknown> => v !== null && typeof v === 'object' && !Array.isArray(v);\nexport function responseError(status: number, value: unknown, fallback = 'Request failed'): ApiError {\n return new ApiError(status, record(value) && typeof value.code === 'number' ? value.code : 0,\n record(value) && typeof value.message === 'string' ? value.message : record(value) && typeof value.msg === 'string' ? value.msg : fallback,\n { errorCode: record(value) && typeof value.errorCode === 'string' ? value.errorCode : undefined });\n}\n\n/** An immutable configuration snapshot. Each request resolves optional credential callbacks once. */\nexport class HttpClient {\n private readonly config: Readonly<ClientConfig>;\n readonly timeoutMs: number;\n constructor(config: ClientConfig = {}) {\n this.config = Object.freeze({ ...config });\n this.timeoutMs = config.transportTimeoutMs ?? 60_000;\n if (!Number.isInteger(this.timeoutMs) || this.timeoutMs < 1 || this.timeoutMs > 2_147_483_647) throw new TypeError('Invalid transportTimeoutMs');\n }\n getBaseURL(): string {\n const host = this.config.apiHost ?? this.config.getApiHost?.() ?? getEnvVar('TIER0_API_HOST');\n if (!host?.trim()) throw new Error('Tier0 SDK v2: apiHost or TIER0_API_HOST is required.');\n const base = host.trim().replace(/\\/+$/, '');\n const url = new URL(/^https?:\\/\\//i.test(base) ? base : `https://${base}`);\n if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new TypeError('Invalid apiHost');\n return url.href.replace(/\\/+$/, '');\n }\n getApiKey(): string | undefined { return this.config.apiKey ?? this.config.getApiKey?.() ?? getEnvVar('TIER0_API_KEY'); }\n getFetch(): typeof globalThis.fetch { return this.config.fetch ?? globalThis.fetch; }\n\n private async exchange(path: string, init: RequestInit, options: RequestOptions, mutation: boolean): Promise<{ text: string; status: number; ok: boolean }> {\n if (!path.startsWith('/') || path.startsWith('//') || path.includes('\\\\')) throw new TypeError('A relative API path is required');\n const url = this.getBaseURL() + path;\n const key = this.getApiKey();\n const headers = new Headers(init.headers);\n headers.set('Content-Type', 'application/json');\n if (key) { headers.set('X-API-Key', key); headers.set('Authorization', `Bearer ${key}`); }\n const controller = new AbortController();\n let expired = false;\n let started = false;\n let response: Response | undefined;\n let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n let rejectAbort: (error: Error) => void = () => undefined;\n const fail = () => {\n controller.abort();\n void reader?.cancel().catch(() => undefined);\n rejectAbort(new TransportError(expired ? 'TIMEOUT' : 'ABORTED', mutation && started, response?.status));\n };\n const aborted = new Promise<never>((_, reject) => { rejectAbort = reject; });\n const timer = setTimeout(() => { expired = true; fail(); }, this.timeoutMs);\n options.signal?.addEventListener('abort', fail, { once: true });\n try {\n if (options.signal?.aborted) throw new TransportError('ABORTED', false);\n const request = async () => {\n started = true;\n try { response = await this.getFetch()(url, { ...init, headers, redirect: 'manual', signal: controller.signal }); }\n catch { throw new TransportError(expired ? 'TIMEOUT' : controller.signal.aborted ? 'ABORTED' : 'NETWORK', mutation, response?.status); }\n const maxBytes = 20 * 1024 * 1024;\n if (Number(response.headers.get('content-length')) > maxBytes) { await response.body?.cancel(); throw new TransportError('PROTOCOL', mutation, response.status); }\n if (!response.body) return { text: '', status: response.status, ok: response.ok };\n reader = response.body.getReader();\n const decoder = new TextDecoder('utf-8', { fatal: true });\n const chunks: string[] = [];\n let size = 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > maxBytes) { await reader.cancel(); throw new Error('Response too large'); }\n chunks.push(decoder.decode(value, { stream: true }));\n }\n chunks.push(decoder.decode());\n } catch { throw new TransportError('PROTOCOL', mutation, response.status); }\n finally { reader.releaseLock(); reader = undefined; }\n return { text: chunks.join(''), status: response.status, ok: response.ok };\n };\n return await Promise.race([request(), aborted]);\n } finally { clearTimeout(timer); options.signal?.removeEventListener('abort', fail); }\n }\n\n async operation<T>(operation: Operation, input: OperationInput = {}, options: RequestOptions = {}): Promise<T> {\n let path = operation.path;\n for (const name of operation.pathParams) {\n const value = input.params?.[name];\n if (!value || value === '.' || value === '..' || /[/\\\\\\u0000-\\u001f\\u007f]/.test(value)) throw new TypeError(`Invalid path parameter: ${name}`);\n path = path.replace(`{${name}}`, encodeURIComponent(value));\n }\n const query = new URLSearchParams();\n for (const [name, value] of Object.entries(input.query ?? {})) {\n if (value !== undefined) query.set(name, String(value));\n }\n if (query.size) path += `?${query}`;\n if (operation.mode === 'download') {\n // Resolve the signed URL through the JSON endpoint, then fetch without platform credentials.\n const urlPath = path.replace('/files/download', '/files/url');\n const result = await this.get<{ code: number; data?: { fileUrl?: string } }>(urlPath, options);\n if (result.code !== 200 || !result.data?.fileUrl) throw responseError(200, result, 'Invalid download URL response');\n const url = new URL(result.data.fileUrl);\n if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new TypeError('Invalid download URL');\n const response = await this.getFetch()(url, { signal: options.signal, credentials: 'omit' });\n if (!response.ok) throw new ApiError(response.status, 0, 'File download failed');\n return response as T;\n }\n let body = input.body ?? {};\n if (path === '/openapi/v2/notifications/send') {\n if (!record(body)) throw new TypeError('Notification body must be an object');\n const channels = body.channels ?? ['web', 'mobile'];\n if (!Array.isArray(channels) || channels.some(c => c !== 'web' && c !== 'mobile')) throw new TypeError('Notification channels must be web or mobile');\n body = { ...body, channels: [...new Set(channels)] };\n }\n if (path === '/openapi/v2/apps/access-members/list' && record(body) && body.scope === undefined) {\n // The platform injects TIER0_RUNTIME: a Builder preview lists the draft roles, a deployment the production version.\n const runtime = getEnvVar('TIER0_RUNTIME');\n const scope = runtime === 'preview' ? 'draft' : runtime === 'deployed' ? 'production' : undefined;\n if (scope) body = { ...body, scope };\n }\n const serialized = operation.method === 'GET' ? undefined : encodeUnsV2JSON(body, operation.requestSchema ?? 'V1_Empty');\n const response = await this.exchange(path, { method: operation.method, body: serialized }, options, !operation.readonly);\n let value: unknown;\n try { value = decodeUnsV2JSON(response.text, operation.responseSchema); }\n catch {\n if (!response.ok) throw new ApiError(response.status, 0, 'Non-JSON API error');\n throw new TransportError('PROTOCOL', !operation.readonly, response.status);\n }\n if (!response.ok) throw responseError(response.status, value);\n if (operation.mode === 'envelope') {\n if (!record(value) || typeof value.code !== 'number') throw new TransportError('PROTOCOL', !operation.readonly, response.status);\n if (value.code !== 200) throw responseError(response.status, value);\n if (!Object.hasOwn(value, 'data')) throw new TransportError('PROTOCOL', !operation.readonly, response.status);\n return value.data as T;\n }\n return value as T;\n }\n\n private async raw<T>(method: string, path: string, body?: unknown, options: RequestOptions = {}): Promise<T> {\n const response = await this.exchange(path, { method, body: body === undefined ? undefined : encodeUnsV2JSON(body, 'V1_Empty') }, options, method !== 'GET');\n let value: unknown;\n try { value = decodeUnsV2JSON(response.text, 'V1_Empty'); }\n catch { throw new ApiError(response.status, 0, 'Invalid API response'); }\n if (!response.ok || (record(value) && typeof value.code === 'number' && value.code !== 200)) throw responseError(response.status, value);\n return value as T;\n }\n get<T>(path: string, options?: RequestOptions): Promise<T> { return this.raw('GET', path, undefined, options); }\n post<T>(path: string, body: unknown, options?: RequestOptions): Promise<T> { return this.raw('POST', path, body, options); }\n}\n\n// Used by standalone domain clients. createClient() never reads or changes this default.\nlet defaultClient = new HttpClient();\nexport function configureClient(config: ClientConfig): void { defaultClient = new HttpClient(config); }\nexport function getClient(): HttpClient { return defaultClient; }\n"]}
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/openapi/client.ts"],"names":[],"mappings":";;;AA6CA,sCAIC;AA6ID,0CAAuG;AACvG,8BAAiE;AA/LjE,sDAA8C;AAC9C,4EAAmE;AACnE,iDAAsE;AAyBtE,MAAa,QAAS,SAAQ,KAAK;IAGZ;IAAyB;IAAuB;IAF5D,SAAS,CAAU;IACnB,cAAc,CAAU;IACjC,YAAqB,MAAc,EAAW,IAAY,EAAW,GAAW,EAC9E,UAA4D,EAAE;QAC9D,KAAK,CAAC,QAAQ,MAAM,KAAK,GAAG,EAAE,CAAC,CAAC;QAFb,WAAM,GAAN,MAAM,CAAQ;QAAW,SAAI,GAAJ,IAAI,CAAQ;QAAW,QAAG,GAAH,GAAG,CAAQ;QAG9E,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;QACnC,IAAI,CAAC,cAAc,GAAG,OAAO,CAAC,cAAc,IAAI,KAAK,CAAC;IACxD,CAAC;CACF;AAVD,4BAUC;AACD,MAAa,cAAe,SAAQ,QAAQ;IAC1C,YAAY,IAAoD,EAAE,cAAuB,EAAE,MAAM,GAAG,CAAC;QACnG,KAAK,CAAC,MAAM,EAAE,CAAC,E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AG,CAAC,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;IAChH,IAAI,CAAI,IAAY,EAAE,IAAa,EAAE,OAAwB,IAAgB,OAAO,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;CAC7H;AAtID,gCAsIC;AAED,yFAAyF;AACzF,IAAI,aAAa,GAAG,IAAI,UAAU,EAAE,CAAC;AACrC,SAAgB,eAAe,CAAC,MAAoB,IAAU,aAAa,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACvG,SAAgB,SAAS,KAAiB,OAAO,aAAa,CAAC,CAAC,CAAC","sourcesContent":["import { getEnvVar } from '../runtime-env.js';\nimport { invalidResponseHint } from '../connection-diagnostics.js';\nimport { decodeUnsV2JSON, encodeUnsV2JSON } from '../uns-v2/codec.js';\n\nexport interface ClientConfig {\n apiHost?: string;\n apiKey?: string;\n getApiHost?: () => string | undefined;\n getApiKey?: () => string | undefined;\n fetch?: typeof globalThis.fetch;\n transportTimeoutMs?: number;\n}\nexport interface RequestOptions { signal?: AbortSignal }\nexport interface Operation {\n method: string;\n path: string;\n readonly pathParams: readonly string[];\n mode: 'envelope' | 'direct' | 'download';\n readonly: boolean;\n requestSchema?: string;\n responseSchema: string;\n}\nexport interface OperationInput {\n params?: Record<string, string>;\n query?: object;\n body?: unknown;\n}\nexport class ApiError extends Error {\n readonly errorCode?: string;\n readonly outcomeUnknown: boolean;\n constructor(readonly status: number, readonly code: number, readonly msg: string,\n details: { errorCode?: string; outcomeUnknown?: boolean } = {}) {\n super(`HTTP ${status}: ${msg}`);\n this.name = 'ApiError';\n this.errorCode = details.errorCode;\n this.outcomeUnknown = details.outcomeUnknown ?? false;\n }\n}\nexport class TransportError extends ApiError {\n constructor(kind: 'TIMEOUT' | 'ABORTED' | 'NETWORK' | 'PROTOCOL', outcomeUnknown: boolean, status = 0) {\n super(status, 0, `Tier0 SDK v2 ${kind.toLowerCase()} error`, { errorCode: `SDK_${kind}`, outcomeUnknown });\n this.name = 'TransportError';\n }\n}\nconst record = (v: unknown): v is Record<string, unknown> => v !== null && typeof v === 'object' && !Array.isArray(v);\nexport function responseError(status: number, value: unknown, fallback = 'Request failed'): ApiError {\n return new ApiError(status, record(value) && typeof value.code === 'number' ? value.code : 0,\n record(value) && typeof value.message === 'string' ? value.message : record(value) && typeof value.msg === 'string' ? value.msg : fallback,\n { errorCode: record(value) && typeof value.errorCode === 'string' ? value.errorCode : undefined });\n}\n\n/** An immutable configuration snapshot. Each request resolves optional credential callbacks once. */\nexport class HttpClient {\n private readonly config: Readonly<ClientConfig>;\n readonly timeoutMs: number;\n constructor(config: ClientConfig = {}) {\n this.config = Object.freeze({ ...config });\n this.timeoutMs = config.transportTimeoutMs ?? 60_000;\n if (!Number.isInteger(this.timeoutMs) || this.timeoutMs < 1 || this.timeoutMs > 2_147_483_647) throw new TypeError('Invalid transportTimeoutMs');\n }\n getBaseURL(): string {\n const host = this.config.apiHost ?? this.config.getApiHost?.() ?? getEnvVar('TIER0_API_HOST');\n if (!host?.trim()) throw new Error('Tier0 SDK v2: apiHost or TIER0_API_HOST is required.');\n const base = host.trim().replace(/\\/+$/, '');\n const url = new URL(/^https?:\\/\\//i.test(base) ? base : `https://${base}`);\n if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new TypeError('Invalid apiHost');\n return url.href.replace(/\\/+$/, '');\n }\n getApiKey(): string | undefined { return this.config.apiKey ?? this.config.getApiKey?.() ?? getEnvVar('TIER0_API_KEY'); }\n getFetch(): typeof globalThis.fetch { return this.config.fetch ?? globalThis.fetch; }\n\n private async exchange(path: string, init: RequestInit, options: RequestOptions, mutation: boolean): Promise<{ text: string; status: number; ok: boolean }> {\n if (!path.startsWith('/') || path.startsWith('//') || path.includes('\\\\')) throw new TypeError('A relative API path is required');\n const url = this.getBaseURL() + path;\n const key = this.getApiKey();\n const headers = new Headers(init.headers);\n headers.set('Content-Type', 'application/json');\n if (key) { headers.set('X-API-Key', key); headers.set('Authorization', `Bearer ${key}`); }\n const controller = new AbortController();\n let expired = false;\n let started = false;\n let response: Response | undefined;\n let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n let rejectAbort: (error: Error) => void = () => undefined;\n const fail = () => {\n controller.abort();\n void reader?.cancel().catch(() => undefined);\n rejectAbort(new TransportError(expired ? 'TIMEOUT' : 'ABORTED', mutation && started, response?.status));\n };\n const aborted = new Promise<never>((_, reject) => { rejectAbort = reject; });\n const timer = setTimeout(() => { expired = true; fail(); }, this.timeoutMs);\n options.signal?.addEventListener('abort', fail, { once: true });\n try {\n if (options.signal?.aborted) throw new TransportError('ABORTED', false);\n const request = async () => {\n started = true;\n try { response = await this.getFetch()(url, { ...init, headers, redirect: 'manual', signal: controller.signal }); }\n catch { throw new TransportError(expired ? 'TIMEOUT' : controller.signal.aborted ? 'ABORTED' : 'NETWORK', mutation, response?.status); }\n const maxBytes = 20 * 1024 * 1024;\n if (Number(response.headers.get('content-length')) > maxBytes) { await response.body?.cancel(); throw new TransportError('PROTOCOL', mutation, response.status); }\n if (!response.body) return { text: '', status: response.status, ok: response.ok };\n reader = response.body.getReader();\n const decoder = new TextDecoder('utf-8', { fatal: true });\n const chunks: string[] = [];\n let size = 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > maxBytes) { await reader.cancel(); throw new Error('Response too large'); }\n chunks.push(decoder.decode(value, { stream: true }));\n }\n chunks.push(decoder.decode());\n } catch { throw new TransportError('PROTOCOL', mutation, response.status); }\n finally { reader.releaseLock(); reader = undefined; }\n return { text: chunks.join(''), status: response.status, ok: response.ok };\n };\n return await Promise.race([request(), aborted]);\n } finally { clearTimeout(timer); options.signal?.removeEventListener('abort', fail); }\n }\n\n async operation<T>(operation: Operation, input: OperationInput = {}, options: RequestOptions = {}): Promise<T> {\n let path = operation.path;\n for (const name of operation.pathParams) {\n const value = input.params?.[name];\n if (!value || value === '.' || value === '..' || /[/\\\\\\u0000-\\u001f\\u007f]/.test(value)) throw new TypeError(`Invalid path parameter: ${name}`);\n path = path.replace(`{${name}}`, encodeURIComponent(value));\n }\n const query = new URLSearchParams();\n for (const [name, value] of Object.entries(input.query ?? {})) {\n if (value !== undefined) query.set(name, String(value));\n }\n if (query.size) path += `?${query}`;\n if (operation.mode === 'download') {\n // Resolve the signed URL through the JSON endpoint, then fetch without platform credentials.\n const urlPath = path.replace('/files/download', '/files/url');\n const result = await this.get<{ code: number; data?: { fileUrl?: string } }>(urlPath, options);\n if (result.code !== 200 || !result.data?.fileUrl) throw responseError(200, result, 'Invalid download URL response');\n const url = new URL(result.data.fileUrl);\n if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new TypeError('Invalid download URL');\n const response = await this.getFetch()(url, { signal: options.signal, credentials: 'omit' });\n if (!response.ok) throw new ApiError(response.status, 0, 'File download failed');\n return response as T;\n }\n let body = input.body ?? {};\n if (path === '/openapi/v2/notifications/send') {\n if (!record(body)) throw new TypeError('Notification body must be an object');\n const channels = body.channels ?? ['web', 'mobile'];\n if (!Array.isArray(channels) || channels.some(c => c !== 'web' && c !== 'mobile')) throw new TypeError('Notification channels must be web or mobile');\n body = { ...body, channels: [...new Set(channels)] };\n }\n if (path === '/openapi/v2/apps/access-members/list' && record(body) && body.scope === undefined) {\n // The platform injects TIER0_RUNTIME: a Builder preview lists the draft roles, a deployment the production version.\n const runtime = getEnvVar('TIER0_RUNTIME');\n const scope = runtime === 'preview' ? 'draft' : runtime === 'deployed' ? 'production' : undefined;\n if (scope) body = { ...body, scope };\n }\n const serialized = operation.method === 'GET' ? undefined : encodeUnsV2JSON(body, operation.requestSchema ?? 'V1_Empty');\n const response = await this.exchange(path, { method: operation.method, body: serialized }, options, !operation.readonly);\n let value: unknown;\n try { value = decodeUnsV2JSON(response.text, operation.responseSchema); }\n catch {\n if (!response.ok) throw new ApiError(response.status, 0, `Non-JSON API error. ${invalidResponseHint(response.status)}`);\n throw new TransportError('PROTOCOL', !operation.readonly, response.status);\n }\n if (!response.ok) throw responseError(response.status, value);\n if (operation.mode === 'envelope') {\n if (!record(value) || typeof value.code !== 'number') throw new TransportError('PROTOCOL', !operation.readonly, response.status);\n if (value.code !== 200) throw responseError(response.status, value);\n if (!Object.hasOwn(value, 'data')) throw new TransportError('PROTOCOL', !operation.readonly, response.status);\n return value.data as T;\n }\n return value as T;\n }\n\n private async raw<T>(method: string, path: string, body?: unknown, options: RequestOptions = {}): Promise<T> {\n const response = await this.exchange(path, { method, body: body === undefined ? undefined : encodeUnsV2JSON(body, 'V1_Empty') }, options, method !== 'GET');\n let value: unknown;\n try { value = decodeUnsV2JSON(response.text, 'V1_Empty'); }\n catch { throw new ApiError(response.status, 0, `Invalid API response. ${invalidResponseHint(response.status)}`); }\n if (!response.ok || (record(value) && typeof value.code === 'number' && value.code !== 200)) throw responseError(response.status, value);\n return value as T;\n }\n get<T>(path: string, options?: RequestOptions): Promise<T> { return this.raw('GET', path, undefined, options); }\n post<T>(path: string, body: unknown, options?: RequestOptions): Promise<T> { return this.raw('POST', path, body, options); }\n}\n\n// Used by standalone domain clients. createClient() never reads or changes this default.\nlet defaultClient = new HttpClient();\nexport function configureClient(config: ClientConfig): void { defaultClient = new HttpClient(config); }\nexport function getClient(): HttpClient { return defaultClient; }\n"]}
@@ -6,6 +6,7 @@ exports.assertEventId = assertEventId;
6
6
  exports.createUnsV2Client = createUnsV2Client;
7
7
  const cloud_transport_js_1 = require("../cloud-transport.js");
8
8
  const client_js_1 = require("../openapi/client.js");
9
+ const connection_diagnostics_js_1 = require("../connection-diagnostics.js");
9
10
  const codec_js_1 = require("./codec.js");
10
11
  const sse_js_1 = require("./sse.js");
11
12
  const generated_js_1 = require("./generated.js");
@@ -213,7 +214,7 @@ class UnsV2ClientCore {
213
214
  value = (0, codec_js_1.decodeUnsV2JSON)(response.text, response.status === 200 ? operation.response : 'UnsV2ErrorResponse');
214
215
  }
215
216
  catch {
216
- throw invalid('Invalid UNS v2 response.', false);
217
+ throw invalid(`Invalid UNS v2 response. ${(0, connection_diagnostics_js_1.invalidResponseHint)(response.status)}`, false);
217
218
  }
218
219
  if (response.status !== 200) {
219
220
  const info = errorInfo(value, response.status, name);
@@ -271,7 +272,7 @@ class UnsV2ClientCore {
271
272
  }
272
273
  if ('text' in opened) {
273
274
  const unavailable = opened.status === 502 || opened.status === 503 || opened.status === 504;
274
- const invalid = (enveloped) => localError('Invalid UNS v2 event stream response.', name, false, 'UNS_V2_PROTOCOL_ERROR', opened.status, unavailable, {
275
+ const invalid = (enveloped) => localError(`Invalid UNS v2 event stream response. ${(0, connection_diagnostics_js_1.invalidResponseHint)(opened.status)}`, name, false, 'UNS_V2_PROTOCOL_ERROR', opened.status, unavailable, {
275
276
  notStarted: !enveloped && rejectedBeforeUns(opened.status),
276
277
  });
277
278
  let value;
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/uns-v2/client.ts"],"names":[],"mappings":";;;AA6HA,0CAgBC;AAkED,sCAIC;AA0MD,8CAKC;AAlaD,8DAK+B;AAC/B,oDAAuF;AACvF,yCAA8D;AAC9D,qCAAwE;AACxE,iDASwB;AASX,QAAA,iBAAiB,GAA8B,CAAC,YAAY,EAAE,YAAY,EAAE,WAAW,EAAE,SAAS,CAAC,CAAC;AA4BjH;;;;;GAKG;AACH,MAAa,UAAW,SAAQ,KAAK;IAC1B,MAAM,CAAU;IAChB,SAAS,CAAsB;IAC/B,IAAI,CAAS;IACb,SAAS,CAAU;IACnB,SAAS,CAAiB;IAC1B,KAAK,CAAa;IAClB,IAAI,CAAU;IACd,IAAI,CAAU;IACd,OAAO,CAAiB;IACxB,MAAM,CAAU;IAChB,MAAM,CAAU;IAChB,OAAO,CAAU;IACjB,IAAI,CAAW;IAExB,YAAY,OAAe,EAAE,IAAoB;QAC/C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,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,CAAC;AAED,2FAA2F;AAC9E,QAAA,KAAK,GAAG,iBAAiB,EAAE,CAAC","sourcesContent":["import {\n CloudTransport,\n CloudTransportError,\n UNS_V2_MAX_REQUEST_BYTES,\n type CloudTransportConfig,\n} from '../cloud-transport.js';\nimport { getClient, type HttpClient, type RequestOptions } from '../openapi/client.js';\nimport { decodeUnsV2JSON, encodeUnsV2JSON } from './codec.js';\nimport { parseServerSentEvents, ServerSentEventsError } from './sse.js';\nimport {\n UNS_V2_OPERATIONS,\n UNS_V2_STREAM_OPERATIONS,\n type CloudRecordSubscribeReq,\n type UnsV2OperationName,\n type UnsV2StreamOperationName,\n type UnsV2Operations,\n type UnsV2Request,\n type UnsV2Response,\n} from './generated.js';\n\ntype RecordValue = Record<string, unknown>;\n\n/**\n * How far a failed request got. `unknown` only for a mutation whose commit\n * cannot be confirmed; a read is never `unknown`.\n */\nexport type UnsV2Execution = 'notStarted' | 'rolledBack' | 'committed' | 'unknown';\nexport const UNS_V2_EXECUTIONS: readonly UnsV2Execution[] = ['notStarted', 'rolledBack', 'committed', 'unknown'];\n\n/** Whether the identical request (same idempotency key) may be sent again, and after how long. */\nexport interface UnsV2Retry {\n safe: boolean;\n afterMs?: number;\n}\n\n/** Generated POST operations, or a GET event stream such as `recordSubscribe`. */\nexport type UnsV2ErrorOperation = UnsV2OperationName | UnsV2StreamOperationName;\n\nexport interface UnsV2ErrorInfo {\n status?: number;\n operation: UnsV2ErrorOperation;\n code: string;\n requestId?: string;\n execution: UnsV2Execution;\n retry: UnsV2Retry;\n opId?: string;\n path?: string;\n details?: RecordValue[];\n repair?: string;\n reason?: string;\n queryId?: string;\n /** The error envelope's `data`, verbatim; stable access codes such as `data.reason` live here. */\n data?: unknown;\n}\n\n/**\n * A failed UNS v2 call. `execution` and `retry` come from the error body; for\n * failures without one (timeout, network, invalid response) the SDK fills them\n * like the gateway does: a read `rolledBack` and safe to resend, a mutation\n * `unknown` and not safe. This client never retries; it exposes the advice.\n */\nexport class UnsV2Error extends Error implements UnsV2ErrorInfo {\n readonly status?: number;\n readonly operation: UnsV2ErrorOperation;\n readonly code: string;\n readonly requestId?: string;\n readonly execution: UnsV2Execution;\n readonly retry: UnsV2Retry;\n readonly opId?: string;\n readonly path?: string;\n readonly details?: RecordValue[];\n readonly repair?: string;\n readonly reason?: string;\n readonly queryId?: string;\n readonly data?: unknown;\n\n constructor(message: string, info: UnsV2ErrorInfo) {\n super(message);\n this.name = 'UnsV2Error';\n Object.assign(this, info);\n this.status = info.status;\n this.operation = info.operation;\n this.code = info.code;\n this.execution = info.execution;\n this.retry = info.retry;\n }\n\n get outcomeUnknown(): boolean {\n return this.execution === 'unknown';\n }\n}\n\n/**\n * `execution: \"unknown\"`: a mutation may have committed. Reconcile (read back,\n * or replay with the same idempotency key when `retry.safe`) before acting again.\n */\nexport class UnsV2OutcomeUnknownError extends UnsV2Error {\n constructor(message: string, info: UnsV2ErrorInfo) {\n super(message, info);\n this.name = 'UnsV2OutcomeUnknownError';\n }\n}\n\nfunction record(value: unknown): value is RecordValue {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction resourcePath(operation: { path: string; readonly pathParams: readonly string[] }, request: unknown): string {\n let path = operation.path;\n for (const key of operation.pathParams) {\n const value = record(request) && Object.prototype.hasOwnProperty.call(request, key) ? request[key] : undefined;\n if (typeof value !== 'string' || value.length < 1 || value.length > 128 ||\n value === '.' || value === '..' || /[/\\\\\\u0000-\\u001f\\u007f]/.test(value)) {\n throw new TypeError(`Tier0 SDK: invalid UNS v2 path identity ${key}.`);\n }\n path = path.replace(`:${key}`, encodeURIComponent(value));\n }\n return path;\n}\n\nfunction afterMs(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined;\n}\n\n/** The wire error object (an envelope's `error`, a batch item's `error`); undefined when it is not one. */\nexport function parseUnsV2Fault(value: unknown): Omit<UnsV2ErrorInfo, 'status' | 'operation' | 'requestId' | 'data'> | undefined {\n if (!record(value) || typeof value.code !== 'string' || !Array.isArray(value.details) ||\n !UNS_V2_EXECUTIONS.includes(value.execution as UnsV2Execution) ||\n !record(value.retry) || typeof value.retry.safe !== 'boolean') return undefined;\n const wait = afterMs(value.retry.afterMs);\n return {\n code: value.code,\n execution: value.execution as UnsV2Execution,\n retry: { safe: value.retry.safe, ...(wait === undefined ? {} : { afterMs: wait }) },\n opId: typeof value.opId === 'string' ? value.opId : undefined,\n path: typeof value.path === 'string' ? value.path : undefined,\n details: value.details.every(record) ? value.details : undefined,\n repair: typeof value.repair === 'string' ? value.repair : undefined,\n reason: typeof value.reason === 'string' ? value.reason : undefined,\n queryId: typeof value.queryId === 'string' ? value.queryId : undefined,\n };\n}\n\nfunction errorInfo(value: unknown, status: number, operation: UnsV2ErrorOperation): UnsV2ErrorInfo | undefined {\n if (!record(value)) return undefined;\n const fault = parseUnsV2Fault(value.error);\n if (!fault) return undefined;\n return {\n ...fault,\n status,\n operation,\n requestId: typeof value.requestId === 'string' ? value.requestId : undefined,\n data: value.data ?? undefined,\n };\n}\n\n/**\n * Builds the error for a failure without a UNS error body. The gateway's rule\n * applies: a read is `rolledBack` (safe to resend when `safeRead`), a mutation\n * `unknown` and not safe. `notStarted` overrides both for answers that prove\n * the request never reached UNS.\n */\nfunction localError(\n message: string,\n operation: UnsV2ErrorOperation,\n mutation: boolean,\n code: string,\n status?: number,\n safeRead = true,\n extra: { notStarted?: boolean; afterMs?: number } = {},\n): UnsV2Error {\n const info: UnsV2ErrorInfo = {\n status,\n operation,\n code,\n execution: extra.notStarted ? 'notStarted' : mutation ? 'unknown' : 'rolledBack',\n retry: { safe: !mutation && safeRead, ...(extra.afterMs === undefined || mutation ? {} : { afterMs: extra.afterMs }) },\n };\n return info.execution === 'unknown' ? new UnsV2OutcomeUnknownError(message, info) : new UnsV2Error(message, info);\n}\n\n/** `Retry-After` as delay-seconds or an HTTP date, in milliseconds from now. */\nfunction retryAfterMs(value: string | undefined): number | undefined {\n if (value === undefined) return undefined;\n if (/^\\d+$/.test(value.trim())) return Number(value.trim()) * 1000;\n const at = Date.parse(value);\n return Number.isNaN(at) ? undefined : Math.max(0, at - Date.now());\n}\n\n/**\n * UNS v2 routes answer every error with the envelope, so a 4xx whose body is\n * no envelope at all comes from an intermediary (edge 401 / 413 page) that\n * never forwarded the request; 408 is the exception, the request may have\n * been forwarded.\n */\nconst rejectedBeforeUns = (status: number) => status >= 400 && status < 500 && status !== 408;\n\n/** Contract limits of one `records:subscribe` stream. */\nexport const UNS_V2_SUBSCRIBE_MAX_COLLECTIONS = 64;\nexport const UNS_V2_SUBSCRIBE_MAX_RECORD_IDS = 100;\nconst EVENT_ID_MAX_LENGTH = 8192;\n\n/**\n * Rejects a resume position that cannot be an event id (1–8192 visible ASCII\n * characters), such as a `Last-Event-ID` with CR/LF taken from a browser:\n * sent as a header it would fail every connection.\n */\nexport function assertEventId(value: string): void {\n if (typeof value !== 'string' || value.length < 1 || value.length > EVENT_ID_MAX_LENGTH || !/^[\\x21-\\x7e]+$/.test(value)) {\n throw new TypeError(`Tier0 SDK: lastEventId must be 1–${EVENT_ID_MAX_LENGTH} visible ASCII characters.`);\n }\n}\n\n/**\n * Query of `records:subscribe`; the resume position travels as `lastEventId`\n * (the `Last-Event-ID` header). Without `collectionIds` the stream covers every\n * collection the caller may read (an App key: every collection granted to the App).\n */\nexport type UnsV2RecordSubscribeRequest = Pick<CloudRecordSubscribeReq, 'collectionIds' | 'recordIds'>;\n\n/**\n * A committed record change. Events carry identities only: read the record to\n * see its data. `restricted`: the collection has employee data rules, so who\n * may see this record depends on the employee (see `data.subscribe`).\n */\nexport interface UnsV2RecordChangeEvent {\n type: 'change';\n /** Stream position (also the frame id); resume after it with `lastEventId`. */\n eventId: string;\n collectionId: string;\n recordId: string;\n revision: number;\n change: 'record' | 'delete';\n occurredAt: number;\n restricted: boolean;\n}\n\nexport type UnsV2SubscriptionEvent =\n | UnsV2RecordChangeEvent\n /** Sent on connect and every 15 s; `eventId` is the current position, resumable like a change's. */\n | { type: 'heartbeat'; eventId?: string }\n /**\n * The server closes the stream after it. `CURSOR_EXPIRED`: the position is\n * outside the 24 h retention; `SCOPE_CHANGED`: access narrowed. Reload, then\n * subscribe again without `lastEventId`.\n */\n | { type: 'reset'; reason: string; message?: string };\n\nfunction changeEvent(value: unknown): UnsV2RecordChangeEvent | undefined {\n if (!record(value) || typeof value.eventId !== 'string' || typeof value.collectionId !== 'string' ||\n typeof value.recordId !== 'string' || typeof value.revision !== 'number' || !Number.isSafeInteger(value.revision) ||\n (value.change !== 'record' && value.change !== 'delete') || typeof value.occurredAt !== 'number' ||\n typeof value.restricted !== 'boolean') return undefined;\n return {\n type: 'change',\n eventId: value.eventId,\n collectionId: value.collectionId,\n recordId: value.recordId,\n revision: value.revision,\n change: value.change,\n occurredAt: value.occurredAt,\n restricted: value.restricted,\n };\n}\n\nexport class UnsV2ClientCore {\n private readonly transport: CloudTransport;\n\n constructor(resolveClient: () => HttpClient = getClient, config: CloudTransportConfig = {}) {\n this.transport = new CloudTransport(resolveClient, config);\n }\n\n async call<Name extends UnsV2OperationName>(name: Name, request: UnsV2Request<Name>, options: RequestOptions = {}): Promise<UnsV2Response<Name>> {\n options.signal?.throwIfAborted();\n if (typeof name !== 'string' || !Object.prototype.hasOwnProperty.call(UNS_V2_OPERATIONS, name)) {\n throw new TypeError('Tier0 SDK: unknown UNS v2 operation.');\n }\n const operation = UNS_V2_OPERATIONS[name];\n const mutation = operation.mutation;\n const path = resourcePath(operation, request);\n const body = encodeUnsV2JSON(request, operation.request);\n if (new TextEncoder().encode(body).byteLength > UNS_V2_MAX_REQUEST_BYTES) {\n throw new TypeError('Tier0 SDK: UNS v2 request body exceeds the 16777216-byte contract limit.');\n }\n let response: Awaited<ReturnType<CloudTransport['postText']>>;\n try {\n response = await this.transport.postText(path, body, options, name);\n } catch (error) {\n if (!(error instanceof CloudTransportError)) throw error;\n const message = error.kind === 'TRANSPORT_TIMEOUT'\n ? 'UNS v2 HTTP transport deadline exceeded.'\n : error.kind === 'PROTOCOL_ERROR' ? 'Invalid UNS v2 HTTP response.'\n : error.kind === 'TRANSPORT_ABORTED' ? 'UNS v2 request aborted.' : 'UNS v2 transport failed.';\n const resendable = error.kind === 'TRANSPORT_TIMEOUT' || error.kind === 'TRANSPORT_ERROR';\n throw localError(message, name, mutation, `UNS_V2_${error.kind}`, error.status, resendable);\n }\n\n // An ingress answers 502/503/504 without the UNS envelope during rollouts and restarts.\n const unavailable = response.status === 502 || response.status === 503 || response.status === 504;\n // `enveloped`: the body looks like a UNS envelope, so UNS may have answered it.\n const invalid = (message: string, enveloped: boolean) => localError(message, name, mutation, 'UNS_V2_PROTOCOL_ERROR', response.status, unavailable, {\n notStarted: !enveloped && rejectedBeforeUns(response.status),\n afterMs: unavailable ? retryAfterMs(response.retryAfter) : undefined,\n });\n let value: unknown;\n try {\n value = decodeUnsV2JSON(response.text, response.status === 200 ? operation.response : 'UnsV2ErrorResponse');\n } catch {\n throw invalid('Invalid UNS v2 response.', false);\n }\n\n if (response.status !== 200) {\n const info = errorInfo(value, response.status, name);\n if (!info || !record(value) || value.code !== response.status) {\n throw invalid('Invalid UNS v2 error response.', record(value) && typeof value.code === 'number');\n }\n // A read never has an unknown outcome; hold UNS to the rule it states for itself.\n if (!mutation && info.execution === 'unknown') info.execution = 'rolledBack';\n const message = typeof value.msg === 'string' ? value.msg : info.code;\n throw info.execution === 'unknown' ? new UnsV2OutcomeUnknownError(message, info) : new UnsV2Error(message, info);\n }\n\n if (!record(value) || value.code !== 200 || typeof value.msg !== 'string' ||\n typeof value.requestId !== 'string' || !Object.prototype.hasOwnProperty.call(value, 'data')) {\n throw localError('Invalid UNS v2 success envelope.', name, mutation, 'UNS_V2_PROTOCOL_ERROR', response.status, false);\n }\n return value as UnsV2Response<Name>;\n }\n\n /**\n * Opens one `records:subscribe` event stream and yields its events until\n * the server ends it or `signal` aborts (the generator then returns). It\n * neither reconnects nor watches heartbeats; `data.subscribe` does. A\n * refused or broken connection throws UnsV2Error (operation\n * `recordSubscribe`, a read: `retry.safe` says whether to reconnect).\n */\n async *subscribeRecords(request: UnsV2RecordSubscribeRequest, options: RequestOptions & { lastEventId?: string } = {}): AsyncGenerator<UnsV2SubscriptionEvent> {\n const name = 'recordSubscribe';\n const { collectionIds, recordIds } = request;\n if (collectionIds !== undefined && (!Array.isArray(collectionIds) || collectionIds.length < 1 || collectionIds.length > UNS_V2_SUBSCRIBE_MAX_COLLECTIONS)) {\n throw new TypeError(`Tier0 SDK: records:subscribe lists 1–${UNS_V2_SUBSCRIBE_MAX_COLLECTIONS} collections, or none for all.`);\n }\n if (recordIds !== undefined && (recordIds.length < 1 || recordIds.length > UNS_V2_SUBSCRIBE_MAX_RECORD_IDS || collectionIds?.length !== 1)) {\n throw new TypeError(`Tier0 SDK: records:subscribe takes 1–${UNS_V2_SUBSCRIBE_MAX_RECORD_IDS} recordIds of exactly one collection.`);\n }\n if (options.lastEventId !== undefined) assertEventId(options.lastEventId);\n // Repeated query parameters, as the contract specifies.\n const query = new URLSearchParams();\n for (const id of collectionIds ?? []) query.append('collectionIds', id);\n for (const id of recordIds ?? []) query.append('recordIds', id);\n const path = UNS_V2_STREAM_OPERATIONS.recordSubscribe.path + (query.size ? `?${query}` : '');\n let opened: Awaited<ReturnType<CloudTransport['getEventStream']>>;\n try {\n opened = await this.transport.getEventStream(path, options, name);\n } catch (error) {\n if (!(error instanceof CloudTransportError)) throw error;\n if (error.kind === 'TRANSPORT_ABORTED') return;\n const resendable = error.kind === 'TRANSPORT_TIMEOUT' || error.kind === 'TRANSPORT_ERROR';\n throw localError('UNS v2 event stream could not be opened.', name, false, `UNS_V2_${error.kind}`, error.status, resendable);\n }\n if ('text' in opened) {\n const unavailable = opened.status === 502 || opened.status === 503 || opened.status === 504;\n const invalid = (enveloped: boolean) => localError('Invalid UNS v2 event stream response.', name, false, 'UNS_V2_PROTOCOL_ERROR', opened.status, unavailable, {\n notStarted: !enveloped && rejectedBeforeUns(opened.status),\n });\n let value: unknown;\n try {\n value = decodeUnsV2JSON(opened.text, 'UnsV2ErrorResponse');\n } catch {\n throw invalid(false);\n }\n const info = opened.status === 200 ? undefined : errorInfo(value, opened.status, name);\n if (!info || !record(value) || value.code !== opened.status) throw invalid(record(value) && typeof value.code === 'number');\n // A subscription is a read: never an unknown outcome.\n if (info.execution === 'unknown') info.execution = 'rolledBack';\n throw new UnsV2Error(typeof value.msg === 'string' ? value.msg : info.code, info);\n }\n try {\n for await (const event of parseServerSentEvents(opened.stream)) {\n // A keep-alive comment counts as a heartbeat too.\n if ('comment' in event) {\n yield { type: 'heartbeat' };\n } else if (event.event === 'heartbeat') {\n yield event.id === undefined ? { type: 'heartbeat' } : { type: 'heartbeat', eventId: event.id };\n } else if (event.event === 'reset') {\n let body: unknown;\n try { body = JSON.parse(event.data); } catch { body = undefined; }\n if (!record(body) || typeof body.reason !== 'string') {\n throw localError('Invalid UNS v2 reset event.', name, false, 'UNS_V2_PROTOCOL_ERROR', 200, true);\n }\n yield typeof body.message === 'string'\n ? { type: 'reset', reason: body.reason, message: body.message }\n : { type: 'reset', reason: body.reason };\n } else if (event.event === 'change') {\n let parsed: UnsV2RecordChangeEvent | undefined;\n try { parsed = changeEvent(JSON.parse(event.data)); } catch { parsed = undefined; }\n if (!parsed) throw localError('Invalid UNS v2 change event.', name, false, 'UNS_V2_PROTOCOL_ERROR', 200, true);\n yield parsed;\n }\n }\n } catch (error) {\n if (options.signal?.aborted) return;\n if (error instanceof UnsV2Error) throw error;\n if (error instanceof ServerSentEventsError) throw localError(error.message, name, false, 'UNS_V2_PROTOCOL_ERROR', 200, true);\n throw localError('UNS v2 event stream broke.', name, false, 'UNS_V2_TRANSPORT_ERROR', 200, true);\n } finally {\n opened.close();\n }\n }\n}\n\nexport type UnsV2Client = UnsV2ClientCore & UnsV2Operations;\n\nexport function createUnsV2Client(resolveClient: () => HttpClient = getClient, config: CloudTransportConfig = {}): UnsV2Client {\n const core = new UnsV2ClientCore(resolveClient, config);\n const methods = Object.fromEntries(Object.keys(UNS_V2_OPERATIONS).map(name => [name, (request: unknown, options?: RequestOptions) =>\n core.call(name as UnsV2OperationName, request as UnsV2Request<UnsV2OperationName>, options)]));\n return Object.assign(core, methods) as unknown as UnsV2Client;\n}\n\n/** Uses configureClient()/TIER0_API_HOST/TIER0_API_KEY and does not imply v2 readiness. */\nexport const unsV2 = createUnsV2Client();\n"]}
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/uns-v2/client.ts"],"names":[],"mappings":";;;AA8HA,0CAgBC;AAkED,sCAIC;AA0MD,8CAKC;AAnaD,8DAK+B;AAC/B,oDAAuF;AACvF,4EAAmE;AACnE,yCAA8D;AAC9D,qCAAwE;AACxE,iDASwB;AASX,QAAA,iBAAiB,GAA8B,CAAC,YAAY,EAAE,YAAY,EAAE,WAAW,EAAE,SAAS,CAAC,CAAC;AA4BjH;;;;;GAKG;AACH,MAAa,UAAW,SAAQ,KAAK;IAC1B,MAAM,CAAU;IAChB,SAAS,CAAsB;IAC/B,IAAI,CAAS;IACb,SAAS,CAAU;IACnB,SAAS,CAAiB;IAC1B,KAAK,CAAa;IAClB,IAAI,CAAU;IACd,IAAI,CAAU;IACd,OAAO,CAAiB;IACxB,MAAM,CAAU;IAChB,MAAM,CAAU;IAChB,OAAO,CAAU;IACjB,IAAI,CAAW;IAExB,YAAY,OAAe,EAAE,IAAoB;QAC/C,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,YAAY,CAAC;QACzB,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QAC1B,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC1B,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;QAChC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;QACtB,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;QAChC,IAAI,CAAC,KAAK,GAAG,I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;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,OAAO,CAAC,MAAM,EAAE,OAAO;gBAAE,OAAO;YACpC,IAAI,KAAK,YAAY,UAAU;gBAAE,MAAM,KAAK,CAAC;YAC7C,IAAI,KAAK,YAAY,8BAAqB;gBAAE,MAAM,UAAU,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,uBAAuB,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;YAC7H,MAAM,UAAU,CAAC,4BAA4B,EAAE,IAAI,EAAE,KAAK,EAAE,wBAAwB,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;QACnG,CAAC;gBAAS,CAAC;YACT,MAAM,CAAC,KAAK,EAAE,CAAC;QACjB,CAAC;IACH,CAAC;CACF;AAhJD,0CAgJC;AAID,SAAgB,iBAAiB,CAAC,gBAAkC,qBAAS,EAAE,SAA+B,EAAE;IAC9G,MAAM,IAAI,GAAG,IAAI,eAAe,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC;IACxD,MAAM,OAAO,GAAG,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,gCAAiB,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,OAAgB,EAAE,OAAwB,EAAE,EAAE,CAClI,IAAI,CAAC,IAAI,CAAC,IAA0B,EAAE,OAA2C,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IACjG,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,CAA2B,CAAC;AAChE,CAAC;AAED,2FAA2F;AAC9E,QAAA,KAAK,GAAG,iBAAiB,EAAE,CAAC","sourcesContent":["import {\n CloudTransport,\n CloudTransportError,\n UNS_V2_MAX_REQUEST_BYTES,\n type CloudTransportConfig,\n} from '../cloud-transport.js';\nimport { getClient, type HttpClient, type RequestOptions } from '../openapi/client.js';\nimport { invalidResponseHint } from '../connection-diagnostics.js';\nimport { decodeUnsV2JSON, encodeUnsV2JSON } from './codec.js';\nimport { parseServerSentEvents, ServerSentEventsError } from './sse.js';\nimport {\n UNS_V2_OPERATIONS,\n UNS_V2_STREAM_OPERATIONS,\n type CloudRecordSubscribeReq,\n type UnsV2OperationName,\n type UnsV2StreamOperationName,\n type UnsV2Operations,\n type UnsV2Request,\n type UnsV2Response,\n} from './generated.js';\n\ntype RecordValue = Record<string, unknown>;\n\n/**\n * How far a failed request got. `unknown` only for a mutation whose commit\n * cannot be confirmed; a read is never `unknown`.\n */\nexport type UnsV2Execution = 'notStarted' | 'rolledBack' | 'committed' | 'unknown';\nexport const UNS_V2_EXECUTIONS: readonly UnsV2Execution[] = ['notStarted', 'rolledBack', 'committed', 'unknown'];\n\n/** Whether the identical request (same idempotency key) may be sent again, and after how long. */\nexport interface UnsV2Retry {\n safe: boolean;\n afterMs?: number;\n}\n\n/** Generated POST operations, or a GET event stream such as `recordSubscribe`. */\nexport type UnsV2ErrorOperation = UnsV2OperationName | UnsV2StreamOperationName;\n\nexport interface UnsV2ErrorInfo {\n status?: number;\n operation: UnsV2ErrorOperation;\n code: string;\n requestId?: string;\n execution: UnsV2Execution;\n retry: UnsV2Retry;\n opId?: string;\n path?: string;\n details?: RecordValue[];\n repair?: string;\n reason?: string;\n queryId?: string;\n /** The error envelope's `data`, verbatim; stable access codes such as `data.reason` live here. */\n data?: unknown;\n}\n\n/**\n * A failed UNS v2 call. `execution` and `retry` come from the error body; for\n * failures without one (timeout, network, invalid response) the SDK fills them\n * like the gateway does: a read `rolledBack` and safe to resend, a mutation\n * `unknown` and not safe. This client never retries; it exposes the advice.\n */\nexport class UnsV2Error extends Error implements UnsV2ErrorInfo {\n readonly status?: number;\n readonly operation: UnsV2ErrorOperation;\n readonly code: string;\n readonly requestId?: string;\n readonly execution: UnsV2Execution;\n readonly retry: UnsV2Retry;\n readonly opId?: string;\n readonly path?: string;\n readonly details?: RecordValue[];\n readonly repair?: string;\n readonly reason?: string;\n readonly queryId?: string;\n readonly data?: unknown;\n\n constructor(message: string, info: UnsV2ErrorInfo) {\n super(message);\n this.name = 'UnsV2Error';\n Object.assign(this, info);\n this.status = info.status;\n this.operation = info.operation;\n this.code = info.code;\n this.execution = info.execution;\n this.retry = info.retry;\n }\n\n get outcomeUnknown(): boolean {\n return this.execution === 'unknown';\n }\n}\n\n/**\n * `execution: \"unknown\"`: a mutation may have committed. Reconcile (read back,\n * or replay with the same idempotency key when `retry.safe`) before acting again.\n */\nexport class UnsV2OutcomeUnknownError extends UnsV2Error {\n constructor(message: string, info: UnsV2ErrorInfo) {\n super(message, info);\n this.name = 'UnsV2OutcomeUnknownError';\n }\n}\n\nfunction record(value: unknown): value is RecordValue {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction resourcePath(operation: { path: string; readonly pathParams: readonly string[] }, request: unknown): string {\n let path = operation.path;\n for (const key of operation.pathParams) {\n const value = record(request) && Object.prototype.hasOwnProperty.call(request, key) ? request[key] : undefined;\n if (typeof value !== 'string' || value.length < 1 || value.length > 128 ||\n value === '.' || value === '..' || /[/\\\\\\u0000-\\u001f\\u007f]/.test(value)) {\n throw new TypeError(`Tier0 SDK: invalid UNS v2 path identity ${key}.`);\n }\n path = path.replace(`:${key}`, encodeURIComponent(value));\n }\n return path;\n}\n\nfunction afterMs(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined;\n}\n\n/** The wire error object (an envelope's `error`, a batch item's `error`); undefined when it is not one. */\nexport function parseUnsV2Fault(value: unknown): Omit<UnsV2ErrorInfo, 'status' | 'operation' | 'requestId' | 'data'> | undefined {\n if (!record(value) || typeof value.code !== 'string' || !Array.isArray(value.details) ||\n !UNS_V2_EXECUTIONS.includes(value.execution as UnsV2Execution) ||\n !record(value.retry) || typeof value.retry.safe !== 'boolean') return undefined;\n const wait = afterMs(value.retry.afterMs);\n return {\n code: value.code,\n execution: value.execution as UnsV2Execution,\n retry: { safe: value.retry.safe, ...(wait === undefined ? {} : { afterMs: wait }) },\n opId: typeof value.opId === 'string' ? value.opId : undefined,\n path: typeof value.path === 'string' ? value.path : undefined,\n details: value.details.every(record) ? value.details : undefined,\n repair: typeof value.repair === 'string' ? value.repair : undefined,\n reason: typeof value.reason === 'string' ? value.reason : undefined,\n queryId: typeof value.queryId === 'string' ? value.queryId : undefined,\n };\n}\n\nfunction errorInfo(value: unknown, status: number, operation: UnsV2ErrorOperation): UnsV2ErrorInfo | undefined {\n if (!record(value)) return undefined;\n const fault = parseUnsV2Fault(value.error);\n if (!fault) return undefined;\n return {\n ...fault,\n status,\n operation,\n requestId: typeof value.requestId === 'string' ? value.requestId : undefined,\n data: value.data ?? undefined,\n };\n}\n\n/**\n * Builds the error for a failure without a UNS error body. The gateway's rule\n * applies: a read is `rolledBack` (safe to resend when `safeRead`), a mutation\n * `unknown` and not safe. `notStarted` overrides both for answers that prove\n * the request never reached UNS.\n */\nfunction localError(\n message: string,\n operation: UnsV2ErrorOperation,\n mutation: boolean,\n code: string,\n status?: number,\n safeRead = true,\n extra: { notStarted?: boolean; afterMs?: number } = {},\n): UnsV2Error {\n const info: UnsV2ErrorInfo = {\n status,\n operation,\n code,\n execution: extra.notStarted ? 'notStarted' : mutation ? 'unknown' : 'rolledBack',\n retry: { safe: !mutation && safeRead, ...(extra.afterMs === undefined || mutation ? {} : { afterMs: extra.afterMs }) },\n };\n return info.execution === 'unknown' ? new UnsV2OutcomeUnknownError(message, info) : new UnsV2Error(message, info);\n}\n\n/** `Retry-After` as delay-seconds or an HTTP date, in milliseconds from now. */\nfunction retryAfterMs(value: string | undefined): number | undefined {\n if (value === undefined) return undefined;\n if (/^\\d+$/.test(value.trim())) return Number(value.trim()) * 1000;\n const at = Date.parse(value);\n return Number.isNaN(at) ? undefined : Math.max(0, at - Date.now());\n}\n\n/**\n * UNS v2 routes answer every error with the envelope, so a 4xx whose body is\n * no envelope at all comes from an intermediary (edge 401 / 413 page) that\n * never forwarded the request; 408 is the exception, the request may have\n * been forwarded.\n */\nconst rejectedBeforeUns = (status: number) => status >= 400 && status < 500 && status !== 408;\n\n/** Contract limits of one `records:subscribe` stream. */\nexport const UNS_V2_SUBSCRIBE_MAX_COLLECTIONS = 64;\nexport const UNS_V2_SUBSCRIBE_MAX_RECORD_IDS = 100;\nconst EVENT_ID_MAX_LENGTH = 8192;\n\n/**\n * Rejects a resume position that cannot be an event id (1–8192 visible ASCII\n * characters), such as a `Last-Event-ID` with CR/LF taken from a browser:\n * sent as a header it would fail every connection.\n */\nexport function assertEventId(value: string): void {\n if (typeof value !== 'string' || value.length < 1 || value.length > EVENT_ID_MAX_LENGTH || !/^[\\x21-\\x7e]+$/.test(value)) {\n throw new TypeError(`Tier0 SDK: lastEventId must be 1–${EVENT_ID_MAX_LENGTH} visible ASCII characters.`);\n }\n}\n\n/**\n * Query of `records:subscribe`; the resume position travels as `lastEventId`\n * (the `Last-Event-ID` header). Without `collectionIds` the stream covers every\n * collection the caller may read (an App key: every collection granted to the App).\n */\nexport type UnsV2RecordSubscribeRequest = Pick<CloudRecordSubscribeReq, 'collectionIds' | 'recordIds'>;\n\n/**\n * A committed record change. Events carry identities only: read the record to\n * see its data. `restricted`: the collection has employee data rules, so who\n * may see this record depends on the employee (see `data.subscribe`).\n */\nexport interface UnsV2RecordChangeEvent {\n type: 'change';\n /** Stream position (also the frame id); resume after it with `lastEventId`. */\n eventId: string;\n collectionId: string;\n recordId: string;\n revision: number;\n change: 'record' | 'delete';\n occurredAt: number;\n restricted: boolean;\n}\n\nexport type UnsV2SubscriptionEvent =\n | UnsV2RecordChangeEvent\n /** Sent on connect and every 15 s; `eventId` is the current position, resumable like a change's. */\n | { type: 'heartbeat'; eventId?: string }\n /**\n * The server closes the stream after it. `CURSOR_EXPIRED`: the position is\n * outside the 24 h retention; `SCOPE_CHANGED`: access narrowed. Reload, then\n * subscribe again without `lastEventId`.\n */\n | { type: 'reset'; reason: string; message?: string };\n\nfunction changeEvent(value: unknown): UnsV2RecordChangeEvent | undefined {\n if (!record(value) || typeof value.eventId !== 'string' || typeof value.collectionId !== 'string' ||\n typeof value.recordId !== 'string' || typeof value.revision !== 'number' || !Number.isSafeInteger(value.revision) ||\n (value.change !== 'record' && value.change !== 'delete') || typeof value.occurredAt !== 'number' ||\n typeof value.restricted !== 'boolean') return undefined;\n return {\n type: 'change',\n eventId: value.eventId,\n collectionId: value.collectionId,\n recordId: value.recordId,\n revision: value.revision,\n change: value.change,\n occurredAt: value.occurredAt,\n restricted: value.restricted,\n };\n}\n\nexport class UnsV2ClientCore {\n private readonly transport: CloudTransport;\n\n constructor(resolveClient: () => HttpClient = getClient, config: CloudTransportConfig = {}) {\n this.transport = new CloudTransport(resolveClient, config);\n }\n\n async call<Name extends UnsV2OperationName>(name: Name, request: UnsV2Request<Name>, options: RequestOptions = {}): Promise<UnsV2Response<Name>> {\n options.signal?.throwIfAborted();\n if (typeof name !== 'string' || !Object.prototype.hasOwnProperty.call(UNS_V2_OPERATIONS, name)) {\n throw new TypeError('Tier0 SDK: unknown UNS v2 operation.');\n }\n const operation = UNS_V2_OPERATIONS[name];\n const mutation = operation.mutation;\n const path = resourcePath(operation, request);\n const body = encodeUnsV2JSON(request, operation.request);\n if (new TextEncoder().encode(body).byteLength > UNS_V2_MAX_REQUEST_BYTES) {\n throw new TypeError('Tier0 SDK: UNS v2 request body exceeds the 16777216-byte contract limit.');\n }\n let response: Awaited<ReturnType<CloudTransport['postText']>>;\n try {\n response = await this.transport.postText(path, body, options, name);\n } catch (error) {\n if (!(error instanceof CloudTransportError)) throw error;\n const message = error.kind === 'TRANSPORT_TIMEOUT'\n ? 'UNS v2 HTTP transport deadline exceeded.'\n : error.kind === 'PROTOCOL_ERROR' ? 'Invalid UNS v2 HTTP response.'\n : error.kind === 'TRANSPORT_ABORTED' ? 'UNS v2 request aborted.' : 'UNS v2 transport failed.';\n const resendable = error.kind === 'TRANSPORT_TIMEOUT' || error.kind === 'TRANSPORT_ERROR';\n throw localError(message, name, mutation, `UNS_V2_${error.kind}`, error.status, resendable);\n }\n\n // An ingress answers 502/503/504 without the UNS envelope during rollouts and restarts.\n const unavailable = response.status === 502 || response.status === 503 || response.status === 504;\n // `enveloped`: the body looks like a UNS envelope, so UNS may have answered it.\n const invalid = (message: string, enveloped: boolean) => localError(message, name, mutation, 'UNS_V2_PROTOCOL_ERROR', response.status, unavailable, {\n notStarted: !enveloped && rejectedBeforeUns(response.status),\n afterMs: unavailable ? retryAfterMs(response.retryAfter) : undefined,\n });\n let value: unknown;\n try {\n value = decodeUnsV2JSON(response.text, response.status === 200 ? operation.response : 'UnsV2ErrorResponse');\n } catch {\n throw invalid(`Invalid UNS v2 response. ${invalidResponseHint(response.status)}`, false);\n }\n\n if (response.status !== 200) {\n const info = errorInfo(value, response.status, name);\n if (!info || !record(value) || value.code !== response.status) {\n throw invalid('Invalid UNS v2 error response.', record(value) && typeof value.code === 'number');\n }\n // A read never has an unknown outcome; hold UNS to the rule it states for itself.\n if (!mutation && info.execution === 'unknown') info.execution = 'rolledBack';\n const message = typeof value.msg === 'string' ? value.msg : info.code;\n throw info.execution === 'unknown' ? new UnsV2OutcomeUnknownError(message, info) : new UnsV2Error(message, info);\n }\n\n if (!record(value) || value.code !== 200 || typeof value.msg !== 'string' ||\n typeof value.requestId !== 'string' || !Object.prototype.hasOwnProperty.call(value, 'data')) {\n throw localError('Invalid UNS v2 success envelope.', name, mutation, 'UNS_V2_PROTOCOL_ERROR', response.status, false);\n }\n return value as UnsV2Response<Name>;\n }\n\n /**\n * Opens one `records:subscribe` event stream and yields its events until\n * the server ends it or `signal` aborts (the generator then returns). It\n * neither reconnects nor watches heartbeats; `data.subscribe` does. A\n * refused or broken connection throws UnsV2Error (operation\n * `recordSubscribe`, a read: `retry.safe` says whether to reconnect).\n */\n async *subscribeRecords(request: UnsV2RecordSubscribeRequest, options: RequestOptions & { lastEventId?: string } = {}): AsyncGenerator<UnsV2SubscriptionEvent> {\n const name = 'recordSubscribe';\n const { collectionIds, recordIds } = request;\n if (collectionIds !== undefined && (!Array.isArray(collectionIds) || collectionIds.length < 1 || collectionIds.length > UNS_V2_SUBSCRIBE_MAX_COLLECTIONS)) {\n throw new TypeError(`Tier0 SDK: records:subscribe lists 1–${UNS_V2_SUBSCRIBE_MAX_COLLECTIONS} collections, or none for all.`);\n }\n if (recordIds !== undefined && (recordIds.length < 1 || recordIds.length > UNS_V2_SUBSCRIBE_MAX_RECORD_IDS || collectionIds?.length !== 1)) {\n throw new TypeError(`Tier0 SDK: records:subscribe takes 1–${UNS_V2_SUBSCRIBE_MAX_RECORD_IDS} recordIds of exactly one collection.`);\n }\n if (options.lastEventId !== undefined) assertEventId(options.lastEventId);\n // Repeated query parameters, as the contract specifies.\n const query = new URLSearchParams();\n for (const id of collectionIds ?? []) query.append('collectionIds', id);\n for (const id of recordIds ?? []) query.append('recordIds', id);\n const path = UNS_V2_STREAM_OPERATIONS.recordSubscribe.path + (query.size ? `?${query}` : '');\n let opened: Awaited<ReturnType<CloudTransport['getEventStream']>>;\n try {\n opened = await this.transport.getEventStream(path, options, name);\n } catch (error) {\n if (!(error instanceof CloudTransportError)) throw error;\n if (error.kind === 'TRANSPORT_ABORTED') return;\n const resendable = error.kind === 'TRANSPORT_TIMEOUT' || error.kind === 'TRANSPORT_ERROR';\n throw localError('UNS v2 event stream could not be opened.', name, false, `UNS_V2_${error.kind}`, error.status, resendable);\n }\n if ('text' in opened) {\n const unavailable = opened.status === 502 || opened.status === 503 || opened.status === 504;\n const invalid = (enveloped: boolean) => localError(`Invalid UNS v2 event stream response. ${invalidResponseHint(opened.status)}`, name, false, 'UNS_V2_PROTOCOL_ERROR', opened.status, unavailable, {\n notStarted: !enveloped && rejectedBeforeUns(opened.status),\n });\n let value: unknown;\n try {\n value = decodeUnsV2JSON(opened.text, 'UnsV2ErrorResponse');\n } catch {\n throw invalid(false);\n }\n const info = opened.status === 200 ? undefined : errorInfo(value, opened.status, name);\n if (!info || !record(value) || value.code !== opened.status) throw invalid(record(value) && typeof value.code === 'number');\n // A subscription is a read: never an unknown outcome.\n if (info.execution === 'unknown') info.execution = 'rolledBack';\n throw new UnsV2Error(typeof value.msg === 'string' ? value.msg : info.code, info);\n }\n try {\n for await (const event of parseServerSentEvents(opened.stream)) {\n // A keep-alive comment counts as a heartbeat too.\n if ('comment' in event) {\n yield { type: 'heartbeat' };\n } else if (event.event === 'heartbeat') {\n yield event.id === undefined ? { type: 'heartbeat' } : { type: 'heartbeat', eventId: event.id };\n } else if (event.event === 'reset') {\n let body: unknown;\n try { body = JSON.parse(event.data); } catch { body = undefined; }\n if (!record(body) || typeof body.reason !== 'string') {\n throw localError('Invalid UNS v2 reset event.', name, false, 'UNS_V2_PROTOCOL_ERROR', 200, true);\n }\n yield typeof body.message === 'string'\n ? { type: 'reset', reason: body.reason, message: body.message }\n : { type: 'reset', reason: body.reason };\n } else if (event.event === 'change') {\n let parsed: UnsV2RecordChangeEvent | undefined;\n try { parsed = changeEvent(JSON.parse(event.data)); } catch { parsed = undefined; }\n if (!parsed) throw localError('Invalid UNS v2 change event.', name, false, 'UNS_V2_PROTOCOL_ERROR', 200, true);\n yield parsed;\n }\n }\n } catch (error) {\n if (options.signal?.aborted) return;\n if (error instanceof UnsV2Error) throw error;\n if (error instanceof ServerSentEventsError) throw localError(error.message, name, false, 'UNS_V2_PROTOCOL_ERROR', 200, true);\n throw localError('UNS v2 event stream broke.', name, false, 'UNS_V2_TRANSPORT_ERROR', 200, true);\n } finally {\n opened.close();\n }\n }\n}\n\nexport type UnsV2Client = UnsV2ClientCore & UnsV2Operations;\n\nexport function createUnsV2Client(resolveClient: () => HttpClient = getClient, config: CloudTransportConfig = {}): UnsV2Client {\n const core = new UnsV2ClientCore(resolveClient, config);\n const methods = Object.fromEntries(Object.keys(UNS_V2_OPERATIONS).map(name => [name, (request: unknown, options?: RequestOptions) =>\n core.call(name as UnsV2OperationName, request as UnsV2Request<UnsV2OperationName>, options)]));\n return Object.assign(core, methods) as unknown as UnsV2Client;\n}\n\n/** Uses configureClient()/TIER0_API_HOST/TIER0_API_KEY and does not imply v2 readiness. */\nexport const unsV2 = createUnsV2Client();\n"]}
@@ -0,0 +1,2 @@
1
+ /** Static advice only: never include credentials, response bodies or configured URLs. */
2
+ export declare function invalidResponseHint(status: number): string;
@@ -0,0 +1,17 @@
1
+ /** Static advice only: never include credentials, response bodies or configured URLs. */
2
+ export function invalidResponseHint(status) {
3
+ if (status === 404 || status === 405) {
4
+ return 'Check apiHost / TIER0_API_HOST: use this environment\'s OpenAPI gateway base URL, not its platform webpage or MCP URL. Confirm that the gateway exposes /openapi/v2 routes; obtain the address from the environment deployment guide or administrator.';
5
+ }
6
+ if (status === 401) {
7
+ return 'Check that apiHost / TIER0_API_HOST targets the intended OpenAPI gateway, then check that the API key is present, valid and belongs to that environment. An intermediary may also require authentication.';
8
+ }
9
+ if (status === 403) {
10
+ return 'Check the credential\'s permissions for this operation and any gateway access restrictions. A non-JSON response alone does not prove the API key is invalid.';
11
+ }
12
+ if (status === 502 || status === 503 || status === 504) {
13
+ return 'The gateway or upstream service may be temporarily unavailable. Check service health; do not replace the API key based on this response. Before repeating a write, check whether it committed.';
14
+ }
15
+ return 'Check apiHost / TIER0_API_HOST and the gateway response format against the environment deployment guide; OpenAPI JSON responses are required.';
16
+ }
17
+ //# sourceMappingURL=connection-diagnostics.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connection-diagnostics.js","sourceRoot":"","sources":["../../src/connection-diagnostics.ts"],"names":[],"mappings":"AAAA,yFAAyF;AACzF,MAAM,UAAU,mBAAmB,CAAC,MAAc;IAChD,IAAI,MAAM,KAAK,GAAG,IAAI,MAAM,KAAK,GAAG,EAAE,CAAC;QACrC,OAAO,wPAAwP,CAAC;IAClQ,CAAC;IACD,IAAI,MAAM,KAAK,GAAG,EAAE,CAAC;QACnB,OAAO,2MAA2M,CAAC;IACrN,CAAC;IACD,IAAI,MAAM,KAAK,GAAG,EAAE,CAAC;QACnB,OAAO,8JAA8J,CAAC;IACxK,CAAC;IACD,IAAI,MAAM,KAAK,GAAG,IAAI,MAAM,KAAK,GAAG,IAAI,MAAM,KAAK,GAAG,EAAE,CAAC;QACvD,OAAO,gMAAgM,CAAC;IAC1M,CAAC;IACD,OAAO,+IAA+I,CAAC;AACzJ,CAAC","sourcesContent":["/** Static advice only: never include credentials, response bodies or configured URLs. */\nexport function invalidResponseHint(status: number): string {\n if (status === 404 || status === 405) {\n return 'Check apiHost / TIER0_API_HOST: use this environment\\'s OpenAPI gateway base URL, not its platform webpage or MCP URL. Confirm that the gateway exposes /openapi/v2 routes; obtain the address from the environment deployment guide or administrator.';\n }\n if (status === 401) {\n return 'Check that apiHost / TIER0_API_HOST targets the intended OpenAPI gateway, then check that the API key is present, valid and belongs to that environment. An intermediary may also require authentication.';\n }\n if (status === 403) {\n return 'Check the credential\\'s permissions for this operation and any gateway access restrictions. A non-JSON response alone does not prove the API key is invalid.';\n }\n if (status === 502 || status === 503 || status === 504) {\n return 'The gateway or upstream service may be temporarily unavailable. Check service health; do not replace the API key based on this response. Before repeating a write, check whether it committed.';\n }\n return 'Check apiHost / TIER0_API_HOST and the gateway response format against the environment deployment guide; OpenAPI JSON responses are required.';\n}\n"]}
@@ -16,7 +16,7 @@ import type { UnsV2Error, UnsV2Execution, UnsV2Retry } from '../uns-v2/client.js
16
16
  export declare const ACCESS_REASONS: {
17
17
  /** 403: the collection exists, but this App's grant does not cover it or the operation. */
18
18
  readonly notGranted: "COLLECTION_NOT_GRANTED";
19
- /** 403 or 404: the collection is gone (hard-deleted or archived). */
19
+ /** 403 or 404: the collection is missing, or the write target is archived. */
20
20
  readonly notFound: "COLLECTION_NOT_FOUND";
21
21
  /** 403: the grant covers the operation, the App key lacks `data.missingPermission`. */
22
22
  readonly permissionMissing: "APP_PERMISSION_MISSING";