@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.
- package/CHANGELOG.md +6 -0
- package/README.md +6 -4
- package/dist/cjs/connection-diagnostics.d.ts +2 -0
- package/dist/cjs/connection-diagnostics.js +20 -0
- package/dist/cjs/connection-diagnostics.js.map +1 -0
- package/dist/cjs/data/error.d.ts +1 -1
- package/dist/cjs/data/error.js +2 -2
- package/dist/cjs/data/error.js.map +1 -1
- package/dist/cjs/openapi/client.js +3 -2
- package/dist/cjs/openapi/client.js.map +1 -1
- package/dist/cjs/uns-v2/client.js +3 -2
- package/dist/cjs/uns-v2/client.js.map +1 -1
- package/dist/esm/connection-diagnostics.d.ts +2 -0
- package/dist/esm/connection-diagnostics.js +17 -0
- package/dist/esm/connection-diagnostics.js.map +1 -0
- package/dist/esm/data/error.d.ts +1 -1
- package/dist/esm/data/error.js +2 -2
- package/dist/esm/data/error.js.map +1 -1
- package/dist/esm/openapi/client.js +3 -2
- package/dist/esm/openapi/client.js.map +1 -1
- package/dist/esm/uns-v2/client.js +3 -2
- package/dist/esm/uns-v2/client.js.map +1 -1
- package/package.json +1 -1
- package/skills/tier0-sdk-v2/SKILL.md +2 -0
- package/skills/tier0-sdk-v2/references/local-connection.md +61 -0
- package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/consistency.md +2 -2
- package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/errors.md +4 -2
- package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/modeling.md +3 -1
- package/skills/tier0-sdk-v2/tier0-sdk-v2-data/references/schema-evolution.md +2 -0
- package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/SKILL.md +1 -1
- package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/delete.md +25 -19
- package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/namespace.md +3 -3
- package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/read.md +7 -1
- package/skills/tier0-sdk-v2/tier0-sdk-v2-uns/references/restore.md +12 -13
package/dist/esm/data/error.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
export const ACCESS_REASONS = {
|
|
7
7
|
/** 403: the collection exists, but this App's grant does not cover it or the operation. */
|
|
8
8
|
notGranted: 'COLLECTION_NOT_GRANTED',
|
|
9
|
-
/** 403 or 404: the collection is
|
|
9
|
+
/** 403 or 404: the collection is missing, or the write target is archived. */
|
|
10
10
|
notFound: 'COLLECTION_NOT_FOUND',
|
|
11
11
|
/** 403: the grant covers the operation, the App key lacks `data.missingPermission`. */
|
|
12
12
|
permissionMissing: 'APP_PERMISSION_MISSING',
|
|
@@ -86,7 +86,7 @@ const CODE_HINTS = {
|
|
|
86
86
|
VERSION_CONFLICT: 'The record changed since it was read; reload it and retry with the new revision.',
|
|
87
87
|
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.",
|
|
88
88
|
INDEX_QUOTA_EXCEEDED: 'The workspace index quota (200, counting every index that physically exists) is exhausted. Remove unused indexes through the tier0 MCP.',
|
|
89
|
-
COLLECTION_TOO_LARGE: '
|
|
89
|
+
COLLECTION_TOO_LARGE: 'Legacy recordsArchivedAt restoration handles at most 2000 records; current collection archive / restore retains records without that limit.',
|
|
90
90
|
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.",
|
|
91
91
|
APP_NOT_READY: 'The platform is still preparing this App (e.g. right after an import); retry shortly.',
|
|
92
92
|
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":"AAWA;;;;GAIG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG;IAC5B,2FAA2F;IAC3F,UAAU,EAAE,wBAAwB;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,KAAK,IAAI,2DAA2D,CAAC;IACzI,CAAC;SAAM,IAAI,IAAI,EAAE,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":"AAWA;;;;GAIG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG;IAC5B,2FAA2F;IAC3F,UAAU,EAAE,wBAAwB;IACpC,8EAA8E;IAC9E,QAAQ,EAAE,sBAAsB;IAChC,uFAAuF;IACvF,iBAAiB,EAAE,wBAAwB;CACnC,CAAC;AAEX,MAAM,OAAO,SAAU,SAAQ,KAAK;IAClC,gEAAgE;IACvD,MAAM,CAAS;IACxB,kEAAkE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AM,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 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"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { getEnvVar } from '../runtime-env.js';
|
|
2
|
+
import { invalidResponseHint } from '../connection-diagnostics.js';
|
|
2
3
|
import { decodeUnsV2JSON, encodeUnsV2JSON } from '../uns-v2/codec.js';
|
|
3
4
|
export class ApiError extends Error {
|
|
4
5
|
status;
|
|
@@ -178,7 +179,7 @@ export class HttpClient {
|
|
|
178
179
|
}
|
|
179
180
|
catch {
|
|
180
181
|
if (!response.ok)
|
|
181
|
-
throw new ApiError(response.status, 0,
|
|
182
|
+
throw new ApiError(response.status, 0, `Non-JSON API error. ${invalidResponseHint(response.status)}`);
|
|
182
183
|
throw new TransportError('PROTOCOL', !operation.readonly, response.status);
|
|
183
184
|
}
|
|
184
185
|
if (!response.ok)
|
|
@@ -201,7 +202,7 @@ export class HttpClient {
|
|
|
201
202
|
value = decodeUnsV2JSON(response.text, 'V1_Empty');
|
|
202
203
|
}
|
|
203
204
|
catch {
|
|
204
|
-
throw new ApiError(response.status, 0,
|
|
205
|
+
throw new ApiError(response.status, 0, `Invalid API response. ${invalidResponseHint(response.status)}`);
|
|
205
206
|
}
|
|
206
207
|
if (!response.ok || (record(value) && typeof value.code === 'number' && value.code !== 200))
|
|
207
208
|
throw responseError(response.status, value);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/openapi/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAyBtE,MAAM,OAAO,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;AACD,MAAM,OAAO,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;QA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IAAI,UAAU,EAAE,CAAC;AACrC,MAAM,UAAU,eAAe,CAAC,MAAoB,IAAU,aAAa,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACvG,MAAM,UAAU,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":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAyBtE,MAAM,OAAO,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,C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O,KAAU,CAAC;IACpB,CAAC;IACD,GAAG,CAAI,IAAY,EAAE,OAAwB,IAAgB,OAAO,IAAI,CAAC,GAAG,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;AAED,yFAAyF;AACzF,IAAI,aAAa,GAAG,IAAI,UAAU,EAAE,CAAC;AACrC,MAAM,UAAU,eAAe,CAAC,MAAoB,IAAU,aAAa,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACvG,MAAM,UAAU,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"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { CloudTransport, CloudTransportError, UNS_V2_MAX_REQUEST_BYTES, } from '../cloud-transport.js';
|
|
2
2
|
import { getClient } from '../openapi/client.js';
|
|
3
|
+
import { invalidResponseHint } from '../connection-diagnostics.js';
|
|
3
4
|
import { decodeUnsV2JSON, encodeUnsV2JSON } from './codec.js';
|
|
4
5
|
import { parseServerSentEvents, ServerSentEventsError } from './sse.js';
|
|
5
6
|
import { UNS_V2_OPERATIONS, UNS_V2_STREAM_OPERATIONS, } from './generated.js';
|
|
@@ -205,7 +206,7 @@ export class UnsV2ClientCore {
|
|
|
205
206
|
value = decodeUnsV2JSON(response.text, response.status === 200 ? operation.response : 'UnsV2ErrorResponse');
|
|
206
207
|
}
|
|
207
208
|
catch {
|
|
208
|
-
throw invalid(
|
|
209
|
+
throw invalid(`Invalid UNS v2 response. ${invalidResponseHint(response.status)}`, false);
|
|
209
210
|
}
|
|
210
211
|
if (response.status !== 200) {
|
|
211
212
|
const info = errorInfo(value, response.status, name);
|
|
@@ -263,7 +264,7 @@ export class UnsV2ClientCore {
|
|
|
263
264
|
}
|
|
264
265
|
if ('text' in opened) {
|
|
265
266
|
const unavailable = opened.status === 502 || opened.status === 503 || opened.status === 504;
|
|
266
|
-
const invalid = (enveloped) => localError(
|
|
267
|
+
const invalid = (enveloped) => localError(`Invalid UNS v2 event stream response. ${invalidResponseHint(opened.status)}`, name, false, 'UNS_V2_PROTOCOL_ERROR', opened.status, unavailable, {
|
|
267
268
|
notStarted: !enveloped && rejectedBeforeUns(opened.status),
|
|
268
269
|
});
|
|
269
270
|
let value;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/uns-v2/client.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,wBAAwB,GAEzB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,SAAS,EAAwC,MAAM,sBAAsB,CAAC;AACvF,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC9D,OAAO,EAAE,qBAAqB,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AACxE,OAAO,EACL,iBAAiB,EACjB,wBAAwB,GAOzB,MAAM,gBAAgB,CAAC;AASxB,MAAM,CAAC,MAAM,iBAAiB,GAA8B,CAAC,YAAY,EAAE,YAAY,EAAE,WAAW,EAAE,SA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,MAAM,CAAC,CAAC;IACxD,MAAM,OAAO,GAAG,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,iBAAiB,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;AAC3F,MAAM,CAAC,MAAM,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":"AAAA,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,wBAAwB,GAEzB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,SAAS,EAAwC,MAAM,sBAAsB,CAAC;AACvF,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC9D,OAAO,EAAE,qBAAqB,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AACxE,OAAO,EACL,iBAAiB,EACjB,wBAAwB,GAOzB,MAAM,gBAAgB,CAAC;AASxB,MAAM,CAAC,MAAM,iBAAiB,GAA8B,CAAC,YAAY,EAAE,YAAY,EAAE,WAAW,EAAE,SAAS,CAAC,CAAC;AA4BjH;;;;;GAKG;AACH,MAAM,OAAO,UAAW,SAAQ,KAAK;IAC1B,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,aAAa,EAAE,MAAM,CAAC,CAAC;IACxD,MAAM,OAAO,GAAG,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,iBAAiB,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;AAC3F,MAAM,CAAC,MAAM,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"]}
|
package/package.json
CHANGED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# 本地连接与排错
|
|
2
|
+
|
|
3
|
+
个人 Key 可用于本地脚本、数据分析和调试。SDK 与 MCP 是两种调用入口;MCP 已连接不代表本地 SDK 已配置地址或凭证。读取已有普通 collection 不要求创建或部署平台 App,也不需要 App ID。实际访问范围由个人 Key 及其所属用户的权限决定。
|
|
4
|
+
|
|
5
|
+
## 确定 API 地址
|
|
6
|
+
|
|
7
|
+
`apiHost` / `TIER0_API_HOST` 填写当前环境的 **OpenAPI 网关基础地址**,不附加 `/openapi/v2`、页面路径或 Workspace ID;SDK 自动添加接口路径。平台网页地址、MCP 地址与网关地址不能互换。
|
|
8
|
+
|
|
9
|
+
| 已知平台环境 | OpenAPI 网关基础地址 |
|
|
10
|
+
| --- | --- |
|
|
11
|
+
| 阿里云 ACK 开发环境 `https://dev.tier0.cn` | `https://api-dev.tier0.cn` |
|
|
12
|
+
|
|
13
|
+
其他环境或私有化部署:从该环境的部署/接入指南取得 OpenAPI 公网入口;若指南未提供,向环境管理员确认“对本机可达、暴露 `/openapi/v2` 的网关基础地址”。不要靠网页域名拼接或猜测地址。若没有对外暴露网关,需由管理员提供入口或网络接入方式,SDK 无法补齐部署。
|
|
14
|
+
|
|
15
|
+
私有化地址通过 `apiHost` 或环境变量显式配置,支持已有的基础路径前缀。本地 HTTP 网关需写明 `http://`,裸域名默认 HTTPS。SDK 不从 Key 推断地址,不探测候选域名、不自动切换 Host,也不跟随 API 重定向传递密钥。
|
|
16
|
+
|
|
17
|
+
## 个人 Key 读取已有集合
|
|
18
|
+
|
|
19
|
+
安装 SDK,使用 Node.js 20.19+。在本机创建 `.env.local`,将它加入 `.gitignore`,填入已经确认的网关、个人 Key 和 collection ID。密钥只留在本地受控配置或服务端,不写进代码、浏览器变量、日志或提交记录。
|
|
20
|
+
|
|
21
|
+
```dotenv
|
|
22
|
+
TIER0_API_HOST=https://api-dev.tier0.cn
|
|
23
|
+
TIER0_API_KEY=填入该环境的个人Key
|
|
24
|
+
TIER0_COLLECTION_ID=填入已有collection的ID
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
将以下代码保存为 `read-records.mjs`,按已知集合 ID 直接读取。
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
import { createClient } from '@tier0/sdk-v2';
|
|
31
|
+
|
|
32
|
+
const collectionId = process.env.TIER0_COLLECTION_ID;
|
|
33
|
+
if (!collectionId) throw new Error('请设置 TIER0_COLLECTION_ID');
|
|
34
|
+
const client = createClient();
|
|
35
|
+
const result = await client.uns.recordFind({ collectionId, limit: 20 });
|
|
36
|
+
console.dir(result.data, { depth: null });
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
node --env-file=.env.local read-records.mjs
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
示例只读第一页,后续按 `pageInfo` 分页;不会创建集合、修改 Schema 或写入种子数据。collection 由 MCP、页面或其他应用创建不影响此调用方式,知道 ID 不代表取得权限。长期团队应用使用独立 App 身份,避免依赖某个员工的个人 Key。
|
|
44
|
+
|
|
45
|
+
个人 Key 也可通过数据层的 `data.collection({ collectionId })` 引用已有集合、跳过 ensure(见[已有集合用法](../tier0-sdk-v2-data/references/modeling.md));`defineCollection` 声明集合的自动 ensure 需要平台签发的 App Key。
|
|
46
|
+
|
|
47
|
+
## 按响应排错
|
|
48
|
+
|
|
49
|
+
| 响应或错误 | 下一步 |
|
|
50
|
+
| --- | --- |
|
|
51
|
+
| HTML / 非 JSON 404、405 | 核对网关基础地址及 `/openapi/v2` 路由;不要先更换 Key。网页域名可能只提供前端页面。 |
|
|
52
|
+
| 401 | 先确认目标网关,再检查 Key 是否提供、是否有效、是否属于该环境;网关前的代理也可能要求认证。 |
|
|
53
|
+
| 403 | 检查当前凭证的资源/操作权限与网关访问限制;不等同于 Key 无效。 |
|
|
54
|
+
| 502、503、504 | 检查网关和上游服务健康;重发写入前确认执行结果,避免重复写入。 |
|
|
55
|
+
| 200 但返回 HTML / `SDK_PROTOCOL` | 核对网关地址、代理转发及响应格式;页面可打开不代表 OpenAPI 可用。 |
|
|
56
|
+
| 网络错误或超时 | 检查 DNS、网络接入、TLS 和服务连通性;不能仅据此判断凭证无效。 |
|
|
57
|
+
| 正常 JSON 业务错误 | 按服务端错误码、权限信息和请求 ID 排查;JSON 404 也可能表示业务资源不存在。 |
|
|
58
|
+
|
|
59
|
+
身份或 Workspace 不明确时,可单独调用 `client.system.whoami()` 核对返回的 `workspaceID`;它不是读取记录的前置步骤。无密钥请求返回 401 只证明已到达认证入口,不能证明某个 Key 有权读取目标集合。
|
|
60
|
+
|
|
61
|
+
错误提示不回显 Key、配置 URL 或原始 HTML;SDK 保留原有错误类型、HTTP 状态和执行/重试语义,不自动更换凭证或重试。
|
|
@@ -63,8 +63,8 @@ export function servingEmployee(): boolean {
|
|
|
63
63
|
|
|
64
64
|
## 首次访问与自愈
|
|
65
65
|
|
|
66
|
-
|
|
66
|
+
进程内第一次访问声明集合时一次性 ensure 全部声明:缺失的集合会被创建(随后写入种子),更宽的声明会放宽存储,存储永远不会被收窄。ensure 失败不缓存,下一次请求会重试(刚导入的 App 可能短暂返回 `APP_NOT_READY`,数据层先自动重试,仍失败时按 503 回答)。已有 ID 引用 `data.collection({ collectionId })` 跳过 ensure,可按原授权[读取回收集合历史](../../tier0-sdk-v2-uns/references/read.md#回收集合的历史读取)。
|
|
67
67
|
|
|
68
|
-
|
|
68
|
+
声明集合的调用被 `COLLECTION_NOT_FOUND` 或 `COLLECTION_NOT_GRANTED` 拒绝时,数据层重新 ensure(重建并重新写入种子),并在集合 ID 确实变化时把该调用重试一次。每个 client 每 30 秒最多重建一次;已有 ID 引用不触发重建。历史读取成功、`APP_GRANT_REVOKED` 或 `OWNER_APP_TRASHED` 均不触发自愈。延续旧集合游标的分页、`updateMany` / `deleteMany` 的续写直接失败,不会重试。
|
|
69
69
|
|
|
70
70
|
Preview(`environment: 'preview'`,`NODE_ENV` 不是 production 时的默认值)下,Schema 冲突或 ensure 警告会让请求失败并带上详情;部署环境只记录日志、继续服务。`ignored` 提示从不让请求失败:存储比声明更宽的部分记为 info,`ANNOTATION_NOT_APPLIED`(ensure 不会改写的描述)记为指向 `schema:replace` 的 warning。
|
|
@@ -80,7 +80,9 @@ export function toResponse(error: unknown): Response {
|
|
|
80
80
|
| `APP_GRANT_REVOKED` (403) | 管理员撤销了本 App 对集合的授权;ensure 不会自动恢复,请管理员处理 |
|
|
81
81
|
| `APP_QUOTA_EXCEEDED` (409) | `data.resource` 指出触达的每 App 上限(64):`collections` → 归档不用的集合;`indexes` → 从声明删索引并 `schema:replace`;`archivedCollections` → 恢复一个或请管理员清理 |
|
|
82
82
|
| `INDEX_QUOTA_EXCEEDED` (409) | Workspace 实际存在的索引已达 200;删除不用的索引 |
|
|
83
|
-
| `COLLECTION_TOO_LARGE` (409) |
|
|
83
|
+
| `COLLECTION_TOO_LARGE` (409) | 仅旧 recordsArchivedAt 墓碑恢复有 2000 条上限(`data.maxRecords`);当前 archive / restore 保留记录,不受该上限限制 |
|
|
84
|
+
| `OWNER_APP_TRASHED`(`data.reason`) | 所属 App 在回收站;恢复 App 后再写入,不触发自动重建 |
|
|
85
|
+
| `DIRECTORY_IN_TRASH`(`data.reason`) | 子项随目录回收,需恢复原目录;不逐个恢复子项 |
|
|
84
86
|
| `FORBIDDEN` (403) | Key 不能做该操作(其他 App 或共享集合),或 Key 已吊销 |
|
|
85
87
|
|
|
86
|
-
记录调用上的 `data.reason`:`COLLECTION_NOT_GRANTED`(403,授权不覆盖该集合或操作)与 `COLLECTION_NOT_FOUND`(403/404
|
|
88
|
+
记录调用上的 `data.reason`:`COLLECTION_NOT_GRANTED`(403,授权不覆盖该集合或操作)与 `COLLECTION_NOT_FOUND`(403/404,集合不存在或写入目标已回收)仅对声明集合触发[自愈](consistency.md#首次访问与自愈),已有 ID 引用直接报告错误;回收不使已有授权的历史读取失效。`APP_PERMISSION_MISSING`(403,`data.missingPermission`)表示 Key 缺少权限,例如删除记录需要 `uns.delete`——业务记录通常以状态结束(`CANCELLED`、`ARCHIVED`)而不是删除。
|
|
@@ -150,9 +150,11 @@ export const loginCodes = defineCollection({
|
|
|
150
150
|
|
|
151
151
|
- 字段声明为 `z.number().int()`,存 Unix 毫秒(通常是 `Date.now()`);记录在该时刻再过 `expireAfterSeconds`(60–31536000 秒)后被删除。删除有分钟级延迟,读取时仍要自己比较时间。
|
|
152
152
|
- 每个集合最多 1 个 TTL 索引,只能是单个 `path`、不能 `unique`。缺这个字段的记录不会过期。
|
|
153
|
-
- 过期删除是**物理删除**,不能 restore
|
|
153
|
+
- 过期删除是**物理删除**,不能 restore;集合有效时,软删除的记录同样按 TTL 清理,集合回收后停止 TTL 清理。
|
|
154
154
|
- ensure 只能新增 TTL 或把时间加长;缩短或去掉要通过 tier0 MCP 的 `schema:replace`。
|
|
155
155
|
|
|
156
|
+
集合软删除和 App 回收保留查询索引,物理索引仍占配额;归档不释放索引空间,见[回收规则](../../tier0-sdk-v2-uns/references/delete.md#回收规则)。
|
|
157
|
+
|
|
156
158
|
## 种子数据
|
|
157
159
|
|
|
158
160
|
种子是基线记录:固定 `_id`,各生命周期状态自洽,相互引用用这些 ID;每个集合最多 1000 条。只在 ensure 报告集合为 `created` 时写入一次(每 200 条一个原子分块,分块带固定幂等键,重试安全);修改 `seed` 不会改动已存在的集合。不要在服务启动或列表为空时从代码插入基线数据。构建期可以对每条种子调用 `validateDocument(definition, document)` 校验。
|
|
@@ -38,4 +38,6 @@ export function replaceBody(expectedRevision: number) {
|
|
|
38
38
|
|
|
39
39
|
Schema 中 `ignored`、`warnings`、`conflicts`、`violations` 的路径用 `.` 连接属性,用 `[]` 表示数组元素(`lines.[].qty`)。
|
|
40
40
|
|
|
41
|
+
集合 archive 的数据与授权变化见[回收规则](../../tier0-sdk-v2-uns/references/delete.md#回收规则),restore 的范围与授权区别见[恢复](../../tier0-sdk-v2-uns/references/restore.md)。
|
|
42
|
+
|
|
41
43
|
新声明的 number/integer 默认带 double/int32 格式;ensure 不改写已有字段注解,原无格式字段仍保持 legacy 显示。已有字段格式迁移需读取并保留完整 Schema,先通过 schema:replace dryRun 检查,再按明确迁移授权执行。
|
|
@@ -46,7 +46,7 @@ export async function readAppRecords(collectionId: string) {
|
|
|
46
46
|
1. 记录行是 id/data/revision;filter 与 update 的业务路径用 name、customer.name,不加 data.;系统路径用 _id、_meta.revision。
|
|
47
47
|
2. 改/删使用最近写回执或读取取得的 revision 作为 expectedRevision;创建时可用 returnDocument:'after' 取得快照。历史重放不是当前最新版本,冲突时显式处理;不同操作使用独立意图键,长度上限以当前操作契约为准。
|
|
48
48
|
3. metadataUpdateOne 的 $set.recordSchema 替换完整 Schema,不迁移已有记录;未更新的 sampleSchema/indexes 保留。先预检兼容性。
|
|
49
|
-
4. metadataDeleteOne/Many
|
|
49
|
+
4. metadataDeleteOne/Many 软删除保留数据与索引,历史按既有授权只读;目录原子回收有效子树,恢复只覆盖同次批次,详见[回收规则](references/delete.md#回收规则)。metadataPurge 永久清理明确 ID 的回收站集合,accepted 只表示任务已受理,须用 jobs 查询逐项结果。Record 删除会物理删除关联 Sample,恢复 Record 不会恢复这些 Sample。
|
|
50
50
|
5. recordFind 使用 pageInfo.hasMore/nextCursor,limit 1–200;sort 为 [['field',1]]。单页不是全量,跨页不是稳定快照。
|
|
51
51
|
6. Sample 的时间是 Unix 毫秒,查询范围 [from,to)。Record 代表业务实体,不用覆盖它来保存历史。
|
|
52
52
|
|