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

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;
@@ -7971,10 +8124,19 @@ const createEntityProtocol = (definition) => {
7971
8124
  id: identifier,
7972
8125
  idempotencyKey: operationKey
7973
8126
  }),
8127
+ requestSchema(definition, "restore", {
8128
+ expectedRevision: identifier,
8129
+ id: identifier,
8130
+ idempotencyKey: operationKey
8131
+ }),
7974
8132
  requestSchema(definition, "upload", {
7975
8133
  field: uploadText,
7976
8134
  filename: uploadText,
7977
- mimeType: uploadText
8135
+ mimeType: uploadText,
8136
+ size: {
8137
+ minimum: 0,
8138
+ type: "integer"
8139
+ }
7978
8140
  })
7979
8141
  ]
7980
8142
  });
@@ -8126,6 +8288,7 @@ const createEntityProtocol = (definition) => {
8126
8288
  get: validateRecord,
8127
8289
  list: coherentPage(validatePage),
8128
8290
  list_members: coherentPage(validateMemberPage),
8291
+ restore: validateRecord,
8129
8292
  update: validateRecord,
8130
8293
  upload: validateUploadSlot
8131
8294
  };
@@ -8169,193 +8332,8 @@ const createEntityProtocol = (definition) => {
8169
8332
  }
8170
8333
  };
