@hol-org/cigar 0.9.4
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/LICENSE +201 -0
- package/NOTICE +5 -0
- package/README.md +68 -0
- package/dist/client.d.ts +16 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +839 -0
- package/dist/client.js.map +1 -0
- package/dist/digest.d.ts +21 -0
- package/dist/digest.d.ts.map +1 -0
- package/dist/digest.js +406 -0
- package/dist/digest.js.map +1 -0
- package/dist/errors.d.ts +35 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +54 -0
- package/dist/errors.js.map +1 -0
- package/dist/examples/quickstart.d.ts +2 -0
- package/dist/examples/quickstart.d.ts.map +1 -0
- package/dist/examples/quickstart.js +32 -0
- package/dist/examples/quickstart.js.map +1 -0
- package/dist/examples/two-agent-observer.d.ts +9 -0
- package/dist/examples/two-agent-observer.d.ts.map +1 -0
- package/dist/examples/two-agent-observer.js +59 -0
- package/dist/examples/two-agent-observer.js.map +1 -0
- package/dist/examples/verify-shared-bundle.d.ts +2 -0
- package/dist/examples/verify-shared-bundle.d.ts.map +1 -0
- package/dist/examples/verify-shared-bundle.js +13 -0
- package/dist/examples/verify-shared-bundle.js.map +1 -0
- package/dist/generated/cigar_service_pb.d.ts +642 -0
- package/dist/generated/cigar_service_pb.d.ts.map +1 -0
- package/dist/generated/cigar_service_pb.js +55 -0
- package/dist/generated/cigar_service_pb.js.map +1 -0
- package/dist/generated/context_abi_pb.d.ts +3429 -0
- package/dist/generated/context_abi_pb.d.ts.map +1 -0
- package/dist/generated/context_abi_pb.js +1386 -0
- package/dist/generated/context_abi_pb.js.map +1 -0
- package/dist/generated/errors.d.ts +242 -0
- package/dist/generated/errors.d.ts.map +1 -0
- package/dist/generated/errors.js +38 -0
- package/dist/generated/errors.js.map +1 -0
- package/dist/generated/generated/error_codes_pb.d.ts +188 -0
- package/dist/generated/generated/error_codes_pb.d.ts.map +1 -0
- package/dist/generated/generated/error_codes_pb.js +191 -0
- package/dist/generated/generated/error_codes_pb.js.map +1 -0
- package/dist/generated/models.d.ts +472 -0
- package/dist/generated/models.d.ts.map +1 -0
- package/dist/generated/models.js +314 -0
- package/dist/generated/models.js.map +1 -0
- package/dist/generated/operations.d.ts +912 -0
- package/dist/generated/operations.d.ts.map +1 -0
- package/dist/generated/operations.js +50 -0
- package/dist/generated/operations.js.map +1 -0
- package/dist/idempotency.d.ts +3 -0
- package/dist/idempotency.d.ts.map +1 -0
- package/dist/idempotency.js +16 -0
- package/dist/idempotency.js.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +13 -0
- package/dist/index.js.map +1 -0
- package/dist/release.json +6 -0
- package/dist/types.d.ts +115 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/dist/verify-replay.d.ts +3 -0
- package/dist/verify-replay.d.ts.map +1 -0
- package/dist/verify-replay.js +391 -0
- package/dist/verify-replay.js.map +1 -0
- package/dist/verify-vectors.d.ts +3 -0
- package/dist/verify-vectors.d.ts.map +1 -0
- package/dist/verify-vectors.js +383 -0
- package/dist/verify-vectors.js.map +1 -0
- package/dist/workflow-session.d.ts +93 -0
- package/dist/workflow-session.d.ts.map +1 -0
- package/dist/workflow-session.js +550 -0
- package/dist/workflow-session.js.map +1 -0
- package/fixtures/semantic-bundle-v1.json +13 -0
- package/package.json +60 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,IAAI,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAE3D,OAAO,EACL,aAAa,EACb,iBAAiB,EACjB,kBAAkB,EAClB,cAAc,EACd,eAAe,EACf,WAAW,GAEZ,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,UAAU,EAA8C,MAAM,2BAA2B,CAAC;AAC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AO,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,CAAC,QAAQ,EAAE,WAAW,EAAE,eAAe,CAAC,MAAM,CAAC,YAAY,EAAE,eAAe,CAAC,EAAE,CAAC;IACvH,CAAC;CACF;AAID,SAAS,YAAY,CAAC,IAAY;IAChC,MAAM,SAAS,GAAI,MAA6C,CAAC,IAAI,CAAC,CAAC;IACvE,IAAI,OAAO,SAAS,KAAK,QAAQ,IAAI,SAAS,KAAK,IAAI,IAAI,CAAC,CAAC,QAAQ,IAAI,SAAS,CAAC,EAAE,CAAC;QACpF,MAAM,IAAI,KAAK,CAAC,2BAA2B,IAAI,aAAa,CAAC,CAAC;IAChE,CAAC;IACD,OAAO,SAAkC,CAAC;AAC5C,CAAC;AAED,KAAK,MAAM,WAAW,IAAI,MAAM,CAAC,IAAI,CAAC,UAAU,CAAkB,EAAE,CAAC;IACnE,MAAM,CAAC,cAAc,CAAC,WAAW,CAAC,SAAS,EAAE,WAAW,EAAE;QACxD,YAAY,EAAE,KAAK;QACnB,UAAU,EAAE,KAAK;QACjB,KAAK,CAEH,OAAuC,EACvC,OAAqB;YAErB,OAAO,UAAU,CAAC,WAAW,CAAC,CAAC,MAAM;gBACnC,CAAC,CAAC,IAAI,CAAC,oBAAoB,CAAC,WAAW,EAAE,OAAO,EAAE,YAAY,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC,SAAS,IAAI,EAAE,CAAC,EAAE,OAAO,CAAC;gBACjH,CAAC,CAAC,IAAI,CAAC,oBAAoB,CAAC,WAAW,EAAE,OAAO,EAAE,YAAY,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC,YAAY,CAAC,EAAE,OAAO,CAAC,CAAC;QACnH,CAAC;QACD,QAAQ,EAAE,KAAK;KAChB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { setTimeout as delay } from \"node:timers/promises\";\n\nimport {\n CigarApiError,\n CigarTimeoutError,\n CompatibilityError,\n TransportError,\n ValidationError,\n isRetryable,\n type ProblemDetails,\n} from \"./errors.js\";\nimport { OPERATIONS, type GeneratedOperations, type OperationId } from \"./generated/operations.js\";\nimport { ERROR_CATALOG, type ErrorCode } from \"./generated/errors.js\";\nimport * as models from \"./generated/models.js\";\nimport { validateIdempotencyKey } from \"./idempotency.js\";\nimport { decodeOperationPayload, encodeOperationPayload } from \"./digest.js\";\nimport type {\n CallOptions,\n ClientOptions,\n Compatibility,\n EventStream,\n OperationEvent,\n OperationRequest,\n OperationResponse,\n PathParameter,\n TypedEventStream,\n TypedOperationEvent,\n TypedOperationRequest,\n TypedOperationResponse,\n} from \"./types.js\";\nimport type { PayloadModel } from \"./generated/models.js\";\n\nconst MAX_PAYLOAD_BYTES = 16 * 1024 * 1024;\nconst MAX_EVENT_BYTES = 1024 * 1024;\nconst MAX_PROBLEM_BYTES = 64 * 1024;\nconst MAX_TIMEOUT_MS = 300_000;\nconst MAX_CURSOR_BYTES = 4096;\nconst PATH_NAME = /^[a-z][a-z0-9_]{0,63}$/u;\nconst PATH_VALUE = /^[A-Za-z0-9._~-]{1,256}$/u;\n\nfunction exactBase64url(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString(\"base64url\");\n}\n\nfunction decodeBase64url(value: unknown, maximum: number): Uint8Array {\n if (typeof value !== \"string\" || !/^[A-Za-z0-9_-]*$/u.test(value)) {\n throw new TransportError(\"server returned invalid base64url payload\");\n }\n const decoded = Buffer.from(value, \"base64url\");\n if (decoded.length > maximum || decoded.toString(\"base64url\") !== value) {\n throw new TransportError(\"server returned non-canonical or oversized payload\");\n }\n return Uint8Array.from(decoded);\n}\n\nfunction boundedText(value: unknown, maximum: number, field: string, required = false): string | undefined {\n if (value === undefined && !required) return undefined;\n if (typeof value !== \"string\" || (required && value.length === 0) || Buffer.byteLength(value) > maximum) {\n throw new TransportError(`server returned invalid ${field}`);\n }\n return value;\n}\n\nfunction parseResponse(operationId: OperationId, value: unknown, maximum = MAX_PAYLOAD_BYTES): OperationResponse {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TransportError(\"server returned a non-object response\");\n }\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record).sort().join(\",\");\n const allowed = [\"next_page_cursor\", \"operation_id\", \"payload_cbor\", \"semantic_etag\"];\n if (Object.keys(record).some((key) => !allowed.includes(key))) {\n throw new TransportError(`server returned unknown response fields: ${keys}`);\n }\n if (record.operation_id !== operationId) throw new TransportError(\"server operation identity mismatch\");\n const semanticEtag = boundedText(record.semantic_etag, 256, \"semantic_etag\");\n const nextPageCursor = boundedText(record.next_page_cursor, MAX_CURSOR_BYTES, \"next_page_cursor\");\n return {\n operationId,\n payloadCbor: decodeBase64url(record.payload_cbor, maximum),\n ...(semanticEtag === undefined ? {} : { semanticEtag }),\n ...(nextPageCursor === undefined ? {} : { nextPageCursor }),\n };\n}\n\nasync function boundedBytes(response: Response, maximum: number, field: string): Promise<Uint8Array> {\n const declared = response.headers.get(\"content-length\");\n if (declared !== null && (!/^(?:0|[1-9][0-9]*)$/u.test(declared) || Number(declared) > maximum)) {\n throw new TransportError(`${field} content length exceeds its bound`);\n }\n if (response.body === null) return new Uint8Array();\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.length;\n if (total > maximum) {\n await reader.cancel();\n throw new TransportError(`${field} exceeds its bound`);\n }\n chunks.push(value);\n }\n const result = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.length;\n }\n return result;\n}\n\nfunction parseJson(bytes: Uint8Array, field: string): unknown {\n try {\n const source = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n assertUniqueJsonKeys(source);\n return JSON.parse(source);\n } catch (cause) {\n throw new TransportError(`${field} is not valid UTF-8 JSON`, { cause });\n }\n}\n\nfunction assertUniqueJsonKeys(source: string): void {\n let position = 0;\n let nodes = 0;\n const whitespace = /[\\u0009\\u000a\\u000d\\u0020]/u;\n const skipWhitespace = (): void => {\n while (position < source.length && whitespace.test(source[position] ?? \"\")) position += 1;\n };\n const stringToken = (): string => {\n if (source[position] !== '\"') throw new Error(\"expected JSON string\");\n const start = position;\n position += 1;\n for (;;) {\n const character = source[position];\n if (character === undefined || character.charCodeAt(0) < 0x20) throw new Error(\"invalid JSON string\");\n position += 1;\n if (character === '\"') return JSON.parse(source.slice(start, position)) as string;\n if (character !== \"\\\\\") continue;\n const escape = source[position];\n if (escape === undefined || !'\"\\\\/bfnrtu'.includes(escape)) throw new Error(\"invalid JSON escape\");\n position += 1;\n if (escape === \"u\") {\n const scalar = source.slice(position, position + 4);\n if (!/^[0-9a-fA-F]{4}$/u.test(scalar)) throw new Error(\"invalid JSON Unicode escape\");\n position += 4;\n }\n }\n };\n const value = (depth: number): void => {\n nodes += 1;\n if (depth > 64 || nodes > 100_000) throw new Error(\"JSON exceeds nesting or node bounds\");\n skipWhitespace();\n const initial = source[position];\n if (initial === '\"') {\n stringToken();\n return;\n }\n if (initial === \"{\") {\n position += 1;\n skipWhitespace();\n const keys = new Set<string>();\n if (source[position] === \"}\") {\n position += 1;\n return;\n }\n for (;;) {\n skipWhitespace();\n const key = stringToken();\n if (keys.has(key)) throw new Error(\"JSON object contains a duplicate key\");\n keys.add(key);\n skipWhitespace();\n if (source[position] !== \":\") throw new Error(\"JSON object lacks a colon\");\n position += 1;\n value(depth + 1);\n skipWhitespace();\n if (source[position] === \"}\") {\n position += 1;\n return;\n }\n if (source[position] !== \",\") throw new Error(\"JSON object lacks a separator\");\n position += 1;\n }\n }\n if (initial === \"[\") {\n position += 1;\n skipWhitespace();\n if (source[position] === \"]\") {\n position += 1;\n return;\n }\n for (;;) {\n value(depth + 1);\n skipWhitespace();\n if (source[position] === \"]\") {\n position += 1;\n return;\n }\n if (source[position] !== \",\") throw new Error(\"JSON array lacks a separator\");\n position += 1;\n }\n }\n const start = position;\n while (position < source.length && !/[\\u0009\\u000a\\u000d\\u0020,\\]}]/u.test(source[position] ?? \"\")) position += 1;\n if (position === start) throw new Error(\"JSON value is missing\");\n JSON.parse(source.slice(start, position));\n };\n value(0);\n skipWhitespace();\n if (position !== source.length) throw new Error(\"JSON contains trailing data\");\n}\n\nasync function problem(response: Response): Promise<CigarApiError> {\n const contentType = response.headers.get(\"content-type\")?.split(\";\", 1)[0]?.trim();\n if (contentType !== \"application/problem+json\") {\n throw new TransportError(`HTTP ${response.status} did not use application/problem+json`);\n }\n const value = parseJson(\n await boundedBytes(response, MAX_PROBLEM_BYTES, `HTTP ${response.status} problem`),\n `HTTP ${response.status} problem`,\n );\n return decodeProblem(response.status, value);\n}\n\nfunction decodeProblem(status: number, value: unknown): CigarApiError {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TransportError(`HTTP ${status} contained an invalid CIGAR problem`);\n }\n const candidate = value as Record<string, unknown>;\n const expected = [\"code\", \"correlation_id\", \"details\", \"http_status\", \"message\", \"remediation\", \"retry\", \"schema_version\"].sort();\n const actual = Object.keys(candidate).sort();\n if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) {\n throw new TransportError(`HTTP ${status} contained unknown or missing problem fields`);\n }\n if (candidate.schema_version !== \"cigar.problem.v1\" || typeof candidate.code !== \"string\" || !(candidate.code in ERROR_CATALOG)) {\n throw new TransportError(`HTTP ${status} contained an unsupported CIGAR problem`);\n }\n const code = candidate.code as ErrorCode;\n const definition = ERROR_CATALOG[code];\n if (candidate.http_status !== status || candidate.http_status !== definition.httpStatus || candidate.retry !== definition.retry) {\n throw new TransportError(`HTTP ${status} problem disagrees with the frozen error catalog`);\n }\n if (\n typeof candidate.message !== \"string\" || candidate.message.length === 0 || Buffer.byteLength(candidate.message) > 4096\n || typeof candidate.remediation !== \"string\" || candidate.remediation.length === 0 || Buffer.byteLength(candidate.remediation) > 4096\n || typeof candidate.correlation_id !== \"string\"\n || !/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u.test(candidate.correlation_id)\n || typeof candidate.details !== \"object\" || candidate.details === null || Array.isArray(candidate.details)\n || Object.keys(candidate.details).length > 256\n ) {\n throw new TransportError(`HTTP ${status} contained an invalid bounded CIGAR problem`);\n }\n return new CigarApiError(status, candidate as unknown as ProblemDetails);\n}\n\nfunction validateTimeout(value: number): number {\n if (!Number.isInteger(value) || value < 1 || value > MAX_TIMEOUT_MS) {\n throw new ValidationError(`timeout must be an integer in 1..${MAX_TIMEOUT_MS} milliseconds`);\n }\n return value;\n}\n\nconst AMBIENT_PROXY_ENVIRONMENT = [\n \"ALL_PROXY\",\n \"HTTPS_PROXY\",\n \"HTTP_PROXY\",\n \"NODE_USE_ENV_PROXY\",\n \"all_proxy\",\n \"https_proxy\",\n \"http_proxy\",\n] as const;\n\nfunction ambientProxyConfigured(): boolean {\n const runtime = globalThis as typeof globalThis & {\n process?: { env?: Readonly<Record<string, string | undefined>> };\n };\n const environment = runtime.process?.env;\n return environment !== undefined && AMBIENT_PROXY_ENVIRONMENT.some((name) => {\n const value = environment[name];\n return value !== undefined && value.trim() !== \"\" && value.trim() !== \"0\";\n });\n}\n\nfunction pathParameters(parameters: readonly PathParameter[] | undefined): readonly PathParameter[] {\n const sorted = [...(parameters ?? [])].sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);\n if (sorted.length > 8) throw new ValidationError(\"at most eight path parameters are allowed\");\n for (let index = 0; index < sorted.length; index += 1) {\n const item = sorted[index];\n if (item === undefined || !PATH_NAME.test(item.name) || !PATH_VALUE.test(item.value)) {\n throw new ValidationError(\"path parameters must use the frozen name/value alphabets\");\n }\n if (index > 0 && sorted[index - 1]?.name === item.name) {\n throw new ValidationError(\"path parameter names must be unique\");\n }\n }\n return sorted;\n}\n\nfunction bindPath(template: string, parameters: readonly PathParameter[]): string {\n const expected = [...template.matchAll(/\\{([a-z][a-z0-9_]*)\\}/gu)].map((match) => match[1]);\n if (expected.length !== parameters.length || expected.some((name) => !parameters.some((item) => item.name === name))) {\n throw new ValidationError(\"request path parameters do not exactly match the operation path\");\n }\n return parameters.reduce((path, item) => path.replace(`{${item.name}}`, item.value), template);\n}\n\nclass HttpEventStream implements EventStream {\n #closed = false;\n #lastEventId?: string;\n readonly #controller = new AbortController();\n readonly #iterate: () => AsyncGenerator<OperationEvent>;\n #iterator?: AsyncGenerator<OperationEvent>;\n\n constructor(iterate: () => AsyncGenerator<OperationEvent>) {\n this.#iterate = iterate;\n }\n\n get lastEventId(): string | undefined {\n return this.#lastEventId;\n }\n\n remember(eventId: string): void {\n this.#lastEventId = eventId;\n }\n\n get closed(): boolean {\n return this.#closed;\n }\n\n get signal(): AbortSignal {\n return this.#controller.signal;\n }\n\n close(): void {\n if (this.#closed) return;\n this.#closed = true;\n this.#controller.abort(new DOMException(\"CIGAR event stream closed\", \"AbortError\"));\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n this.close();\n }\n\n [Symbol.asyncIterator](): AsyncIterator<OperationEvent> {\n this.#iterator ??= this.#iterate();\n return this.#iterator;\n }\n}\n\nclass TypedHttpEventStream<T> implements TypedEventStream<T> {\n readonly #raw: EventStream;\n readonly #model: PayloadModel<T>;\n\n constructor(raw: EventStream, model: PayloadModel<T>) {\n this.#raw = raw;\n this.#model = model;\n }\n\n get lastEventId(): string | undefined {\n return this.#raw.lastEventId;\n }\n\n close(): void {\n this.#raw.close();\n }\n\n async [Symbol.asyncDispose](): Promise<void> {\n this.close();\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<TypedOperationEvent<T>> {\n for await (const event of this.#raw) {\n const decoded = decodeOperationPayload(event.payloadCbor) as T;\n yield {\n operationId: event.operationId,\n eventId: event.eventId,\n payload: this.#model.create(decoded),\n payloadCbor: Uint8Array.from(event.payloadCbor),\n };\n }\n }\n}\n\nexport class CigarClient {\n readonly #baseUrl: URL;\n readonly #token?: ClientOptions[\"bearerToken\"];\n readonly #timeoutMs: number;\n readonly #maxAttempts: number;\n readonly #fetch: typeof globalThis.fetch;\n readonly #apiVersion: \"1\";\n\n constructor(options: ClientOptions) {\n try {\n this.#baseUrl = new URL(options.baseUrl);\n } catch (cause) {\n throw new ValidationError(\"baseUrl must be an absolute HTTP(S) origin\", { cause });\n }\n if (!new Set([\"http:\", \"https:\"]).has(this.#baseUrl.protocol)) {\n throw new ValidationError(\"baseUrl must use HTTP or HTTPS\");\n }\n if (this.#baseUrl.username !== \"\" || this.#baseUrl.password !== \"\" || this.#baseUrl.search !== \"\" || this.#baseUrl.hash !== \"\") {\n throw new ValidationError(\"baseUrl must not contain credentials, query, or fragment\");\n }\n if (this.#baseUrl.pathname !== \"/\" && this.#baseUrl.pathname !== \"\") {\n throw new ValidationError(\"baseUrl must be an origin with no path prefix\");\n }\n const loopback = this.#baseUrl.hostname === \"localhost\"\n || this.#baseUrl.hostname === \"127.0.0.1\"\n || this.#baseUrl.hostname === \"::1\"\n || this.#baseUrl.hostname === \"[::1]\";\n if (this.#baseUrl.protocol === \"http:\" && (!loopback || options.allowInsecureLoopback !== true)) {\n throw new ValidationError(\"cleartext HTTP requires explicit allowInsecureLoopback for a loopback host\");\n }\n if (this.#baseUrl.protocol === \"https:\" && options.bearerToken === undefined) {\n throw new ValidationError(\"remote HTTPS requires an explicit bearer token provider\");\n }\n if (typeof options.bearerToken === \"string\" && !/^[\\x21-\\x7e]{1,8192}$/u.test(options.bearerToken)) {\n throw new ValidationError(\"bearer token must be 1..8192 visible ASCII bytes\");\n }\n this.#baseUrl.pathname = \"\";\n this.#token = options.bearerToken;\n this.#timeoutMs = validateTimeout(options.defaultTimeoutMs ?? 30_000);\n this.#maxAttempts = options.maxAttempts ?? 3;\n if (!Number.isInteger(this.#maxAttempts) || this.#maxAttempts < 1 || this.#maxAttempts > 8) {\n throw new ValidationError(\"maxAttempts must be in 1..8\");\n }\n if (options.fetch !== undefined && options.trustCustomFetch !== true) {\n throw new ValidationError(\"custom fetch requires explicit trustCustomFetch acknowledgement\");\n }\n if (options.fetch === undefined && ambientProxyConfigured()) {\n throw new ValidationError(\"ambient proxy configuration requires an explicitly trusted custom fetch\");\n }\n this.#fetch = options.fetch ?? globalThis.fetch;\n if (options.apiVersion !== undefined && options.apiVersion !== \"1\") {\n throw new ValidationError(\"apiVersion must be the frozen v1 line\");\n }\n this.#apiVersion = options.apiVersion ?? \"1\";\n }\n\n async negotiate(options?: CallOptions): Promise<Compatibility> {\n const empty = { payloadCbor: new Uint8Array() } satisfies OperationRequest;\n const version = await this.invokeOperation(\"getVersion\", empty, options);\n const capabilities = await this.invokeOperation(\"getCapabilities\", empty, options);\n return { apiVersion: this.#apiVersion, version, capabilities };\n }\n\n async invokeTypedOperation<RequestPayload, ResponsePayload>(\n operationId: OperationId,\n request: TypedOperationRequest<RequestPayload>,\n responseModel: PayloadModel<ResponsePayload>,\n options?: CallOptions,\n ): Promise<TypedOperationResponse<ResponsePayload>> {\n const raw = await this.invokeOperation(operationId, this.#typedRequest(operationId, request), options);\n const decoded = decodeOperationPayload(raw.payloadCbor) as ResponsePayload;\n return {\n operationId: raw.operationId,\n payload: responseModel.create(decoded),\n payloadCbor: Uint8Array.from(raw.payloadCbor),\n ...(raw.semanticEtag === undefined ? {} : { semanticEtag: raw.semanticEtag }),\n ...(raw.nextPageCursor === undefined ? {} : { nextPageCursor: raw.nextPageCursor }),\n };\n }\n\n streamTypedOperation<RequestPayload, EventPayload>(\n operationId: OperationId,\n request: TypedOperationRequest<RequestPayload>,\n eventModel: PayloadModel<EventPayload>,\n options?: CallOptions,\n ): TypedEventStream<EventPayload> {\n return new TypedHttpEventStream(\n this.streamOperation(operationId, this.#typedRequest(operationId, request), options),\n eventModel,\n );\n }\n\n #typedRequest<T>(operationId: OperationId, request: TypedOperationRequest<T>): OperationRequest {\n const definition = OPERATIONS[operationId];\n if (definition.stream && request.pageCursor !== undefined) {\n throw new ValidationError(\"SSE resume uses CallOptions.resumeFrom, not a pagination cursor\");\n }\n const validatedPayload = payloadModel(definition.requestType).create(request.payload);\n if (typeof validatedPayload !== \"object\" || validatedPayload === null) {\n throw new ValidationError(`${definition.requestType} payload must be an object`);\n }\n const record = validatedPayload as Record<string, unknown>;\n const pathParameters = definition.pathFields.map((name) => {\n const value = record[name];\n if (typeof value !== \"string\") throw new ValidationError(`${definition.requestType}.${name} must be a path string`);\n return { name, value };\n });\n return {\n payloadCbor: definition.httpMethod === \"GET\" ? new Uint8Array() : encodeOperationPayload(validatedPayload),\n pathParameters,\n ...(request.idempotencyKey === undefined ? {} : { idempotencyKey: request.idempotencyKey }),\n ...(request.expectedRevision === undefined ? {} : { expectedRevision: request.expectedRevision }),\n ...(request.dryRun === undefined ? {} : { dryRun: request.dryRun }),\n ...(request.pageCursor === undefined ? {} : { pageCursor: request.pageCursor }),\n ...(request.pageSize === undefined ? {} : { pageSize: request.pageSize }),\n };\n }\n\n async *paginate(\n operationId: OperationId,\n request: OperationRequest,\n options?: CallOptions,\n ): AsyncGenerator<OperationResponse> {\n if (OPERATIONS[operationId].stream) throw new ValidationError(\"stream operations cannot be paginated\");\n let cursor = request.pageCursor;\n const seen = new Set<string>();\n for (;;) {\n const pageRequest: OperationRequest = cursor === undefined\n ? { ...request }\n : { ...request, pageCursor: cursor };\n const response = await this.invokeOperation(operationId, pageRequest, options);\n yield response;\n if (response.nextPageCursor === undefined) return;\n if (seen.has(response.nextPageCursor)) throw new TransportError(\"pagination cursor cycle detected\");\n seen.add(response.nextPageCursor);\n cursor = response.nextPageCursor;\n }\n }\n\n async invokeOperation(\n operationId: OperationId,\n request: OperationRequest,\n options?: CallOptions,\n ): Promise<OperationResponse> {\n const definition = OPERATIONS[operationId];\n if (definition.stream) throw new ValidationError(\"use streamOperation for streaming operations\");\n const attempts = this.#attempts(operationId, request, options);\n const timeoutMs = validateTimeout(options?.timeoutMs ?? this.#timeoutMs);\n const deadline = Date.now() + timeoutMs;\n let lastError: unknown;\n for (let attempt = 1; attempt <= attempts; attempt += 1) {\n if (deadline <= Date.now()) throw new CigarTimeoutError(\"CIGAR request deadline elapsed\");\n try {\n return await this.#unary(operationId, request, deadline, options);\n } catch (error) {\n lastError = error;\n if (attempt === attempts || !isRetryable(error)) throw error;\n const backoff = Math.min(100 * 2 ** (attempt - 1), 1_000);\n const remaining = deadline - Date.now();\n if (remaining <= backoff) throw new CigarTimeoutError(\"CIGAR request deadline elapsed\", { cause: error });\n await delay(backoff, undefined, { signal: options?.signal });\n }\n }\n throw lastError;\n }\n\n streamOperation(operationId: OperationId, request: OperationRequest, options?: CallOptions): EventStream {\n if (!OPERATIONS[operationId].stream) throw new ValidationError(\"operation is not a stream\");\n if (request.pageCursor !== undefined) throw new ValidationError(\"SSE resume uses CallOptions.resumeFrom, not pageCursor\");\n let stream: HttpEventStream;\n stream = new HttpEventStream(() => this.#events(stream, operationId, request, options));\n return stream;\n }\n\n #attempts(operationId: OperationId, request: OperationRequest, options: CallOptions | undefined): number {\n const requested = options?.maxAttempts ?? this.#maxAttempts;\n if (!Number.isInteger(requested) || requested < 1 || requested > 8) {\n throw new ValidationError(\"maxAttempts must be in 1..8\");\n }\n if (operationId === \"dispatchEffect\") return 1;\n const definition = OPERATIONS[operationId];\n if (!definition.mutation) return requested;\n return request.idempotencyKey === undefined ? 1 : requested;\n }\n\n async #headers(\n operationId: OperationId,\n timeoutMs: number,\n signal?: AbortSignal,\n externalSignal?: AbortSignal,\n ): Promise<Headers> {\n const headers = new Headers({\n accept: \"application/json, application/problem+json\",\n \"x-cigar-api-version\": this.#apiVersion,\n \"x-cigar-operation-id\": operationId,\n \"x-cigar-timeout-ms\": String(timeoutMs),\n });\n if (this.#token !== undefined) {\n let token: string;\n try {\n if (typeof this.#token !== \"function\") token = this.#token;\n else if (signal === undefined) token = await this.#token();\n else {\n const provider = Promise.resolve(this.#token(signal));\n token = await new Promise<string>((resolve, reject) => {\n const aborted = (): void => reject(signal.reason);\n signal.addEventListener(\"abort\", aborted, { once: true });\n provider.then(resolve, reject).finally(() => signal.removeEventListener(\"abort\", aborted)).catch(() => undefined);\n });\n }\n } catch (cause) {\n if (externalSignal?.aborted === true) throw cause;\n if (signal?.aborted === true) throw new CigarTimeoutError(\"CIGAR request deadline elapsed\", { cause });\n throw new TransportError(\"bearer token provider failed\", { cause });\n }\n if (!/^[\\x21-\\x7e]{1,8192}$/u.test(token)) throw new ValidationError(\"bearer token must be 1..8192 visible ASCII bytes\");\n headers.set(\"authorization\", `Bearer ${token}`);\n }\n return headers;\n }\n\n #signal(options: CallOptions | undefined, timeoutMs: number, internal?: AbortSignal): AbortSignal {\n const timeout = AbortSignal.timeout(timeoutMs);\n const signals = [timeout];\n if (options?.signal !== undefined) signals.push(options.signal);\n if (internal !== undefined) signals.push(internal);\n return signals.length === 1 ? timeout : AbortSignal.any(signals);\n }\n\n async #unary(\n operationId: OperationId,\n request: OperationRequest,\n deadline: number,\n options?: CallOptions,\n ): Promise<OperationResponse> {\n const definition = OPERATIONS[operationId];\n const timeoutMs = Math.max(1, deadline - Date.now());\n const parameters = pathParameters(request.pathParameters);\n let path = bindPath(definition.httpPath, parameters);\n const requestSignal = this.#signal(options, timeoutMs);\n const headers = await this.#headers(operationId, timeoutMs, requestSignal, options?.signal);\n const payload = Uint8Array.from(request.payloadCbor ?? []);\n if (payload.length > definition.requestMaxBytes) throw new ValidationError(\"request payload exceeds operation bound\");\n let body: string | undefined;\n if (definition.httpMethod === \"GET\") {\n if (payload.length !== 0 || request.idempotencyKey !== undefined || request.expectedRevision !== undefined || request.dryRun === true) {\n throw new ValidationError(\"GET operations do not carry payload or mutation metadata\");\n }\n const query = new URLSearchParams();\n if (request.pageCursor !== undefined) {\n if (Buffer.byteLength(request.pageCursor) > MAX_CURSOR_BYTES) throw new ValidationError(\"page cursor exceeds bound\");\n query.set(\"page_cursor\", request.pageCursor);\n }\n if (request.pageSize !== undefined) {\n if (!Number.isInteger(request.pageSize) || request.pageSize < 1 || request.pageSize > 1000) throw new ValidationError(\"pageSize must be in 1..1000\");\n query.set(\"page_size\", String(request.pageSize));\n }\n const encoded = query.toString();\n if (encoded !== \"\") path += `?${encoded}`;\n } else {\n if (definition.idempotencyRequired) {\n if (request.idempotencyKey === undefined) throw new ValidationError(`${operationId} requires an idempotency key`);\n headers.set(\"idempotency-key\", validateIdempotencyKey(request.idempotencyKey));\n } else if (request.idempotencyKey !== undefined) {\n throw new ValidationError(`${operationId} does not accept an idempotency key`);\n }\n if (definition.revisionRequired) {\n if (request.expectedRevision === undefined || request.expectedRevision.length === 0 || request.expectedRevision.length > 256) {\n throw new ValidationError(`${operationId} requires a bounded expected revision`);\n }\n headers.set(\"if-match\", request.expectedRevision);\n } else if (request.expectedRevision !== undefined) {\n throw new ValidationError(`${operationId} does not accept an expected revision`);\n }\n headers.set(\"content-type\", \"application/json\");\n body = JSON.stringify({\n operation_id: operationId,\n payload_cbor: exactBase64url(payload),\n dry_run: request.dryRun ?? false,\n ...(request.idempotencyKey === undefined ? {} : { idempotency_key: request.idempotencyKey }),\n ...(request.expectedRevision === undefined ? {} : { expected_revision: request.expectedRevision }),\n ...(request.pageCursor === undefined ? {} : { page_cursor: request.pageCursor }),\n ...(request.pageSize === undefined ? {} : { page_size: request.pageSize }),\n path_parameters: parameters,\n });\n }\n let response: Response;\n try {\n const init: RequestInit = {\n method: definition.httpMethod,\n headers,\n signal: requestSignal,\n redirect: \"error\",\n ...(body === undefined ? {} : { body }),\n };\n response = await this.#fetch(new URL(path, `${this.#baseUrl.toString()}/`), init);\n } catch (cause) {\n if (options?.signal?.aborted === true) throw cause;\n if (cause instanceof DOMException && cause.name === \"TimeoutError\") throw new CigarTimeoutError(\"CIGAR request deadline elapsed\", { cause });\n throw new TransportError(\"CIGAR transport failed\", { cause });\n }\n if (!response.ok) throw await problem(response);\n const serverVersion = response.headers.get(\"x-cigar-api-version\");\n if (serverVersion !== null && serverVersion !== this.#apiVersion) {\n throw new CompatibilityError(`server API version ${serverVersion} is incompatible with ${this.#apiVersion}`);\n }\n const contentType = response.headers.get(\"content-type\")?.split(\";\", 1)[0]?.trim();\n if (contentType === \"application/openmetrics-text\") {\n return {\n operationId,\n payloadCbor: await boundedBytes(response, definition.responseMaxBytes, \"metrics response\"),\n };\n }\n if (contentType !== \"application/json\") {\n throw new TransportError(`unexpected response content type ${contentType}`);\n }\n const wrapperMaximum = Math.ceil(definition.responseMaxBytes * 4 / 3) + 16_384;\n return parseResponse(\n operationId,\n parseJson(await boundedBytes(response, wrapperMaximum, \"operation response\"), \"operation response\"),\n definition.responseMaxBytes,\n );\n }\n\n async *#events(\n stream: HttpEventStream,\n operationId: OperationId,\n request: OperationRequest,\n options?: CallOptions,\n ): AsyncGenerator<OperationEvent> {\n const timeoutMs = validateTimeout(options?.timeoutMs ?? this.#timeoutMs);\n const deadline = Date.now() + timeoutMs;\n const parameters = pathParameters(request.pathParameters);\n const definition = OPERATIONS[operationId];\n const path = bindPath(definition.httpPath, parameters);\n let resume = options?.resumeFrom;\n if (resume !== undefined && !/^[\\x21-\\x7e]{1,256}$/u.test(resume)) {\n throw new ValidationError(\"resumeFrom must be a bounded visible-ASCII event ID\");\n }\n const attempts = options?.maxAttempts ?? this.#maxAttempts;\n if (!Number.isInteger(attempts) || attempts < 1 || attempts > 8) {\n throw new ValidationError(\"maxAttempts must be in 1..8\");\n }\n const seen = new Set<string>(resume === undefined ? [] : [resume]);\n for (let attempt = 1; attempt <= attempts && !stream.closed; attempt += 1) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) throw new CigarTimeoutError(\"CIGAR stream deadline elapsed\");\n const requestSignal = this.#signal(options, remaining, stream.signal);\n let headers: Headers;\n try {\n headers = await this.#headers(operationId, remaining, requestSignal, options?.signal);\n } catch (error) {\n if (stream.closed) return;\n throw error;\n }\n headers.set(\"accept\", \"text/event-stream, application/problem+json\");\n if (resume !== undefined) headers.set(\"last-event-id\", resume);\n let retryCause: unknown = new TransportError(\"CIGAR event stream ended before close\");\n let cleanEnd = false;\n let response: Response | undefined;\n try {\n response = await this.#fetch(new URL(path, `${this.#baseUrl.toString()}/`), {\n method: \"GET\",\n headers,\n signal: requestSignal,\n redirect: \"error\",\n });\n } catch (cause) {\n if (stream.closed || options?.signal?.aborted === true) return;\n retryCause = new TransportError(\"CIGAR event stream failed\", { cause });\n }\n if (response !== undefined) {\n if (!response.ok) {\n retryCause = await problem(response);\n if (!isRetryable(retryCause)) throw retryCause;\n } else {\n const contentType = response.headers.get(\"content-type\")?.split(\";\", 1)[0]?.trim();\n if (contentType !== \"text/event-stream\") throw new TransportError(\"stream response must use text/event-stream\");\n if (response.body === null) throw new TransportError(\"event stream response has no body\");\n const iterator = response.body.pipeThrough(new TextDecoderStream(\"utf-8\", { fatal: true }))[Symbol.asyncIterator]();\n let pending = \"\";\n for (;;) {\n let next: IteratorResult<string>;\n try {\n next = await iterator.next();\n } catch (cause) {\n retryCause = new TransportError(\"event stream body read failed\", { cause });\n break;\n }\n if (next.done) {\n cleanEnd = true;\n break;\n }\n if (stream.closed) return;\n pending += next.value.replace(/\\r\\n/gu, \"\\n\");\n if (Buffer.byteLength(pending) > MAX_EVENT_BYTES * 2) throw new TransportError(\"event frame exceeds bound\");\n let boundary: number;\n while ((boundary = pending.indexOf(\"\\n\\n\")) >= 0) {\n const frame = pending.slice(0, boundary);\n pending = pending.slice(boundary + 2);\n const parsed = this.#event(operationId, frame);\n if (parsed === undefined) continue;\n if (parsed instanceof CigarApiError) throw parsed;\n if (seen.has(parsed.eventId)) continue;\n if (seen.size >= 100_000) throw new TransportError(\"event identity set exceeds its bound\");\n seen.add(parsed.eventId);\n resume = parsed.eventId;\n stream.remember(parsed.eventId);\n yield parsed;\n }\n }\n }\n }\n if (stream.closed) return;\n if (attempt === attempts) {\n if (cleanEnd) return;\n throw retryCause;\n }\n const backoff = Math.min(100 * 2 ** (attempt - 1), 1_000);\n if (deadline - Date.now() <= backoff) {\n throw new CigarTimeoutError(\"CIGAR stream deadline elapsed\", { cause: retryCause });\n }\n await delay(backoff, undefined, { signal: options?.signal });\n }\n }\n\n #event(operationId: OperationId, frame: string): OperationEvent | CigarApiError | undefined {\n let eventType = \"message\";\n let id: string | undefined;\n const data: string[] = [];\n for (const line of frame.split(\"\\n\")) {\n if (line === \"\" || line.startsWith(\":\")) continue;\n const colon = line.indexOf(\":\");\n const field = colon < 0 ? line : line.slice(0, colon);\n const value = colon < 0 ? \"\" : line.slice(colon + 1).replace(/^ /u, \"\");\n if (field === \"event\") eventType = value;\n else if (field === \"id\") id = value;\n else if (field === \"data\") data.push(value);\n }\n if (data.length === 0) return undefined;\n let decoded: unknown;\n try {\n decoded = parseJson(new TextEncoder().encode(data.join(\"\\n\")), \"event data\");\n } catch (cause) {\n throw new TransportError(\"event data is not valid JSON\", { cause });\n }\n if (eventType === \"problem\") {\n if (typeof decoded !== \"object\" || decoded === null || Array.isArray(decoded)) {\n throw new TransportError(\"problem event is not an object\");\n }\n const status = (decoded as Record<string, unknown>).http_status;\n if (!Number.isInteger(status)) throw new TransportError(\"problem event lacks its HTTP status\");\n return decodeProblem(status as number, decoded);\n }\n if (typeof decoded !== \"object\" || decoded === null || Array.isArray(decoded)) throw new TransportError(\"event is not an object\");\n const record = decoded as Record<string, unknown>;\n const eventFields = Object.keys(record).sort();\n if (eventFields.join(\",\") !== \"event_id,operation_id,payload_cbor\") {\n throw new TransportError(\"event contains unknown or missing fields\");\n }\n if (\n record.operation_id !== operationId\n || typeof record.event_id !== \"string\"\n || !/^[\\x21-\\x7e]{1,256}$/u.test(record.event_id)\n || record.event_id !== id\n ) {\n throw new TransportError(\"event identity mismatch\");\n }\n return { operationId, eventId: record.event_id, payloadCbor: decodeBase64url(record.payload_cbor, MAX_EVENT_BYTES) };\n }\n}\n\nexport interface CigarClient extends GeneratedOperations {}\n\nfunction payloadModel(name: string): PayloadModel<unknown> {\n const candidate = (models as unknown as Record<string, unknown>)[name];\n if (typeof candidate !== \"object\" || candidate === null || !(\"create\" in candidate)) {\n throw new Error(`generated payload model ${name} is missing`);\n }\n return candidate as PayloadModel<unknown>;\n}\n\nfor (const operationId of Object.keys(OPERATIONS) as OperationId[]) {\n Object.defineProperty(CigarClient.prototype, operationId, {\n configurable: false,\n enumerable: false,\n value(\n this: CigarClient,\n request: TypedOperationRequest<unknown>,\n options?: CallOptions,\n ): Promise<TypedOperationResponse<unknown>> | TypedEventStream<unknown> {\n return OPERATIONS[operationId].stream\n ? this.streamTypedOperation(operationId, request, payloadModel(OPERATIONS[operationId].eventType ?? \"\"), options)\n : this.invokeTypedOperation(operationId, request, payloadModel(OPERATIONS[operationId].responseType), options);\n },\n writable: false,\n });\n}\n"]}
|
package/dist/digest.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { SemanticContextBundle, SemanticContextDelta } from "./types.js";
|
|
2
|
+
type Canonical = boolean | bigint | number | string | Uint8Array | readonly Canonical[] | {
|
|
3
|
+
readonly [key: string]: Canonical;
|
|
4
|
+
};
|
|
5
|
+
/** Encode the frozen CIGAR deterministic-CBOR subset. */
|
|
6
|
+
export declare function deterministicCbor(value: Canonical): Uint8Array;
|
|
7
|
+
/** Encode one schema-derived operation payload exactly like cigar-api. */
|
|
8
|
+
export declare function encodeOperationPayload(value: unknown): Uint8Array;
|
|
9
|
+
/** Strictly decode one canonical typed operation payload. */
|
|
10
|
+
export declare function decodeOperationPayload(source: Uint8Array): unknown;
|
|
11
|
+
/** Compute an ordinary raw SHA-256 multihash (used for sealed delta JSON). */
|
|
12
|
+
export declare function rawMultihash(bytes: Uint8Array): string;
|
|
13
|
+
/** Compute the semantic v1 bundle identity, excluding the self-derived bundle_id. */
|
|
14
|
+
export declare function bundleId(bundle: SemanticContextBundle): string;
|
|
15
|
+
/** Validate structural invariants and prove the content-derived bundle identity. */
|
|
16
|
+
export declare function verifyBundle(bundle: SemanticContextBundle): void;
|
|
17
|
+
export declare function deltaDigest(delta: SemanticContextDelta): string;
|
|
18
|
+
/** Apply and verify a sealed delta against an exact expected target bundle. */
|
|
19
|
+
export declare function applyContextDelta(base: SemanticContextBundle, expectedTarget: SemanticContextBundle, delta: SemanticContextDelta, sealedDigest: string): SemanticContextBundle;
|
|
20
|
+
export {};
|
|
21
|
+
//# sourceMappingURL=digest.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"digest.d.ts","sourceRoot":"","sources":["../src/digest.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAuB,qBAAqB,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAEnG,KAAK,SAAS,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,UAAU,GAAG,SAAS,SAAS,EAAE,GAAG;IAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAAC;AA8ChI,yDAAyD;AACzD,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,SAAS,GAAG,UAAU,CAE9D;AA6DD,0EAA0E;AAC1E,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,UAAU,CAEjE;AA2FD,6DAA6D;AAC7D,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,UAAU,GAAG,OAAO,CAOlE;AAaD,8EAA8E;AAC9E,wBAAgB,YAAY,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAEtD;AA4DD,qFAAqF;AACrF,wBAAgB,QAAQ,CAAC,MAAM,EAAE,qBAAqB,GAAG,MAAM,CAW9D;AAED,oFAAoF;AACpF,wBAAgB,YAAY,CAAC,MAAM,EAAE,qBAAqB,GAAG,IAAI,CA4BhE;AAsBD,wBAAgB,WAAW,CAAC,KAAK,EAAE,oBAAoB,GAAG,MAAM,CAG/D;AAED,+EAA+E;AAC/E,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,qBAAqB,EAC3B,cAAc,EAAE,qBAAqB,EACrC,KAAK,EAAE,oBAAoB,EAC3B,YAAY,EAAE,MAAM,GACnB,qBAAqB,CAiCvB","sourcesContent":["import { createHash } from \"node:crypto\";\n\nimport { ValidationError } from \"./errors.js\";\nimport type { SemanticBundleBlock, SemanticContextBundle, SemanticContextDelta } from \"./types.js\";\n\ntype Canonical = boolean | bigint | number | string | Uint8Array | readonly Canonical[] | { readonly [key: string]: Canonical };\n\nconst DIGEST = /^1220[0-9a-f]{64}$/u;\nconst LANE_ORDER = new Map([\n [\"rules\", 0],\n [\"task\", 1],\n [\"evidence\", 2],\n [\"history\", 3],\n [\"tools\", 4],\n]);\n\nfunction concatenate(parts: readonly Uint8Array[]): Uint8Array {\n const result = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));\n let offset = 0;\n for (const part of parts) {\n result.set(part, offset);\n offset += part.length;\n }\n return result;\n}\n\nfunction head(major: number, argument: bigint): Uint8Array {\n if (argument < 0n || argument > 0xffff_ffff_ffff_ffffn) throw new ValidationError(\"canonical integer exceeds u64\");\n const prefix = major << 5;\n if (argument < 24n) return Uint8Array.of(prefix | Number(argument));\n const widths: readonly [bigint, number, number][] = [\n [0xffn, 24, 1],\n [0xffffn, 25, 2],\n [0xffff_ffffn, 26, 4],\n [0xffff_ffff_ffff_ffffn, 27, 8],\n ];\n for (const [maximum, additional, width] of widths) {\n if (argument <= maximum) {\n const output = new Uint8Array(width + 1);\n output[0] = prefix | additional;\n let remainder = argument;\n for (let index = width; index > 0; index -= 1) {\n output[index] = Number(remainder & 0xffn);\n remainder >>= 8n;\n }\n return output;\n }\n }\n throw new ValidationError(\"canonical integer exceeds u64\");\n}\n\n/** Encode the frozen CIGAR deterministic-CBOR subset. */\nexport function deterministicCbor(value: Canonical): Uint8Array {\n return encodeCanonical(value, 0, { nodes: 0 });\n}\n\nfunction encodeCanonical(value: Canonical, depth: number, budget: { nodes: number }): Uint8Array {\n budget.nodes += 1;\n if (depth > 64 || budget.nodes > 100_000) throw new ValidationError(\"canonical value exceeds nesting or node bounds\");\n if (value === false) return Uint8Array.of(0xf4);\n if (value === true) return Uint8Array.of(0xf5);\n if (typeof value === \"number\") {\n if (!Number.isSafeInteger(value)) throw new ValidationError(\"canonical numbers must be safe integers; use bigint for wider values\");\n return encodeCanonical(BigInt(value), depth, budget);\n }\n if (typeof value === \"bigint\") {\n if (value < -(1n << 63n)) throw new ValidationError(\"canonical signed integer is below i64\");\n return value >= 0n ? head(0, value) : head(1, -1n - value);\n }\n if (typeof value === \"string\") {\n const encoded = new TextEncoder().encode(value.normalize(\"NFC\"));\n return concatenate([head(3, BigInt(encoded.length)), encoded]);\n }\n if (value instanceof Uint8Array) return concatenate([head(2, BigInt(value.length)), value]);\n if (Array.isArray(value)) {\n return concatenate([head(4, BigInt(value.length)), ...value.map((child) => encodeCanonical(child, depth + 1, budget))]);\n }\n if (typeof value !== \"object\" || value === null) throw new ValidationError(\"null is not canonical\");\n const entries = Object.entries(value).map(([key, child]) => {\n if (child === undefined || child === null) throw new ValidationError(\"undefined and null are not canonical\");\n return { key: encodeCanonical(key, depth + 1, budget), child };\n });\n entries.sort((left, right) => Buffer.compare(left.key, right.key));\n for (let index = 1; index < entries.length; index += 1) {\n if (Buffer.compare(entries[index - 1]?.key ?? new Uint8Array(), entries[index]?.key ?? new Uint8Array()) === 0) {\n throw new ValidationError(\"canonical map contains a duplicate key\");\n }\n }\n return concatenate([\n head(5, BigInt(entries.length)),\n ...entries.flatMap(({ key, child }) => [key, encodeCanonical(child, depth + 1, budget)]),\n ]);\n}\n\nfunction canonicalPayload(value: unknown, depth = 0, budget = { nodes: 0 }): Canonical {\n budget.nodes += 1;\n if (depth > 64 || budget.nodes > 100_000) throw new ValidationError(\"operation payload exceeds nesting or node bounds\");\n if (typeof value === \"boolean\" || typeof value === \"string\" || typeof value === \"bigint\" || value instanceof Uint8Array) {\n return value;\n }\n if (typeof value === \"number\") {\n if (!Number.isSafeInteger(value)) throw new ValidationError(\"payload numbers must be safe integers; use bigint for int64/uint64\");\n return value;\n }\n if (Array.isArray(value)) return value.map((child) => canonicalPayload(child, depth + 1, budget));\n if (typeof value === \"object\" && value !== null) {\n const result: Record<string, Canonical> = {};\n for (const [key, child] of Object.entries(value)) {\n if (child !== undefined) result[key] = canonicalPayload(child, depth + 1, budget);\n }\n return result;\n }\n throw new ValidationError(\"operation payload contains null, undefined, or a non-canonical value\");\n}\n\n/** Encode one schema-derived operation payload exactly like cigar-api. */\nexport function encodeOperationPayload(value: unknown): Uint8Array {\n return deterministicCbor(canonicalPayload(value));\n}\n\nclass PayloadCborParser {\n #position = 0;\n #nodes = 0;\n readonly #source: Uint8Array;\n\n constructor(source: Uint8Array) {\n this.#source = source;\n }\n\n get done(): boolean {\n return this.#position === this.#source.length;\n }\n\n #exact(length: number): Uint8Array {\n const end = this.#position + length;\n if (!Number.isSafeInteger(length) || length < 0 || end > this.#source.length) throw new ValidationError(\"payload CBOR is truncated\");\n const value = this.#source.slice(this.#position, end);\n this.#position = end;\n return value;\n }\n\n #byte(): number {\n const value = this.#exact(1)[0];\n if (value === undefined) throw new ValidationError(\"payload CBOR is truncated\");\n return value;\n }\n\n #argument(additional: number): bigint {\n if (additional < 24) return BigInt(additional);\n const widths = new Map([[24, 1], [25, 2], [26, 4], [27, 8]]);\n const width = widths.get(additional);\n if (width === undefined) throw new ValidationError(\"payload CBOR uses an indefinite or reserved form\");\n let value = 0n;\n for (const byte of this.#exact(width)) value = (value << 8n) | BigInt(byte);\n const minimum = new Map([[1, 24n], [2, 0x100n], [4, 0x1_0000n], [8, 0x1_0000_0000n]]).get(width);\n if (minimum === undefined || value < minimum) throw new ValidationError(\"payload CBOR integer is non-canonical\");\n return value;\n }\n\n parse(depth = 0): Canonical {\n this.#nodes += 1;\n if (depth > 64 || this.#nodes > 100_000) throw new ValidationError(\"payload CBOR exceeds nesting or node bounds\");\n const initial = this.#byte();\n const major = initial >> 5;\n const additional = initial & 31;\n if (major === 0 || major === 1) {\n const argument = this.#argument(additional);\n const value = major === 0 ? argument : -1n - argument;\n if (value < -(1n << 63n)) throw new ValidationError(\"payload CBOR integer exceeds i64\");\n return value >= BigInt(Number.MIN_SAFE_INTEGER) && value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : value;\n }\n if (major === 2 || major === 3) {\n const length = Number(this.#argument(additional));\n const bytes = this.#exact(length);\n if (major === 2) return bytes;\n try {\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes).normalize(\"NFC\");\n } catch (cause) {\n throw new ValidationError(\"payload CBOR text is invalid UTF-8\", { cause });\n }\n }\n if (major === 4) {\n const length = Number(this.#argument(additional));\n if (!Number.isSafeInteger(length) || length > 100_000) throw new ValidationError(\"payload CBOR collection exceeds its node bound\");\n return Array.from({ length }, () => this.parse(depth + 1));\n }\n if (major === 5) {\n const length = Number(this.#argument(additional));\n if (!Number.isSafeInteger(length) || length > 100_000) throw new ValidationError(\"payload CBOR collection exceeds its node bound\");\n const result: Record<string, Canonical> = {};\n let previous: Uint8Array | undefined;\n for (let index = 0; index < length; index += 1) {\n const start = this.#position;\n const key = this.parse(depth + 1);\n const encoded = this.#source.slice(start, this.#position);\n if (typeof key !== \"string\" || (previous !== undefined && Buffer.compare(previous, encoded) >= 0) || key in result) {\n throw new ValidationError(\"payload CBOR map keys are not canonical and unique\");\n }\n previous = encoded;\n result[key] = this.parse(depth + 1);\n }\n return result;\n }\n if (major === 7 && additional === 20) return false;\n if (major === 7 && additional === 21) return true;\n throw new ValidationError(\"payload CBOR contains a forbidden tag, null, float, or simple value\");\n }\n}\n\n/** Strictly decode one canonical typed operation payload. */\nexport function decodeOperationPayload(source: Uint8Array): unknown {\n const parser = new PayloadCborParser(source);\n const value = parser.parse();\n if (!parser.done || Buffer.compare(deterministicCbor(value), source) !== 0) {\n throw new ValidationError(\"payload CBOR is not deterministic\");\n }\n return value;\n}\n\nfunction multihash(domain: string, canonical: Uint8Array): string {\n const digest = createHash(\"sha256\")\n .update(domain)\n .update(Uint8Array.of(0))\n .update(\"v1\")\n .update(Uint8Array.of(0))\n .update(canonical)\n .digest(\"hex\");\n return `1220${digest}`;\n}\n\n/** Compute an ordinary raw SHA-256 multihash (used for sealed delta JSON). */\nexport function rawMultihash(bytes: Uint8Array): string {\n return `1220${createHash(\"sha256\").update(bytes).digest(\"hex\")}`;\n}\n\nfunction assertDigest(value: string, field: string): void {\n if (!DIGEST.test(value)) throw new ValidationError(`${field} must be a lowercase SHA-256 multihash`);\n}\n\nfunction exactKeys(value: object, expected: readonly string[], context: string): void {\n const actual = Object.keys(value).sort();\n const sorted = [...expected].sort();\n if (actual.length !== sorted.length || actual.some((key, index) => key !== sorted[index])) {\n throw new ValidationError(`${context} has unknown or missing fields`);\n }\n}\n\nfunction validateBlock(block: SemanticBundleBlock, index: number): void {\n const expected = [\"block_id\", \"lane\", \"representation\", \"content_digest\", \"token_count\", \"provenance\"];\n const receiptPresent = Object.hasOwn(block, \"transform_receipt\");\n if (receiptPresent) expected.push(\"transform_receipt\");\n exactKeys(block, expected, `block ${index}`);\n assertDigest(block.block_id, `block ${index} id`);\n assertDigest(block.content_digest, `block ${index} content digest`);\n if (!LANE_ORDER.has(block.lane)) throw new ValidationError(`block ${index} has an unknown lane`);\n if (![\"exact\", \"extracted\", \"summarized\", \"redacted\"].includes(block.representation)) {\n throw new ValidationError(`block ${index} has an unknown representation`);\n }\n if (!Number.isInteger(block.token_count) || block.token_count < 1 || block.token_count > 0xffff_ffff) {\n throw new ValidationError(`block ${index} token count is invalid`);\n }\n if (block.provenance.length < 1 || block.provenance.length > 10_000) {\n throw new ValidationError(`block ${index} provenance count is invalid`);\n }\n block.provenance.forEach((item) => assertDigest(item, `block ${index} provenance`));\n if (!block.provenance.every((item, ordinal) => ordinal === 0 || (block.provenance[ordinal - 1] ?? \"\") < item)) {\n throw new ValidationError(`block ${index} provenance must be sorted and unique`);\n }\n const receiptRequired = block.representation === \"extracted\" || block.representation === \"summarized\";\n if (receiptRequired !== receiptPresent) {\n throw new ValidationError(`block ${index} extracted and summarized representations require exactly one transform receipt`);\n }\n if (receiptPresent) {\n assertDigest(block.transform_receipt as string, `block ${index} transform receipt`);\n }\n}\n\nfunction canonicalBlock(block: SemanticBundleBlock): Record<string, Canonical> {\n return {\n block_id: block.block_id,\n lane: block.lane,\n representation: block.representation,\n content_digest: block.content_digest,\n token_count: block.token_count,\n provenance: block.provenance,\n ...(block.transform_receipt === undefined ? {} : { transform_receipt: block.transform_receipt }),\n };\n}\n\nfunction canonicalExtensions(value: Readonly<Record<string, unknown>>): Record<string, Canonical> {\n return value as Record<string, Canonical>;\n}\n\n/** Compute the semantic v1 bundle identity, excluding the self-derived bundle_id. */\nexport function bundleId(bundle: SemanticContextBundle): string {\n bundle.blocks.forEach((block, index) => validateBlock(block, index));\n const fields: Record<string, Canonical> = {\n schema_version: bundle.schema_version,\n contract_digest: bundle.contract_digest,\n manifest_digest: bundle.manifest_digest,\n blocks: bundle.blocks.map(canonicalBlock),\n total_tokens: bundle.total_tokens,\n extensions: canonicalExtensions(bundle.extensions),\n };\n return multihash(\"CIGAR-BUNDLE\", deterministicCbor([2, fields]));\n}\n\n/** Validate structural invariants and prove the content-derived bundle identity. */\nexport function verifyBundle(bundle: SemanticContextBundle): void {\n exactKeys(\n bundle,\n [\"schema_version\", \"bundle_id\", \"contract_digest\", \"manifest_digest\", \"blocks\", \"total_tokens\", \"extensions\"],\n \"bundle\",\n );\n if (bundle.schema_version !== \"cigar.context-bundle.v1\") throw new ValidationError(\"unsupported bundle schema\");\n assertDigest(bundle.bundle_id, \"bundle id\");\n assertDigest(bundle.contract_digest, \"contract digest\");\n assertDigest(bundle.manifest_digest, \"manifest digest\");\n if (bundle.blocks.length > 10_000) throw new ValidationError(\"bundle has too many blocks\");\n let total = 0;\n let previous: SemanticBundleBlock | undefined;\n for (const [index, block] of bundle.blocks.entries()) {\n validateBlock(block, index);\n const order = LANE_ORDER.get(block.lane) ?? -1;\n const previousOrder = previous === undefined ? -1 : (LANE_ORDER.get(previous.lane) ?? -1);\n if (previous !== undefined && (order < previousOrder || (order === previousOrder && block.block_id <= previous.block_id))) {\n throw new ValidationError(\"bundle blocks must be lane/id sorted and unique\");\n }\n total += block.token_count;\n if (total > 0xffff_ffff) throw new ValidationError(\"bundle token sum exceeds u32\");\n previous = block;\n }\n if (!Number.isInteger(bundle.total_tokens) || bundle.total_tokens !== total) {\n throw new ValidationError(\"bundle token total is not exact\");\n }\n if (bundleId(bundle) !== bundle.bundle_id) throw new ValidationError(\"bundle identity verification failed\");\n}\n\nfunction deltaJson(delta: SemanticContextDelta): Uint8Array {\n const blocks = delta.added_blocks.map((block) => ({\n block_id: block.block_id,\n lane: block.lane,\n representation: block.representation,\n content_digest: block.content_digest,\n token_count: block.token_count,\n provenance: [...block.provenance],\n ...(block.transform_receipt === undefined ? {} : { transform_receipt: block.transform_receipt }),\n }));\n return new TextEncoder().encode(JSON.stringify({\n schema_version: delta.schema_version,\n base_bundle_id: delta.base_bundle_id,\n target_bundle_id: delta.target_bundle_id,\n added_blocks: blocks,\n removed_block_ids: [...delta.removed_block_ids],\n resulting_tokens: delta.resulting_tokens,\n }));\n}\n\nexport function deltaDigest(delta: SemanticContextDelta): string {\n delta.added_blocks.forEach((block, index) => validateBlock(block, index));\n return rawMultihash(deltaJson(delta));\n}\n\n/** Apply and verify a sealed delta against an exact expected target bundle. */\nexport function applyContextDelta(\n base: SemanticContextBundle,\n expectedTarget: SemanticContextBundle,\n delta: SemanticContextDelta,\n sealedDigest: string,\n): SemanticContextBundle {\n verifyBundle(base);\n verifyBundle(expectedTarget);\n exactKeys(delta, [\"schema_version\", \"base_bundle_id\", \"target_bundle_id\", \"added_blocks\", \"removed_block_ids\", \"resulting_tokens\"], \"delta\");\n if (delta.schema_version !== \"cigar.context-delta.v1\") throw new ValidationError(\"unsupported delta schema\");\n if (delta.base_bundle_id !== base.bundle_id) throw new ValidationError(\"delta base does not match\");\n if (delta.target_bundle_id !== expectedTarget.bundle_id) throw new ValidationError(\"delta target does not match\");\n if (deltaDigest(delta) !== sealedDigest) throw new ValidationError(\"sealed delta digest does not match\");\n const blocks = new Map(base.blocks.map((block) => [block.block_id, block]));\n let previousRemoved = \"\";\n for (const id of delta.removed_block_ids) {\n assertDigest(id, \"removed block id\");\n if (id <= previousRemoved || !blocks.delete(id)) throw new ValidationError(\"delta removal set is invalid for the base\");\n previousRemoved = id;\n }\n let previousAdded = \"\";\n for (const [index, block] of delta.added_blocks.entries()) {\n validateBlock(block, index);\n if (block.block_id <= previousAdded || blocks.has(block.block_id)) throw new ValidationError(\"delta addition set is invalid\");\n if (delta.removed_block_ids.includes(block.block_id)) throw new ValidationError(\"delta both adds and removes a block\");\n blocks.set(block.block_id, block);\n previousAdded = block.block_id;\n }\n if (delta.resulting_tokens !== expectedTarget.total_tokens || blocks.size !== expectedTarget.blocks.length) {\n throw new ValidationError(\"delta result does not match target accounting\");\n }\n for (const target of expectedTarget.blocks) {\n const actual = blocks.get(target.block_id);\n if (actual === undefined || JSON.stringify(actual) !== JSON.stringify(target)) {\n throw new ValidationError(\"delta result does not reproduce the target\");\n }\n }\n return structuredClone(expectedTarget);\n}\n"]}
|