@milaboratories/pl-client 3.14.6 → 3.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/PromiseTracker.d.ts +1 -2
- package/dist/core/PromiseTracker.d.ts.map +1 -1
- package/dist/core/abstract_stream.d.ts +2 -3
- package/dist/core/abstract_stream.d.ts.map +1 -1
- package/dist/core/auth.d.ts +2 -4
- package/dist/core/auth.d.ts.map +1 -1
- package/dist/core/cache.d.ts +1 -3
- package/dist/core/cache.d.ts.map +1 -1
- package/dist/core/capabilities.d.ts +2 -3
- package/dist/core/capabilities.d.ts.map +1 -1
- package/dist/core/client.cjs +7 -0
- package/dist/core/client.cjs.map +1 -1
- package/dist/core/client.d.ts +8 -5
- package/dist/core/client.d.ts.map +1 -1
- package/dist/core/client.js +7 -0
- package/dist/core/client.js.map +1 -1
- package/dist/core/config.d.ts +29 -31
- package/dist/core/config.d.ts.map +1 -1
- package/dist/core/default_client.d.ts +2 -4
- package/dist/core/default_client.d.ts.map +1 -1
- package/dist/core/driver.d.ts +4 -6
- package/dist/core/driver.d.ts.map +1 -1
- package/dist/core/errors.d.ts +20 -22
- package/dist/core/errors.d.ts.map +1 -1
- package/dist/core/final.d.ts +4 -5
- package/dist/core/final.d.ts.map +1 -1
- package/dist/core/ll_client.cjs +10 -0
- package/dist/core/ll_client.cjs.map +1 -1
- package/dist/core/ll_client.d.ts +9 -5
- package/dist/core/ll_client.d.ts.map +1 -1
- package/dist/core/ll_client.js +10 -0
- package/dist/core/ll_client.js.map +1 -1
- package/dist/core/ll_transaction.d.ts +4 -6
- package/dist/core/ll_transaction.d.ts.map +1 -1
- package/dist/core/stat.d.ts +2 -3
- package/dist/core/stat.d.ts.map +1 -1
- package/dist/core/transaction.d.ts +30 -32
- package/dist/core/transaction.d.ts.map +1 -1
- package/dist/core/tree_filter.d.ts +14 -10
- package/dist/core/tree_filter.d.ts.map +1 -1
- package/dist/core/types.d.ts +54 -55
- package/dist/core/types.d.ts.map +1 -1
- package/dist/core/unauth_client.d.ts +4 -6
- package/dist/core/unauth_client.d.ts.map +1 -1
- package/dist/core/user_resources.cjs +23 -0
- package/dist/core/user_resources.cjs.map +1 -1
- package/dist/core/user_resources.d.ts +33 -7
- package/dist/core/user_resources.d.ts.map +1 -1
- package/dist/core/user_resources.js +23 -0
- package/dist/core/user_resources.js.map +1 -1
- package/dist/core/wire.d.ts +5 -7
- package/dist/core/wire.d.ts.map +1 -1
- package/dist/helpers/pl.d.ts +32 -34
- package/dist/helpers/pl.d.ts.map +1 -1
- package/dist/helpers/poll.d.ts +8 -9
- package/dist/helpers/poll.d.ts.map +1 -1
- package/dist/helpers/tx_helpers.d.ts +2 -4
- package/dist/helpers/tx_helpers.d.ts.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/proto-grpc/github.com/googleapis/googleapis/google/rpc/status.d.ts +2 -4
- package/dist/proto-grpc/github.com/googleapis/googleapis/google/rpc/status.d.ts.map +1 -1
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.cjs +163 -0
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.cjs.map +1 -1
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.cjs +19 -3
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.cjs.map +1 -1
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.d.ts +29 -5
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.d.ts.map +1 -1
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.js +19 -3
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.js.map +1 -1
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.d.ts +2217 -428
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.d.ts.map +1 -1
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.js +162 -1
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.js.map +1 -1
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api_types.d.ts +51 -30
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api_types.d.ts.map +1 -1
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/base_types.d.ts +7 -9
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/base_types.d.ts.map +1 -1
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/resource_types.d.ts +6 -8
- package/dist/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/resource_types.d.ts.map +1 -1
- package/dist/proto-grpc/google/protobuf/any.d.ts +2 -4
- package/dist/proto-grpc/google/protobuf/any.d.ts.map +1 -1
- package/dist/proto-grpc/google/protobuf/duration.d.ts +2 -4
- package/dist/proto-grpc/google/protobuf/duration.d.ts.map +1 -1
- package/dist/proto-grpc/google/protobuf/timestamp.d.ts +2 -4
- package/dist/proto-grpc/google/protobuf/timestamp.d.ts.map +1 -1
- package/dist/proto-grpc/google/rpc/code.d.ts +1 -2
- package/dist/proto-grpc/google/rpc/code.d.ts.map +1 -1
- package/dist/proto-rest/index.d.ts +6 -8
- package/dist/proto-rest/index.d.ts.map +1 -1
- package/dist/proto-rest/plapi.d.ts +241 -122
- package/dist/proto-rest/plapi.d.ts.map +1 -1
- package/dist/test/tcp-proxy.d.ts +3 -5
- package/dist/test/tcp-proxy.d.ts.map +1 -1
- package/dist/test/test_config.d.ts +13 -14
- package/dist/test/test_config.d.ts.map +1 -1
- package/package.json +7 -7
- package/src/core/client.ts +9 -0
- package/src/core/ll_client.ts +15 -0
- package/src/core/user_resources.ts +39 -0
- package/src/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client.ts +34 -3
- package/src/proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.ts +206 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ll_client.js","names":["GrpcPlApiClient","status","GrpcStatus"],"sources":["../../src/core/ll_client.ts"],"sourcesContent":["import { PlatformClient as GrpcPlApiClient } from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client\";\nimport type { ClientOptions, Interceptor } from \"@grpc/grpc-js\";\nimport {\n ChannelCredentials,\n InterceptingCall,\n status as GrpcStatus,\n compressionAlgorithms,\n} from \"@grpc/grpc-js\";\nimport type {\n AuthInformation,\n AuthOps,\n PlClientConfig,\n PlConnectionStatus,\n PlConnectionStatusListener,\n} from \"./config\";\nimport {\n plAddressToConfig,\n type wireProtocol,\n SUPPORTED_WIRE_PROTOCOLS,\n DEFAULT_LOGIN_TIMEOUT,\n deriveUnaryDeadline,\n smoothRtt,\n} from \"./config\";\nimport type { GrpcOptions } from \"@protobuf-ts/grpc-transport\";\nimport { GrpcTransport } from \"@protobuf-ts/grpc-transport\";\nimport { LLPlTransaction } from \"./ll_transaction\";\nimport { setResourceSignaturesRequired } from \"./types\";\nimport { parsePlJwt } from \"../util/pl\";\nimport { type Dispatcher, interceptors } from \"undici\";\nimport type { Middleware } from \"openapi-fetch\";\nimport { inferAuthRefreshTime } from \"./auth\";\nimport { hasCapability, type BackendCapability } from \"./capabilities\";\nimport { defaultHttpDispatcher } from \"@milaboratories/pl-http\";\nimport type { WireClientProvider, WireClientProviderFactory, WireConnection } from \"./wire\";\nimport { parseHttpAuth } from \"@milaboratories/pl-model-common\";\nimport type * as grpcTypes from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport {\n type PlApiPaths,\n type PlRestClientType,\n createClient,\n parseResponseError,\n} from \"../proto-rest\";\nimport { notEmpty, retry, withTimeout, type RetryOptions } from \"@milaboratories/ts-helpers\";\nimport { Code } from \"../proto-grpc/google/rpc/code\";\nimport { WebSocketBiDiStream } from \"./websocket_stream\";\nimport {\n AuthAPI_Role,\n TxAPI_ClientMessage,\n TxAPI_ServerMessage,\n} from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport type { MiLogger } from \"@milaboratories/ts-helpers\";\nimport { isAbortedError, isTransientCallFailure, isUnauthenticated } from \"./errors\";\nimport { Timestamp } from \"../proto-grpc/google/protobuf/timestamp\";\n\nexport interface PlCallOps {\n timeout?: number;\n abortSignal?: AbortSignal;\n}\n\n/** Bounded retry for idempotent unary calls. Deliberately short: these calls sit on the\n * connect path and gate the UI, so a few quick attempts beat a long grind. */\nconst IDEMPOTENT_RETRY_OPTIONS: RetryOptions = {\n type: \"exponentialBackoff\",\n maxAttempts: 4,\n initialDelay: 200,\n backoffMultiplier: 2,\n jitter: 0.3,\n maxDelay: 2_000,\n};\n\n// Parses leading \"<major>.<minor>.<patch>\" from a version string like\n// \"3.1.1\" or \"3.1.1-rc1\" and returns true if the parsed version is >= target.\n// Returns false for unparseable versions (safer to assume an old backend).\nfunction isVersionAtLeast(version: string, target: [number, number, number]): boolean {\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(version);\n if (!match) return false;\n const parsed: [number, number, number] = [Number(match[1]), Number(match[2]), Number(match[3])];\n for (let i = 0; i < 3; i++) {\n if (parsed[i] !== target[i]) return parsed[i] > target[i];\n }\n return true;\n}\n\n// Returns true iff `version` is strictly after the release tag `target`. Dev\n// builds (`git describe`-style, e.g. \"3.5.0-224-g0ca182\") are considered\n// AFTER the matching release tag — they include commits past the tag and so\n// have any change merged after it. Released versions with the same triplet\n// return false (we want the tag itself to be excluded).\n//\n// Examples for target [3,5,0]:\n// \"3.5.0\" → false (the tagged release)\n// \"3.5.0-224-g0ca182\" → true (dev build past the tag)\n// \"3.5.1\" → true\n// \"3.4.9\" → false\n// Returns false for unparseable versions.\nfunction isAfterVersion(version: string, target: [number, number, number]): boolean {\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(.*)$/.exec(version);\n if (!match) return false;\n const parsed: [number, number, number] = [Number(match[1]), Number(match[2]), Number(match[3])];\n const suffix = match[4];\n for (let i = 0; i < 3; i++) {\n if (parsed[i] !== target[i]) return parsed[i] > target[i];\n }\n return suffix !== \"\";\n}\n\nclass WireClientProviderImpl<Client> implements WireClientProvider<Client> {\n private client: Client | undefined = undefined;\n\n constructor(\n private readonly wireOpts: () => WireConnection,\n private readonly clientConstructor: (wireOpts: WireConnection) => Client,\n ) {}\n\n public reset(): void {\n this.client = undefined;\n }\n\n public get(): Client {\n if (this.client === undefined) this.client = this.clientConstructor(this.wireOpts());\n return this.client;\n }\n}\n\n/** Abstract out low level networking and authorization details */\nexport class LLPlClient implements WireClientProviderFactory {\n /** Initial authorization information */\n private authInformation?: AuthInformation;\n /** Will be executed by the client when it is required */\n private readonly onAuthUpdate?: (newInfo: AuthInformation) => void;\n /** Will be executed if auth-related error happens during normal client operation */\n private readonly onAuthError?: () => void;\n /** Will be executed by the client when it is required */\n private readonly onAuthRefreshProblem?: (error: unknown) => void;\n /** Threshold after which auth info refresh is required */\n private refreshTimestamp?: number;\n\n /** Cached Ping response. Populated by build() before it returns; refreshed by every later ping(). */\n private _serverInfo?: grpcTypes.MaintenanceAPI_Ping_Response;\n private _authMethodsSync?: grpcTypes.AuthAPI_ListMethods_Response;\n\n private _status: PlConnectionStatus = \"OK\";\n private authProbeInFlight = false;\n private readonly statusListener?: PlConnectionStatusListener;\n\n private _wireProto: wireProtocol = \"grpc\";\n private _wireConn!: WireConnection;\n\n /** The live GrpcOptions object handed to GrpcTransport. The transport keeps it by\n * reference and re-reads it on every call, so mutating `timeout` here retunes\n * subsequent deadlines without tearing down the connection. */\n private _grpcOptions?: GrpcOptions;\n\n /** Smoothed round-trip estimate in ms, from ping timings. Undefined until the first\n * successful ping, in which case the configured deadline is used as-is. */\n private _rttMs?: number;\n\n private readonly _restInterceptors: Dispatcher.DispatcherComposeInterceptor[];\n private readonly _restMiddlewares: Middleware[];\n private readonly _grpcInterceptors: Interceptor[];\n private readonly providers: WeakRef<WireClientProviderImpl<any>>[] = [];\n\n public readonly clientProvider: WireClientProvider<PlRestClientType | GrpcPlApiClient>;\n\n public readonly httpDispatcher: Dispatcher;\n\n public static async build(\n configOrAddress: PlClientConfig | string,\n ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n logger?: MiLogger;\n useAutoDetectWireProtocol?: boolean;\n } = {},\n ) {\n const conf =\n typeof configOrAddress === \"string\" ? plAddressToConfig(configOrAddress) : configOrAddress;\n\n const pl = new LLPlClient(conf, ops);\n\n // FIXME(rfiskov)[MILAB-5275]: Investigate why autodetect randomly fails; temporary turn it off.\n if (ops.useAutoDetectWireProtocol) {\n await pl.detectOptimalWireProtocol();\n }\n\n // Guarantee a ping happened so capability-gated paths (login, refresh) can branch synchronously.\n // In the autodetect path the loop's last successful ping already populated _serverInfo via the\n // side-effect in ping(); this fallback covers the path where autodetect is disabled.\n // Retried, not bare: this ping is the first contact with the server, so DNS and LB\n // warm-up land here. A single transient failure must not fail the whole connect.\n // (Not inside ping() itself: the autodetect path already wraps it in its own retry.)\n if (!pl._serverInfo) await pl.withIdempotentRetry(\"ping\", () => pl.ping());\n\n // Install the process-global signature-strictness flag based on backend version.\n setResourceSignaturesRequired(pl.supportsResourceSignatures);\n\n // Guarantee authMethods happened so client can make weighted decision on which auth method to use.\n if (!pl._authMethodsSync) await pl.authMethods();\n\n return pl;\n }\n\n private constructor(\n public readonly conf: PlClientConfig,\n private readonly ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n logger?: MiLogger;\n } = {},\n ) {\n const { auth, statusListener } = ops;\n\n if (auth !== undefined) {\n this.refreshTimestamp = inferAuthRefreshTime(\n auth.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n this.authInformation = auth.authInformation;\n this.onAuthUpdate = auth.onUpdate;\n this.onAuthRefreshProblem = auth.onUpdateError;\n this.onAuthError = auth.onAuthError;\n }\n\n this._restInterceptors = [];\n this._restMiddlewares = [];\n this._grpcInterceptors = [];\n\n if (auth !== undefined) {\n this._restInterceptors.push(this.createRestAuthInterceptor());\n this._grpcInterceptors.push(this.createGrpcAuthInterceptor());\n }\n this._restInterceptors.push(interceptors.retry({ statusCodes: [] })); // Handle errors with openapi-fetch middleware.\n this._restMiddlewares.push(this.createRestErrorMiddleware());\n this._grpcInterceptors.push(this.createGrpcErrorInterceptor());\n\n this.httpDispatcher = defaultHttpDispatcher(this.conf.httpProxy);\n if (this.conf.wireProtocol) {\n this._wireProto = this.conf.wireProtocol;\n }\n\n this.initWireConnection(this._wireProto);\n\n if (statusListener !== undefined) {\n this.statusListener = statusListener;\n statusListener(this._status);\n }\n\n this.clientProvider = this.createWireClientProvider((wireConn) => {\n if (wireConn.type === \"grpc\") {\n return new GrpcPlApiClient(wireConn.Transport);\n } else {\n return createClient<PlApiPaths>({\n hostAndPort: wireConn.Config.hostAndPort,\n ssl: wireConn.Config.ssl,\n dispatcher: wireConn.Dispatcher,\n middlewares: wireConn.Middlewares,\n });\n }\n });\n }\n\n private initWireConnection(protocol: wireProtocol) {\n switch (protocol) {\n case \"rest\":\n this.initRestConnection();\n return;\n case \"grpc\":\n this.initGrpcConnection(this.ops.shouldUseGzip ?? false);\n return;\n default:\n ((v: never) => {\n throw new Error(\n `Unsupported wire protocol '${v as string}'. Use one of: ${SUPPORTED_WIRE_PROTOCOLS.join(\", \")}`,\n );\n })(protocol);\n }\n }\n\n private initRestConnection(): void {\n const dispatcher = defaultHttpDispatcher(this.conf.grpcProxy, this._restInterceptors);\n this._replaceWireConnection({\n type: \"rest\",\n Config: this.conf,\n Dispatcher: dispatcher,\n Middlewares: this._restMiddlewares,\n });\n }\n\n /**\n * Initializes (or reinitializes) _grpcTransport\n * @param gzip - whether to enable gzip compression\n */\n private initGrpcConnection(gzip: boolean) {\n const clientOptions: ClientOptions = {\n \"grpc.keepalive_time_ms\": 30_000, // 30 seconds\n \"grpc.service_config_disable_resolution\": 1, // Disable DNS TXT lookups for service config\n // Raises the per-stream and connection-level HTTP/2 windows. Node's 64 KB default\n // caps a big single-stream read (project open) at window/RTT rather than link speed,\n // and a lost WINDOW_UPDATE can deadlock it under packet loss.\n \"grpc-node.flow_control_window\": 16 * 1024 * 1024, // 16 MiB\n interceptors: this._grpcInterceptors,\n };\n\n if (gzip) clientOptions[\"grpc.default_compression_algorithm\"] = compressionAlgorithms.gzip;\n\n //\n // Leaving it here for now\n // https://github.com/grpc/grpc-node/issues/2788\n //\n // We should implement message pooling algorithm to overcome hardcoded NO_DELAY behaviour\n // of HTTP/2 and allow our small messages to batch together.\n //\n const grpcOptions: GrpcOptions = {\n host: this.conf.hostAndPort,\n timeout: this.unaryDeadline(),\n channelCredentials: this.conf.ssl\n ? ChannelCredentials.createSsl()\n : ChannelCredentials.createInsecure(),\n clientOptions,\n };\n\n const grpcProxy =\n typeof this.conf.grpcProxy === \"string\" ? { url: this.conf.grpcProxy } : this.conf.grpcProxy;\n\n if (grpcProxy?.url) {\n const url = new URL(grpcProxy.url);\n if (grpcProxy.auth) {\n const parsed = parseHttpAuth(grpcProxy.auth);\n if (parsed.scheme !== \"Basic\") {\n throw new Error(`Unsupported auth scheme: ${parsed.scheme as string}.`);\n }\n url.username = parsed.username;\n url.password = parsed.password;\n }\n process.env.grpc_proxy = url.toString();\n } else {\n delete process.env.grpc_proxy;\n }\n\n this._grpcOptions = grpcOptions;\n this._replaceWireConnection({ type: \"grpc\", Transport: new GrpcTransport(grpcOptions) });\n }\n\n /** Unary deadline derived from the observed RTT, floored by the configured value so\n * a fast link behaves exactly as before, and capped by\n * {@link MAX_ADAPTIVE_REQUEST_TIMEOUT}. */\n private unaryDeadline(): number {\n return deriveUnaryDeadline(this.conf.defaultRequestTimeout, this._rttMs);\n }\n\n /** Folds a fresh round-trip sample into the estimate and retunes the live unary\n * deadline. Called after every successful ping. */\n private recordRtt(sampleMs: number): void {\n this._rttMs = smoothRtt(this._rttMs, sampleMs);\n\n if (this._grpcOptions) {\n const next = this.unaryDeadline();\n if (next !== this._grpcOptions.timeout) {\n this.ops.logger?.info(\n `Unary deadline retuned to ${next}ms (rtt estimate ${Math.round(this._rttMs)}ms)`,\n );\n this._grpcOptions.timeout = next;\n }\n }\n }\n\n /** Smoothed round-trip estimate in ms, or undefined before the first ping. */\n public get rttEstimateMs(): number | undefined {\n return this._rttMs;\n }\n\n /** Runs an idempotent unary call with a bounded retry on transient transport failures.\n * Safe only for calls with no side effects, since a retry may duplicate the request. */\n private async withIdempotentRetry<T>(name: string, cb: () => Promise<T>): Promise<T> {\n return await retry(cb, IDEMPOTENT_RETRY_OPTIONS, (e: unknown) => {\n if (!isTransientCallFailure(e)) return false;\n this.ops.logger?.info(`${name}: transient failure, retrying. err=${String(e)}`);\n return true;\n });\n }\n\n private _replaceWireConnection(newConn: WireConnection): void {\n const oldConn = this._wireConn;\n this._wireConn = newConn;\n this._wireProto = newConn.type;\n\n // Reset all providers to let them reinitialize their clients\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n // at the same time we need to remove providers that are no longer valid\n this.providers.splice(i, 1);\n i--;\n } else {\n provider.reset();\n }\n }\n\n if (oldConn !== undefined && oldConn.type === \"grpc\") oldConn.Transport.close();\n }\n\n private providerCleanupCounter = 0;\n\n /**\n * Creates a provider for a grpc client. Returned provider will create fresh client whenever the underlying transport is reset.\n *\n * @param clientConstructor - a factory function that creates a grpc client\n */\n public createWireClientProvider<Client>(\n clientConstructor: (transport: WireConnection) => Client,\n ): WireClientProvider<Client> {\n // We need to cleanup providers periodically to avoid memory leaks.\n // This is a simple heuristic to avoid memory leaks.\n // We could use a more sophisticated algorithm, but this is good enough for now.\n this.providerCleanupCounter++;\n if (this.providerCleanupCounter >= 16) {\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n this.providers.splice(i, 1);\n i--;\n }\n }\n this.providerCleanupCounter = 0;\n }\n\n const provider = new WireClientProviderImpl<Client>(() => this._wireConn, clientConstructor);\n this.providers.push(new WeakRef(provider));\n return provider;\n }\n\n public get wireConnection(): WireConnection {\n return this._wireConn;\n }\n\n public get wireProtocol(): wireProtocol | undefined {\n return this._wireProto;\n }\n\n /** Returns true if client is authenticated. Even with anonymous auth information\n * connection is considered authenticated. Unauthenticated clients are used for\n * login and similar tasks, see {@link UnauthenticatedPlClient}. */\n public get authenticated(): boolean {\n return this.authInformation !== undefined;\n }\n\n /** null means anonymous connection */\n public get authUser(): string | null {\n if (!this.authenticated) throw new Error(\"Client is not authenticated\");\n if (this.authInformation?.jwtToken) {\n if (this.hasCapability(\"auth:v2\")) {\n return parsePlJwt(this.authInformation?.jwtToken).sub;\n }\n return parsePlJwt(this.authInformation?.jwtToken).user.login;\n } else return null;\n }\n\n private updateStatus(newStatus: PlConnectionStatus) {\n process.nextTick(() => {\n if (this._status !== newStatus) {\n this._status = newStatus;\n if (this.statusListener !== undefined) this.statusListener(this._status);\n if (newStatus === \"Unauthenticated\" && this.onAuthError !== undefined) this.onAuthError();\n }\n });\n }\n\n /**\n * UNAUTHENTICATED covers both a dead session (must reset) and a per-request authorization failure\n * such as a revoked resource signature (must not). Disambiguate by probing getSessionInfo — an\n * authenticated call with no resource signature: success means the session is alive and the failure\n * was resource-level; a probe that is itself Unauthenticated means real auth loss. Coalesced via\n * authProbeInFlight so a burst of failures costs one probe.\n */\n private async verifyThenMaybeEscalateUnauthenticated(): Promise<void> {\n if (this._status !== \"OK\" || this.authProbeInFlight) return;\n this.authProbeInFlight = true;\n try {\n await this.getSessionInfo();\n } catch (e) {\n if (isUnauthenticated(e)) this.updateStatus(\"Unauthenticated\");\n } finally {\n this.authProbeInFlight = false;\n }\n }\n\n public get status(): PlConnectionStatus {\n return this._status;\n }\n\n private authRefreshInProgress: boolean = false;\n\n private refreshAuthInformationIfNeeded(): void {\n if (\n this.refreshTimestamp === undefined ||\n Date.now() < this.refreshTimestamp ||\n this.authRefreshInProgress ||\n this._status === \"Unauthenticated\"\n )\n return;\n\n // Running refresh in background`\n this.authRefreshInProgress = true;\n void (async () => {\n try {\n const ttl = BigInt(this.conf.authTTLSeconds);\n const token = this.hasCapability(\"auth:v2\")\n ? await this.refreshToken({ ttlSeconds: ttl })\n : await this.getJwtToken(ttl);\n this.authInformation = { jwtToken: token };\n this.refreshTimestamp = inferAuthRefreshTime(\n this.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n if (this.onAuthUpdate) this.onAuthUpdate(this.authInformation);\n } catch (e: unknown) {\n if (this.onAuthRefreshProblem) this.onAuthRefreshProblem(e);\n } finally {\n this.authRefreshInProgress = false;\n }\n })();\n }\n\n /**\n * Creates middleware that parses error responses and handles them centrally.\n * This middleware runs before openapi-fetch parses the response, so we need to\n * manually parse the response body for error responses.\n */\n private createRestErrorMiddleware(): Middleware {\n return {\n onResponse: async ({ request: _request, response, options: _options }) => {\n const { body, ...resOptions } = response;\n\n if ([502, 503, 504].includes(response.status)) {\n // Service unavailable, bad gateway, gateway timeout\n this.updateStatus(\"Disconnected\");\n return new Response(body, { ...resOptions, status: response.status });\n }\n\n const respErr = await parseResponseError(response);\n if (!respErr.error) {\n // No error: nice!\n return new Response(respErr.origBody ?? body, { ...resOptions, status: response.status });\n }\n\n if (typeof respErr.error === \"string\") {\n // Non-standard error or normal response: let later middleware to deal wit it.\n return new Response(respErr.error, { ...resOptions, status: response.status });\n }\n\n if (respErr.error.code === Code.UNAUTHENTICATED) {\n void this.verifyThenMaybeEscalateUnauthenticated();\n }\n\n // Let later middleware to deal with standard gRPC error.\n return new Response(respErr.origBody, { ...resOptions, status: response.status });\n },\n };\n }\n\n /** Detects certain errors and update client status accordingly when using GRPC wire connection */\n private createGrpcErrorInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n next(metadata, {\n onReceiveStatus: (status, next) => {\n if (status.code == GrpcStatus.UNAUTHENTICATED)\n // (!!!) don't change to \"===\"\n void this.verifyThenMaybeEscalateUnauthenticated();\n if (status.code == GrpcStatus.UNAVAILABLE)\n // (!!!) don't change to \"===\"\n this.updateStatus(\"Disconnected\");\n next(status);\n },\n });\n },\n });\n };\n }\n\n private createRestAuthInterceptor(): Dispatcher.DispatcherComposeInterceptor {\n return (dispatch) => {\n return (options, handler) => {\n if (this.authInformation?.jwtToken !== undefined) {\n // TODO: check this magic really works and gets called\n options.headers = {\n ...options.headers,\n authorization: \"Bearer \" + this.authInformation.jwtToken,\n };\n this.refreshAuthInformationIfNeeded();\n }\n\n return dispatch(options, handler);\n };\n };\n }\n\n /** Injects authentication information if needed */\n private createGrpcAuthInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n if (this.authInformation?.jwtToken !== undefined) {\n metadata.set(\"authorization\", \"Bearer \" + this.authInformation.jwtToken);\n this.refreshAuthInformationIfNeeded();\n next(metadata, listener);\n } else {\n next(metadata, listener);\n }\n },\n });\n };\n }\n\n public async getJwtToken(\n ttlSeconds: bigint,\n options?: { authorization?: string; role?: AuthAPI_Role },\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const role = options?.role ?? AuthAPI_Role.UNSPECIFIED;\n\n if (cl instanceof GrpcPlApiClient) {\n const meta: Record<string, string> = {};\n if (options?.authorization) meta.authorization = options.authorization;\n return (\n await cl.getJWTToken(\n {\n expiration: { seconds: ttlSeconds, nanos: 0 },\n requestedRole: role,\n },\n { meta, timeout: DEFAULT_LOGIN_TIMEOUT },\n ).response\n ).token;\n } else {\n const headers: Record<string, string> = {};\n if (options?.authorization) headers.authorization = options.authorization;\n const resp = cl.POST(\"/v1/auth/jwt-token\", {\n body: { expiration: `${ttlSeconds}s`, requestedRole: role },\n headers,\n });\n return notEmpty((await resp).data, \"REST: empty response for JWT token request\").token;\n }\n }\n\n /** Login via username/password. Returns a fresh JWT. Backend creates a new session per call. */\n public async loginBasic(\n user: string,\n password: string,\n opts: { ttlSeconds?: bigint; role?: AuthAPI_Role } = {},\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const role = opts.role ?? AuthAPI_Role.UNSPECIFIED;\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login(\n {\n credentials: {\n oneofKind: \"basic\",\n basic: { login: user, password },\n },\n expiration: { seconds: ttl, nanos: 0 },\n requestedRole: role,\n },\n { timeout: DEFAULT_LOGIN_TIMEOUT },\n ).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n // openapi-typescript generated all body fields as required, but Login.Request\n // has a credentials oneof — only one of `basic`/`token` is sent. Cast around it.\n body: {\n basic: { login: user, password },\n expiration: `${ttl}s`,\n requestedRole: role,\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for login request\").token;\n }\n }\n\n /** Login via opaque bearer token (controller pre-shared secret, OIDC id-token, etc.).\n * String input is UTF-8 encoded. Returns a fresh Platforma JWT. */\n public async loginWithToken(\n token: Uint8Array | string,\n opts: { ttlSeconds?: bigint; role?: AuthAPI_Role } = {},\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const role = opts.role ?? AuthAPI_Role.UNSPECIFIED;\n const bytes = typeof token === \"string\" ? Buffer.from(token, \"utf8\") : token;\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login(\n {\n credentials: {\n oneofKind: \"token\",\n token: { token: bytes },\n },\n expiration: { seconds: ttl, nanos: 0 },\n requestedRole: role,\n },\n { timeout: DEFAULT_LOGIN_TIMEOUT },\n ).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n // openapi-typescript marks all body fields as required, but Login.Request has a oneof.\n // REST encodes `bytes` as a base64 string.\n body: {\n token: { token: Buffer.from(bytes).toString(\"base64\") },\n expiration: `${ttl}s`,\n requestedRole: role,\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for login request\").token;\n }\n }\n\n /** Login via SSO: forwards the raw IdP /token JSON body to the backend.\n * Backend validates signature + nonce + audience and mints a Platforma JWT. */\n public async loginSSO(tokenResponse: Uint8Array): Promise<string> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login(\n {\n credentials: {\n oneofKind: \"sso\",\n sso: { tokenResponse },\n },\n },\n { timeout: DEFAULT_LOGIN_TIMEOUT },\n ).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n body: {\n sso: { tokenResponse: Buffer.from(tokenResponse).toString(\"base64\") },\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for SSO login request\").token;\n }\n }\n\n /** Request a one-time PKCE nonce + its expiry from the backend. The desktop is\n * expected to place the nonce verbatim into the OIDC auth-request before\n * redirecting to the IdP; the backend enforces the expiry on {@link loginSSO}. */\n public async beginSSOLogin(): Promise<{ nonce: string; expiresAt: Date; clientSecret?: string }> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n const resp = (await cl.beginSSOLogin({}).response).flow;\n if (resp.oneofKind !== \"publicPkce\") {\n throw new Error(`beginSSOLogin: unsupported flow ${resp.oneofKind}`);\n }\n const exp = notEmpty(resp.publicPkce.expiresAt, \"beginSSOLogin: missing expiresAt\");\n return {\n nonce: resp.publicPkce.nonce,\n expiresAt: Timestamp.toDate(exp),\n clientSecret: resp.publicPkce.clientSecret,\n };\n } else {\n const wsResponse = notEmpty(\n (await cl.POST(\"/v1/auth/sso/begin-login\", { body: {} })).data,\n \"REST: empty response for beginSSOLogin request\",\n );\n const pkce = notEmpty(wsResponse.publicPkce, \"REST: missing publicPkce in beginSSOLogin\");\n return {\n nonce: pkce.nonce,\n expiresAt: new Date(pkce.expiresAt),\n clientSecret: pkce.clientSecret,\n };\n }\n }\n\n /** Refresh the current JWT, preserving session id and role. */\n public async refreshToken(opts: { ttlSeconds?: bigint } = {}): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const currentToken = notEmpty(\n this.authInformation?.jwtToken,\n \"refreshToken called without a current JWT\",\n );\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.refreshToken(\n {\n token: currentToken,\n expiration: { seconds: ttl, nanos: 0 },\n },\n { timeout: DEFAULT_LOGIN_TIMEOUT },\n ).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/refresh\", {\n body: { token: currentToken, expiration: `${ttl}s` },\n });\n return notEmpty((await resp).data, \"REST: empty response for refresh request\").token;\n }\n }\n\n public async ping(): Promise<grpcTypes.MaintenanceAPI_Ping_Response> {\n const cl = this.clientProvider.get();\n let resp: grpcTypes.MaintenanceAPI_Ping_Response;\n // Ping is the cheapest call we make, so its duration is our best RTT proxy.\n const startedAt = performance.now();\n if (cl instanceof GrpcPlApiClient) {\n resp = (await cl.ping({})).response;\n } else {\n // The REST ping response predates the `capabilities` field (proto field 9).\n // Old servers omit it; treat absence as empty capability list.\n const pingData = notEmpty(\n (await cl.GET(\"/v1/ping\")).data,\n \"REST: empty response for ping request\",\n );\n resp = {\n ...(pingData as unknown as grpcTypes.MaintenanceAPI_Ping_Response),\n capabilities: (pingData as any).capabilities ?? [],\n };\n }\n this.recordRtt(performance.now() - startedAt);\n this._serverInfo = resp;\n return resp;\n }\n\n /** Cached Ping response. Always populated post-build(); throws if accessed earlier. */\n public get serverInfo(): grpcTypes.MaintenanceAPI_Ping_Response {\n if (!this._serverInfo) {\n throw new Error(\"LLPlClient.serverInfo accessed before build() completed\");\n }\n return this._serverInfo;\n }\n\n /** Synchronous capability check against the cached Ping response. */\n public hasCapability(capability: BackendCapability): boolean {\n return hasCapability(this.serverInfo.capabilities, capability);\n }\n\n /** True if the backend produces signed resource ids (and accepts the\n * setDefaultColor TX request). Tagged at 3.3.0 — backends older than this\n * return resources without signatures and reject color-proof requests. */\n public get supportsResourceSignatures(): boolean {\n return isVersionAtLeast(this.serverInfo.coreVersion, [3, 3, 0]);\n }\n\n /**\n * True if the backend honors per-file `permissions` on workdir fill rules, so\n * `exec.builder().writeFile/addFile({ writable: true })` takes effect. When false\n * the requested mode is ignored and files land at the canonical archive perm.\n *\n * [3, 5, 0] excludes the tagged 3.5.0 release but includes dev builds past the\n * tag (e.g. \"3.5.0-224-g0ca182\"), which is where the support lands.\n */\n public get supportsWritableWorkdirFiles(): boolean {\n return isAfterVersion(this.serverInfo.coreVersion, [3, 5, 0]);\n }\n\n /**\n * Detects the best available wire protocol.\n * If wireProtocol is explicitly configured, does nothing.\n * Otherwise probes the current protocol via ping; if it fails, switches to the alternative.\n */\n private async detectOptimalWireProtocol() {\n if (this.conf.wireProtocol) {\n return;\n }\n\n // Each retry is:\n // - ping request timeout (100 to 3_000ms)\n // - backoff delay (30 to 500ms)\n //\n // 30 attempts are ~43 seconds of overall waiting time.\n // Think twice on overall time this thing takes to complete when changing these parameters.\n // It may block UI when connecting to the server and loading projects list.\n const pingTimeoutFactor = 1.3;\n const maxPingTimeoutMs = 3_000;\n const retryOptions: RetryOptions = {\n type: \"exponentialBackoff\",\n maxAttempts: 30,\n initialDelay: 30,\n backoffMultiplier: 1.3,\n jitter: 0.2,\n maxDelay: 500,\n };\n\n let attempt = 1;\n let pingTimeoutMs = 100;\n await retry(\n () => withTimeout(this.ping(), pingTimeoutMs),\n retryOptions,\n (e: unknown) => {\n if (isAbortedError(e)) {\n this.ops.logger?.info(\n `Wire proto autodetect: ping timed out after ${pingTimeoutMs}ms: attempt=${attempt}, wire=${this._wireProto}`,\n );\n\n if (attempt % 2 === 0) {\n // We have 2 wire protocols to check. Increase timeout each 2 attempts.\n pingTimeoutMs = Math.min(\n Math.round(pingTimeoutMs * pingTimeoutFactor),\n maxPingTimeoutMs,\n );\n }\n } else {\n this.ops.logger?.info(\n `Wire proto autodetect: ping failed: attempt=${attempt}, wire=${this._wireProto}, err=${String(e)}`,\n );\n }\n\n attempt++;\n const protocol = this._wireProto === \"grpc\" ? \"rest\" : \"grpc\";\n this.ops.logger?.info(\n `Wire protocol autodetect next attempt: will try wire '${protocol}' with timeout ${pingTimeoutMs}ms`,\n );\n this.initWireConnection(protocol);\n return true;\n },\n );\n }\n\n public async license(): Promise<grpcTypes.MaintenanceAPI_License_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.license({})).response;\n } else {\n const resp = notEmpty(\n (await cl.GET(\"/v1/license\")).data,\n \"REST: empty response for license request\",\n );\n return {\n status: resp.status,\n isOk: resp.isOk,\n responseBody: Uint8Array.from(Buffer.from(resp.responseBody)),\n };\n }\n }\n\n public async authMethods(): Promise<grpcTypes.AuthAPI_ListMethods_Response> {\n const cl = this.clientProvider.get();\n let resp: grpcTypes.AuthAPI_ListMethods_Response;\n if (cl instanceof GrpcPlApiClient) {\n resp = (await cl.authMethods({})).response;\n } else {\n const wsResponse = notEmpty(\n (await cl.GET(\"/v1/auth/methods\")).data,\n \"REST: empty response for auth methods request\",\n );\n // OpenAPI schema flattens the protobuf oneof into `{ basic?, token? }`,\n // while protobuf-ts models it as a discriminated union. Reshape per item.\n resp = {\n methods: (wsResponse.methods ?? []).map((m): grpcTypes.AuthAPI_ListMethods_MethodInfo => {\n const base = { id: m.id, description: m.description };\n if (m.basic !== undefined) {\n return { ...base, method: { oneofKind: \"basic\", basic: m.basic } };\n }\n if (m.token !== undefined) {\n return { ...base, method: { oneofKind: \"token\", token: m.token } };\n }\n if (m.sso !== undefined) {\n return { ...base, method: { oneofKind: \"sso\", sso: m.sso } };\n }\n return { ...base, method: { oneofKind: undefined } };\n }),\n };\n }\n\n this._authMethodsSync = resp;\n return resp;\n }\n\n public get authMethodsSync(): grpcTypes.AuthAPI_ListMethods_Response {\n if (!this._authMethodsSync) {\n throw new Error(\"LLPlClient.authMethodsSync accessed before build() completed\");\n }\n return this._authMethodsSync;\n }\n\n public async getUserRoot(\n opts: { login?: string; createIfNotExists?: boolean } = {},\n ): Promise<grpcTypes.AuthAPI_GetUserRoot_Response> {\n // Retryable even with createIfNotExists: the call is get-or-create keyed on login, so a\n // second attempt returns the existing root rather than making another one.\n return await this.withIdempotentRetry(\"getUserRoot\", () => this.getUserRootOnce(opts));\n }\n\n private async getUserRootOnce(\n opts: { login?: string; createIfNotExists?: boolean } = {},\n ): Promise<grpcTypes.AuthAPI_GetUserRoot_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.getUserRoot({\n login: opts.login ?? \"\",\n createIfNotExists: opts.createIfNotExists ?? false,\n })\n ).response;\n } else {\n const resp = notEmpty(\n (\n await cl.POST(\"/v1/auth/user-root\", {\n body: {\n login: opts.login ?? \"\",\n createIfNotExists: opts.createIfNotExists ?? false,\n },\n })\n ).data,\n \"REST: empty response for getUserRoot request\",\n );\n return {\n userRoot: resp.userRoot\n ? {\n resourceId: BigInt(resp.userRoot.resourceId),\n resourceSignature: Uint8Array.from(\n Buffer.from(resp.userRoot.resourceSignature, \"base64\"),\n ),\n }\n : undefined,\n };\n }\n }\n\n public async listUserResources(\n opts: { login?: string; startFrom?: bigint; limit?: number } = {},\n ): Promise<grpcTypes.AuthAPI_ListUserResources_Response[]> {\n const cl = this.clientProvider.get();\n\n if (!(cl instanceof GrpcPlApiClient)) {\n throw new Error(\"ListUserResources requires gRPC wire protocol; REST is not supported\");\n }\n\n const call = cl.listUserResources({\n login: opts.login ?? \"\",\n startFrom: opts.startFrom ?? 0n,\n limit: opts.limit ?? 0,\n });\n const responses: grpcTypes.AuthAPI_ListUserResources_Response[] = [];\n for await (const msg of call.responses) {\n responses.push(msg);\n }\n return responses;\n }\n\n /** Returns the authenticated caller's session id and effective role.\n * Models the {@link getUserRoot} wrapper: gRPC unary with a REST fallback. */\n public async getSessionInfo(): Promise<grpcTypes.AuthAPI_GetSessionInfo_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.getSessionInfo({})).response;\n } else {\n const resp = notEmpty(\n (await cl.POST(\"/v1/auth/session-info\", { body: {} })).data,\n \"REST: empty response for getSessionInfo request\",\n );\n return {\n sessionId: Uint8Array.from(Buffer.from(resp.sessionId, \"base64\")),\n role: resp.role as AuthAPI_Role,\n };\n }\n }\n\n /** Lists the users known to the server — the recipient picker's source. A user\n * becomes known on first login; provisioned users who have never logged in do not\n * appear. gRPC-only (unary, no REST binding). */\n public async listUsers(): Promise<grpcTypes.AuthAPI_User[]> {\n const cl = this.clientProvider.get();\n\n if (!(cl instanceof GrpcPlApiClient)) {\n throw new Error(\"ListUsers requires gRPC wire protocol; REST is not supported\");\n }\n\n return (await cl.listUsers({})).response.users;\n }\n\n public async txSync(txId: bigint): Promise<void> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n await cl.txSync({ txId: BigInt(txId) });\n } else {\n await cl.POST(\"/v1/tx-sync\", { body: { txId: txId.toString() } });\n }\n }\n\n createTx(rw: boolean, ops: PlCallOps = {}): LLPlTransaction {\n return new LLPlTransaction((abortSignal) => {\n let totalAbortSignal = abortSignal;\n if (ops.abortSignal) totalAbortSignal = AbortSignal.any([totalAbortSignal, ops.abortSignal]);\n\n const timeout =\n ops.timeout ??\n (rw ? this.conf.defaultRWTransactionTimeout : this.conf.defaultROTransactionTimeout);\n\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return cl.tx({\n abort: totalAbortSignal,\n timeout,\n });\n }\n\n const wireConn = this.wireConnection;\n if (wireConn.type === \"rest\") {\n // For REST/WebSocket protocol, timeout needs to be converted to AbortSignal\n if (timeout !== undefined) {\n totalAbortSignal = AbortSignal.any([totalAbortSignal, AbortSignal.timeout(timeout)]);\n }\n\n // The gRPC transport has the auth interceptor that already handles it, but here we need to refresh the auth information to be safe.\n this.refreshAuthInformationIfNeeded();\n\n const wsUrl = this.conf.ssl\n ? `wss://${this.conf.hostAndPort}/v1/ws/tx`\n : `ws://${this.conf.hostAndPort}/v1/ws/tx`;\n\n return new WebSocketBiDiStream(\n wsUrl,\n (msg) => TxAPI_ClientMessage.toBinary(msg),\n (data) => TxAPI_ServerMessage.fromBinary(new Uint8Array(data)),\n {\n abortSignal: totalAbortSignal,\n jwtToken: this.authInformation?.jwtToken,\n dispatcher: wireConn.Dispatcher,\n\n onComplete: async (stream) =>\n stream.requests.send({\n // Ask server to gracefully close the stream on its side, if not done yet.\n requestId: 0,\n request: { oneofKind: \"streamClose\", streamClose: {} },\n }),\n },\n );\n }\n\n throw new Error(`transactions are not supported for wire protocol ${this._wireProto}`);\n });\n }\n\n /** Closes underlying transport */\n public async close() {\n if (this.wireConnection.type === \"grpc\") {\n this.wireConnection.Transport.close();\n } else {\n // TODO: close all WS connections\n }\n await this.httpDispatcher.destroy();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA6DA,MAAM,2BAAyC;CAC7C,MAAM;CACN,aAAa;CACb,cAAc;CACd,mBAAmB;CACnB,QAAQ;CACR,UAAU;AACZ;AAKA,SAAS,iBAAiB,SAAiB,QAA2C;CACpF,MAAM,QAAQ,yBAAyB,KAAK,OAAO;CACnD,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,SAAmC;EAAC,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;CAAC;CAC9F,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KACrB,IAAI,OAAO,OAAO,OAAO,IAAI,OAAO,OAAO,KAAK,OAAO;CAEzD,OAAO;AACT;AAcA,SAAS,eAAe,SAAiB,QAA2C;CAClF,MAAM,QAAQ,8BAA8B,KAAK,OAAO;CACxD,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,SAAmC;EAAC,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;CAAC;CAC9F,MAAM,SAAS,MAAM;CACrB,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KACrB,IAAI,OAAO,OAAO,OAAO,IAAI,OAAO,OAAO,KAAK,OAAO;CAEzD,OAAO,WAAW;AACpB;AAEA,IAAM,yBAAN,MAA2E;CAItD;CAC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M,KAAK,KAAK,eAAe,IAAI;GACnC,IAAI,cAAcA,gBAChB,OAAO,GAAG,GAAG;IACX,OAAO;IACP;GACF,CAAC;GAGH,MAAM,WAAW,KAAK;GACtB,IAAI,SAAS,SAAS,QAAQ;IAE5B,IAAI,YAAY,KAAA,GACd,mBAAmB,YAAY,IAAI,CAAC,kBAAkB,YAAY,QAAQ,OAAO,CAAC,CAAC;IAIrF,KAAK,+BAA+B;IAMpC,OAAO,IAAI,oBAJG,KAAK,KAAK,MACpB,SAAS,KAAK,KAAK,YAAY,aAC/B,QAAQ,KAAK,KAAK,YAAY,aAI/B,QAAQ,oBAAoB,SAAS,GAAG,IACxC,SAAS,oBAAoB,WAAW,IAAI,WAAW,IAAI,CAAC,GAC7D;KACE,aAAa;KACb,UAAU,KAAK,iBAAiB;KAChC,YAAY,SAAS;KAErB,YAAY,OAAO,WACjB,OAAO,SAAS,KAAK;MAEnB,WAAW;MACX,SAAS;OAAE,WAAW;OAAe,aAAa,CAAC;MAAE;KACvD,CAAC;IACL,CACF;GACF;GAEA,MAAM,IAAI,MAAM,oDAAoD,KAAK,YAAY;EACvF,CAAC;CACH;;CAGA,MAAa,QAAQ;EACnB,IAAI,KAAK,eAAe,SAAS,QAC/B,KAAK,eAAe,UAAU,MAAM;EAItC,MAAM,KAAK,eAAe,QAAQ;CACpC;AACF"}
|
|
1
|
+
{"version":3,"file":"ll_client.js","names":["GrpcPlApiClient","status","GrpcStatus"],"sources":["../../src/core/ll_client.ts"],"sourcesContent":["import { PlatformClient as GrpcPlApiClient } from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.client\";\nimport type { ClientOptions, Interceptor } from \"@grpc/grpc-js\";\nimport {\n ChannelCredentials,\n InterceptingCall,\n status as GrpcStatus,\n compressionAlgorithms,\n} from \"@grpc/grpc-js\";\nimport type {\n AuthInformation,\n AuthOps,\n PlClientConfig,\n PlConnectionStatus,\n PlConnectionStatusListener,\n} from \"./config\";\nimport {\n plAddressToConfig,\n type wireProtocol,\n SUPPORTED_WIRE_PROTOCOLS,\n DEFAULT_LOGIN_TIMEOUT,\n deriveUnaryDeadline,\n smoothRtt,\n} from \"./config\";\nimport type { GrpcOptions } from \"@protobuf-ts/grpc-transport\";\nimport { GrpcTransport } from \"@protobuf-ts/grpc-transport\";\nimport { LLPlTransaction } from \"./ll_transaction\";\nimport { setResourceSignaturesRequired } from \"./types\";\nimport { parsePlJwt } from \"../util/pl\";\nimport { type Dispatcher, interceptors } from \"undici\";\nimport type { Middleware } from \"openapi-fetch\";\nimport { inferAuthRefreshTime } from \"./auth\";\nimport { hasCapability, type BackendCapability } from \"./capabilities\";\nimport { defaultHttpDispatcher } from \"@milaboratories/pl-http\";\nimport type { WireClientProvider, WireClientProviderFactory, WireConnection } from \"./wire\";\nimport { parseHttpAuth } from \"@milaboratories/pl-model-common\";\nimport type * as grpcTypes from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport {\n type PlApiPaths,\n type PlRestClientType,\n createClient,\n parseResponseError,\n} from \"../proto-rest\";\nimport { notEmpty, retry, withTimeout, type RetryOptions } from \"@milaboratories/ts-helpers\";\nimport { Code } from \"../proto-grpc/google/rpc/code\";\nimport { WebSocketBiDiStream } from \"./websocket_stream\";\nimport {\n AuthAPI_Role,\n TxAPI_ClientMessage,\n TxAPI_ServerMessage,\n} from \"../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api\";\nimport type { MiLogger } from \"@milaboratories/ts-helpers\";\nimport { isAbortedError, isTransientCallFailure, isUnauthenticated } from \"./errors\";\nimport { Timestamp } from \"../proto-grpc/google/protobuf/timestamp\";\n\nexport interface PlCallOps {\n timeout?: number;\n abortSignal?: AbortSignal;\n}\n\n/** Bounded retry for idempotent unary calls. Deliberately short: these calls sit on the\n * connect path and gate the UI, so a few quick attempts beat a long grind. */\nconst IDEMPOTENT_RETRY_OPTIONS: RetryOptions = {\n type: \"exponentialBackoff\",\n maxAttempts: 4,\n initialDelay: 200,\n backoffMultiplier: 2,\n jitter: 0.3,\n maxDelay: 2_000,\n};\n\n// Parses leading \"<major>.<minor>.<patch>\" from a version string like\n// \"3.1.1\" or \"3.1.1-rc1\" and returns true if the parsed version is >= target.\n// Returns false for unparseable versions (safer to assume an old backend).\nfunction isVersionAtLeast(version: string, target: [number, number, number]): boolean {\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(version);\n if (!match) return false;\n const parsed: [number, number, number] = [Number(match[1]), Number(match[2]), Number(match[3])];\n for (let i = 0; i < 3; i++) {\n if (parsed[i] !== target[i]) return parsed[i] > target[i];\n }\n return true;\n}\n\n// Returns true iff `version` is strictly after the release tag `target`. Dev\n// builds (`git describe`-style, e.g. \"3.5.0-224-g0ca182\") are considered\n// AFTER the matching release tag — they include commits past the tag and so\n// have any change merged after it. Released versions with the same triplet\n// return false (we want the tag itself to be excluded).\n//\n// Examples for target [3,5,0]:\n// \"3.5.0\" → false (the tagged release)\n// \"3.5.0-224-g0ca182\" → true (dev build past the tag)\n// \"3.5.1\" → true\n// \"3.4.9\" → false\n// Returns false for unparseable versions.\nfunction isAfterVersion(version: string, target: [number, number, number]): boolean {\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(.*)$/.exec(version);\n if (!match) return false;\n const parsed: [number, number, number] = [Number(match[1]), Number(match[2]), Number(match[3])];\n const suffix = match[4];\n for (let i = 0; i < 3; i++) {\n if (parsed[i] !== target[i]) return parsed[i] > target[i];\n }\n return suffix !== \"\";\n}\n\nclass WireClientProviderImpl<Client> implements WireClientProvider<Client> {\n private client: Client | undefined = undefined;\n\n constructor(\n private readonly wireOpts: () => WireConnection,\n private readonly clientConstructor: (wireOpts: WireConnection) => Client,\n ) {}\n\n public reset(): void {\n this.client = undefined;\n }\n\n public get(): Client {\n if (this.client === undefined) this.client = this.clientConstructor(this.wireOpts());\n return this.client;\n }\n}\n\n/** Abstract out low level networking and authorization details */\nexport class LLPlClient implements WireClientProviderFactory {\n /** Initial authorization information */\n private authInformation?: AuthInformation;\n /** Will be executed by the client when it is required */\n private readonly onAuthUpdate?: (newInfo: AuthInformation) => void;\n /** Will be executed if auth-related error happens during normal client operation */\n private readonly onAuthError?: () => void;\n /** Will be executed by the client when it is required */\n private readonly onAuthRefreshProblem?: (error: unknown) => void;\n /** Threshold after which auth info refresh is required */\n private refreshTimestamp?: number;\n\n /** Cached Ping response. Populated by build() before it returns; refreshed by every later ping(). */\n private _serverInfo?: grpcTypes.MaintenanceAPI_Ping_Response;\n private _authMethodsSync?: grpcTypes.AuthAPI_ListMethods_Response;\n\n private _status: PlConnectionStatus = \"OK\";\n private authProbeInFlight = false;\n private readonly statusListener?: PlConnectionStatusListener;\n\n private _wireProto: wireProtocol = \"grpc\";\n private _wireConn!: WireConnection;\n\n /** The live GrpcOptions object handed to GrpcTransport. The transport keeps it by\n * reference and re-reads it on every call, so mutating `timeout` here retunes\n * subsequent deadlines without tearing down the connection. */\n private _grpcOptions?: GrpcOptions;\n\n /** Smoothed round-trip estimate in ms, from ping timings. Undefined until the first\n * successful ping, in which case the configured deadline is used as-is. */\n private _rttMs?: number;\n\n private readonly _restInterceptors: Dispatcher.DispatcherComposeInterceptor[];\n private readonly _restMiddlewares: Middleware[];\n private readonly _grpcInterceptors: Interceptor[];\n private readonly providers: WeakRef<WireClientProviderImpl<any>>[] = [];\n\n public readonly clientProvider: WireClientProvider<PlRestClientType | GrpcPlApiClient>;\n\n public readonly httpDispatcher: Dispatcher;\n\n public static async build(\n configOrAddress: PlClientConfig | string,\n ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n logger?: MiLogger;\n useAutoDetectWireProtocol?: boolean;\n } = {},\n ) {\n const conf =\n typeof configOrAddress === \"string\" ? plAddressToConfig(configOrAddress) : configOrAddress;\n\n const pl = new LLPlClient(conf, ops);\n\n // FIXME(rfiskov)[MILAB-5275]: Investigate why autodetect randomly fails; temporary turn it off.\n if (ops.useAutoDetectWireProtocol) {\n await pl.detectOptimalWireProtocol();\n }\n\n // Guarantee a ping happened so capability-gated paths (login, refresh) can branch synchronously.\n // In the autodetect path the loop's last successful ping already populated _serverInfo via the\n // side-effect in ping(); this fallback covers the path where autodetect is disabled.\n // Retried, not bare: this ping is the first contact with the server, so DNS and LB\n // warm-up land here. A single transient failure must not fail the whole connect.\n // (Not inside ping() itself: the autodetect path already wraps it in its own retry.)\n if (!pl._serverInfo) await pl.withIdempotentRetry(\"ping\", () => pl.ping());\n\n // Install the process-global signature-strictness flag based on backend version.\n setResourceSignaturesRequired(pl.supportsResourceSignatures);\n\n // Guarantee authMethods happened so client can make weighted decision on which auth method to use.\n if (!pl._authMethodsSync) await pl.authMethods();\n\n return pl;\n }\n\n private constructor(\n public readonly conf: PlClientConfig,\n private readonly ops: {\n auth?: AuthOps;\n statusListener?: PlConnectionStatusListener;\n shouldUseGzip?: boolean;\n logger?: MiLogger;\n } = {},\n ) {\n const { auth, statusListener } = ops;\n\n if (auth !== undefined) {\n this.refreshTimestamp = inferAuthRefreshTime(\n auth.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n this.authInformation = auth.authInformation;\n this.onAuthUpdate = auth.onUpdate;\n this.onAuthRefreshProblem = auth.onUpdateError;\n this.onAuthError = auth.onAuthError;\n }\n\n this._restInterceptors = [];\n this._restMiddlewares = [];\n this._grpcInterceptors = [];\n\n if (auth !== undefined) {\n this._restInterceptors.push(this.createRestAuthInterceptor());\n this._grpcInterceptors.push(this.createGrpcAuthInterceptor());\n }\n this._restInterceptors.push(interceptors.retry({ statusCodes: [] })); // Handle errors with openapi-fetch middleware.\n this._restMiddlewares.push(this.createRestErrorMiddleware());\n this._grpcInterceptors.push(this.createGrpcErrorInterceptor());\n\n this.httpDispatcher = defaultHttpDispatcher(this.conf.httpProxy);\n if (this.conf.wireProtocol) {\n this._wireProto = this.conf.wireProtocol;\n }\n\n this.initWireConnection(this._wireProto);\n\n if (statusListener !== undefined) {\n this.statusListener = statusListener;\n statusListener(this._status);\n }\n\n this.clientProvider = this.createWireClientProvider((wireConn) => {\n if (wireConn.type === \"grpc\") {\n return new GrpcPlApiClient(wireConn.Transport);\n } else {\n return createClient<PlApiPaths>({\n hostAndPort: wireConn.Config.hostAndPort,\n ssl: wireConn.Config.ssl,\n dispatcher: wireConn.Dispatcher,\n middlewares: wireConn.Middlewares,\n });\n }\n });\n }\n\n private initWireConnection(protocol: wireProtocol) {\n switch (protocol) {\n case \"rest\":\n this.initRestConnection();\n return;\n case \"grpc\":\n this.initGrpcConnection(this.ops.shouldUseGzip ?? false);\n return;\n default:\n ((v: never) => {\n throw new Error(\n `Unsupported wire protocol '${v as string}'. Use one of: ${SUPPORTED_WIRE_PROTOCOLS.join(\", \")}`,\n );\n })(protocol);\n }\n }\n\n private initRestConnection(): void {\n const dispatcher = defaultHttpDispatcher(this.conf.grpcProxy, this._restInterceptors);\n this._replaceWireConnection({\n type: \"rest\",\n Config: this.conf,\n Dispatcher: dispatcher,\n Middlewares: this._restMiddlewares,\n });\n }\n\n /**\n * Initializes (or reinitializes) _grpcTransport\n * @param gzip - whether to enable gzip compression\n */\n private initGrpcConnection(gzip: boolean) {\n const clientOptions: ClientOptions = {\n \"grpc.keepalive_time_ms\": 30_000, // 30 seconds\n \"grpc.service_config_disable_resolution\": 1, // Disable DNS TXT lookups for service config\n // Raises the per-stream and connection-level HTTP/2 windows. Node's 64 KB default\n // caps a big single-stream read (project open) at window/RTT rather than link speed,\n // and a lost WINDOW_UPDATE can deadlock it under packet loss.\n \"grpc-node.flow_control_window\": 16 * 1024 * 1024, // 16 MiB\n interceptors: this._grpcInterceptors,\n };\n\n if (gzip) clientOptions[\"grpc.default_compression_algorithm\"] = compressionAlgorithms.gzip;\n\n //\n // Leaving it here for now\n // https://github.com/grpc/grpc-node/issues/2788\n //\n // We should implement message pooling algorithm to overcome hardcoded NO_DELAY behaviour\n // of HTTP/2 and allow our small messages to batch together.\n //\n const grpcOptions: GrpcOptions = {\n host: this.conf.hostAndPort,\n timeout: this.unaryDeadline(),\n channelCredentials: this.conf.ssl\n ? ChannelCredentials.createSsl()\n : ChannelCredentials.createInsecure(),\n clientOptions,\n };\n\n const grpcProxy =\n typeof this.conf.grpcProxy === \"string\" ? { url: this.conf.grpcProxy } : this.conf.grpcProxy;\n\n if (grpcProxy?.url) {\n const url = new URL(grpcProxy.url);\n if (grpcProxy.auth) {\n const parsed = parseHttpAuth(grpcProxy.auth);\n if (parsed.scheme !== \"Basic\") {\n throw new Error(`Unsupported auth scheme: ${parsed.scheme as string}.`);\n }\n url.username = parsed.username;\n url.password = parsed.password;\n }\n process.env.grpc_proxy = url.toString();\n } else {\n delete process.env.grpc_proxy;\n }\n\n this._grpcOptions = grpcOptions;\n this._replaceWireConnection({ type: \"grpc\", Transport: new GrpcTransport(grpcOptions) });\n }\n\n /** Unary deadline derived from the observed RTT, floored by the configured value so\n * a fast link behaves exactly as before, and capped by\n * {@link MAX_ADAPTIVE_REQUEST_TIMEOUT}. */\n private unaryDeadline(): number {\n return deriveUnaryDeadline(this.conf.defaultRequestTimeout, this._rttMs);\n }\n\n /** Folds a fresh round-trip sample into the estimate and retunes the live unary\n * deadline. Called after every successful ping. */\n private recordRtt(sampleMs: number): void {\n this._rttMs = smoothRtt(this._rttMs, sampleMs);\n\n if (this._grpcOptions) {\n const next = this.unaryDeadline();\n if (next !== this._grpcOptions.timeout) {\n this.ops.logger?.info(\n `Unary deadline retuned to ${next}ms (rtt estimate ${Math.round(this._rttMs)}ms)`,\n );\n this._grpcOptions.timeout = next;\n }\n }\n }\n\n /** Smoothed round-trip estimate in ms, or undefined before the first ping. */\n public get rttEstimateMs(): number | undefined {\n return this._rttMs;\n }\n\n /** Runs an idempotent unary call with a bounded retry on transient transport failures.\n * Safe only for calls with no side effects, since a retry may duplicate the request. */\n private async withIdempotentRetry<T>(name: string, cb: () => Promise<T>): Promise<T> {\n return await retry(cb, IDEMPOTENT_RETRY_OPTIONS, (e: unknown) => {\n if (!isTransientCallFailure(e)) return false;\n this.ops.logger?.info(`${name}: transient failure, retrying. err=${String(e)}`);\n return true;\n });\n }\n\n private _replaceWireConnection(newConn: WireConnection): void {\n const oldConn = this._wireConn;\n this._wireConn = newConn;\n this._wireProto = newConn.type;\n\n // Reset all providers to let them reinitialize their clients\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n // at the same time we need to remove providers that are no longer valid\n this.providers.splice(i, 1);\n i--;\n } else {\n provider.reset();\n }\n }\n\n if (oldConn !== undefined && oldConn.type === \"grpc\") oldConn.Transport.close();\n }\n\n private providerCleanupCounter = 0;\n\n /**\n * Creates a provider for a grpc client. Returned provider will create fresh client whenever the underlying transport is reset.\n *\n * @param clientConstructor - a factory function that creates a grpc client\n */\n public createWireClientProvider<Client>(\n clientConstructor: (transport: WireConnection) => Client,\n ): WireClientProvider<Client> {\n // We need to cleanup providers periodically to avoid memory leaks.\n // This is a simple heuristic to avoid memory leaks.\n // We could use a more sophisticated algorithm, but this is good enough for now.\n this.providerCleanupCounter++;\n if (this.providerCleanupCounter >= 16) {\n for (let i = 0; i < this.providers.length; i++) {\n const provider = this.providers[i].deref();\n if (provider === undefined) {\n this.providers.splice(i, 1);\n i--;\n }\n }\n this.providerCleanupCounter = 0;\n }\n\n const provider = new WireClientProviderImpl<Client>(() => this._wireConn, clientConstructor);\n this.providers.push(new WeakRef(provider));\n return provider;\n }\n\n public get wireConnection(): WireConnection {\n return this._wireConn;\n }\n\n public get wireProtocol(): wireProtocol | undefined {\n return this._wireProto;\n }\n\n /** Returns true if client is authenticated. Even with anonymous auth information\n * connection is considered authenticated. Unauthenticated clients are used for\n * login and similar tasks, see {@link UnauthenticatedPlClient}. */\n public get authenticated(): boolean {\n return this.authInformation !== undefined;\n }\n\n /** null means anonymous connection */\n public get authUser(): string | null {\n if (!this.authenticated) throw new Error(\"Client is not authenticated\");\n if (this.authInformation?.jwtToken) {\n if (this.hasCapability(\"auth:v2\")) {\n return parsePlJwt(this.authInformation?.jwtToken).sub;\n }\n return parsePlJwt(this.authInformation?.jwtToken).user.login;\n } else return null;\n }\n\n private updateStatus(newStatus: PlConnectionStatus) {\n process.nextTick(() => {\n if (this._status !== newStatus) {\n this._status = newStatus;\n if (this.statusListener !== undefined) this.statusListener(this._status);\n if (newStatus === \"Unauthenticated\" && this.onAuthError !== undefined) this.onAuthError();\n }\n });\n }\n\n /**\n * UNAUTHENTICATED covers both a dead session (must reset) and a per-request authorization failure\n * such as a revoked resource signature (must not). Disambiguate by probing getSessionInfo — an\n * authenticated call with no resource signature: success means the session is alive and the failure\n * was resource-level; a probe that is itself Unauthenticated means real auth loss. Coalesced via\n * authProbeInFlight so a burst of failures costs one probe.\n */\n private async verifyThenMaybeEscalateUnauthenticated(): Promise<void> {\n if (this._status !== \"OK\" || this.authProbeInFlight) return;\n this.authProbeInFlight = true;\n try {\n await this.getSessionInfo();\n } catch (e) {\n if (isUnauthenticated(e)) this.updateStatus(\"Unauthenticated\");\n } finally {\n this.authProbeInFlight = false;\n }\n }\n\n public get status(): PlConnectionStatus {\n return this._status;\n }\n\n private authRefreshInProgress: boolean = false;\n\n private refreshAuthInformationIfNeeded(): void {\n if (\n this.refreshTimestamp === undefined ||\n Date.now() < this.refreshTimestamp ||\n this.authRefreshInProgress ||\n this._status === \"Unauthenticated\"\n )\n return;\n\n // Running refresh in background`\n this.authRefreshInProgress = true;\n void (async () => {\n try {\n const ttl = BigInt(this.conf.authTTLSeconds);\n const token = this.hasCapability(\"auth:v2\")\n ? await this.refreshToken({ ttlSeconds: ttl })\n : await this.getJwtToken(ttl);\n this.authInformation = { jwtToken: token };\n this.refreshTimestamp = inferAuthRefreshTime(\n this.authInformation,\n this.conf.authMaxRefreshSeconds,\n );\n if (this.onAuthUpdate) this.onAuthUpdate(this.authInformation);\n } catch (e: unknown) {\n if (this.onAuthRefreshProblem) this.onAuthRefreshProblem(e);\n } finally {\n this.authRefreshInProgress = false;\n }\n })();\n }\n\n /**\n * Creates middleware that parses error responses and handles them centrally.\n * This middleware runs before openapi-fetch parses the response, so we need to\n * manually parse the response body for error responses.\n */\n private createRestErrorMiddleware(): Middleware {\n return {\n onResponse: async ({ request: _request, response, options: _options }) => {\n const { body, ...resOptions } = response;\n\n if ([502, 503, 504].includes(response.status)) {\n // Service unavailable, bad gateway, gateway timeout\n this.updateStatus(\"Disconnected\");\n return new Response(body, { ...resOptions, status: response.status });\n }\n\n const respErr = await parseResponseError(response);\n if (!respErr.error) {\n // No error: nice!\n return new Response(respErr.origBody ?? body, { ...resOptions, status: response.status });\n }\n\n if (typeof respErr.error === \"string\") {\n // Non-standard error or normal response: let later middleware to deal wit it.\n return new Response(respErr.error, { ...resOptions, status: response.status });\n }\n\n if (respErr.error.code === Code.UNAUTHENTICATED) {\n void this.verifyThenMaybeEscalateUnauthenticated();\n }\n\n // Let later middleware to deal with standard gRPC error.\n return new Response(respErr.origBody, { ...resOptions, status: response.status });\n },\n };\n }\n\n /** Detects certain errors and update client status accordingly when using GRPC wire connection */\n private createGrpcErrorInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n next(metadata, {\n onReceiveStatus: (status, next) => {\n if (status.code == GrpcStatus.UNAUTHENTICATED)\n // (!!!) don't change to \"===\"\n void this.verifyThenMaybeEscalateUnauthenticated();\n if (status.code == GrpcStatus.UNAVAILABLE)\n // (!!!) don't change to \"===\"\n this.updateStatus(\"Disconnected\");\n next(status);\n },\n });\n },\n });\n };\n }\n\n private createRestAuthInterceptor(): Dispatcher.DispatcherComposeInterceptor {\n return (dispatch) => {\n return (options, handler) => {\n if (this.authInformation?.jwtToken !== undefined) {\n // TODO: check this magic really works and gets called\n options.headers = {\n ...options.headers,\n authorization: \"Bearer \" + this.authInformation.jwtToken,\n };\n this.refreshAuthInformationIfNeeded();\n }\n\n return dispatch(options, handler);\n };\n };\n }\n\n /** Injects authentication information if needed */\n private createGrpcAuthInterceptor(): Interceptor {\n return (options, nextCall) => {\n return new InterceptingCall(nextCall(options), {\n start: (metadata, listener, next) => {\n if (this.authInformation?.jwtToken !== undefined) {\n metadata.set(\"authorization\", \"Bearer \" + this.authInformation.jwtToken);\n this.refreshAuthInformationIfNeeded();\n next(metadata, listener);\n } else {\n next(metadata, listener);\n }\n },\n });\n };\n }\n\n public async getJwtToken(\n ttlSeconds: bigint,\n options?: { authorization?: string; role?: AuthAPI_Role },\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const role = options?.role ?? AuthAPI_Role.UNSPECIFIED;\n\n if (cl instanceof GrpcPlApiClient) {\n const meta: Record<string, string> = {};\n if (options?.authorization) meta.authorization = options.authorization;\n return (\n await cl.getJWTToken(\n {\n expiration: { seconds: ttlSeconds, nanos: 0 },\n requestedRole: role,\n },\n { meta, timeout: DEFAULT_LOGIN_TIMEOUT },\n ).response\n ).token;\n } else {\n const headers: Record<string, string> = {};\n if (options?.authorization) headers.authorization = options.authorization;\n const resp = cl.POST(\"/v1/auth/jwt-token\", {\n body: { expiration: `${ttlSeconds}s`, requestedRole: role },\n headers,\n });\n return notEmpty((await resp).data, \"REST: empty response for JWT token request\").token;\n }\n }\n\n /** Login via username/password. Returns a fresh JWT. Backend creates a new session per call. */\n public async loginBasic(\n user: string,\n password: string,\n opts: { ttlSeconds?: bigint; role?: AuthAPI_Role } = {},\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const role = opts.role ?? AuthAPI_Role.UNSPECIFIED;\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login(\n {\n credentials: {\n oneofKind: \"basic\",\n basic: { login: user, password },\n },\n expiration: { seconds: ttl, nanos: 0 },\n requestedRole: role,\n },\n { timeout: DEFAULT_LOGIN_TIMEOUT },\n ).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n // openapi-typescript generated all body fields as required, but Login.Request\n // has a credentials oneof — only one of `basic`/`token` is sent. Cast around it.\n body: {\n basic: { login: user, password },\n expiration: `${ttl}s`,\n requestedRole: role,\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for login request\").token;\n }\n }\n\n /** Login via opaque bearer token (controller pre-shared secret, OIDC id-token, etc.).\n * String input is UTF-8 encoded. Returns a fresh Platforma JWT. */\n public async loginWithToken(\n token: Uint8Array | string,\n opts: { ttlSeconds?: bigint; role?: AuthAPI_Role } = {},\n ): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const role = opts.role ?? AuthAPI_Role.UNSPECIFIED;\n const bytes = typeof token === \"string\" ? Buffer.from(token, \"utf8\") : token;\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login(\n {\n credentials: {\n oneofKind: \"token\",\n token: { token: bytes },\n },\n expiration: { seconds: ttl, nanos: 0 },\n requestedRole: role,\n },\n { timeout: DEFAULT_LOGIN_TIMEOUT },\n ).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n // openapi-typescript marks all body fields as required, but Login.Request has a oneof.\n // REST encodes `bytes` as a base64 string.\n body: {\n token: { token: Buffer.from(bytes).toString(\"base64\") },\n expiration: `${ttl}s`,\n requestedRole: role,\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for login request\").token;\n }\n }\n\n /** Login via SSO: forwards the raw IdP /token JSON body to the backend.\n * Backend validates signature + nonce + audience and mints a Platforma JWT. */\n public async loginSSO(tokenResponse: Uint8Array): Promise<string> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.login(\n {\n credentials: {\n oneofKind: \"sso\",\n sso: { tokenResponse },\n },\n },\n { timeout: DEFAULT_LOGIN_TIMEOUT },\n ).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/login\", {\n body: {\n sso: { tokenResponse: Buffer.from(tokenResponse).toString(\"base64\") },\n } as any,\n });\n return notEmpty((await resp).data, \"REST: empty response for SSO login request\").token;\n }\n }\n\n /** Request a one-time PKCE nonce + its expiry from the backend. The desktop is\n * expected to place the nonce verbatim into the OIDC auth-request before\n * redirecting to the IdP; the backend enforces the expiry on {@link loginSSO}. */\n public async beginSSOLogin(): Promise<{ nonce: string; expiresAt: Date; clientSecret?: string }> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n const resp = (await cl.beginSSOLogin({}).response).flow;\n if (resp.oneofKind !== \"publicPkce\") {\n throw new Error(`beginSSOLogin: unsupported flow ${resp.oneofKind}`);\n }\n const exp = notEmpty(resp.publicPkce.expiresAt, \"beginSSOLogin: missing expiresAt\");\n return {\n nonce: resp.publicPkce.nonce,\n expiresAt: Timestamp.toDate(exp),\n clientSecret: resp.publicPkce.clientSecret,\n };\n } else {\n const wsResponse = notEmpty(\n (await cl.POST(\"/v1/auth/sso/begin-login\", { body: {} })).data,\n \"REST: empty response for beginSSOLogin request\",\n );\n const pkce = notEmpty(wsResponse.publicPkce, \"REST: missing publicPkce in beginSSOLogin\");\n return {\n nonce: pkce.nonce,\n expiresAt: new Date(pkce.expiresAt),\n clientSecret: pkce.clientSecret,\n };\n }\n }\n\n /** Refresh the current JWT, preserving session id and role. */\n public async refreshToken(opts: { ttlSeconds?: bigint } = {}): Promise<string> {\n const cl = this.clientProvider.get();\n const ttl = opts.ttlSeconds ?? BigInt(this.conf.authTTLSeconds);\n const currentToken = notEmpty(\n this.authInformation?.jwtToken,\n \"refreshToken called without a current JWT\",\n );\n\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.refreshToken(\n {\n token: currentToken,\n expiration: { seconds: ttl, nanos: 0 },\n },\n { timeout: DEFAULT_LOGIN_TIMEOUT },\n ).response\n ).token;\n } else {\n const resp = cl.POST(\"/v1/auth/refresh\", {\n body: { token: currentToken, expiration: `${ttl}s` },\n });\n return notEmpty((await resp).data, \"REST: empty response for refresh request\").token;\n }\n }\n\n public async ping(): Promise<grpcTypes.MaintenanceAPI_Ping_Response> {\n const cl = this.clientProvider.get();\n let resp: grpcTypes.MaintenanceAPI_Ping_Response;\n // Ping is the cheapest call we make, so its duration is our best RTT proxy.\n const startedAt = performance.now();\n if (cl instanceof GrpcPlApiClient) {\n resp = (await cl.ping({})).response;\n } else {\n // The REST ping response predates the `capabilities` field (proto field 9).\n // Old servers omit it; treat absence as empty capability list.\n const pingData = notEmpty(\n (await cl.GET(\"/v1/ping\")).data,\n \"REST: empty response for ping request\",\n );\n resp = {\n ...(pingData as unknown as grpcTypes.MaintenanceAPI_Ping_Response),\n capabilities: (pingData as any).capabilities ?? [],\n };\n }\n this.recordRtt(performance.now() - startedAt);\n this._serverInfo = resp;\n return resp;\n }\n\n /** Cached Ping response. Always populated post-build(); throws if accessed earlier. */\n public get serverInfo(): grpcTypes.MaintenanceAPI_Ping_Response {\n if (!this._serverInfo) {\n throw new Error(\"LLPlClient.serverInfo accessed before build() completed\");\n }\n return this._serverInfo;\n }\n\n /** Synchronous capability check against the cached Ping response. */\n public hasCapability(capability: BackendCapability): boolean {\n return hasCapability(this.serverInfo.capabilities, capability);\n }\n\n /** True if the backend produces signed resource ids (and accepts the\n * setDefaultColor TX request). Tagged at 3.3.0 — backends older than this\n * return resources without signatures and reject color-proof requests. */\n public get supportsResourceSignatures(): boolean {\n return isVersionAtLeast(this.serverInfo.coreVersion, [3, 3, 0]);\n }\n\n /**\n * True if the backend honors per-file `permissions` on workdir fill rules, so\n * `exec.builder().writeFile/addFile({ writable: true })` takes effect. When false\n * the requested mode is ignored and files land at the canonical archive perm.\n *\n * [3, 5, 0] excludes the tagged 3.5.0 release but includes dev builds past the\n * tag (e.g. \"3.5.0-224-g0ca182\"), which is where the support lands.\n */\n public get supportsWritableWorkdirFiles(): boolean {\n return isAfterVersion(this.serverInfo.coreVersion, [3, 5, 0]);\n }\n\n /**\n * Detects the best available wire protocol.\n * If wireProtocol is explicitly configured, does nothing.\n * Otherwise probes the current protocol via ping; if it fails, switches to the alternative.\n */\n private async detectOptimalWireProtocol() {\n if (this.conf.wireProtocol) {\n return;\n }\n\n // Each retry is:\n // - ping request timeout (100 to 3_000ms)\n // - backoff delay (30 to 500ms)\n //\n // 30 attempts are ~43 seconds of overall waiting time.\n // Think twice on overall time this thing takes to complete when changing these parameters.\n // It may block UI when connecting to the server and loading projects list.\n const pingTimeoutFactor = 1.3;\n const maxPingTimeoutMs = 3_000;\n const retryOptions: RetryOptions = {\n type: \"exponentialBackoff\",\n maxAttempts: 30,\n initialDelay: 30,\n backoffMultiplier: 1.3,\n jitter: 0.2,\n maxDelay: 500,\n };\n\n let attempt = 1;\n let pingTimeoutMs = 100;\n await retry(\n () => withTimeout(this.ping(), pingTimeoutMs),\n retryOptions,\n (e: unknown) => {\n if (isAbortedError(e)) {\n this.ops.logger?.info(\n `Wire proto autodetect: ping timed out after ${pingTimeoutMs}ms: attempt=${attempt}, wire=${this._wireProto}`,\n );\n\n if (attempt % 2 === 0) {\n // We have 2 wire protocols to check. Increase timeout each 2 attempts.\n pingTimeoutMs = Math.min(\n Math.round(pingTimeoutMs * pingTimeoutFactor),\n maxPingTimeoutMs,\n );\n }\n } else {\n this.ops.logger?.info(\n `Wire proto autodetect: ping failed: attempt=${attempt}, wire=${this._wireProto}, err=${String(e)}`,\n );\n }\n\n attempt++;\n const protocol = this._wireProto === \"grpc\" ? \"rest\" : \"grpc\";\n this.ops.logger?.info(\n `Wire protocol autodetect next attempt: will try wire '${protocol}' with timeout ${pingTimeoutMs}ms`,\n );\n this.initWireConnection(protocol);\n return true;\n },\n );\n }\n\n public async license(): Promise<grpcTypes.MaintenanceAPI_License_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.license({})).response;\n } else {\n const resp = notEmpty(\n (await cl.GET(\"/v1/license\")).data,\n \"REST: empty response for license request\",\n );\n return {\n status: resp.status,\n isOk: resp.isOk,\n responseBody: Uint8Array.from(Buffer.from(resp.responseBody)),\n };\n }\n }\n\n public async authMethods(): Promise<grpcTypes.AuthAPI_ListMethods_Response> {\n const cl = this.clientProvider.get();\n let resp: grpcTypes.AuthAPI_ListMethods_Response;\n if (cl instanceof GrpcPlApiClient) {\n resp = (await cl.authMethods({})).response;\n } else {\n const wsResponse = notEmpty(\n (await cl.GET(\"/v1/auth/methods\")).data,\n \"REST: empty response for auth methods request\",\n );\n // OpenAPI schema flattens the protobuf oneof into `{ basic?, token? }`,\n // while protobuf-ts models it as a discriminated union. Reshape per item.\n resp = {\n methods: (wsResponse.methods ?? []).map((m): grpcTypes.AuthAPI_ListMethods_MethodInfo => {\n const base = { id: m.id, description: m.description };\n if (m.basic !== undefined) {\n return { ...base, method: { oneofKind: \"basic\", basic: m.basic } };\n }\n if (m.token !== undefined) {\n return { ...base, method: { oneofKind: \"token\", token: m.token } };\n }\n if (m.sso !== undefined) {\n return { ...base, method: { oneofKind: \"sso\", sso: m.sso } };\n }\n return { ...base, method: { oneofKind: undefined } };\n }),\n };\n }\n\n this._authMethodsSync = resp;\n return resp;\n }\n\n public get authMethodsSync(): grpcTypes.AuthAPI_ListMethods_Response {\n if (!this._authMethodsSync) {\n throw new Error(\"LLPlClient.authMethodsSync accessed before build() completed\");\n }\n return this._authMethodsSync;\n }\n\n public async getUserRoot(\n opts: { login?: string; createIfNotExists?: boolean } = {},\n ): Promise<grpcTypes.AuthAPI_GetUserRoot_Response> {\n // Retryable even with createIfNotExists: the call is get-or-create keyed on login, so a\n // second attempt returns the existing root rather than making another one.\n return await this.withIdempotentRetry(\"getUserRoot\", () => this.getUserRootOnce(opts));\n }\n\n private async getUserRootOnce(\n opts: { login?: string; createIfNotExists?: boolean } = {},\n ): Promise<grpcTypes.AuthAPI_GetUserRoot_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (\n await cl.getUserRoot({\n login: opts.login ?? \"\",\n createIfNotExists: opts.createIfNotExists ?? false,\n })\n ).response;\n } else {\n const resp = notEmpty(\n (\n await cl.POST(\"/v1/auth/user-root\", {\n body: {\n login: opts.login ?? \"\",\n createIfNotExists: opts.createIfNotExists ?? false,\n },\n })\n ).data,\n \"REST: empty response for getUserRoot request\",\n );\n return {\n userRoot: resp.userRoot\n ? {\n resourceId: BigInt(resp.userRoot.resourceId),\n resourceSignature: Uint8Array.from(\n Buffer.from(resp.userRoot.resourceSignature, \"base64\"),\n ),\n }\n : undefined,\n };\n }\n }\n\n public async listUserResources(\n opts: { login?: string; startFrom?: bigint; limit?: number } = {},\n ): Promise<grpcTypes.AuthAPI_ListUserResources_Response[]> {\n const cl = this.clientProvider.get();\n\n if (!(cl instanceof GrpcPlApiClient)) {\n throw new Error(\"ListUserResources requires gRPC wire protocol; REST is not supported\");\n }\n\n const call = cl.listUserResources({\n login: opts.login ?? \"\",\n startFrom: opts.startFrom ?? 0n,\n limit: opts.limit ?? 0,\n });\n const responses: grpcTypes.AuthAPI_ListUserResources_Response[] = [];\n for await (const msg of call.responses) {\n responses.push(msg);\n }\n return responses;\n }\n\n /** Returns the authenticated caller's session id and effective role.\n * Models the {@link getUserRoot} wrapper: gRPC unary with a REST fallback. */\n public async getSessionInfo(): Promise<grpcTypes.AuthAPI_GetSessionInfo_Response> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return (await cl.getSessionInfo({})).response;\n } else {\n const resp = notEmpty(\n (await cl.POST(\"/v1/auth/session-info\", { body: {} })).data,\n \"REST: empty response for getSessionInfo request\",\n );\n return {\n sessionId: Uint8Array.from(Buffer.from(resp.sessionId, \"base64\")),\n role: resp.role as AuthAPI_Role,\n };\n }\n }\n\n /** Lists the users known to the server — the recipient picker's source. A user\n * becomes known on first login; provisioned users who have never logged in do not\n * appear. gRPC-only (unary, no REST binding). */\n public async listUsers(): Promise<grpcTypes.AuthAPI_User[]> {\n const cl = this.clientProvider.get();\n\n if (!(cl instanceof GrpcPlApiClient)) {\n throw new Error(\"ListUsers requires gRPC wire protocol; REST is not supported\");\n }\n\n return (await cl.listUsers({})).response.users;\n }\n\n /** Deletes a user account: the record, its identity-index entries (login, email and any\n * alternative of either), its grants, and its root resource with everything still attached\n * under it. Admin/controller credentials only, and irreversible — re-attach anything worth\n * keeping to another user's root first.\n * gRPC-only (unary, no REST binding), like {@link listUsers}. */\n public async deleteUser(login: string): Promise<grpcTypes.AuthAPI_DeleteUser_Response> {\n const cl = this.clientProvider.get();\n\n if (!(cl instanceof GrpcPlApiClient)) {\n throw new Error(\"DeleteUser requires gRPC wire protocol; REST is not supported\");\n }\n\n return (await cl.deleteUser({ login })).response;\n }\n\n public async txSync(txId: bigint): Promise<void> {\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n await cl.txSync({ txId: BigInt(txId) });\n } else {\n await cl.POST(\"/v1/tx-sync\", { body: { txId: txId.toString() } });\n }\n }\n\n createTx(rw: boolean, ops: PlCallOps = {}): LLPlTransaction {\n return new LLPlTransaction((abortSignal) => {\n let totalAbortSignal = abortSignal;\n if (ops.abortSignal) totalAbortSignal = AbortSignal.any([totalAbortSignal, ops.abortSignal]);\n\n const timeout =\n ops.timeout ??\n (rw ? this.conf.defaultRWTransactionTimeout : this.conf.defaultROTransactionTimeout);\n\n const cl = this.clientProvider.get();\n if (cl instanceof GrpcPlApiClient) {\n return cl.tx({\n abort: totalAbortSignal,\n timeout,\n });\n }\n\n const wireConn = this.wireConnection;\n if (wireConn.type === \"rest\") {\n // For REST/WebSocket protocol, timeout needs to be converted to AbortSignal\n if (timeout !== undefined) {\n totalAbortSignal = AbortSignal.any([totalAbortSignal, AbortSignal.timeout(timeout)]);\n }\n\n // The gRPC transport has the auth interceptor that already handles it, but here we need to refresh the auth information to be safe.\n this.refreshAuthInformationIfNeeded();\n\n const wsUrl = this.conf.ssl\n ? `wss://${this.conf.hostAndPort}/v1/ws/tx`\n : `ws://${this.conf.hostAndPort}/v1/ws/tx`;\n\n return new WebSocketBiDiStream(\n wsUrl,\n (msg) => TxAPI_ClientMessage.toBinary(msg),\n (data) => TxAPI_ServerMessage.fromBinary(new Uint8Array(data)),\n {\n abortSignal: totalAbortSignal,\n jwtToken: this.authInformation?.jwtToken,\n dispatcher: wireConn.Dispatcher,\n\n onComplete: async (stream) =>\n stream.requests.send({\n // Ask server to gracefully close the stream on its side, if not done yet.\n requestId: 0,\n request: { oneofKind: \"streamClose\", streamClose: {} },\n }),\n },\n );\n }\n\n throw new Error(`transactions are not supported for wire protocol ${this._wireProto}`);\n });\n }\n\n /** Closes underlying transport */\n public async close() {\n if (this.wireConnection.type === \"grpc\") {\n this.wireConnection.Transport.close();\n } else {\n // TODO: close all WS connections\n }\n await this.httpDispatcher.destroy();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA6DA,MAAM,2BAAyC;CAC7C,MAAM;CACN,aAAa;CACb,cAAc;CACd,mBAAmB;CACnB,QAAQ;CACR,UAAU;AACZ;AAKA,SAAS,iBAAiB,SAAiB,QAA2C;CACpF,MAAM,QAAQ,yBAAyB,KAAK,OAAO;CACnD,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,SAAmC;EAAC,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;CAAC;CAC9F,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KACrB,IAAI,OAAO,OAAO,OAAO,IAAI,OAAO,OAAO,KAAK,OAAO;CAEzD,OAAO;AACT;AAcA,SAAS,eAAe,SAAiB,QAA2C;CAClF,MAAM,QAAQ,8BAA8B,KAAK,OAAO;CACxD,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,SAAmC;EAAC,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;CAAC;CAC9F,MAAM,SAAS,MAAM;CACrB,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KACrB,IAAI,OAAO,OAAO,OAAO,IAAI,OAAO,OAAO,KAAK,OAAO;CAEzD,OAAO,WAAW;AACpB;AAEA,IAAM,yBAAN,MAA2E;CAItD;CACA;CAJnB,SAAqC,KAAA;CAErC,YACE,UACA,mBACA;EAFiB,KAAA,WAAA;EACA,KA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B,YAAY,IAAI,CAAC,kBAAkB,IAAI,WAAW,CAAC;GAE3F,MAAM,UACJ,IAAI,YACH,KAAK,KAAK,KAAK,8BAA8B,KAAK,KAAK;GAE1D,MAAM,KAAK,KAAK,eAAe,IAAI;GACnC,IAAI,cAAcA,gBAChB,OAAO,GAAG,GAAG;IACX,OAAO;IACP;GACF,CAAC;GAGH,MAAM,WAAW,KAAK;GACtB,IAAI,SAAS,SAAS,QAAQ;IAE5B,IAAI,YAAY,KAAA,GACd,mBAAmB,YAAY,IAAI,CAAC,kBAAkB,YAAY,QAAQ,OAAO,CAAC,CAAC;IAIrF,KAAK,+BAA+B;IAMpC,OAAO,IAAI,oBAJG,KAAK,KAAK,MACpB,SAAS,KAAK,KAAK,YAAY,aAC/B,QAAQ,KAAK,KAAK,YAAY,aAI/B,QAAQ,oBAAoB,SAAS,GAAG,IACxC,SAAS,oBAAoB,WAAW,IAAI,WAAW,IAAI,CAAC,GAC7D;KACE,aAAa;KACb,UAAU,KAAK,iBAAiB;KAChC,YAAY,SAAS;KAErB,YAAY,OAAO,WACjB,OAAO,SAAS,KAAK;MAEnB,WAAW;MACX,SAAS;OAAE,WAAW;OAAe,aAAa,CAAC;MAAE;KACvD,CAAC;IACL,CACF;GACF;GAEA,MAAM,IAAI,MAAM,oDAAoD,KAAK,YAAY;EACvF,CAAC;CACH;;CAGA,MAAa,QAAQ;EACnB,IAAI,KAAK,eAAe,SAAS,QAC/B,KAAK,eAAe,UAAU,MAAM;EAItC,MAAM,KAAK,eAAe,QAAQ;CACpC;AACF"}
|
|
@@ -1,16 +1,15 @@
|
|
|
1
1
|
import { TxAPI_ClientMessage, TxAPI_ServerMessage } from "../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.js";
|
|
2
2
|
import { BiDiStream } from "./abstract_stream.js";
|
|
3
|
-
|
|
4
3
|
//#region src/core/ll_transaction.d.ts
|
|
5
|
-
type ClientMessageRequest = TxAPI_ClientMessage["request"];
|
|
6
|
-
type ServerMessageResponse = TxAPI_ServerMessage["response"];
|
|
4
|
+
export type ClientMessageRequest = TxAPI_ClientMessage["request"];
|
|
5
|
+
export type ServerMessageResponse = TxAPI_ServerMessage["response"];
|
|
7
6
|
type TxStream = BiDiStream<TxAPI_ClientMessage, TxAPI_ServerMessage>;
|
|
8
|
-
type OneOfKind<T extends {
|
|
7
|
+
export type OneOfKind<T extends {
|
|
9
8
|
oneofKind: unknown;
|
|
10
9
|
}, Kind extends T["oneofKind"]> = Extract<T, {
|
|
11
10
|
oneofKind: Kind;
|
|
12
11
|
}>;
|
|
13
|
-
declare class LLPlTransaction {
|
|
12
|
+
export declare class LLPlTransaction {
|
|
14
13
|
/** Bidirectional channel through which transaction communicates with the server */
|
|
15
14
|
private readonly stream;
|
|
16
15
|
/** Used to abort ongoing transaction stream */
|
|
@@ -52,5 +51,4 @@ declare class LLPlTransaction {
|
|
|
52
51
|
private isTerminalResponse;
|
|
53
52
|
}
|
|
54
53
|
//#endregion
|
|
55
|
-
export { ClientMessageRequest, LLPlTransaction, OneOfKind, ServerMessageResponse };
|
|
56
54
|
//# sourceMappingURL=ll_transaction.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ll_transaction.d.ts","names":[],"sources":["../../src/core/ll_transaction.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"ll_transaction.d.ts","names":[],"sources":["../../src/core/ll_transaction.ts"],"mappings":";;;YAeY,uBAAuB;YAEvB,wBAAwB;KAE/B,WAAW,WAAW,qBAAqB;YAEpC,UAAU;EAAY;GAAsB,aAAa,kBAAkB,QACrF;EACE,WAAW;;qBAuIF;;mBAEM;;mBAGA;;;UAIT;;mBAGS;;;;UAKT;;;UAIA;;UAEA;;UAGA;;mBAGS;mBAEA;EAEjB,YAAY,gBAAgB,aAAa,gBAAgB;UAOjD;UAUM;;UA2LA;;EAyBP,MAAM,QAAQ;;EAQR,SAAS;EAUT,KAAK,aAAa,mCAC7B,GAAG,UAAU,sBAAsB,OACnC,6BACC,QAAQ,UAAU,uBAAuB;EAC/B,KAAK,aAAa,mCAC7B,GAAG,UAAU,sBAAsB,OACnC,4BACC,QAAQ,UAAU,uBAAuB;EAgDrC,WAAW,aAAa,mCAC7B,GAAG,UAAU,sBAAsB,QAClC,cAAc,UAAU,uBAAuB;UAiB1C;;EAGK,YAAQ;UAMb"}
|
package/dist/core/stat.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
//#region src/core/stat.d.ts
|
|
2
|
-
type TxStat = {
|
|
2
|
+
export type TxStat = {
|
|
3
3
|
txCount: number;
|
|
4
4
|
timeMs: number;
|
|
5
5
|
rootsCreated: number;
|
|
@@ -28,11 +28,10 @@ type TxStat = {
|
|
|
28
28
|
kvGetRequests: number;
|
|
29
29
|
kvGetBytes: number;
|
|
30
30
|
};
|
|
31
|
-
type AllTxStat = {
|
|
31
|
+
export type AllTxStat = {
|
|
32
32
|
committed: TxStat;
|
|
33
33
|
conflict: TxStat;
|
|
34
34
|
error: TxStat;
|
|
35
35
|
};
|
|
36
36
|
//#endregion
|
|
37
|
-
export { AllTxStat, TxStat };
|
|
38
37
|
//# sourceMappingURL=stat.d.ts.map
|
package/dist/core/stat.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stat.d.ts","names":[],"sources":["../../src/core/stat.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"stat.d.ts","names":[],"sources":["../../src/core/stat.ts"],"mappings":";YAAY;EACV;EACA;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EAEA;EACA;EAEA;EACA;EACA;EACA;EACA;EAEA;EACA;EACA;EACA;EACA;EACA;EAEA;EACA;EACA;EAEA;EACA;;YA0EU;EACV,WAAW;EACX,UAAU;EACV,OAAO"}
|
|
@@ -6,10 +6,9 @@ import { ResourceDataCacheRecord } from "./cache.js";
|
|
|
6
6
|
import { TxStat } from "./stat.js";
|
|
7
7
|
import { PromiseTracker } from "./PromiseTracker.js";
|
|
8
8
|
import { LRUCache } from "lru-cache";
|
|
9
|
-
|
|
10
9
|
//#region src/core/transaction.d.ts
|
|
11
10
|
/** Reference to resource, used only within transaction */
|
|
12
|
-
interface ResourceRef {
|
|
11
|
+
export interface ResourceRef {
|
|
13
12
|
/** Global resource id of newly created resources, become available only
|
|
14
13
|
* after response for the corresponding creation request is received. */
|
|
15
14
|
readonly globalId: Promise<SignedResourceId>;
|
|
@@ -18,16 +17,16 @@ interface ResourceRef {
|
|
|
18
17
|
readonly localId: LocalResourceId;
|
|
19
18
|
}
|
|
20
19
|
/** Key-Value pair from resource-attached KV storage */
|
|
21
|
-
interface KeyValue {
|
|
20
|
+
export interface KeyValue {
|
|
22
21
|
key: string;
|
|
23
22
|
value: Uint8Array;
|
|
24
23
|
}
|
|
25
24
|
/** Key-Value pair from resource-attached KV storage */
|
|
26
|
-
interface KeyValueString {
|
|
25
|
+
export interface KeyValueString {
|
|
27
26
|
key: string;
|
|
28
27
|
value: string;
|
|
29
28
|
}
|
|
30
|
-
type ResourceTreeItem = ResourceData & {
|
|
29
|
+
export type ResourceTreeItem = ResourceData & {
|
|
31
30
|
kv: KeyValue[];
|
|
32
31
|
traverseWasStopped: boolean;
|
|
33
32
|
};
|
|
@@ -38,7 +37,7 @@ type ResourceTreeItem = ResourceData & {
|
|
|
38
37
|
* narrow on `frameKind` before accessing type-specific fields.
|
|
39
38
|
* Note: `frameKind` is distinct from `ResourceData.kind` (which is the resource kind).
|
|
40
39
|
*/
|
|
41
|
-
type ResourceTreeFrame = (ResourceTreeItem & {
|
|
40
|
+
export type ResourceTreeFrame = (ResourceTreeItem & {
|
|
42
41
|
frameKind: "resource";
|
|
43
42
|
}) | {
|
|
44
43
|
frameKind: "stopMarker";
|
|
@@ -51,26 +50,26 @@ interface _FieldId<RId> {
|
|
|
51
50
|
/** Field name */
|
|
52
51
|
fieldName: string;
|
|
53
52
|
}
|
|
54
|
-
type FieldId = _FieldId<SignedResourceId>;
|
|
55
|
-
type FieldRef = _FieldId<ResourceRef>;
|
|
56
|
-
type LocalFieldId = _FieldId<LocalResourceId>;
|
|
57
|
-
type AnyFieldId = FieldId | LocalFieldId;
|
|
58
|
-
type AnyResourceRef = ResourceRef | LocalResourceId | SignedResourceId;
|
|
59
|
-
type AnyFieldRef = _FieldId<AnyResourceRef>;
|
|
60
|
-
type AnyRef = AnyResourceRef | AnyFieldRef;
|
|
61
|
-
declare function isField(ref: AnyRef): ref is AnyFieldRef;
|
|
62
|
-
declare function isResource(ref: AnyRef): ref is AnyResourceRef;
|
|
63
|
-
declare function isResourceId(ref: AnyRef): ref is SignedResourceId;
|
|
64
|
-
declare function isFieldRef(ref: AnyFieldRef): ref is FieldRef;
|
|
65
|
-
declare function isResourceRef(ref: AnyRef): ref is ResourceRef;
|
|
66
|
-
declare function toFieldId(ref: AnyFieldRef): AnyFieldId;
|
|
67
|
-
declare function toGlobalFieldId(ref: FieldRef | FieldId): Promise<FieldId>;
|
|
68
|
-
interface ResourceIdWithSignature {
|
|
53
|
+
export type FieldId = _FieldId<SignedResourceId>;
|
|
54
|
+
export type FieldRef = _FieldId<ResourceRef>;
|
|
55
|
+
export type LocalFieldId = _FieldId<LocalResourceId>;
|
|
56
|
+
export type AnyFieldId = FieldId | LocalFieldId;
|
|
57
|
+
export type AnyResourceRef = ResourceRef | LocalResourceId | SignedResourceId;
|
|
58
|
+
export type AnyFieldRef = _FieldId<AnyResourceRef>;
|
|
59
|
+
export type AnyRef = AnyResourceRef | AnyFieldRef;
|
|
60
|
+
export declare function isField(ref: AnyRef): ref is AnyFieldRef;
|
|
61
|
+
export declare function isResource(ref: AnyRef): ref is AnyResourceRef;
|
|
62
|
+
export declare function isResourceId(ref: AnyRef): ref is SignedResourceId;
|
|
63
|
+
export declare function isFieldRef(ref: AnyFieldRef): ref is FieldRef;
|
|
64
|
+
export declare function isResourceRef(ref: AnyRef): ref is ResourceRef;
|
|
65
|
+
export declare function toFieldId(ref: AnyFieldRef): AnyFieldId;
|
|
66
|
+
export declare function toGlobalFieldId(ref: FieldRef | FieldId): Promise<FieldId>;
|
|
67
|
+
export interface ResourceIdWithSignature {
|
|
69
68
|
resourceId: bigint;
|
|
70
69
|
resourceSignature: ResourceSignature;
|
|
71
70
|
}
|
|
72
71
|
/** Access level handed to a grant recipient (see {@link PlTransaction.grantAccess}). */
|
|
73
|
-
interface GrantPermissions {
|
|
72
|
+
export interface GrantPermissions {
|
|
74
73
|
/** Write access = ability to modify the resource subtree + re-share it. */
|
|
75
74
|
writable: boolean;
|
|
76
75
|
}
|
|
@@ -78,21 +77,21 @@ interface GrantPermissions {
|
|
|
78
77
|
* Distinguishes a regular user-to-user grant from a system-level public grant.
|
|
79
78
|
* Re-export of the wire enum so callers need not reach into the generated proto.
|
|
80
79
|
*/
|
|
81
|
-
declare const GrantType: typeof AuthAPI_GrantAccess_GrantType;
|
|
82
|
-
type GrantType = AuthAPI_GrantAccess_GrantType;
|
|
80
|
+
export declare const GrantType: typeof AuthAPI_GrantAccess_GrantType;
|
|
81
|
+
export type GrantType = AuthAPI_GrantAccess_GrantType;
|
|
83
82
|
/**
|
|
84
83
|
* Effective role of an authenticated session (controller / workflow / user / admin).
|
|
85
84
|
* Re-export of the wire enum so callers need not reach into the generated proto.
|
|
86
85
|
* Returned by {@link LLPlClient.getSessionInfo} and surfaced as
|
|
87
86
|
* {@link PlClient.currentUserRole}.
|
|
88
87
|
*/
|
|
89
|
-
declare const Role: typeof AuthAPI_Role;
|
|
90
|
-
type Role = AuthAPI_Role;
|
|
91
|
-
declare function isEveryoneUserLogin(login: string): boolean;
|
|
92
|
-
declare function toGlobalResourceId(ref: AnyResourceRef): Promise<SignedResourceId>;
|
|
93
|
-
declare function field(resourceId: AnyResourceRef, fieldName: string): AnyFieldRef;
|
|
88
|
+
export declare const Role: typeof AuthAPI_Role;
|
|
89
|
+
export type Role = AuthAPI_Role;
|
|
90
|
+
export declare function isEveryoneUserLogin(login: string): boolean;
|
|
91
|
+
export declare function toGlobalResourceId(ref: AnyResourceRef): Promise<SignedResourceId>;
|
|
92
|
+
export declare function field(resourceId: AnyResourceRef, fieldName: string): AnyFieldRef;
|
|
94
93
|
/** If transaction commit failed due to write conflicts */
|
|
95
|
-
declare class TxCommitConflict extends Error {
|
|
94
|
+
export declare class TxCommitConflict extends Error {
|
|
96
95
|
name: string;
|
|
97
96
|
}
|
|
98
97
|
/**
|
|
@@ -103,7 +102,7 @@ declare class TxCommitConflict extends Error {
|
|
|
103
102
|
*
|
|
104
103
|
* This class encapsulates finalization stage and provides ready-to-communication transaction object.
|
|
105
104
|
* */
|
|
106
|
-
declare class PlTransaction {
|
|
105
|
+
export declare class PlTransaction {
|
|
107
106
|
private readonly ll;
|
|
108
107
|
readonly name: string;
|
|
109
108
|
readonly writable: boolean;
|
|
@@ -285,5 +284,4 @@ declare class PlTransaction {
|
|
|
285
284
|
private static nextLocalTxId;
|
|
286
285
|
}
|
|
287
286
|
//#endregion
|
|
288
|
-
export { AnyFieldId, AnyFieldRef, AnyRef, AnyResourceRef, FieldId, FieldRef, GrantPermissions, GrantType, KeyValue, KeyValueString, LocalFieldId, PlTransaction, ResourceIdWithSignature, ResourceRef, ResourceTreeFrame, ResourceTreeItem, Role, TxCommitConflict, field, isEveryoneUserLogin, isField, isFieldRef, isResource, isResourceId, isResourceRef, toFieldId, toGlobalFieldId, toGlobalResourceId };
|
|
289
287
|
//# sourceMappingURL=transaction.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction.d.ts","names":[],"sources":["../../src/core/transaction.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"transaction.d.ts","names":[],"sources":["../../src/core/transaction.ts"],"mappings":";;;;;;;;;;iBAkEiB;;;WAGN,UAAU,QAAQ;;;WAIlB,SAAS;;;iBAIH;EACf;EACA,OAAO;;;iBAIQ;EACf;EACA;;YAGU,mBAAmB;EAAiB,IAAI;EAAY;;;;;;;;;YASpD,qBACP;EAAqB;;EACpB;EAAyB,IAAI;EAAkB;;UAE3C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AW,KAAK;EAOhB,YAAY,KAAK;EAWX,cAAc,KAAK,iBAAiB,QAAQ;EAsB5C,oBAAoB,KAAK,iBAAiB,QAAQ;EASlD,8BAA8B,KAAK,iBAAiB,QAAQ;EAI5D,oCACX,KAAK,iBACJ,QAAQ;EAIJ,UAAU,KAAK,gBAAgB,aAAa,OAAO;EAanD,aAAa,KAAK,gBAAgB;EAU5B,UAAU,KAAK,gBAAgB,cAAc,QAAQ;EAoBrD,gBAAgB,KAAK,gBAAgB,cAAc;EAInD,cAAc,GAAG,KAAK,gBAAgB,cAAc,QAAQ;EAI5D,kBACX,KAAK,gBACL,cACC,QAAQ;EAqBE,wBACX,KAAK,gBACL,cACC;EAOU,sBAAsB,GAAG,KAAK,gBAAgB,cAAc,QAAQ;;EAkB1E,oBAAoB,KAAK,QAAQ,mBAAmB,WAAW,kBAAkB;EAW3E,iBAAa;;EAMb,YAAQ;;;EAUR,SAAK;;;;;;;;;;;;;;;;;;;;;;EA6BX,aACL,QAAQ,eAAe,qBACvB;IACE,cAAc;IACd,oBAAoB;IACpB;IACA;MAED,cAAc;UAqFT;iBAIO;iBAEA"}
|
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
import { ResourceAPI_Tree_Filter, ResourceAPI_Tree_Filter_OperatorType, ResourceAPI_Tree_Filter_Property } from "../proto-grpc/github.com/milaboratory/pl/plapi/plapiproto/api.js";
|
|
2
|
-
|
|
3
2
|
//#region src/core/tree_filter.d.ts
|
|
4
3
|
/** Shorthand alias for the filter predicate type. */
|
|
5
|
-
type Filter = ResourceAPI_Tree_Filter;
|
|
4
|
+
export type Filter = ResourceAPI_Tree_Filter;
|
|
6
5
|
/** Shorthand alias for the Property enum. */
|
|
7
|
-
type Property = ResourceAPI_Tree_Filter_Property;
|
|
6
|
+
export type Property = ResourceAPI_Tree_Filter_Property;
|
|
8
7
|
/**
|
|
9
8
|
* Builder helpers for {@link ResourceAPI_Tree_Filter} predicates used in
|
|
10
9
|
* `ResourceAPI_Tree_Request.fieldFilter` and `traverseStopRules`.
|
|
@@ -13,14 +12,19 @@ type Property = ResourceAPI_Tree_Filter_Property;
|
|
|
13
12
|
* - `FIELD_NAME` is only valid inside `fieldFilter`.
|
|
14
13
|
* - `IS_FINAL`, `ALL_OUTPUTS_FINAL`, and resource-level boolean predicates are only valid inside `traverseStopRules`.
|
|
15
14
|
*/
|
|
16
|
-
declare const treeFilter: {
|
|
15
|
+
export declare const treeFilter: {
|
|
17
16
|
readonly and: (...children: Filter[]) => Filter;
|
|
18
17
|
readonly or: (...children: Filter[]) => Filter;
|
|
19
|
-
readonly not: (child: Filter) => Filter;
|
|
20
|
-
|
|
21
|
-
readonly
|
|
22
|
-
|
|
23
|
-
readonly
|
|
18
|
+
readonly not: (child: Filter) => Filter;
|
|
19
|
+
/** Exact-match predicate on a string property. */
|
|
20
|
+
readonly eq: (prop: Property, value: string) => Filter;
|
|
21
|
+
/** Regex-match predicate on a string property. */
|
|
22
|
+
readonly match: (prop: Property, pattern: string) => Filter;
|
|
23
|
+
/** Boolean-equality predicate. */
|
|
24
|
+
readonly boolEq: (prop: Property, value: boolean) => Filter;
|
|
25
|
+
/** Match resources whose type string equals `name` exactly. */
|
|
26
|
+
readonly resourceTypeEq: (name: string) => Filter;
|
|
27
|
+
/** Match resources whose type string satisfies the regex `pattern`. */
|
|
24
28
|
readonly resourceTypeMatch: (pattern: string) => Filter;
|
|
25
29
|
/**
|
|
26
30
|
* Match field edges whose name equals `name` exactly.
|
|
@@ -81,5 +85,5 @@ declare const treeFilter: {
|
|
|
81
85
|
readonly readyOrDuplicateOrError: () => Filter;
|
|
82
86
|
};
|
|
83
87
|
//#endregion
|
|
84
|
-
export {
|
|
88
|
+
export { ResourceAPI_Tree_Filter_OperatorType as FilterOperatorType, ResourceAPI_Tree_Filter_Property as FilterProperty, type ResourceAPI_Tree_Filter };
|
|
85
89
|
//# sourceMappingURL=tree_filter.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tree_filter.d.ts","names":[],"sources":["../../src/core/tree_filter.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"tree_filter.d.ts","names":[],"sources":["../../src/core/tree_filter.ts"],"mappings":";;;YASY,SAAS;;YAGT,WAAW;;;;;;;;;qBAcV;WAGX,SAAG,UAAc,aAAW;WAO5B,QAAE,UAAc,aAAW;WAO3B,MAAG,OAAQ,WAAS;;WAUpB,KAAE,MAAO,UAAQ,kBAAkB;;WASnC,QAAK,MAAO,UAAQ,oBAAoB;;WASxC,SAAM,MAAO,UAAQ,mBAAmB;;WAWxC,iBAAc,iBAAgB;;WAK9B,oBAAiB,oBAAmB;;;;;WAQpC,cAAW,iBAAgB;;;;;WAQ3B,iBAAc,oBAAmB;;;;;WAQjC,UAAO,mBAAkB;;;;;WAQzB,kBAAe,mBAAkB;;;;;;WASjC,8BAA2B,mBAAkB;;;;;;WAY7C,cAAW,mBAAkB;;;;;;;;WAW7B,YAAS,mBAAkB;;;;;WAQ3B,gBAAa,mBAAkB;;;;;;;;;;;;WAe/B,+BAA2B"}
|