@collective-intelligence/external-apps-client-sdk 0.1.35 → 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,3 +1,11 @@
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";
1
9
  var __create = Object.create;
2
10
  var __defProp = Object.defineProperty;
3
11
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -5,6 +13,15 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
5
13
  var __getProtoOf = Object.getPrototypeOf;
6
14
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
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
+ };
8
25
  var __copyProps = (to, from, except, desc) => {
9
26
  if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
27
  key = keys[i];
@@ -19,6 +36,59 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
19
36
  value: mod,
20
37
  enumerable: true
21
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() }) {};
22
92
  const completeOperationRegistry = (ids) => ids;
23
93
  /** Generated, curated external-application operation authority. */
24
94
  const clientOperationIds = completeOperationRegistry([
@@ -57,6 +127,37 @@ const clientOperationIds = completeOperationRegistry([
57
127
  ]);
58
128
  const clientOperationIdSet = new Set(clientOperationIds);
59
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));
60
161
  const isRecord$1 = (value) => value !== null && Object(value) === value && !Array.isArray(value);
61
162
  const textField = (value, key) => {
62
163
  const field = value[key];
@@ -298,6 +399,7 @@ const dedicatedResult = (value) => {
298
399
  const isRecord = (value) => value !== null && Object(value) === value && !Array.isArray(value);
299
400
  const isString = (value) => typeof value === "string";
300
401
  const isBoolean = (value) => typeof value === "boolean";
402
+ /** The `CiErrorCode` of a backend error code. */
301
403
  const backendErrorCode = (value) => {
302
404
  switch (value) {
303
405
  case "authentication_required": return "unauthenticated";
@@ -317,21 +419,21 @@ const transportFailure = (response, value) => {
317
419
  const code = isString(rawCode) ? backendErrorCode(rawCode) : "internal";
318
420
  return {
319
421
  correlationId: isString(value.correlationId) ? value.correlationId : response.headers.get("x-correlation-id") ?? "unavailable",
320
- error: {
422
+ error: new CiError({
321
423
  code,
322
424
  message: isString(value.error.message) ? value.error.message : "The CI operation failed",
323
425
  retryable: isBoolean(value.error.retryable) ? value.error.retryable : response.status >= 500
324
- },
426
+ }),
325
427
  ok: false
326
428
  };
327
429
  }
328
430
  return {
329
431
  correlationId: response.headers.get("x-correlation-id") ?? "unavailable",
330
- error: {
432
+ error: new CiError({
331
433
  code: response.status === 429 ? "rate_limited" : "internal",
332
434
  message: "The CI operation returned an invalid response",
333
435
  retryable: response.status === 429 || response.status >= 500
334
- },
436
+ }),
335
437
  ok: false
336
438
  };
337
439
  };
@@ -340,82 +442,94 @@ const clientFailure = (error) => ({
340
442
  error,
341
443
  ok: false
342
444
  });
343
- const responseJson = async (response) => {
445
+ const responseJson = (response) => Effect.promise(async () => {
344
446
  try {
345
447
  return await response.json();
346
448
  } catch {
347
449
  return null;
348
450
  }
349
- };
350
- const createHttpOperationTransport = ({ authorization, basePath, credentials = "omit", fetch, origin }) => ({ execute: async (operationId, input, options) => {
351
- 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({
352
471
  code: "invalid_request",
353
472
  message: "The operation is not part of the client-safe registry",
354
473
  retryable: false
355
- });
356
- if (options === void 0 || options.organizationId.length === 0) return clientFailure({
474
+ }));
475
+ if (options.organizationId.length === 0) return clientFailure(new CiError({
357
476
  code: "invalid_request",
358
477
  message: "organizationId is required",
359
478
  retryable: false
360
- });
479
+ }));
361
480
  const call = dedicatedHttpCall(operationId, input);
362
- if (call === null) return clientFailure({
481
+ if (call === null) return clientFailure(new CiError({
363
482
  code: "invalid_request",
364
483
  message: `${operationId} was removed from Application HTTP; use /application/v1/resources`,
365
484
  retryable: false
366
- });
485
+ }));
367
486
  const headers = new Headers({ "x-organization-id": options.organizationId });
368
487
  if (call.body !== void 0) headers.set("content-type", "application/json");
369
- let accessToken;
370
- try {
371
- accessToken = await authorization?.();
372
- } catch {
373
- return clientFailure({
374
- code: "unauthenticated",
375
- message: "CI login is required",
376
- retryable: false
377
- });
378
- }
379
- 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}`);
380
495
  if (call.idempotencyKey !== void 0) headers.set("idempotency-key", call.idempotencyKey);
381
496
  if (call.lastEventId !== void 0) headers.set("last-event-id", call.lastEventId);
382
497
  const search = new URLSearchParams(call.query ?? {}).toString();
383
498
  const endpoint = new URL(`${basePath}${call.pathname}${search === "" ? "" : `?${search}`}`, origin);
384
- let response;
385
499
  const requestInit = {
386
500
  credentials,
387
501
  headers,
388
502
  method: call.method
389
503
  };
390
504
  if (call.body !== void 0) requestInit.body = JSON.stringify(call.body);
391
- if (options.signal !== void 0) requestInit.signal = options.signal;
392
- try {
393
- response = await fetch(endpoint, requestInit);
394
- } catch {
395
- return clientFailure({
396
- code: "unavailable",
397
- message: "The CI operation could not be reached",
398
- retryable: true
399
- });
400
- }
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";
401
513
  if (call.parse === "event_stream") {
402
- if (!response.ok) return transportFailure(response, await responseJson(response));
403
- 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
+ });
404
519
  return {
405
- correlationId: response.headers.get("x-correlation-id") ?? "unavailable",
520
+ correlationId: headerCorrelation,
406
521
  ok: true,
407
- value: page
522
+ value: parseRunEventStream(text)
408
523
  };
409
524
  }
410
- const value = await responseJson(response);
525
+ const value = yield* responseJson(response);
411
526
  if (!response.ok) return transportFailure(response, value);
412
- const headerCorrelation = response.headers.get("x-correlation-id") ?? "unavailable";
413
527
  return {
414
528
  correlationId: isRecord(value) && isString(value.correlationId) ? value.correlationId : headerCorrelation,
415
529
  ok: true,
416
530
  value: dedicatedResult(value)
417
531
  };
418
- } });
532
+ });
419
533
  const parseOriginUrl = (value, field) => {
420
534
  let url;
421
535
  try {
@@ -431,6 +545,25 @@ const parseMountPath = (value) => {
431
545
  const normalized = value.replace(/\/+$/u, "");
432
546
  return normalized === "" ? "" : normalized;
433
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
+ };
434
567
  var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => {
435
568
  Object.defineProperty(exports, "__esModule", { value: true });
436
569
  exports.formatNames = exports.fastFormats = exports.fullFormats = void 0;
@@ -8189,193 +8322,8 @@ const createEntityProtocol = (definition) => {
8189
8322
  }
8190
8323
  };
8191
8324
  };
8192
- const createCommonEntityClient = (options) => {
8193
- const protocol = createEntityProtocol(options.definition);
8194
- const execute = async (input, requestOptions) => {
8195
- const correlationId = options.requestId?.() ?? globalThis.crypto.randomUUID();
8196
- const request = protocol.decodeRequest({
8197
- ...input,
8198
- requestId: correlationId,
8199
- resourceId: options.definition.id
8200
- });
8201
- if (!request.ok) return {
8202
- ...request,
8203
- error: {
8204
- ...request.error,
8205
- outcome: "not_dispatched"
8206
- }
8207
- };
8208
- if (requestOptions?.signal?.aborted) return {
8209
- correlationId,
8210
- error: {
8211
- code: "transport_error",
8212
- message: "The entity request was cancelled before dispatch",
8213
- outcome: "not_dispatched",
8214
- retryable: false
8215
- },
8216
- ok: false
8217
- };
8218
- if (options.definition.capabilities[{
8219
- create: "create",
8220
- delete: "delete",
8221
- get: "get",
8222
- list: "search",
8223
- list_members: "search",
8224
- update: "update",
8225
- upload: "upload"
8226
- }[input.operation]] !== true) return {
8227
- correlationId,
8228
- error: {
8229
- code: "capability_not_supported",
8230
- message: "The entity operation is not supported",
8231
- outcome: "not_dispatched",
8232
- retryable: false
8233
- },
8234
- ok: false
8235
- };
8236
- try {
8237
- const result = await options.transport.execute(request.value, requestOptions);
8238
- const decoded = protocol.decodeResult(input.operation, result, correlationId);
8239
- return !decoded.ok && decoded.error.details?.phase === "response_contract" ? {
8240
- ...decoded,
8241
- error: {
8242
- ...decoded.error,
8243
- outcome: input.operation === "list" || input.operation === "list_members" || input.operation === "get" ? "rejected" : "uncertain"
8244
- }
8245
- } : decoded;
8246
- } catch {
8247
- return {
8248
- correlationId,
8249
- error: {
8250
- code: "transport_error",
8251
- message: "The entity transport failed",
8252
- outcome: input.operation === "list" || input.operation === "list_members" || input.operation === "get" ? "rejected" : "uncertain",
8253
- retryable: false
8254
- },
8255
- ok: false
8256
- };
8257
- }
8258
- };
8259
- return {
8260
- create: (input) => execute({
8261
- ...input,
8262
- operation: "create"
8263
- }),
8264
- definition: options.definition,
8265
- delete: (input) => execute({
8266
- ...input,
8267
- operation: "delete"
8268
- }),
8269
- get: (input, requestOptions) => execute({
8270
- ...input,
8271
- operation: "get"
8272
- }, requestOptions),
8273
- list: (query, requestOptions) => execute({
8274
- operation: "list",
8275
- query
8276
- }, requestOptions),
8277
- listMembers: (parentId, field, query, requestOptions) => execute({
8278
- field,
8279
- operation: "list_members",
8280
- parentId,
8281
- query
8282
- }, requestOptions),
8283
- update: (input) => execute({
8284
- ...input,
8285
- operation: "update"
8286
- }),
8287
- upload: (input, requestOptions) => execute({
8288
- ...input,
8289
- operation: "upload"
8290
- }, requestOptions)
8291
- };
8292
- };
8293
- const capabilityByOperation = {
8294
- create: "create",
8295
- get: "get",
8296
- hard_delete: "hardDelete",
8297
- list: "search",
8298
- restore: "restore",
8299
- soft_delete: "softDelete",
8300
- update: "update"
8301
- };
8302
- const unavailable = (cause) => ({
8303
- code: "transport_error",
8304
- details: { cause: cause instanceof Error ? cause.message : String(cause) },
8305
- message: "The resource transport failed",
8306
- retryable: true
8307
- });
8308
- const defaultRequestId = () => globalThis.crypto.randomUUID();
8309
- const createLegacyResourceClient = (options) => {
8310
- const requestId = options.requestId ?? defaultRequestId;
8311
- const execute = async (request, requestOptions, additionalCapabilities = [], validationError) => {
8312
- const correlationId = requestId();
8313
- if (validationError !== void 0) return {
8314
- correlationId,
8315
- error: validationError,
8316
- ok: false
8317
- };
8318
- const unsupportedCapability = [capabilityByOperation[request.operation], ...additionalCapabilities].find((capability) => options.definition.capabilities[capability] !== true);
8319
- if (unsupportedCapability !== void 0) return {
8320
- correlationId,
8321
- error: {
8322
- code: "capability_not_supported",
8323
- details: { capability: unsupportedCapability },
8324
- message: `Resource ${options.definition.id} does not support ${unsupportedCapability}`,
8325
- retryable: false
8326
- },
8327
- ok: false
8328
- };
8329
- try {
8330
- return await options.transport.execute({
8331
- ...request,
8332
- requestId: correlationId,
8333
- resourceId: options.definition.id
8334
- }, requestOptions);
8335
- } catch (error) {
8336
- return {
8337
- correlationId,
8338
- error: unavailable(error),
8339
- ok: false
8340
- };
8341
- }
8342
- };
8343
- const lifecycle = async (operation, input, requestOptions) => await execute({
8344
- ...input,
8345
- operation
8346
- }, requestOptions);
8347
- return {
8348
- capabilities: options.definition.capabilities,
8349
- create: async (input, requestOptions) => await execute({
8350
- ...input,
8351
- operation: "create"
8352
- }, requestOptions),
8353
- definition: options.definition,
8354
- get: async (input, requestOptions) => await execute({
8355
- ...input,
8356
- operation: "get"
8357
- }, requestOptions, input.includeDeleted === true ? ["includeDeleted"] : []),
8358
- hardDelete: async (input, requestOptions) => await lifecycle("hard_delete", input, requestOptions),
8359
- list: async (query, requestOptions) => await execute({
8360
- operation: "list",
8361
- query
8362
- }, requestOptions, query.includeDeleted === true ? ["includeDeleted"] : [], options.definition.query.pagination.modes.includes(query.pagination.mode) ? void 0 : {
8363
- code: "capability_not_supported",
8364
- details: { paginationMode: query.pagination.mode },
8365
- message: `Resource ${options.definition.id} does not support ${query.pagination.mode} pagination`,
8366
- retryable: false
8367
- }),
8368
- restore: async (input, requestOptions) => await lifecycle("restore", input, requestOptions),
8369
- softDelete: async (input, requestOptions) => await lifecycle("soft_delete", input, requestOptions),
8370
- update: async (input, requestOptions) => await execute({
8371
- ...input,
8372
- operation: "update"
8373
- }, requestOptions)
8374
- };
8375
- };
8376
- function createResourceClient(options) {
8377
- return options.protocol === "entity" ? createCommonEntityClient(options) : createLegacyResourceClient(options);
8378
- }
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";
8379
8327
  const encode = (request) => {
8380
8328
  switch (request.operation) {
8381
8329
  case "list": return {
@@ -8434,71 +8382,406 @@ const encode = (request) => {
8434
8382
  };
8435
8383
  }
8436
8384
  };
8437
- 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) => {
8438
8421
  const { destination, authentication } = options;
8439
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");
8440
8423
  const endpoint = destination.kind === "gateway" ? new URL(destination.endpoint) : new URL(`/application/v1/resources/${encodeURIComponent(destination.schemaFqn)}`, parseOriginUrl(destination.tenantUrl, "tenantUrl"));
8441
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");
8442
8425
  const fetch = options.fetch ?? globalThis.fetch;
8443
8426
  const credentials = authentication.mode === "server_delegated" ? authentication.credentials ?? "same-origin" : "omit";
8444
- return { execute: async (request, requestOptions) => {
8445
- const failure = (error) => ({
8446
- correlationId: request.requestId,
8447
- error,
8448
- ok: false
8449
- });
8450
- const cancelled = () => failure({
8451
- code: "transport_error",
8452
- message: "The entity request was cancelled before dispatch",
8453
- outcome: "not_dispatched",
8454
- retryable: false
8455
- });
8456
- if (requestOptions?.signal?.aborted) return cancelled();
8427
+ return (request, requestOptions) => Effect.gen(function* execute() {
8428
+ if (requestOptions.signal?.aborted) return cancelled(request);
8457
8429
  const encoded = encode(request);
8458
8430
  const headers = new Headers({
8459
8431
  "content-type": "application/json",
8460
8432
  "x-correlation-id": request.requestId
8461
8433
  });
8462
8434
  if (destination.kind === "ci") headers.set("x-organization-id", destination.organizationId);
8463
- try {
8464
- if (authentication.mode === "federated") headers.set("authorization", `Bearer ${await authentication.auth.getAccessToken()}`);
8465
- } catch {
8466
- 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, {
8467
8444
  code: "unauthenticated",
8468
8445
  message: "CI login is required",
8469
8446
  outcome: "not_dispatched",
8470
8447
  retryable: false
8471
8448
  });
8472
- }
8473
- if (requestOptions?.signal?.aborted) return cancelled();
8474
- try {
8475
- const init = {
8476
- credentials,
8477
- headers,
8478
- method: encoded.method,
8479
- redirect: "error"
8480
- };
8481
- if (encoded.body !== void 0) init.body = encoded.body;
8482
- if (requestOptions?.signal !== void 0) init.signal = requestOptions.signal;
8483
- const response = await fetch(`${endpoint.href.replace(/\/$/u, "")}${encoded.path}`, init);
8484
- const result = await response.json();
8485
- if (result.ok === false) return {
8486
- ...result,
8487
- error: {
8488
- ...result.error,
8489
- outcome: result.error.outcome ?? "rejected"
8490
- }
8491
- };
8492
- if (!response.ok) throw new Error("Unexpected successful envelope for failed HTTP response");
8493
- return result;
8494
- } catch {
8495
- 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: {
8496
8491
  code: "transport_error",
8497
- message: "The entity response could not be received",
8498
- outcome: request.operation === "get" || request.operation === "list" || request.operation === "list_members" ? "rejected" : "uncertain",
8492
+ message: request.message,
8493
+ outcome: outcomeOf(request.operation),
8499
8494
  retryable: false
8500
- });
8501
- }
8502
- } };
8495
+ },
8496
+ ok: false
8497
+ };
8498
+ }
8499
+ };
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
+ };
8503
8682
  };
8504
- 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 };
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 };