@collective-intelligence/external-apps-client-sdk 0.1.36 → 0.1.37

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.
@@ -1,4 +1,94 @@
1
- import { r as __toESM, t as __commonJSMin } from "./rolldown-runtime-DC62tzP2.js";
1
+ import * as Predicate from "effect/Predicate";
2
+ import * as Schema from "effect/Schema";
3
+ import * as Config from "effect/Config";
4
+ import * as Context from "effect/Context";
5
+ import * as Effect from "effect/Effect";
6
+ import * as Layer from "effect/Layer";
7
+ import * as Option from "effect/Option";
8
+ import * as ManagedRuntime from "effect/ManagedRuntime";
9
+ var __create = Object.create;
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __getProtoOf = Object.getPrototypeOf;
14
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
15
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
16
+ var __exportAll = (all, no_symbols) => {
17
+ let target = {};
18
+ for (var name in all) __defProp(target, name, {
19
+ get: all[name],
20
+ enumerable: true
21
+ });
22
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
23
+ return target;
24
+ };
25
+ var __copyProps = (to, from, except, desc) => {
26
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
27
+ key = keys[i];
28
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
29
+ get: ((k) => from[k]).bind(null, key),
30
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
31
+ });
32
+ }
33
+ return to;
34
+ };
35
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
36
+ value: mod,
37
+ enumerable: true
38
+ }) : target, mod));
39
+ /** Codes of the Expected Errors that CI returns. The `CiErrorCode` Schema of `./effect` uses this list. */
40
+ const ciErrorCodes = [
41
+ "unauthenticated",
42
+ "forbidden",
43
+ "not_found",
44
+ "conflict",
45
+ "invalid_request",
46
+ "rate_limited",
47
+ "unavailable",
48
+ "internal"
49
+ ];
50
+ var errors_exports = /* @__PURE__ */ __exportAll({
51
+ CiError: () => CiError,
52
+ CiErrorCode: () => CiErrorCode,
53
+ CiTransportError: () => CiTransportError,
54
+ FederatedAuthError: () => FederatedAuthError,
55
+ FederatedAuthErrorCode: () => FederatedAuthErrorCode
56
+ });
57
+ /** Code of an Expected Error that CI returns for an operation. */
58
+ const CiErrorCode = Schema.Literals(ciErrorCodes);
59
+ /** Code of an Expected Error of the federated sign-in flow. */
60
+ const FederatedAuthErrorCode = Schema.Literals([
61
+ "configuration_error",
62
+ "invalid_return_target",
63
+ "invalid_callback",
64
+ "invalid_state",
65
+ "transaction_expired",
66
+ "authorization_failed",
67
+ "token_exchange_failed",
68
+ "reauthorization_required"
69
+ ]);
70
+ /** An Expected Error that CI returns for an operation. */
71
+ var CiError = class extends Schema.TaggedError()("CiError", {
72
+ code: CiErrorCode,
73
+ details: Schema.optionalKey(Schema.Record(Schema.String, Schema.Json)),
74
+ message: Schema.String,
75
+ retryable: Schema.Boolean
76
+ }) {};
77
+ /** An Expected Error of the federated sign-in flow. */
78
+ var FederatedAuthError = class extends Schema.TaggedError()("FederatedAuthError", {
79
+ code: FederatedAuthErrorCode,
80
+ message: Schema.String
81
+ }) {
82
+ constructor(first, second) {
83
+ if (Predicate.isString(first)) super({
84
+ code: first,
85
+ message: Predicate.isString(second) ? second : ""
86
+ });
87
+ else super(first, Predicate.isString(second) ? void 0 : second);
88
+ }
89
+ };
90
+ /** The request did not reach CI, or CI's response was not readable. */
91
+ var CiTransportError = class extends Schema.TaggedError()("CiTransportError", { cause: Schema.Defect() }) {};
2
92
  const completeOperationRegistry = (ids) => ids;
3
93
  /** Generated, curated external-application operation authority. */