8171
8334
  };
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
- }
8335
+ /** A read can be retried; a write that failed in flight can have happened. */
8336
+ const outcomeOf = (operation) => operation === "get" || operation === "list" || operation === "list_members" ? "rejected" : "uncertain";
8359
8337
  const encode = (request) => {
8360
8338
  switch (request.operation) {
8361
8339
  case "list": return {
@@ -8403,82 +8381,431 @@ const encode = (request) => {
8403
8381
  method: "POST",
8404
8382
  path: `/records/${encodeURIComponent(request.id)}/soft-delete`
8405
8383
  };
8384
+ case "restore": return {
8385
+ body: JSON.stringify({
8386
+ expectedRevision: request.expectedRevision,
8387
+ idempotencyKey: request.idempotencyKey
8388
+ }),
8389
+ method: "POST",
8390
+ path: `/records/${encodeURIComponent(request.id)}/restore`
8391
+ };
8406
8392
  case "upload": return {
8407
8393
  body: JSON.stringify({
8408
8394
  field: request.field,
8409
8395
  filename: request.filename,
8410
- mimeType: request.mimeType
8396
+ mimeType: request.mimeType,
8397
+ size: request.size
8411
8398
  }),
8412
8399
  method: "POST",
8413
8400
  path: "/uploads"
8414
8401
  };
8415
8402
  }
8416
8403
  };
8417
- const createEntityHttpTransport = (options) => {
8404
+ const failure$1 = (request, error) => ({
8405
+ correlationId: request.requestId,
8406
+ error,
8407
+ ok: false
8408
+ });
8409
+ const cancelled = (request) => failure$1(request, {
8410
+ code: "transport_error",
8411
+ message: "The entity request was cancelled before dispatch",
8412
+ outcome: "not_dispatched",
8413
+ retryable: false
8414
+ });
8415
+ const transportError = (cause) => new CiTransportError({ cause });
8416
+ /**
8417
+ * The envelope of an entity answer. It throws when the answer is not an
8418
+ * envelope, or is a success for a failed HTTP status: the caller reads such
8419
+ * a throw as a transport failure.
8420
+ */
8421
+ const envelopeOf = (response, result) => {
8422
+ if (result.ok === false) return {
8423
+ ...result,
8424
+ error: {
8425
+ ...result.error,
8426
+ outcome: result.error.outcome ?? "rejected"
8427
+ }
8428
+ };
8429
+ if (!response.ok) throw new Error("Unexpected successful envelope for failed HTTP response");
8430
+ return result;
8431
+ };
8432
+ /**
8433
+ * The entity HTTP adapter of one destination. Early cancellation and a
8434
+ * failed login stay envelopes, as the request was not sent; a request that
8435
+ * does not reach the server, or an answer that cannot be read, fails with
8436
+ * `CiTransportError`. A destination without its CI selectors, or an
8437
+ * endpoint with credentials, query or fragment, throws `TypeError`.
8438
+ */
8439
+ const makeEntityHttpExecute = (options) => {
8418
8440
  const { destination, authentication } = options;
8419
8441
  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
8442
  const endpoint = destination.kind === "gateway" ? new URL(destination.endpoint) : new URL(`/application/v1/resources/${encodeURIComponent(destination.schemaFqn)}`, parseOriginUrl(destination.tenantUrl, "tenantUrl"));
8421
8443
  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
8444
  const fetch = options.fetch ?? globalThis.fetch;
8423
8445
  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();
8446
+ return (request, requestOptions) => Effect.gen(function* execute() {
8447
+ if (requestOptions.signal?.aborted) return cancelled(request);
8437
8448
  const encoded = encode(request);
8438
8449
  const headers = new Headers({
8439
8450
  "content-type": "application/json",
8440
8451
  "x-correlation-id": request.requestId
8441
8452
  });
8442
8453
  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({
8454
+ if (authentication.mode === "federated") {
8455
+ const token = yield* Effect.promise(async () => {
8456
+ try {
8457
+ return { value: await authentication.auth.getAccessToken() };
8458
+ } catch {
8459
+ return null;
8460
+ }
8461
+ });
8462
+ if (token === null) return failure$1(request, {
8447
8463
  code: "unauthenticated",
8448
8464
  message: "CI login is required",
8449
8465
  outcome: "not_dispatched",
8450
8466
  retryable: false
8451
8467
  });
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({
8468
+ headers.set("authorization", `Bearer ${token.value}`);
8469
+ }
8470
+ if (requestOptions.signal?.aborted) return cancelled(request);
8471
+ const init = {
8472
+ credentials,
8473
+ headers,
8474
+ method: encoded.method,
8475
+ redirect: "error"
8476
+ };
8477
+ if (encoded.body !== void 0) init.body = encoded.body;
8478
+ const response = yield* Effect.tryPromise({
8479
+ catch: transportError,
8480
+ try: (signal) => fetch(`${endpoint.href.replace(/\/$/u, "")}${encoded.path}`, {
8481
+ ...init,
8482
+ signal: requestOptions.signal === void 0 ? signal : AbortSignal.any([requestOptions.signal, signal])
8483
+ })
8484
+ });
8485
+ const result = yield* Effect.tryPromise({
8486
+ catch: transportError,
8487
+ try: async () => await response.json()
8488
+ });
8489
+ return yield* Effect.try({
8490
+ catch: transportError,
8491
+ try: () => envelopeOf(response, result)
8492
+ });
8493
+ });
8494
+ };
8495
+ /**
8496
+ * Internal. Runs one entity request of a facade in `runtime`, which holds no
8497
+ * service: the core needs none. A transport failure, or an abort in flight,
8498
+ * resolves `transport_error` with `message`: `rejected` for a read,
8499
+ * `uncertain` for a write.
8500
+ */
8501
+ const runEntityRequest = async (runtime, effect, request) => {
8502
+ const { signal } = request;
8503
+ try {
8504
+ return await runtime.runPromise(effect, signal === void 0 ? void 0 : { signal });
8505
+ } catch (error) {
8506
+ if (!(error instanceof CiTransportError) && signal?.aborted !== true) throw error;
8507
+ return {
8508
+ correlationId: request.correlationId,
8509
+ error: {
8476
8510
  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",
8511
+ message: request.message,
8512
+ outcome: outcomeOf(request.operation),
8479
8513
  retryable: false
8480
- });
8481
- }
8482
- } };
8514
+ },
8515
+ ok: false
8516
+ };
8517
+ }
8518
+ };
8519
+ /**
8520
+ * The Vanilla Facade of the entity HTTP adapter, in a runtime of its own;
8521
+ * `close` disposes it.
8522
+ */
8523
+ const createEntityHttpTransport = (options) => {
8524
+ const execute = makeEntityHttpExecute(options);
8525
+ const runtime = ManagedRuntime.make(Layer.empty);
8526
+ return {
8527
+ close: () => runtime.dispose(),
8528
+ execute: (request, requestOptions = {}) => runEntityRequest(runtime, execute(request, requestOptions), {
8529
+ correlationId: request.requestId,
8530
+ message: "The entity response could not be received",
8531
+ operation: request.operation,
8532
+ signal: requestOptions.signal
8533
+ })
8534
+ };
8535
+ };
8536
+ /**
8537
+ * Resource clients on the Effect Core. One core per Resource Definition
8538
+ * checks each request against the definition (codec, capability, early
8539
+ * cancellation) and dispatches it through an adapter: the entity HTTP
8540
+ * adapter (`../transports/entity-http`) or a transport of the app. The core
8541
+ * keeps the `ResourceResult` envelope of `.`, whose `outcome` tells whether
8542
+ * a write can have happened; only a transport failure fails. `Resources`
8543
+ * moves each failed envelope to the typed channel for `./effect`.
8544
+ */
8545
+ const capabilityOf = {
8546
+ create: "create",
8547
+ delete: "delete",
8548
+ get: "get",
8549
+ list: "search",
8550
+ list_members: "search",
8551
+ restore: "restore",
8552
+ update: "update",
8553
+ upload: "upload"
8554
+ };
8555
+ /** The adapter over an `EntityTransport` of the app; a rejection fails with `CiTransportError`. */
8556
+ const fromEntityTransport = (transport) => (request, options) => Effect.tryPromise({
8557
+ catch: (cause) => cause instanceof CiTransportError ? cause : new CiTransportError({ cause }),
8558
+ try: (signal) => transport.execute(request, { signal: options.signal === void 0 ? signal : AbortSignal.any([options.signal, signal]) })
8559
+ });
8560
+ /** Internal. The envelope core of the entity client of one definition. */
8561
+ const makeEntityCore = (options) => {
8562
+ const protocol = createEntityProtocol(options.definition);
8563
+ /** The correlation id of the next request. */
8564
+ const requestId = options.requestId ?? (() => globalThis.crypto.randomUUID());
8565
+ const execute = (input, correlationId, requestOptions = {}) => Effect.suspend(() => {
8566
+ const request = protocol.decodeRequest({
8567
+ ...input,
8568
+ requestId: correlationId,
8569
+ resourceId: options.definition.id
8570
+ });
8571
+ if (!request.ok) return Effect.succeed({
8572
+ ...request,
8573
+ error: {
8574
+ ...request.error,
8575
+ outcome: "not_dispatched"
8576
+ }
8577
+ });
8578
+ if (requestOptions.signal?.aborted === true) return Effect.succeed({
8579
+ correlationId,
8580
+ error: {
8581
+ code: "transport_error",
8582
+ message: "The entity request was cancelled before dispatch",
8583
+ outcome: "not_dispatched",
8584
+ retryable: false
8585
+ },
8586
+ ok: false
8587
+ });
8588
+ if (options.definition.capabilities[capabilityOf[input.operation]] !== true) return Effect.succeed({
8589
+ correlationId,
8590
+ error: {
8591
+ code: "capability_not_supported",
8592
+ message: "The entity operation is not supported",
8593
+ outcome: "not_dispatched",
8594
+ retryable: false
8595
+ },
8596
+ ok: false
8597
+ });
8598
+ return Effect.map(options.execute(request.value, requestOptions), (result) => {
8599
+ const decoded = protocol.decodeResult(input.operation, result, correlationId);
8600
+ return !decoded.ok && decoded.error.details?.phase === "response_contract" ? {
8601
+ ...decoded,
8602
+ error: {
8603
+ ...decoded.error,
8604
+ outcome: outcomeOf(input.operation)
8605
+ }
8606
+ } : decoded;
8607
+ });
8608
+ });
8609
+ return {
8610
+ definition: options.definition,
8611
+ execute,
8612
+ requestId
8613
+ };
8614
+ };
8615
+ const capabilityByOperation = {
8616
+ create: "create",
8617
+ get: "get",
8618
+ hard_delete: "hardDelete",
8619
+ list: "search",
8620
+ restore: "restore",
8621
+ soft_delete: "softDelete",
8622
+ update: "update"
8623
+ };
8624
+ /**
8625
+ * Internal. The core of the resource client over a `ResourceTransport`:
8626
+ * it checks the capabilities of each request, then dispatches it. A
8627
+ * transport that rejects fails with `CiTransportError`.
8628
+ */
8629
+ const makeResourceCore = (options) => ({ execute: (request, correlationId, checks) => Effect.suspend(() => {
8630
+ if (checks.validationError !== void 0) return Effect.succeed({
8631
+ correlationId,
8632
+ error: checks.validationError,
8633
+ ok: false
8634
+ });
8635
+ const unsupported = [capabilityByOperation[request.operation], ...checks.additionalCapabilities].find((capability) => options.definition.capabilities[capability] !== true);
8636
+ if (unsupported !== void 0) return Effect.succeed({
8637
+ correlationId,
8638
+ error: {
8639
+ code: "capability_not_supported",
8640
+ details: { capability: unsupported },
8641
+ message: `Resource ${options.definition.id} does not support ${unsupported}`,
8642
+ retryable: false
8643
+ },
8644
+ ok: false
8645
+ });
8646
+ return Effect.tryPromise({
8647
+ catch: (cause) => new CiTransportError({ cause }),
8648
+ try: () => options.transport.execute({
8649
+ ...request,
8650
+ requestId: correlationId,
8651
+ resourceId: options.definition.id
8652
+ }, checks.requestOptions)
8653
+ }).pipe(Effect.map((result) => result));
8654
+ }) });
8655
+ /**
8656
+ * Internal. The calls of the legacy resource client of one definition over
8657
+ * a `ResourceTransport`; the `.` facade and `LegacyResources` share them.
8658
+ */
8659
+ const makeLegacyResourceCore = (options) => {
8660
+ const core = makeResourceCore(options);
8661
+ const call = (request, additionalCapabilities = [], validationError) => (correlationId, requestOptions) => core.execute(request, correlationId, {
8662
+ additionalCapabilities,
8663
+ requestOptions,
8664
+ validationError
8665
+ });
8666
+ const { modes } = options.definition.query.pagination;
8667
+ return {
8668
+ create: (input) => call({
8669
+ ...input,
8670
+ operation: "create"
8671
+ }),
8672
+ get: (input) => call({
8673
+ ...input,
8674
+ operation: "get"
8675
+ }, input.includeDeleted === true ? ["includeDeleted"] : []),
8676
+ hardDelete: (input) => call({
8677
+ ...input,
8678
+ operation: "hard_delete"
8679
+ }),
8680
+ list: (query) => call({
8681
+ operation: "list",
8682
+ query
8683
+ }, query.includeDeleted === true ? ["includeDeleted"] : [], modes.includes(query.pagination.mode) ? void 0 : {
8684
+ code: "capability_not_supported",
8685
+ details: { paginationMode: query.pagination.mode },
8686
+ message: `Resource ${options.definition.id} does not support ${query.pagination.mode} pagination`,
8687
+ retryable: false
8688
+ }),
8689
+ restore: (input) => call({
8690
+ ...input,
8691
+ operation: "restore"
8692
+ }),
8693
+ softDelete: (input) => call({
8694
+ ...input,
8695
+ operation: "soft_delete"
8696
+ }),
8697
+ update: (input) => call({
8698
+ ...input,
8699
+ operation: "update"
8700
+ })
8701
+ };
8702
+ };
8703
+ /** The CI code of a resource error code that CI does not have. */
8704
+ const ciCode = (code) => ciErrorCodes.find((candidate) => candidate === code) ?? "invalid_request";
8705
+ /** The `details` of a resource error, with its code and outcome. */
8706
+ const resourceDetails = (error) => error.outcome === void 0 ? {
8707
+ ...error.details,
8708
+ resourceCode: error.code
8709
+ } : {
8710
+ ...error.details,
8711
+ outcome: error.outcome,
8712
+ resourceCode: error.code
8483
8713
  };
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 };
8714
+ /**
8715
+ * The typed failure of a failed envelope: a `transport_error` (the answer
8716
+ * could not be read) is `CiTransportError`; any other error is `CiError`
8717
+ * with the resource code and outcome in its `details`.
8718
+ */
8719
+ const failure = (error) => error.code === "transport_error" ? new CiTransportError({ cause: error }) : new CiError({
8720
+ code: ciCode(error.code),
8721
+ details: resourceDetails(error),
8722
+ message: error.message,
8723
+ retryable: error.retryable
8724
+ });
8725
+ const valueOf = (result) => result.ok ? Effect.succeed(result.value) : Effect.fail(failure(result.error));
8726
+ var Resources = class extends Context.Service()("@collective-intelligence/external-apps-client-sdk/Resources") {};
8727
+ /** `Resources` over the adapter that `executeOf` gives each Resource Definition. */
8728
+ const makeResources = (executeOf, requestId) => Resources.of({ bind: (definition) => {
8729
+ const core = makeEntityCore({
8730
+ definition,
8731
+ execute: executeOf(definition.id),
8732
+ requestId
8733
+ });
8734
+ const call = (effect) => Effect.flatMap(Effect.suspend(() => effect(core.requestId())), valueOf);
8735
+ return {
8736
+ create: (input) => call((id) => core.execute({
8737
+ ...input,
8738
+ operation: "create"
8739
+ }, id)),
8740
+ definition,
8741
+ delete: (input) => call((id) => core.execute({
8742
+ ...input,
8743
+ operation: "delete"
8744
+ }, id)),
8745
+ get: (input) => call((id) => core.execute({
8746
+ ...input,
8747
+ operation: "get"
8748
+ }, id)),
8749
+ list: (query) => call((id) => core.execute({
8750
+ operation: "list",
8751
+ query
8752
+ }, id)),
8753
+ listMembers: (parentId, field, query) => call((id) => core.execute({
8754
+ field,
8755
+ operation: "list_members",
8756
+ parentId,
8757
+ query
8758
+ }, id)),
8759
+ restore: (input) => call((id) => core.execute({
8760
+ ...input,
8761
+ operation: "restore"
8762
+ }, id)),
8763
+ update: (input) => call((id) => core.execute({
8764
+ ...input,
8765
+ operation: "update"
8766
+ }, id)),
8767
+ upload: (input) => call((id) => core.execute({
8768
+ ...input,
8769
+ operation: "upload"
8770
+ }, id))
8771
+ };
8772
+ } });
8773
+ const make = (options) => makeResources((resourceId) => makeEntityHttpExecute({
8774
+ ...options,
8775
+ destination: options.destination(resourceId)
8776
+ }), options.requestId);
8777
+ /** `Resources` over the entity HTTP routes of `destination`. */
8778
+ const layer = (options) => Layer.sync(Resources, () => make(options));
8779
+ /** `layer` with options that Effect `Config` reads. */
8780
+ const layerConfig = (config) => Layer.unwrap(Effect.map(Config.unwrap(config), layer));
8781
+ /**
8782
+ * `Resources` over an `EntityTransport` of the app, as
8783
+ * `createResourceClient` with `protocol: "entity"`. A rejection of the
8784
+ * transport fails with `CiTransportError`.
8785
+ */
8786
+ const layerFromEntityTransport = (options) => Layer.succeed(Resources, makeResources(() => fromEntityTransport(options.transport), options.requestId));
8787
+ /** The `./effect` form of `createResourceClient` over a `ResourceTransport`. */
8788
+ var LegacyResources = class extends Context.Service()("@collective-intelligence/external-apps-client-sdk/LegacyResources") {};
8789
+ const makeLegacy = (options) => LegacyResources.of({ bind: (definition) => {
8790
+ const legacy = makeLegacyResourceCore({
8791
+ definition,
8792
+ transport: options.transport
8793
+ });
8794
+ const requestId = options.requestId ?? (() => globalThis.crypto.randomUUID());
8795
+ const call = (effect) => Effect.flatMap(Effect.suspend(() => effect(requestId())), valueOf);
8796
+ return {
8797
+ create: (input) => call(legacy.create(input)),
8798
+ definition,
8799
+ get: (input) => call(legacy.get(input)),
8800
+ hardDelete: (input) => Effect.asVoid(call(legacy.hardDelete(input))),
8801
+ list: (query) => call(legacy.list(query)),
8802
+ restore: (input) => call(legacy.restore(input)),
8803
+ softDelete: (input) => call(legacy.softDelete(input)),
8804
+ update: (input) => call(legacy.update(input))
8805
+ };
8806
+ } });
8807
+ /** `LegacyResources` over the `ResourceTransport` of `options`. */
8808
+ const layerLegacy = (options) => Layer.succeed(LegacyResources, makeLegacy(options));
8809
+ /** `layerLegacy` with options that Effect `Config` reads. */
8810
+ const layerLegacyConfig = (config) => Layer.unwrap(Effect.map(Config.unwrap(config), layerLegacy));
8811
+ 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 };