4
94
  const clientOperationIds = completeOperationRegistry([
@@ -37,6 +127,37 @@ const clientOperationIds = completeOperationRegistry([
37
127
  ]);
38
128
  const clientOperationIdSet = new Set(clientOperationIds);
39
129
  const isClientOperationId = (value) => clientOperationIdSet.has(value);
130
+ const decodeCiError = Schema.decodeUnknownOption(CiError);
131
+ /**
132
+ * Internal. The `CiError` instance of an envelope error. An executor that
133
+ * the app gives can return an error that is not a valid `CiError`: `details`
134
+ * that are absent or not JSON are dropped, and a code outside `CiErrorCode`
135
+ * becomes `internal`, so an Expected Error always has its class.
136
+ */
137
+ const toCiError = (error) => {
138
+ if (error instanceof CiError) return error;
139
+ const { details, ...fields } = error;
140
+ return decodeCiError({
141
+ ...fields,
142
+ _tag: "CiError",
143
+ details
144
+ }).pipe(Option.orElse(() => decodeCiError({
145
+ ...fields,
146
+ _tag: "CiError"
147
+ })), Option.getOrElse(() => new CiError({
148
+ code: "internal",
149
+ message: Predicate.isString(error.message) ? error.message : "The CI operation failed",
150
+ retryable: error.retryable === true
151
+ })));
152
+ };
153
+ /** Internal. The envelope with a `CiError` instance as its error (AC-015). */
154
+ const toCiResult = (result) => result.ok || result.error instanceof CiError ? result : {
155
+ correlationId: result.correlationId,
156
+ error: toCiError(result.error),
157
+ ok: false
158
+ };
159
+ /** Internal. The value of a success; the `CiError` of a failure in the typed channel. */
160
+ const fromCiResult = (result) => result.ok ? Effect.succeed(result.value) : Effect.fail(toCiError(result.error));
40
161
  const isRecord$1 = (value) => value !== null && Object(value) === value && !Array.isArray(value);
41
162
  const textField = (value, key) => {
42
163
  const field = value[key];
@@ -278,6 +399,7 @@ const dedicatedResult = (value) => {
278
399
  const isRecord = (value) => value !== null && Object(value) === value && !Array.isArray(value);
279
400
  const isString = (value) => typeof value === "string";
280
401
  const isBoolean = (value) => typeof value === "boolean";
402
+ /** The `CiErrorCode` of a backend error code. */
281
403
  const backendErrorCode = (value) => {
282
404
  switch (value) {
283
405
  case "authentication_required": return "unauthenticated";
@@ -297,21 +419,21 @@ const transportFailure = (response, value) => {
297
419
  const code = isString(rawCode) ? backendErrorCode(rawCode) : "internal";
298
420
  return {
299
421
  correlationId: isString(value.correlationId) ? value.correlationId : response.headers.get("x-correlation-id") ?? "unavailable",
300
- error: {
422
+ error: new CiError({
301
423
  code,
302
424
  message: isString(value.error.message) ? value.error.message : "The CI operation failed",
303
425
  retryable: isBoolean(value.error.retryable) ? value.error.retryable : response.status >= 500
304
- },
426
+ }),
305
427
  ok: false
306
428
  };
307
429
  }
308
430
  return {
309
431
  correlationId: response.headers.get("x-correlation-id") ?? "unavailable",
310
- error: {
432
+ error: new CiError({
311
433
  code: response.status === 429 ? "rate_limited" : "internal",
312
434
  message: "The CI operation returned an invalid response",
313
435
  retryable: response.status === 429 || response.status >= 500
314
- },
436
+ }),
315
437
  ok: false
316
438
  };
317
439
  };
@@ -320,82 +442,94 @@ const clientFailure = (error) => ({
320
442
  error,
321
443
  ok: false
322
444
  });
323
- const responseJson = async (response) => {
445
+ const responseJson = (response) => Effect.promise(async () => {
324
446
  try {
325
447
  return await response.json();
326
448
  } catch {
327
449
  return null;
328
450
  }
329
- };
330
- const createHttpOperationTransport = ({ authorization, basePath, credentials = "omit", fetch, origin }) => ({ execute: async (operationId, input, options) => {
331
- if (!isClientOperationId(operationId)) return clientFailure({
451
+ });
452
+ const transportError$1 = (cause) => new CiTransportError({ cause });
453
+ /** The bearer token of `authorization`; `null` when it fails. */
454
+ const accessToken = (authorization) => Effect.promise(async () => {
455
+ try {
456
+ return { token: await authorization?.() };
457
+ } catch {
458
+ return null;
459
+ }
460
+ });
461
+ /**
462
+ * The HTTP adapter of `CiClient`: one operation per dedicated Application
463
+ * HTTP route. A CI error answer is a `CiError` in the envelope, and so is an
464
+ * error answer whose body is not JSON (`internal`, or `rate_limited` for
465
+ * 429). A request that does not reach CI, or an event stream that cannot be
466
+ * read, fails with `CiTransportError`. The signal of `fetch` aborts on the
467
+ * caller's signal and on an interruption of the fiber.
468
+ */
469
+ const makeHttpExecute = ({ authorization, basePath, credentials = "omit", fetch, origin }) => (operationId, input, options) => Effect.gen(function* execute() {
470
+ if (!isClientOperationId(operationId)) return clientFailure(new CiError({
332
471
  code: "invalid_request",
333
472
  message: "The operation is not part of the client-safe registry",
334
473
  retryable: false
335
- });
336
- if (options === void 0 || options.organizationId.length === 0) return clientFailure({
474
+ }));
475
+ if (options.organizationId.length === 0) return clientFailure(new CiError({
337
476
  code: "invalid_request",
338
477
  message: "organizationId is required",
339
478
  retryable: false
340
- });
479
+ }));
341
480
  const call = dedicatedHttpCall(operationId, input);
342
- if (call === null) return clientFailure({
481
+ if (call === null) return clientFailure(new CiError({
343
482
  code: "invalid_request",
344
483
  message: `${operationId} was removed from Application HTTP; use /application/v1/resources`,
345
484
  retryable: false
346
- });
485
+ }));
347
486
  const headers = new Headers({ "x-organization-id": options.organizationId });
348
487
  if (call.body !== void 0) headers.set("content-type", "application/json");
349
- let accessToken;
350
- try {
351
- accessToken = await authorization?.();
352
- } catch {
353
- return clientFailure({
354
- code: "unauthenticated",
355
- message: "CI login is required",
356
- retryable: false
357
- });
358
- }
359
- if (accessToken !== void 0) headers.set("authorization", `Bearer ${accessToken}`);
488
+ const authorized = yield* accessToken(authorization);
489
+ if (authorized === null) return clientFailure(new CiError({
490
+ code: "unauthenticated",
491
+ message: "CI login is required",
492
+ retryable: false
493
+ }));
494
+ if (authorized.token !== void 0) headers.set("authorization", `Bearer ${authorized.token}`);
360
495
  if (call.idempotencyKey !== void 0) headers.set("idempotency-key", call.idempotencyKey);
361
496
  if (call.lastEventId !== void 0) headers.set("last-event-id", call.lastEventId);
362
497
  const search = new URLSearchParams(call.query ?? {}).toString();
363
498
  const endpoint = new URL(`${basePath}${call.pathname}${search === "" ? "" : `?${search}`}`, origin);
364
- let response;
365
499
  const requestInit = {
366
500
  credentials,
367
501
  headers,
368
502
  method: call.method
369
503
  };
370
504
  if (call.body !== void 0) requestInit.body = JSON.stringify(call.body);
371
- if (options.signal !== void 0) requestInit.signal = options.signal;
372
- try {
373
- response = await fetch(endpoint, requestInit);
374
- } catch {
375
- return clientFailure({
376
- code: "unavailable",
377
- message: "The CI operation could not be reached",
378
- retryable: true
379
- });
380
- }
505
+ const response = yield* Effect.tryPromise({
506
+ catch: transportError$1,
507
+ try: (signal) => fetch(endpoint, {
508
+ ...requestInit,
509
+ signal: options.signal === void 0 ? signal : AbortSignal.any([options.signal, signal])
510
+ })
511
+ });
512
+ const headerCorrelation = response.headers.get("x-correlation-id") ?? "unavailable";
381
513
  if (call.parse === "event_stream") {
382
- if (!response.ok) return transportFailure(response, await responseJson(response));
383
- const page = parseRunEventStream(await response.text());
514
+ if (!response.ok) return transportFailure(response, yield* responseJson(response));
515
+ const text = yield* Effect.tryPromise({
516
+ catch: transportError$1,
517
+ try: () => response.text()
518
+ });
384
519
  return {
385
- correlationId: response.headers.get("x-correlation-id") ?? "unavailable",
520
+ correlationId: headerCorrelation,
386
521
  ok: true,
387
- value: page
522
+ value: parseRunEventStream(text)
388
523
  };
389
524
  }
390
- const value = await responseJson(response);
525
+ const value = yield* responseJson(response);
391
526
  if (!response.ok) return transportFailure(response, value);
392
- const headerCorrelation = response.headers.get("x-correlation-id") ?? "unavailable";
393
527
  return {
394
528
  correlationId: isRecord(value) && isString(value.correlationId) ? value.correlationId : headerCorrelation,
395
529
  ok: true,
396
530
  value: dedicatedResult(value)
397
531
  };
398
- } });
532
+ });
399
533
  const parseOriginUrl = (value, field) => {
400
534
  let url;
401
535
  try {
@@ -411,6 +545,25 @@ const parseMountPath = (value) => {
411
545
  const normalized = value.replace(/\/+$/u, "");
412
546
  return normalized === "" ? "" : normalized;
413
547
  };
548
+ /** The HTTP adapter options of a direct transport; a bad `tenantUrl` throws `TypeError`. */
549
+ const directHttpOptions = (options) => ({
550
+ authorization: options.auth.getAccessToken,
551
+ basePath: "/application/v1",
552
+ fetch: options.fetch ?? globalThis.fetch,
553
+ origin: parseOriginUrl(options.tenantUrl, "tenantUrl")
554
+ });
555
+ /** The HTTP adapter options of a proxy transport; a bad `serverUrl` or `path` throws `TypeError`. */
556
+ const proxyHttpOptions = (options) => {
557
+ const origin = parseOriginUrl(options.serverUrl, "serverUrl");
558
+ const basePath = parseMountPath(options.path);
559
+ const { authentication } = options;
560
+ return {
561
+ ...authentication.mode === "federated" ? { authorization: authentication.auth.getAccessToken } : { credentials: authentication.credentials ?? "same-origin" },
562
+ basePath,
563
+ fetch: options.fetch ?? globalThis.fetch,
564
+ origin
565
+ };
566
+ };
414
567
  var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => {
415
568
  Object.defineProperty(exports, "__esModule", { value: true });
416
569
  exports.formatNames = exports.fastFormats = exports.fullFormats = void 0;
@@ -8169,193 +8322,8 @@ const createEntityProtocol = (definition) => {
8169
8322
  }
8170
8323
  };
8171
8324
  };
8172
- const createCommonEntityClient = (options) => {
8173
- const protocol = createEntityProtocol(options.definition);
8174
- const execute = async (input, requestOptions) => {
8175
- const correlationId = options.requestId?.() ?? globalThis.crypto.randomUUID();
8176
- const request = protocol.decodeRequest({
8177
- ...input,
8178
- requestId: correlationId,
8179
- resourceId: options.definition.id
8180
- });
8181
- if (!request.ok) return {
8182
- ...request,
8183
- error: {
8184
- ...request.error,
8185
- outcome: "not_dispatched"
8186
- }
8187
- };
8188
- if (requestOptions?.signal?.aborted) return {
8189
- correlationId,
8190
- error: {
8191
- code: "transport_error",
8192
- message: "The entity request was cancelled before dispatch",
8193
- outcome: "not_dispatched",
8194
- retryable: false
8195
- },
8196
- ok: false
8197
- };
8198
- if (options.definition.capabilities[{
8199
- create: "create",
8200
- delete: "delete",
8201
- get: "get",
8202
- list: "search",
8203
- list_members: "search",
8204
- update: "update",
8205
- upload: "upload"
8206
- }[input.operation]] !== true) return {
8207
- correlationId,
8208
- error: {
8209
- code: "capability_not_supported",
8210
- message: "The entity operation is not supported",
8211
- outcome: "not_dispatched",
8212
- retryable: false
8213
- },
8214
- ok: false
8215
- };
8216
- try {
8217
- const result = await options.transport.execute(request.value, requestOptions);
8218
- const decoded = protocol.decodeResult(input.operation, result, correlationId);
8219
- return !decoded.ok && decoded.error.details?.phase === "response_contract" ? {
8220
- ...decoded,
8221
- error: {
8222
- ...decoded.error,
8223
- outcome: input.operation === "list" || input.operation === "list_members" || input.operation === "get" ? "rejected" : "uncertain"
8224
- }
8225
- } : decoded;
8226
- } catch {
8227
- return {
8228
- correlationId,
8229
- error: {
8230
- code: "transport_error",
8231
- message: "The entity transport failed",
8232
- outcome: input.operation === "list" || input.operation === "list_members" || input.operation === "get" ? "rejected" : "uncertain",
8233
- retryable: false
8234
- },
8235
- ok: false
8236
- };
8237
- }
8238
- };
8239
- return {
8240
- create: (input) => execute({
8241
- ...input,
8242
- operation: "create"
8243
- }),
8244
- definition: options.definition,
8245
- delete: (input) => execute({
8246
- ...input,
8247
- operation: "delete"
8248
- }),
8249
- get: (input, requestOptions) => execute({
8250
- ...input,
8251
- operation: "get"
8252
- }, requestOptions),
8253
- list: (query, requestOptions) => execute({
8254
- operation: "list",
8255
- query
8256
- }, requestOptions),
8257
- listMembers: (parentId, field, query, requestOptions) => execute({
8258
- field,
8259
- operation: "list_members",
8260
- parentId,
8261
- query
8262
- }, requestOptions),
8263
- update: (input) => execute({
8264
- ...input,
8265
- operation: "update"
8266
- }),
8267
- upload: (input, requestOptions) => execute({
8268
- ...input,
8269
- operation: "upload"
8270
- }, requestOptions)
8271
- };
8272
- };
8273
- const capabilityByOperation = {
8274
- create: "create",
8275
- get: "get",
8276
- hard_delete: "hardDelete",
8277
- list: "search",
8278
- restore: "restore",
8279
- soft_delete: "softDelete",
8280
- update: "update"
8281
- };
8282
- const unavailable = (cause) => ({
8283
- code: "transport_error",
8284
- details: { cause: cause instanceof Error ? cause.message : String(cause) },
8285
- message: "The resource transport failed",
8286
- retryable: true
8287
- });
8288
- const defaultRequestId = () => globalThis.crypto.randomUUID();
8289
- const createLegacyResourceClient = (options) => {
8290
- const requestId = options.requestId ?? defaultRequestId;
8291
- const execute = async (request, requestOptions, additionalCapabilities = [], validationError) => {
8292
- const correlationId = requestId();
8293
- if (validationError !== void 0) return {
8294
- correlationId,
8295
- error: validationError,
8296
- ok: false
8297
- };
8298
- const unsupportedCapability = [capabilityByOperation[request.operation], ...additionalCapabilities].find((capability) => options.definition.capabilities[capability] !== true);
8299
- if (unsupportedCapability !== void 0) return {
8300
- correlationId,
8301
- error: {
8302
- code: "capability_not_supported",
8303
- details: { capability: unsupportedCapability },
8304
- message: `Resource ${options.definition.id} does not support ${unsupportedCapability}`,
8305
- retryable: false
8306
- },
8307
- ok: false
8308
- };
8309
- try {
8310
- return await options.transport.execute({
8311
- ...request,
8312
- requestId: correlationId,
8313
- resourceId: options.definition.id
8314
- }, requestOptions);
8315
- } catch (error) {
8316
- return {
8317
- correlationId,
8318
- error: unavailable(error),
8319
- ok: false
8320
- };
8321
- }
8322
- };
8323
- const lifecycle = async (operation, input, requestOptions) => await execute({
8324
- ...input,
8325
- operation
8326
- }, requestOptions);
8327
- return {
8328
- capabilities: options.definition.capabilities,
8329
- create: async (input, requestOptions) => await execute({
8330
- ...input,
8331
- operation: "create"
8332
- }, requestOptions),
8333
- definition: options.definition,
8334
- get: async (input, requestOptions) => await execute({
8335
- ...input,
8336
- operation: "get"
8337
- }, requestOptions, input.includeDeleted === true ? ["includeDeleted"] : []),
8338
- hardDelete: async (input, requestOptions) => await lifecycle("hard_delete", input, requestOptions),
8339
- list: async (query, requestOptions) => await execute({
8340
- operation: "list",
8341
- query
8342
- }, requestOptions, query.includeDeleted === true ? ["includeDeleted"] : [], options.definition.query.pagination.modes.includes(query.pagination.mode) ? void 0 : {
8343
- code: "capability_not_supported",
8344
- details: { paginationMode: query.pagination.mode },
8345
- message: `Resource ${options.definition.id} does not support ${query.pagination.mode} pagination`,
8346
- retryable: false
8347
- }),
8348
- restore: async (input, requestOptions) => await lifecycle("restore", input, requestOptions),
8349
- softDelete: async (input, requestOptions) => await lifecycle("soft_delete", input, requestOptions),
8350
- update: async (input, requestOptions) => await execute({
8351
- ...input,
8352
- operation: "update"
8353
- }, requestOptions)
8354
- };
8355
- };
8356
- function createResourceClient(options) {
8357
- return options.protocol === "entity" ? createCommonEntityClient(options) : createLegacyResourceClient(options);
8358
- }
8325
+ /** A read can be retried; a write that failed in flight can have happened. */
8326
+ const outcomeOf = (operation) => operation === "get" || operation === "list" || operation === "list_members" ? "rejected" : "uncertain";
8359
8327
  const encode = (request) => {
8360
8328
  switch (request.operation) {
8361
8329
  case "list": return {
@@ -8414,71 +8382,406 @@ const encode = (request) => {
8414
8382
  };
8415
8383
  }
8416
8384
  };
8417
- const createEntityHttpTransport = (options) => {
8385
+ const failure$1 = (request, error) => ({
8386
+ correlationId: request.requestId,
8387
+ error,
8388
+ ok: false
8389
+ });
8390
+ const cancelled = (request) => failure$1(request, {
8391
+ code: "transport_error",
8392
+ message: "The entity request was cancelled before dispatch",
8393
+ outcome: "not_dispatched",
8394
+ retryable: false
8395
+ });
8396
+ const transportError = (cause) => new CiTransportError({ cause });
8397
+ /**
8398
+ * The envelope of an entity answer. It throws when the answer is not an
8399
+ * envelope, or is a success for a failed HTTP status: the caller reads such
8400
+ * a throw as a transport failure.
8401
+ */
8402
+ const envelopeOf = (response, result) => {
8403
+ if (result.ok === false) return {
8404
+ ...result,
8405
+ error: {
8406
+ ...result.error,
8407
+ outcome: result.error.outcome ?? "rejected"
8408
+ }
8409
+ };
8410
+ if (!response.ok) throw new Error("Unexpected successful envelope for failed HTTP response");
8411
+ return result;
8412
+ };
8413
+ /**
8414
+ * The entity HTTP adapter of one destination. Early cancellation and a
8415
+ * failed login stay envelopes, as the request was not sent; a request that
8416
+ * does not reach the server, or an answer that cannot be read, fails with
8417
+ * `CiTransportError`. A destination without its CI selectors, or an
8418
+ * endpoint with credentials, query or fragment, throws `TypeError`.
8419
+ */
8420
+ const makeEntityHttpExecute = (options) => {
8418
8421
  const { destination, authentication } = options;
8419
8422
  if (destination.kind === "ci" && (!/^[\w.-]+$/u.test(destination.schemaFqn) || destination.organizationId.trim().length === 0)) throw new TypeError("CI entity destinations require a schema FQN and organization selector");
8420
8423
  const endpoint = destination.kind === "gateway" ? new URL(destination.endpoint) : new URL(`/application/v1/resources/${encodeURIComponent(destination.schemaFqn)}`, parseOriginUrl(destination.tenantUrl, "tenantUrl"));
8421
8424
  if (!["http:", "https:"].includes(endpoint.protocol) || endpoint.username !== "" || endpoint.password !== "" || endpoint.search !== "" || endpoint.hash !== "") throw new TypeError("Entity endpoint must be an HTTP URL without credentials, query or fragment");
8422
8425
  const fetch = options.fetch ?? globalThis.fetch;
8423
8426
  const credentials = authentication.mode === "server_delegated" ? authentication.credentials ?? "same-origin" : "omit";
8424
- return { execute: async (request, requestOptions) => {
8425
- const failure = (error) => ({
8426
- correlationId: request.requestId,
8427
- error,
8428
- ok: false
8429
- });
8430
- const cancelled = () => failure({
8431
- code: "transport_error",
8432
- message: "The entity request was cancelled before dispatch",
8433
- outcome: "not_dispatched",
8434
- retryable: false
8435
- });
8436
- if (requestOptions?.signal?.aborted) return cancelled();
8427
+ return (request, requestOptions) => Effect.gen(function* execute() {
8428
+ if (requestOptions.signal?.aborted) return cancelled(request);
8437
8429
  const encoded = encode(request);
8438
8430
  const headers = new Headers({
8439
8431
  "content-type": "application/json",
8440
8432
  "x-correlation-id": request.requestId
8441
8433
  });
8442
8434
  if (destination.kind === "ci") headers.set("x-organization-id", destination.organizationId);
8443
- try {
8444
- if (authentication.mode === "federated") headers.set("authorization", `Bearer ${await authentication.auth.getAccessToken()}`);
8445
- } catch {
8446
- return failure({
8435
+ if (authentication.mode === "federated") {
8436
+ const token = yield* Effect.promise(async () => {
8437
+ try {
8438
+ return { value: await authentication.auth.getAccessToken() };
8439
+ } catch {
8440
+ return null;
8441
+ }
8442
+ });
8443
+ if (token === null) return failure$1(request, {
8447
8444
  code: "unauthenticated",
8448
8445
  message: "CI login is required",
8449
8446
  outcome: "not_dispatched",
8450
8447
  retryable: false
8451
8448
  });
8452
- }
8453
- if (requestOptions?.signal?.aborted) return cancelled();
8454
- try {
8455
- const init = {
8456
- credentials,
8457
- headers,
8458
- method: encoded.method,
8459
- redirect: "error"
8460
- };
8461
- if (encoded.body !== void 0) init.body = encoded.body;
8462
- if (requestOptions?.signal !== void 0) init.signal = requestOptions.signal;
8463
- const response = await fetch(`${endpoint.href.replace(/\/$/u, "")}${encoded.path}`, init);
8464
- const result = await response.json();
8465
- if (result.ok === false) return {
8466
- ...result,
8467
- error: {
8468
- ...result.error,
8469
- outcome: result.error.outcome ?? "rejected"
8470
- }
8471
- };
8472
- if (!response.ok) throw new Error("Unexpected successful envelope for failed HTTP response");
8473
- return result;
8474
- } catch {
8475
- return failure({
8449
+ headers.set("authorization", `Bearer ${token.value}`);
8450
+ }
8451
+ if (requestOptions.signal?.aborted) return cancelled(request);
8452
+ const init = {
8453
+ credentials,
8454
+ headers,
8455
+ method: encoded.method,
8456
+ redirect: "error"
8457
+ };
8458
+ if (encoded.body !== void 0) init.body = encoded.body;
8459
+ const response = yield* Effect.tryPromise({
8460
+ catch: transportError,
8461
+ try: (signal) => fetch(`${endpoint.href.replace(/\/$/u, "")}${encoded.path}`, {
8462
+ ...init,
8463
+ signal: requestOptions.signal === void 0 ? signal : AbortSignal.any([requestOptions.signal, signal])
8464
+ })
8465
+ });
8466
+ const result = yield* Effect.tryPromise({
8467
+ catch: transportError,
8468
+ try: async () => await response.json()
8469
+ });
8470
+ return yield* Effect.try({
8471
+ catch: transportError,
8472
+ try: () => envelopeOf(response, result)
8473
+ });
8474
+ });
8475
+ };
8476
+ /**
8477
+ * Internal. Runs one entity request of a facade in `runtime`, which holds no
8478
+ * service: the core needs none. A transport failure, or an abort in flight,
8479
+ * resolves `transport_error` with `message`: `rejected` for a read,
8480
+ * `uncertain` for a write.
8481
+ */
8482
+ const runEntityRequest = async (runtime, effect, request) => {
8483
+ const { signal } = request;
8484
+ try {
8485
+ return await runtime.runPromise(effect, signal === void 0 ? void 0 : { signal });
8486
+ } catch (error) {
8487
+ if (!(error instanceof CiTransportError) && signal?.aborted !== true) throw error;
8488
+ return {
8489
+ correlationId: request.correlationId,
8490
+ error: {
8476
8491
  code: "transport_error",
8477
- message: "The entity response could not be received",
8478
- outcome: request.operation === "get" || request.operation === "list" || request.operation === "list_members" ? "rejected" : "uncertain",
8492
+ message: request.message,
8493
+ outcome: outcomeOf(request.operation),
8479
8494
  retryable: false
8480
- });
8481
- }
8482
- } };
8495
+ },
8496
+ ok: false
8497
+ };
8498
+ }
8483
8499
  };
8484
- export { createHttpOperationTransport as a, clientOperationIds as c, isEntityReadLimitError as i, isClientOperationId as l, createResourceClient as n, parseMountPath as o, createEntityProtocol as r, parseOriginUrl as s, createEntityHttpTransport as t };
8500
+ /**
8501
+ * The Vanilla Facade of the entity HTTP adapter, in a runtime of its own;
8502
+ * `close` disposes it.
8503
+ */
8504
+ const createEntityHttpTransport = (options) => {
8505
+ const execute = makeEntityHttpExecute(options);
8506
+ const runtime = ManagedRuntime.make(Layer.empty);
8507
+ return {
8508
+ close: () => runtime.dispose(),
8509
+ execute: (request, requestOptions = {}) => runEntityRequest(runtime, execute(request, requestOptions), {
8510
+ correlationId: request.requestId,
8511
+ message: "The entity response could not be received",
8512
+ operation: request.operation,
8513
+ signal: requestOptions.signal
8514
+ })
8515
+ };
8516
+ };
8517
+ /**
8518
+ * Resource clients on the Effect Core. One core per Resource Definition
8519
+ * checks each request against the definition (codec, capability, early
8520
+ * cancellation) and dispatches it through an adapter: the entity HTTP
8521
+ * adapter (`../transports/entity-http`) or a transport of the app. The core
8522
+ * keeps the `ResourceResult` envelope of `.`, whose `outcome` tells whether
8523
+ * a write can have happened; only a transport failure fails. `Resources`
8524
+ * moves each failed envelope to the typed channel for `./effect`.
8525
+ */
8526
+ const capabilityOf = {
8527
+ create: "create",
8528
+ delete: "delete",
8529
+ get: "get",
8530
+ list: "search",
8531
+ list_members: "search",
8532
+ update: "update",
8533
+ upload: "upload"
8534
+ };
8535
+ /** The adapter over an `EntityTransport` of the app; a rejection fails with `CiTransportError`. */
8536
+ const fromEntityTransport = (transport) => (request, options) => Effect.tryPromise({
8537
+ catch: (cause) => cause instanceof CiTransportError ? cause : new CiTransportError({ cause }),
8538
+ try: (signal) => transport.execute(request, { signal: options.signal === void 0 ? signal : AbortSignal.any([options.signal, signal]) })
8539
+ });
8540
+ /** Internal. The envelope core of the entity client of one definition. */
8541
+ const makeEntityCore = (options) => {
8542
+ const protocol = createEntityProtocol(options.definition);
8543
+ /** The correlation id of the next request. */
8544
+ const requestId = options.requestId ?? (() => globalThis.crypto.randomUUID());
8545
+ const execute = (input, correlationId, requestOptions = {}) => Effect.suspend(() => {
8546
+ const request = protocol.decodeRequest({
8547
+ ...input,
8548
+ requestId: correlationId,
8549
+ resourceId: options.definition.id
8550
+ });
8551
+ if (!request.ok) return Effect.succeed({
8552
+ ...request,
8553
+ error: {
8554
+ ...request.error,
8555
+ outcome: "not_dispatched"
8556
+ }
8557
+ });
8558
+ if (requestOptions.signal?.aborted === true) return Effect.succeed({
8559
+ correlationId,
8560
+ error: {
8561
+ code: "transport_error",
8562
+ message: "The entity request was cancelled before dispatch",
8563
+ outcome: "not_dispatched",
8564
+ retryable: false
8565
+ },
8566
+ ok: false
8567
+ });
8568
+ if (options.definition.capabilities[capabilityOf[input.operation]] !== true) return Effect.succeed({
8569
+ correlationId,
8570
+ error: {
8571
+ code: "capability_not_supported",
8572
+ message: "The entity operation is not supported",
8573
+ outcome: "not_dispatched",
8574
+ retryable: false
8575
+ },
8576
+ ok: false
8577
+ });
8578
+ return Effect.map(options.execute(request.value, requestOptions), (result) => {
8579
+ const decoded = protocol.decodeResult(input.operation, result, correlationId);
8580
+ return !decoded.ok && decoded.error.details?.phase === "response_contract" ? {
8581
+ ...decoded,
8582
+ error: {
8583
+ ...decoded.error,
8584
+ outcome: outcomeOf(input.operation)
8585
+ }
8586
+ } : decoded;
8587
+ });
8588
+ });
8589
+ return {
8590
+ definition: options.definition,
8591
+ execute,
8592
+ requestId
8593
+ };
8594
+ };
8595
+ const capabilityByOperation = {
8596
+ create: "create",
8597
+ get: "get",
8598
+ hard_delete: "hardDelete",
8599
+ list: "search",
8600
+ restore: "restore",
8601
+ soft_delete: "softDelete",
8602
+ update: "update"
8603
+ };
8604
+ /**
8605
+ * Internal. The core of the resource client over a `ResourceTransport`:
8606
+ * it checks the capabilities of each request, then dispatches it. A
8607
+ * transport that rejects fails with `CiTransportError`.
8608
+ */
8609
+ const makeResourceCore = (options) => ({ execute: (request, correlationId, checks) => Effect.suspend(() => {
8610
+ if (checks.validationError !== void 0) return Effect.succeed({
8611
+ correlationId,
8612
+ error: checks.validationError,
8613
+ ok: false
8614
+ });
8615
+ const unsupported = [capabilityByOperation[request.operation], ...checks.additionalCapabilities].find((capability) => options.definition.capabilities[capability] !== true);
8616
+ if (unsupported !== void 0) return Effect.succeed({
8617
+ correlationId,
8618
+ error: {
8619
+ code: "capability_not_supported",
8620
+ details: { capability: unsupported },
8621
+ message: `Resource ${options.definition.id} does not support ${unsupported}`,
8622
+ retryable: false
8623
+ },
8624
+ ok: false
8625
+ });
8626
+ return Effect.tryPromise({
8627
+ catch: (cause) => new CiTransportError({ cause }),
8628
+ try: () => options.transport.execute({
8629
+ ...request,
8630
+ requestId: correlationId,
8631
+ resourceId: options.definition.id
8632
+ }, checks.requestOptions)
8633
+ }).pipe(Effect.map((result) => result));
8634
+ }) });
8635
+ /**
8636
+ * Internal. The calls of the legacy resource client of one definition over
8637
+ * a `ResourceTransport`; the `.` facade and `LegacyResources` share them.
8638
+ */
8639
+ const makeLegacyResourceCore = (options) => {
8640
+ const core = makeResourceCore(options);
8641
+ const call = (request, additionalCapabilities = [], validationError) => (correlationId, requestOptions) => core.execute(request, correlationId, {
8642
+ additionalCapabilities,
8643
+ requestOptions,
8644
+ validationError
8645
+ });
8646
+ const { modes } = options.definition.query.pagination;
8647
+ return {
8648
+ create: (input) => call({
8649
+ ...input,
8650
+ operation: "create"
8651
+ }),
8652
+ get: (input) => call({
8653
+ ...input,
8654
+ operation: "get"
8655
+ }, input.includeDeleted === true ? ["includeDeleted"] : []),
8656
+ hardDelete: (input) => call({
8657
+ ...input,
8658
+ operation: "hard_delete"
8659
+ }),
8660
+ list: (query) => call({
8661
+ operation: "list",
8662
+ query
8663
+ }, query.includeDeleted === true ? ["includeDeleted"] : [], modes.includes(query.pagination.mode) ? void 0 : {
8664
+ code: "capability_not_supported",
8665
+ details: { paginationMode: query.pagination.mode },
8666
+ message: `Resource ${options.definition.id} does not support ${query.pagination.mode} pagination`,
8667
+ retryable: false
8668
+ }),
8669
+ restore: (input) => call({
8670
+ ...input,
8671
+ operation: "restore"
8672
+ }),
8673
+ softDelete: (input) => call({
8674
+ ...input,
8675
+ operation: "soft_delete"
8676
+ }),
8677
+ update: (input) => call({
8678
+ ...input,
8679
+ operation: "update"
8680
+ })
8681
+ };
8682
+ };
8683
+ /** The CI code of a resource error code that CI does not have. */
8684
+ const ciCode = (code) => ciErrorCodes.find((candidate) => candidate === code) ?? "invalid_request";
8685
+ /** The `details` of a resource error, with its code and outcome. */
8686
+ const resourceDetails = (error) => error.outcome === void 0 ? {
8687
+ ...error.details,
8688
+ resourceCode: error.code
8689
+ } : {
8690
+ ...error.details,
8691
+ outcome: error.outcome,
8692
+ resourceCode: error.code
8693
+ };
8694
+ /**
8695
+ * The typed failure of a failed envelope: a `transport_error` (the answer
8696
+ * could not be read) is `CiTransportError`; any other error is `CiError`
8697
+ * with the resource code and outcome in its `details`.
8698
+ */
8699
+ const failure = (error) => error.code === "transport_error" ? new CiTransportError({ cause: error }) : new CiError({
8700
+ code: ciCode(error.code),
8701
+ details: resourceDetails(error),
8702
+ message: error.message,
8703
+ retryable: error.retryable
8704
+ });
8705
+ const valueOf = (result) => result.ok ? Effect.succeed(result.value) : Effect.fail(failure(result.error));
8706
+ var Resources = class extends Context.Service()("@collective-intelligence/external-apps-client-sdk/Resources") {};
8707
+ /** `Resources` over the adapter that `executeOf` gives each Resource Definition. */
8708
+ const makeResources = (executeOf, requestId) => Resources.of({ bind: (definition) => {
8709
+ const core = makeEntityCore({
8710
+ definition,
8711
+ execute: executeOf(definition.id),
8712
+ requestId
8713
+ });
8714
+ const call = (effect) => Effect.flatMap(Effect.suspend(() => effect(core.requestId())), valueOf);
8715
+ return {
8716
+ create: (input) => call((id) => core.execute({
8717
+ ...input,
8718
+ operation: "create"
8719
+ }, id)),
8720
+ definition,
8721
+ delete: (input) => call((id) => core.execute({
8722
+ ...input,
8723
+ operation: "delete"
8724
+ }, id)),
8725
+ get: (input) => call((id) => core.execute({
8726
+ ...input,
8727
+ operation: "get"
8728
+ }, id)),
8729
+ list: (query) => call((id) => core.execute({
8730
+ operation: "list",
8731
+ query
8732
+ }, id)),
8733
+ listMembers: (parentId, field, query) => call((id) => core.execute({
8734
+ field,
8735
+ operation: "list_members",
8736
+ parentId,
8737
+ query
8738
+ }, id)),
8739
+ update: (input) => call((id) => core.execute({
8740
+ ...input,
8741
+ operation: "update"
8742
+ }, id)),
8743
+ upload: (input) => call((id) => core.execute({
8744
+ ...input,
8745
+ operation: "upload"
8746
+ }, id))
8747
+ };
8748
+ } });
8749
+ const make = (options) => makeResources((resourceId) => makeEntityHttpExecute({
8750
+ ...options,
8751
+ destination: options.destination(resourceId)
8752
+ }), options.requestId);
8753
+ /** `Resources` over the entity HTTP routes of `destination`. */
8754
+ const layer = (options) => Layer.sync(Resources, () => make(options));
8755
+ /** `layer` with options that Effect `Config` reads. */
8756
+ const layerConfig = (config) => Layer.unwrap(Effect.map(Config.unwrap(config), layer));
8757
+ /**
8758
+ * `Resources` over an `EntityTransport` of the app, as
8759
+ * `createResourceClient` with `protocol: "entity"`. A rejection of the
8760
+ * transport fails with `CiTransportError`.
8761
+ */
8762
+ const layerFromEntityTransport = (options) => Layer.succeed(Resources, makeResources(() => fromEntityTransport(options.transport), options.requestId));
8763
+ /** The `./effect` form of `createResourceClient` over a `ResourceTransport`. */
8764
+ var LegacyResources = class extends Context.Service()("@collective-intelligence/external-apps-client-sdk/LegacyResources") {};
8765
+ const makeLegacy = (options) => LegacyResources.of({ bind: (definition) => {
8766
+ const legacy = makeLegacyResourceCore({
8767
+ definition,
8768
+ transport: options.transport
8769
+ });
8770
+ const requestId = options.requestId ?? (() => globalThis.crypto.randomUUID());
8771
+ const call = (effect) => Effect.flatMap(Effect.suspend(() => effect(requestId())), valueOf);
8772
+ return {
8773
+ create: (input) => call(legacy.create(input)),
8774
+ definition,
8775
+ get: (input) => call(legacy.get(input)),
8776
+ hardDelete: (input) => Effect.asVoid(call(legacy.hardDelete(input))),
8777
+ list: (query) => call(legacy.list(query)),
8778
+ restore: (input) => call(legacy.restore(input)),
8779
+ softDelete: (input) => call(legacy.softDelete(input)),
8780
+ update: (input) => call(legacy.update(input))
8781
+ };
8782
+ } });
8783
+ /** `LegacyResources` over the `ResourceTransport` of `options`. */
8784
+ const layerLegacy = (options) => Layer.succeed(LegacyResources, makeLegacy(options));
8785
+ /** `layerLegacy` with options that Effect `Config` reads. */
8786
+ const layerLegacyConfig = (config) => Layer.unwrap(Effect.map(Config.unwrap(config), layerLegacy));
8787
+ export { CiError as C, FederatedAuthErrorCode as D, FederatedAuthError as E, errors_exports as O, toCiResult as S, CiTransportError as T, makeHttpExecute as _, layerConfig as a, fromCiResult as b, layerLegacyConfig as c, createEntityHttpTransport as d, runEntityRequest as f, directHttpOptions as g, backendErrorCode as h, layer as i, ciErrorCodes as k, makeEntityCore as l, isEntityReadLimitError as m, Resources as n, layerFromEntityTransport as o, createEntityProtocol as p, fromEntityTransport as r, layerLegacy as s, LegacyResources as t, makeLegacyResourceCore as u, proxyHttpOptions as v, CiErrorCode as w, isClientOperationId as x, clientOperationIds as y };