@collective-intelligence/external-apps-server-sdk 0.1.37 → 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.
- package/README.md +111 -12
- package/dist/{runtime/effect.js → chunks/index-zrrnrqkm.js} +11 -2
- package/dist/effect.d.ts +1349 -0
- package/dist/effect.js +1 -0
- package/dist/gateway.d.ts +9 -3
- package/dist/gateway.js +1 -1
- package/dist/index.d.ts +84 -37
- package/dist/index.js +1 -16
- package/dist/next.d.ts +358 -0
- package/dist/next.js +1 -0
- package/dist/persistence/drizzle-effect.d.ts +23 -4
- package/dist/resources.js +1 -1
- package/dist/runtime/effect.d.ts +137 -106
- package/dist/runtime/next.d.ts +126 -86
- package/dist/runtime/web.d.ts +11 -5
- package/dist/runtime/web.js +1 -1
- package/package.json +20 -11
- package/dist/persistence/drizzle-effect.js +0 -1
- package/dist/runtime/next.js +0 -1
package/dist/runtime/next.d.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import { Bounds, ConnectorContext, DatasetAggregateOperation, DatasetDefinition, DatasetFilter, DatasetOperation, DatasetOrder, DatasetPredicate, DatasetPredicateOperator, DatasetProviderCapabilities, DatasetProviderError, DatasetProviderResult, DatasetQueryIntent, DatasetRecordPage, DatasetResultPage, DatasetScalarType, DatasetSourceLocation, DatasetTimeBucket, DatasetValue, JsonObject, JsonPrimitive, JsonSchemaDocument, JsonValue, OperationDomainDeclaration, PackageSchemaProjection, PortableOperationAuthorization, PortableOperationDeclaration, PortableOperationDelegatedSubjectPolicy, PortableOperationEffect, PortableOperationExecutionPolicy, PortableOperationIdempotency, PortableOperationLimits, PortableOperationPrincipalKind, PortableOperationRetryPolicy, ProjectionFidelity, QueryInput, SafeDiagnostic } from '@collective-intelligence/extensions-sdk';
|
|
4
4
|
import { EntityCreateInput, EntityDeleteInput, EntityListQuery, EntityMemberValue, EntityOperation, EntityOperationResult, EntityPage, EntityRequest, EntityUpdateInput, EntityUploadInput, EntityUploadSlot, IdempotencyKey, PortableResourceSchema, ResourceCapabilities, ResourceCreateInput, ResourceCreateRequest, ResourceCursor, ResourceDefinition, ResourceError, ResourceErrorCode, ResourceFilter, ResourceGetRequest, ResourceId, ResourceIdentityField, ResourceJsonValue, ResourceLifecycleInput, ResourceLifecycleRequest, ResourceListQuery, ResourceListRequest, ResourceListResult, ResourceMutationInput, ResourcePagination, ResourcePaginationMode, ResourceRecord, ResourceRecordId, ResourceResult, ResourceRevision, ResourceSort, ResourceTransportRequest, ResourceUpdateRequest } from '@collective-intelligence/external-apps-client-sdk/resources';
|
|
5
|
+
import * as Redacted from 'effect/Redacted';
|
|
5
6
|
|
|
6
7
|
/** Application login identities are separate from gateway machine callers. */
|
|
7
8
|
export type ApplicationUserIdentity = Readonly<{
|
|
@@ -54,16 +55,21 @@ export interface ExternalApplicationExternalAuditSubject {
|
|
|
54
55
|
readonly mappedUserId?: string;
|
|
55
56
|
readonly subjectId: string;
|
|
56
57
|
}
|
|
57
|
-
|
|
58
|
+
/**
|
|
59
|
+
* A client secret: a string at `.`, or the `Redacted` string that Effect
|
|
60
|
+
* `Config.Redacted` reads for the `./effect` layers.
|
|
61
|
+
*/
|
|
62
|
+
export type ClientSecret = Redacted.Redacted<string> | string;
|
|
63
|
+
export interface ConfidentialCredentials<Secret extends ClientSecret = string> {
|
|
58
64
|
readonly clientId: string;
|
|
59
|
-
readonly clientSecret:
|
|
65
|
+
readonly clientSecret: Secret;
|
|
60
66
|
}
|
|
61
67
|
export interface RotatingConfidentialCredentialProvider {
|
|
62
68
|
readonly getCredentials: () => ConfidentialCredentials | Promise<ConfidentialCredentials>;
|
|
63
69
|
}
|
|
64
|
-
export type ConfidentialCredentialProvider = ConfidentialCredentials | RotatingConfidentialCredentialProvider;
|
|
65
|
-
export type ServiceServerAuthentication = Readonly<{
|
|
66
|
-
credentials: ConfidentialCredentialProvider
|
|
70
|
+
export type ConfidentialCredentialProvider<Secret extends ClientSecret = string> = ConfidentialCredentials<Secret> | RotatingConfidentialCredentialProvider;
|
|
71
|
+
export type ServiceServerAuthentication<Secret extends ClientSecret = string> = Readonly<{
|
|
72
|
+
credentials: ConfidentialCredentialProvider<Secret>;
|
|
67
73
|
mode: "service";
|
|
68
74
|
}>;
|
|
69
75
|
/** Application credentials authorize each call for a required Audit subject in one configured organization. */
|
|
@@ -84,10 +90,12 @@ export type UserAuthScopePolicy = Readonly<{
|
|
|
84
90
|
readScope: string;
|
|
85
91
|
writeScope: string;
|
|
86
92
|
}>;
|
|
93
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/next`. */
|
|
87
94
|
export type CiResourceBinding<Value = unknown, Create = Value, Patch = Partial<Value>> = Readonly<{
|
|
88
95
|
definition: ResourceDefinition<Value, Create, Patch>;
|
|
89
96
|
schemaFqn: string;
|
|
90
97
|
}>;
|
|
98
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/next`. */
|
|
91
99
|
export type CiResourcesOptions = Readonly<{
|
|
92
100
|
auth: Pick<ApplicationUserAuth, "getEntityContext">;
|
|
93
101
|
bindings: readonly CiResourceBinding[];
|
|
@@ -96,6 +104,7 @@ export type CiResourcesOptions = Readonly<{
|
|
|
96
104
|
policy?: UserAuthScopePolicy;
|
|
97
105
|
tenantUrl: string;
|
|
98
106
|
}>;
|
|
107
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/next`. */
|
|
99
108
|
export type RealtimeTicketOptions = Readonly<{
|
|
100
109
|
auth: Pick<ApplicationUserAuth, "getAccessToken">;
|
|
101
110
|
/** The CI organization the signed-in users belong to. */
|
|
@@ -106,12 +115,15 @@ export type RealtimeTicketOptions = Readonly<{
|
|
|
106
115
|
host?: string;
|
|
107
116
|
fetch?: typeof globalThis.fetch;
|
|
108
117
|
}>;
|
|
109
|
-
/** The ticket route answer: a single-use ticket and the stream it opens.
|
|
118
|
+
/** The ticket route answer: a single-use ticket and the stream it opens.
|
|
119
|
+
* @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/next`.
|
|
120
|
+
*/
|
|
110
121
|
export type RealtimeTicketResponse = Readonly<{
|
|
111
122
|
ticket: string;
|
|
112
123
|
expiresAt: string;
|
|
113
124
|
streamUrl: string;
|
|
114
125
|
}>;
|
|
126
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/next`. */
|
|
115
127
|
export type BffResourceMount = Readonly<{
|
|
116
128
|
basePath: string;
|
|
117
129
|
handler: (request: Request) => Promise<Response>;
|
|
@@ -124,10 +136,13 @@ export type ExternalApplicationBffCapabilities = Readonly<{
|
|
|
124
136
|
}> & (Readonly<{
|
|
125
137
|
authentication?: never;
|
|
126
138
|
}> | ServiceCapabilityAuthorization);
|
|
127
|
-
/** The realtime ticket route `POST {basePath}/realtime/ticket`; `basePath` defaults to `/api`.
|
|
139
|
+
/** The realtime ticket route `POST {basePath}/realtime/ticket`; `basePath` defaults to `/api`.
|
|
140
|
+
* @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/next`.
|
|
141
|
+
*/
|
|
128
142
|
export type ExternalApplicationBffRealtime = Omit<RealtimeTicketOptions, "auth"> & Readonly<{
|
|
129
143
|
basePath?: string;
|
|
130
144
|
}>;
|
|
145
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/next`. */
|
|
131
146
|
export type ExternalApplicationBffOptions = Readonly<{
|
|
132
147
|
auth: ApplicationUserAuth;
|
|
133
148
|
authBasePath?: string;
|
|
@@ -137,6 +152,7 @@ export type ExternalApplicationBffOptions = Readonly<{
|
|
|
137
152
|
realtime?: ExternalApplicationBffRealtime;
|
|
138
153
|
resources?: readonly BffResourceMount[];
|
|
139
154
|
}>;
|
|
155
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/next`. */
|
|
140
156
|
export type ExternalApplicationBff = (request: Request) => Promise<Response>;
|
|
141
157
|
export type PrincipalKind = "detached_user" | "service_principal";
|
|
142
158
|
export type DelegatedSubjectPolicy = "allowed" | "forbidden" | "required";
|
|
@@ -317,6 +333,7 @@ export type WorkflowTarget = Readonly<{
|
|
|
317
333
|
workflowFqn: string;
|
|
318
334
|
workflowId?: never;
|
|
319
335
|
}>;
|
|
336
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/next`. */
|
|
320
337
|
export type FixedWorkflowRouteOptions<Input, Params = Record<string, never>> = Readonly<{
|
|
321
338
|
auth: Pick<ApplicationUserAuth, "getAccessToken" | "getEntityContext">;
|
|
322
339
|
fetch?: typeof globalThis.fetch;
|
|
@@ -331,6 +348,7 @@ export type FixedWorkflowRouteOptions<Input, Params = Record<string, never>> = R
|
|
|
331
348
|
}> & WorkflowTarget;
|
|
332
349
|
export type GatewayWebHandler = (request: Request) => Promise<Response>;
|
|
333
350
|
export type GatewayRuntimeKernel = Pick<GatewayKernel, "handle">;
|
|
351
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/next`. */
|
|
334
352
|
export type GatewayNextRouteHandlers = Readonly<{
|
|
335
353
|
DELETE: GatewayWebHandler;
|
|
336
354
|
GET: GatewayWebHandler;
|
|
@@ -338,95 +356,117 @@ export type GatewayNextRouteHandlers = Readonly<{
|
|
|
338
356
|
POST: GatewayWebHandler;
|
|
339
357
|
PUT: GatewayWebHandler;
|
|
340
358
|
}>;
|
|
359
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/next`. */
|
|
341
360
|
export type ResourceNextRouteHandlers = Readonly<{
|
|
342
361
|
DELETE: GatewayWebHandler;
|
|
343
362
|
GET: GatewayWebHandler;
|
|
344
363
|
PATCH: GatewayWebHandler;
|
|
345
364
|
POST: GatewayWebHandler;
|
|
346
365
|
}>;
|
|
347
|
-
|
|
366
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/next`. */
|
|
367
|
+
export declare const cookies: (request: Request) => string | null;
|
|
368
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/next`. */
|
|
369
|
+
export declare const createCiResourceMounts: (options: CiResourcesOptions) => {
|
|
348
370
|
basePath: string;
|
|
349
371
|
handler: (request: Request) => Promise<Response>;
|
|
350
|
-
}[]
|
|
372
|
+
}[];
|
|
373
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/next`. */
|
|
374
|
+
export declare const createExternalApplicationBff: (options: ExternalApplicationBffOptions) => ExternalApplicationBff;
|
|
375
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/next`. */
|
|
376
|
+
export declare const createExternalApplicationBffNextHandlers: (options: ExternalApplicationBffOptions) => GatewayNextRouteHandlers;
|
|
377
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/next`. */
|
|
378
|
+
export declare const createFixedWorkflowRoute: <Input, Params = Record<string, never>>(options: FixedWorkflowRouteOptions<Input, Params>) => ((request: Request, params: Params) => Promise<Response>);
|
|
379
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/next`. */
|
|
380
|
+
export declare const createRealtimeTicketHandler: (options: RealtimeTicketOptions) => ((request: Request) => Promise<Response>);
|
|
381
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/next`. */
|
|
382
|
+
export declare const createGatewayNextRouteHandlers: (kernel: GatewayRuntimeKernel) => GatewayNextRouteHandlers;
|
|
383
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/next`. */
|
|
384
|
+
export declare const createResourceNextRouteHandlers: <Value, Create = Value, Patch = Partial<Value>>(options: ResourceHttpHandlerOptions<Value, Create, Patch>) => ResourceNextRouteHandlers;
|
|
385
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/next`. */
|
|
386
|
+
export declare const headers: (request: Request) => Headers;
|
|
387
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/next`. */
|
|
388
|
+
export declare const publicOriginFromHeaders: (headerList: Headers, fallbackOrigin: string) => string;
|
|
389
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/next`. */
|
|
390
|
+
export declare const requestWithPublicOrigin: (request: Request, publicOrigin: string) => Request;
|
|
351
391
|
|
|
352
392
|
export {
|
|
353
|
-
Bounds,
|
|
354
|
-
ConnectorContext,
|
|
355
|
-
DatasetAggregateOperation,
|
|
356
|
-
DatasetDefinition,
|
|
357
|
-
DatasetFilter,
|
|
358
|
-
DatasetOperation,
|
|
359
|
-
DatasetOrder,
|
|
360
|
-
DatasetPredicate,
|
|
361
|
-
DatasetPredicateOperator,
|
|
362
|
-
DatasetProviderCapabilities,
|
|
363
|
-
DatasetProviderError,
|
|
364
|
-
DatasetProviderResult,
|
|
365
|
-
DatasetQueryIntent,
|
|
366
|
-
DatasetRecordPage,
|
|
367
|
-
DatasetResultPage,
|
|
368
|
-
DatasetScalarType,
|
|
369
|
-
DatasetSourceLocation,
|
|
370
|
-
DatasetTimeBucket,
|
|
371
|
-
DatasetValue,
|
|
372
|
-
EntityCreateInput,
|
|
373
|
-
EntityDeleteInput,
|
|
374
|
-
EntityListQuery,
|
|
375
|
-
EntityMemberValue,
|
|
376
|
-
EntityOperation,
|
|
377
|
-
EntityOperationResult,
|
|
378
|
-
EntityPage,
|
|
379
|
-
EntityRequest,
|
|
380
|
-
EntityUpdateInput,
|
|
381
|
-
EntityUploadInput,
|
|
382
|
-
EntityUploadSlot,
|
|
383
|
-
IdempotencyKey,
|
|
384
|
-
JsonObject,
|
|
385
|
-
JsonPrimitive,
|
|
386
|
-
JsonSchemaDocument,
|
|
387
|
-
JsonValue,
|
|
388
|
-
OperationDomainDeclaration,
|
|
389
|
-
PackageSchemaProjection,
|
|
390
|
-
PortableOperationAuthorization,
|
|
391
|
-
PortableOperationDeclaration,
|
|
392
|
-
PortableOperationDelegatedSubjectPolicy,
|
|
393
|
-
PortableOperationEffect,
|
|
394
|
-
PortableOperationExecutionPolicy,
|
|
395
|
-
PortableOperationIdempotency,
|
|
396
|
-
PortableOperationLimits,
|
|
397
|
-
PortableOperationPrincipalKind,
|
|
398
|
-
PortableOperationRetryPolicy,
|
|
399
|
-
PortableResourceSchema,
|
|
400
|
-
ProjectionFidelity,
|
|
401
|
-
QueryInput,
|
|
402
|
-
ResourceCapabilities,
|
|
403
|
-
ResourceCreateInput,
|
|
404
|
-
ResourceCreateRequest,
|
|
405
|
-
ResourceCursor,
|
|
406
|
-
ResourceDefinition,
|
|
407
|
-
ResourceError,
|
|
408
|
-
ResourceErrorCode,
|
|
409
|
-
ResourceFilter,
|
|
410
|
-
ResourceGetRequest,
|
|
411
|
-
ResourceId,
|
|
412
|
-
ResourceIdentityField,
|
|
413
|
-
ResourceJsonValue,
|
|
414
|
-
ResourceLifecycleInput,
|
|
415
|
-
ResourceLifecycleRequest,
|
|
416
|
-
ResourceListQuery,
|
|
417
|
-
ResourceListRequest,
|
|
418
|
-
ResourceListResult,
|
|
419
|
-
ResourceMutationInput,
|
|
420
|
-
ResourcePagination,
|
|
421
|
-
ResourcePaginationMode,
|
|
422
|
-
ResourceRecord,
|
|
423
|
-
ResourceRecordId,
|
|
424
|
-
ResourceResult,
|
|
425
|
-
ResourceRevision,
|
|
426
|
-
ResourceSort,
|
|
427
|
-
ResourceTransportRequest,
|
|
428
|
-
ResourceUpdateRequest,
|
|
429
|
-
SafeDiagnostic,
|
|
393
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ Bounds,
|
|
394
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ ConnectorContext,
|
|
395
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ DatasetAggregateOperation,
|
|
396
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ DatasetDefinition,
|
|
397
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ DatasetFilter,
|
|
398
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ DatasetOperation,
|
|
399
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ DatasetOrder,
|
|
400
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ DatasetPredicate,
|
|
401
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ DatasetPredicateOperator,
|
|
402
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ DatasetProviderCapabilities,
|
|
403
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ DatasetProviderError,
|
|
404
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ DatasetProviderResult,
|
|
405
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ DatasetQueryIntent,
|
|
406
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ DatasetRecordPage,
|
|
407
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ DatasetResultPage,
|
|
408
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ DatasetScalarType,
|
|
409
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ DatasetSourceLocation,
|
|
410
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ DatasetTimeBucket,
|
|
411
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ DatasetValue,
|
|
412
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ EntityCreateInput,
|
|
413
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ EntityDeleteInput,
|
|
414
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ EntityListQuery,
|
|
415
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ EntityMemberValue,
|
|
416
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ EntityOperation,
|
|
417
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ EntityOperationResult,
|
|
418
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ EntityPage,
|
|
419
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ EntityRequest,
|
|
420
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ EntityUpdateInput,
|
|
421
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ EntityUploadInput,
|
|
422
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ EntityUploadSlot,
|
|
423
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ IdempotencyKey,
|
|
424
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ JsonObject,
|
|
425
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ JsonPrimitive,
|
|
426
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ JsonSchemaDocument,
|
|
427
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ JsonValue,
|
|
428
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ OperationDomainDeclaration,
|
|
429
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ PackageSchemaProjection,
|
|
430
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ PortableOperationAuthorization,
|
|
431
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ PortableOperationDeclaration,
|
|
432
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ PortableOperationDelegatedSubjectPolicy,
|
|
433
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ PortableOperationEffect,
|
|
434
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ PortableOperationExecutionPolicy,
|
|
435
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ PortableOperationIdempotency,
|
|
436
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ PortableOperationLimits,
|
|
437
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ PortableOperationPrincipalKind,
|
|
438
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ PortableOperationRetryPolicy,
|
|
439
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ PortableResourceSchema,
|
|
440
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ ProjectionFidelity,
|
|
441
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ QueryInput,
|
|
442
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceCapabilities,
|
|
443
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceCreateInput,
|
|
444
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceCreateRequest,
|
|
445
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceCursor,
|
|
446
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceDefinition,
|
|
447
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceError,
|
|
448
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceErrorCode,
|
|
449
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceFilter,
|
|
450
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceGetRequest,
|
|
451
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceId,
|
|
452
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceIdentityField,
|
|
453
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceJsonValue,
|
|
454
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceLifecycleInput,
|
|
455
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceLifecycleRequest,
|
|
456
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceListQuery,
|
|
457
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceListRequest,
|
|
458
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceListResult,
|
|
459
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceMutationInput,
|
|
460
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourcePagination,
|
|
461
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourcePaginationMode,
|
|
462
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceRecord,
|
|
463
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceRecordId,
|
|
464
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceResult,
|
|
465
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceRevision,
|
|
466
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceSort,
|
|
467
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceTransportRequest,
|
|
468
|
+
/** @deprecated Import it from `@collective-intelligence/external-apps-client-sdk/resources`. */ ResourceUpdateRequest,
|
|
469
|
+
/** @deprecated Import it from `@collective-intelligence/extensions-sdk`. */ SafeDiagnostic,
|
|
430
470
|
};
|
|
431
471
|
|
|
432
472
|
export {};
|
package/dist/runtime/web.d.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import { Bounds, ConnectorContext, DatasetAggregateOperation, DatasetDefinition, DatasetFilter, DatasetOperation, DatasetOrder, DatasetPredicate, DatasetPredicateOperator, DatasetProviderCapabilities, DatasetProviderError, DatasetProviderResult, DatasetQueryIntent, DatasetRecordPage, DatasetResultPage, DatasetScalarType, DatasetSourceLocation, DatasetTimeBucket, DatasetValue, JsonObject, JsonPrimitive, JsonSchemaDocument, JsonValue, OperationDomainDeclaration, PackageSchemaProjection, PortableOperationAuthorization, PortableOperationDeclaration, PortableOperationDelegatedSubjectPolicy, PortableOperationEffect, PortableOperationExecutionPolicy, PortableOperationIdempotency, PortableOperationLimits, PortableOperationPrincipalKind, PortableOperationRetryPolicy, ProjectionFidelity, QueryInput, SafeDiagnostic } from '@collective-intelligence/extensions-sdk';
|
|
4
4
|
import { IdempotencyKey, PortableResourceSchema, ResourceCapabilities, ResourceCreateRequest, ResourceCursor, ResourceDefinition, ResourceError, ResourceErrorCode, ResourceFilter, ResourceGetRequest, ResourceId, ResourceIdentityField, ResourceJsonValue, ResourceLifecycleRequest, ResourceListQuery, ResourceListRequest, ResourcePagination, ResourcePaginationMode, ResourceRecordId, ResourceResult, ResourceRevision, ResourceSort, ResourceTransportRequest, ResourceUpdateRequest } from '@collective-intelligence/external-apps-client-sdk/resources';
|
|
5
|
+
import * as Redacted from 'effect/Redacted';
|
|
5
6
|
|
|
6
7
|
export type PrincipalKind = "detached_user" | "service_principal";
|
|
7
8
|
export type DelegatedSubjectPolicy = "allowed" | "forbidden" | "required";
|
|
@@ -208,16 +209,21 @@ export interface ExternalApplicationExternalAuditSubject {
|
|
|
208
209
|
readonly mappedUserId?: string;
|
|
209
210
|
readonly subjectId: string;
|
|
210
211
|
}
|
|
211
|
-
|
|
212
|
+
/**
|
|
213
|
+
* A client secret: a string at `.`, or the `Redacted` string that Effect
|
|
214
|
+
* `Config.Redacted` reads for the `./effect` layers.
|
|
215
|
+
*/
|
|
216
|
+
export type ClientSecret = Redacted.Redacted<string> | string;
|
|
217
|
+
export interface ConfidentialCredentials<Secret extends ClientSecret = string> {
|
|
212
218
|
readonly clientId: string;
|
|
213
|
-
readonly clientSecret:
|
|
219
|
+
readonly clientSecret: Secret;
|
|
214
220
|
}
|
|
215
221
|
export interface RotatingConfidentialCredentialProvider {
|
|
216
222
|
readonly getCredentials: () => ConfidentialCredentials | Promise<ConfidentialCredentials>;
|
|
217
223
|
}
|
|
218
|
-
export type ConfidentialCredentialProvider = ConfidentialCredentials | RotatingConfidentialCredentialProvider;
|
|
219
|
-
export type ServiceServerAuthentication = Readonly<{
|
|
220
|
-
credentials: ConfidentialCredentialProvider
|
|
224
|
+
export type ConfidentialCredentialProvider<Secret extends ClientSecret = string> = ConfidentialCredentials<Secret> | RotatingConfidentialCredentialProvider;
|
|
225
|
+
export type ServiceServerAuthentication<Secret extends ClientSecret = string> = Readonly<{
|
|
226
|
+
credentials: ConfidentialCredentialProvider<Secret>;
|
|
221
227
|
mode: "service";
|
|
222
228
|
}>;
|
|
223
229
|
/** Application credentials authorize each call for a required Audit subject in one configured organization. */
|
package/dist/runtime/web.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var __defProp=Object.defineProperty;var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true,configurable:true,set:__exportSetter.bind(all,name)})};var exports_web={};__export(exports_web,{cookies:()=>cookiesFromRequest,createCiResourceMounts:()=>createCiResourceMounts,createExternalApplicationBff:()=>createExternalApplicationBff,createFixedWorkflowRoute:()=>createFixedWorkflowRoute,createGatewayWebHandler:()=>createGatewayWebHandler,createRealtimeTicketHandler:()=>createRealtimeTicketHandler,headers:()=>headersFromRequest,publicOriginFromHeaders:()=>publicOriginFromHeaders,requestWithPublicOrigin:()=>requestWithPublicOrigin});var isAuditSubject=(value)=>value!==null&&value!==undefined&&value.issuer.length>0&&value.subjectId.length>0;var resolveCredentials=async(provider)=>("getCredentials"in provider)?await provider.getCredentials():provider;var basicAuthorization=({clientId,clientSecret})=>{if(clientId.length===0||clientId.includes(":")){throw new TypeError("A non-empty clientId without ':' is required")}if(clientSecret.length===0){throw new TypeError("A non-empty clientSecret is required")}return`Basic ${Buffer.from(`${clientId}:${clientSecret}`,"utf-8").toString("base64")}`};var requireHttpsOrigin=(value,name)=>{let url;try{url=new URL(value)}catch{throw new TypeError(`${name} must contain only an HTTPS origin`)}if(url.protocol!=="https:"||url.origin!==value||url.pathname!=="/"||url.search!==""||url.hash!==""||url.username!==""||url.password!==""){throw new TypeError(`${name} must contain only an HTTPS origin`)}return url.origin};var capabilityPath=/^(?:\/context|\/knowledge(?:\/.*)?|\/agents(?:\/.*)?|\/conversations(?:\/.*)?|\/skills(?:\/.*)?|\/workflows(?:\/.*)?|\/runs\/.+)$/u;var identityHeaders=async(request,options)=>{const headers=new Headers;if(options.authentication===undefined){const accessToken=await options.getAccessToken(request);if(accessToken===null||accessToken.length===0){return null}headers.set("authorization",`Bearer ${accessToken}`);const organizationId=request.headers.get("x-organization-id");if(organizationId!==null){headers.set("x-organization-id",organizationId)}return headers}const auditSubject=await options.getAuditSubject(request);if(!isAuditSubject(auditSubject)){return null}const anonymousVisitor=options.caller==="anonymous_visitor";if(anonymousVisitor&&auditSubject.mappedUserId!==undefined){return null}headers.set("authorization",basicAuthorization(await resolveCredentials(options.authentication.credentials)));headers.set("x-organization-id",options.organizationId);headers.set("x-external-audit-issuer",auditSubject.issuer);headers.set("x-external-audit-subject",auditSubject.subjectId);if(anonymousVisitor){headers.set("x-external-caller-kind","anonymous_visitor")}else if(auditSubject.mappedUserId!==undefined){headers.set("x-external-ci-user-id",auditSubject.mappedUserId)}return headers};var forwardDedicatedCapability=async(request,options)=>{const url=new URL(request.url);const{basePath}=options;if(url.pathname!==basePath&&!url.pathname.startsWith(`${basePath}/`)){return null}const rest=url.pathname.slice(basePath.length);if(!capabilityPath.test(rest)){return new Response(null,{status:404})}const headers=await identityHeaders(request,options);if(headers===null){return Response.json({error:"unauthenticated"},{status:401})}const tenantUrl=requireHttpsOrigin(options.tenantUrl,"tenantUrl");const target=new URL(`/application/v1${rest}${url.search}`,tenantUrl);const correlationId=request.headers.get("x-correlation-id");if(correlationId!==null){headers.set("x-correlation-id",correlationId)}const lastEventId=request.headers.get("last-event-id");if(lastEventId!==null){headers.set("last-event-id",lastEventId)}const contentType=request.headers.get("content-type");if(contentType!==null){headers.set("content-type",contentType)}const idempotencyKey=request.headers.get("idempotency-key")??request.headers.get("x-idempotency-key");if(idempotencyKey!==null){headers.set("idempotency-key",idempotencyKey)}const init={headers,method:request.method,redirect:"manual"};if(request.method!=="GET"&&request.method!=="HEAD"){init.body=await request.arrayBuffer()}const fetch=options.fetch??globalThis.fetch;return await fetch(target,init)};var unauthenticated=()=>Response.json({error:"authentication_required"},{headers:{"cache-control":"no-store"},status:401});var forbidden=()=>Response.json({error:"forbidden"},{status:403});var isReadOperation=(operation)=>operation===undefined||operation==="get"||operation==="list"||operation==="list_members";var authorizeWithUserAuth=(auth,policy)=>(resourceId)=>async(request,operation="get")=>{const context=await auth.getEntityContext(request,resourceId);if(context===null){return unauthenticated()}const scope=isReadOperation(operation)?policy.readScope:policy.writeScope;return context.scopes.includes(scope)?context:forbidden()};import{createEntityHttpTransport}from"@collective-intelligence/external-apps-client-sdk";import{createEntityProtocol}from"@collective-intelligence/external-apps-client-sdk/resources";var credential=Symbol.for("@collective-intelligence/external-apps-server-sdk/ci-entity-invocation");var ciEntityAccessToken=(context)=>{if(!Object.hasOwn(context,credential)){return}const bound=context;return bound[credential]?.(context)};var matchesEntityContext=(context,resourceId)=>context?.resourceId===resourceId&&context.applicationId.length>0&&context.user?.kind==="ci_user"&&context.user.id.length>0&&context.user.issuer===context.issuer&&context.user.organizationId===context.organizationId;var defineCiEntityResource=(input)=>{const{definition}=input;const tenant=new URL(input.tenantUrl);if(tenant.protocol!=="https:"||tenant.username!==""||tenant.password!==""||tenant.pathname!=="/"||tenant.search!==""||tenant.hash!==""){throw new TypeError("CI entity bindings require an HTTPS tenant origin")}const protocol=createEntityProtocol(definition);const destination={kind:"ci",organizationId:input.organizationId,schemaFqn:input.schemaFqn,tenantUrl:tenant.origin};const fetch=input.fetch??globalThis.fetch;const transport=(accessToken)=>createEntityHttpTransport({authentication:{auth:{getAccessToken:()=>accessToken},mode:"federated"},destination,fetch});transport("");return Object.freeze({definition,execute:async(request,context,options)=>{const accessToken=ciEntityAccessToken(context);if(!matchesEntityContext(context,definition.id)||context.issuer!==tenant.origin||context.organizationId!==input.organizationId||accessToken===undefined){return{correlationId:request.requestId,error:{code:"forbidden",message:"The current CI identity is not authorized for this binding",outcome:"not_dispatched",retryable:false},ok:false}}const decoded=protocol.decodeRequest(request);if(!decoded.ok){return{...decoded,error:{...decoded.error,outcome:"not_dispatched"}}}const capability={create:"create",delete:"delete",get:"get",list:"search",list_members:"search",update:"update",upload:"upload"};if(definition.capabilities[capability[decoded.value.operation]]!==true){return{correlationId:request.requestId,error:{code:"capability_not_supported",message:"Resource operation is unsupported",outcome:"not_dispatched",retryable:false},ok:false}}const result=await transport(accessToken).execute(decoded.value,options);const response=protocol.decodeResult(decoded.value.operation,result,request.requestId);return!response.ok&&response.error.details?.phase==="response_contract"?{...response,error:{...response.error,outcome:decoded.value.operation==="get"||decoded.value.operation==="list"||decoded.value.operation==="list_members"?"rejected":"uncertain"}}:response}})};import{createEntityProtocol as createEntityProtocol2}from"@collective-intelligence/external-apps-client-sdk/resources";var unavailableBrand=Symbol.for("@collective-intelligence/external-apps-server-sdk/ApplicationUserAuthUnavailableError");class ApplicationUserAuthUnavailableError extends Error{[unavailableBrand]=true;code="user_auth_unavailable";static[Symbol.hasInstance](value){return value instanceof Error&&unavailableBrand in value&&value[unavailableBrand]===true&&"code"in value&&value.code==="user_auth_unavailable"}constructor(cause){super("Application user authentication is unavailable",{cause});this.name="ApplicationUserAuthUnavailableError"}}var record=(value)=>typeof value==="object"&&value!==null&&!Array.isArray(value)?Object.fromEntries(Object.entries(value)):null;var json=(body,status,correlationId)=>Response.json(body,{headers:{"cache-control":"no-store","x-correlation-id":correlationId},status});var resourceResult=(result)=>{if(result.ok){return json(result,200,result.correlationId)}let status;switch(result.error.code){case"unauthenticated":{status=401;break}case"forbidden":{status=403;break}case"not_found":{status=404;break}case"conflict":{status=409;break}case"rate_limited":{status=429;break}case"unavailable":case"transport_error":{status=503;break}case"internal":{status=500;break}case"capability_not_supported":case"invalid_request":case"upload_not_supported":{status=400;break}default:{status=500}}return json(result,status,result.correlationId)};var resourceRequest=(request,body,resourceId,externalId,action,correlationId)=>{if(request.method==="POST"&&externalId===undefined&&(action==="scan"||action==="search")){const pagination=record(body.pagination);if(pagination===null||pagination.mode!=="cursor"&&pagination.mode!=="page"){return null}const query=body;return{operation:"list",query,requestId:correlationId,resourceId}}if(request.method==="GET"&&externalId!==undefined&&action===undefined){return{id:externalId,operation:"get",requestId:correlationId,resourceId}}if(request.method==="POST"&&externalId===undefined&&action==="records"){if(typeof body.idempotencyKey!=="string"||!("value"in body)){return null}return{idempotencyKey:body.idempotencyKey,operation:"create",requestId:correlationId,resourceId,value:body.value}}if(externalId===undefined||typeof body.expectedRevision!=="string"){return null}const idempotencyKey=typeof body.idempotencyKey==="string"?{idempotencyKey:body.idempotencyKey}:{};if(request.method==="PATCH"&&action===undefined&&"value"in body){return{expectedRevision:body.expectedRevision,id:externalId,...idempotencyKey,operation:"update",requestId:correlationId,resourceId,value:body.value}}const operation=request.method==="DELETE"&&action===undefined?"hard_delete":request.method==="POST"&&action==="soft-delete"?"soft_delete":request.method==="POST"&&action==="restore"?"restore":null;return operation===null?null:{expectedRevision:body.expectedRevision,id:externalId,...idempotencyKey,operation,requestId:correlationId,resourceId}};var readResourceBody=async(request,maximum)=>{if(Number(request.headers.get("content-length"))>maximum){await request.body?.cancel();return null}const reader=request.body?.getReader();if(reader===undefined){return null}const decoder=new TextDecoder("utf-8",{fatal:true});let size=0;let text="";try{for(;;){const{done,value}=await reader.read();if(done){break}size+=value.byteLength;if(size>maximum){await reader.cancel();return null}text+=decoder.decode(value,{stream:true})}text+=decoder.decode();const parsed=JSON.parse(text);if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){return null}return Object.fromEntries(Object.entries(parsed))}catch{return null}finally{reader.releaseLock()}};var trimTrailingSlash=(value)=>value.endsWith("/")?value.slice(0,-1):value;var matchEntityHttpRoute=(pathname,basePath)=>{const prefix=trimTrailingSlash(basePath);if(!pathname.startsWith(`${prefix}/`)){return null}let parts;try{parts=pathname.slice(prefix.length+1).split("/").map(decodeURIComponent)}catch{return null}const[head,id,action]=parts;if(head==="search"&&parts.length===1){return{kind:"search"}}if(head==="records"&&parts.length===1){return{kind:"collection"}}if(head==="uploads"&&parts.length===1){return{kind:"uploads"}}if(head!=="records"||id===undefined||id.length===0){return null}if(parts.length===2){return{id,kind:"record"}}if(parts.length===3&&action==="soft-delete"){return{id,kind:"soft_delete"}}if(parts.length===4&&action==="relation-members"&&parts[3]==="search"){return{id,kind:"relation_members"}}return null};var decodeEntityRoute=(protocol,input,body)=>{if(input.operation==="list_members"){const{field,...query}=body;return protocol.decodeRequest({...input,field,query})}if(input.operation==="upload"){return protocol.decodeRequest({...body,...input})}if(input.operation!=="list"&&input.operation!=="get"){const allowed=["idempotencyKey"];if(input.operation!=="create"){allowed.push("expectedRevision")}if(input.operation==="create"||input.operation==="update"){allowed.push("value")}if(Object.keys(body).some((key)=>!allowed.includes(key))){return{correlationId:input.requestId,error:{code:"invalid_request",details:{issues:[{field:"",keyword:"additionalProperties"}]},message:"Request contains unsupported entity fields",retryable:false},ok:false}}}return protocol.decodeRequest({...input,operation:input.operation==="soft_delete"?"delete":input.operation})};var readResourceRoute=async(request,basePath,resourceId,requestId,maximum)=>{const invalid=(message)=>resourceResult({correlationId:requestId,error:{code:"invalid_request",message,retryable:false},ok:false});const path=new URL(request.url).pathname;const route=matchEntityHttpRoute(path,basePath);if(route===null){return new Response(null,{status:404})}const body=request.method==="GET"?{}:await readResourceBody(request,maximum);if(body===null){return invalid("Request body is invalid or exceeds its limit")}if(route.kind==="relation_members"){const member={operation:"list_members",parentId:route.id,requestId,resourceId};return request.method==="POST"?{body,input:member}:invalid("Invalid resource route or request")}if(route.kind==="uploads"){const upload={operation:"upload",requestId,resourceId};return request.method==="POST"?{body,input:upload}:invalid("Invalid resource route or request")}let externalId;let action;switch(route.kind){case"search":{action="search";break}case"collection":{action="records";break}case"record":{externalId=route.id;break}case"soft_delete":{action="soft-delete";externalId=route.id;break}default:{break}}const input=resourceRequest(request,body,resourceId,externalId,action,requestId);return input===null?invalid("Invalid resource route or request"):{body,input}};var createResourceHttpHandler=(options)=>{const protocol="executeCrud"in options.resource?null:createEntityProtocol2(options.resource.definition);return async(request)=>{const requestId=request.headers.get("x-correlation-id")?.match(/^[\w.-]{1,128}$/u)?.[0]??crypto.randomUUID();const{resource}=options;const route=await readResourceRoute(request,options.basePath,resource.definition.id,requestId,options.maxBodyBytes??1048576);if(route instanceof Response){return route}const{body,input}=route;const decoded=protocol===null?null:decodeEntityRoute(protocol,input,body);if(decoded!==null&&!decoded.ok){return resourceResult(decoded)}try{const operation=decoded?.ok?decoded.value.operation:input.operation;const authorized=await options.authorize(request,operation);if(authorized instanceof Response){return authorized}if(!matchesEntityContext(authorized,resource.definition.id)){return resourceResult({correlationId:requestId,error:{code:"forbidden",message:"The current identity is not authorized for this resource",retryable:false},ok:false})}if("executeCrud"in resource){return input.operation==="upload"||input.operation==="list_members"?new Response(null,{status:404}):resourceResult(await resource.executeCrud(input,authorized))}if(decoded?.ok){return resourceResult(await resource.execute(decoded.value,authorized,{signal:request.signal}))}throw new TypeError("Entity request was not decoded")}catch(error){return resourceResult({correlationId:requestId,error:{code:error instanceof ApplicationUserAuthUnavailableError?"unavailable":"internal",message:"Resource authorization or execution is unavailable",retryable:false},ok:false})}}};var defaultPolicy={readScope:"knowledge:read",writeScope:"knowledge:write"};var createCiResourceMounts=(options)=>{const authorize=authorizeWithUserAuth(options.auth,options.policy??defaultPolicy);return options.bindings.map((binding)=>{const basePath=`/api/resources/${binding.definition.id}`;const resource=options.fetch===undefined?defineCiEntityResource({definition:binding.definition,organizationId:options.organizationId,schemaFqn:binding.schemaFqn,tenantUrl:options.tenantUrl}):defineCiEntityResource({definition:binding.definition,fetch:options.fetch,organizationId:options.organizationId,schemaFqn:binding.schemaFqn,tenantUrl:options.tenantUrl});return{basePath,handler:createResourceHttpHandler({authorize:authorize(binding.definition.id),basePath,resource})}})};var publicOriginFromHeaders=(headerList,fallbackOrigin)=>{const forwardedHost=headerList.get("x-forwarded-host");const forwardedProto=headerList.get("x-forwarded-proto");if(forwardedHost===null||forwardedHost.length===0){return requireHttpsOrigin(fallbackOrigin,"publicOrigin")}const host=forwardedHost.split(",")[0]?.trim()??"";const protoRaw=forwardedProto?.split(",")[0]?.trim();const proto=(protoRaw===undefined||protoRaw.length===0?"https":protoRaw).toLowerCase();if(host.length===0||proto!=="https"){return requireHttpsOrigin(fallbackOrigin,"publicOrigin")}return requireHttpsOrigin(`https://${host}`,"x-forwarded-host")};var cookiesFromRequest=(request)=>request.headers.get("cookie");var headersFromRequest=(request)=>request.headers;var copyRequest=(request,url,headerList)=>{const{method}=request;const init={headers:headerList,method,redirect:"manual",signal:request.signal};if(method!=="GET"&&method!=="HEAD"&&request.body!==null){Object.assign(init,{body:request.body,duplex:"half"})}return new Request(url,init)};var requestWithPublicOrigin=(request,publicOrigin)=>{const current=new URL(request.url);const next=new URL(`${current.pathname}${current.search}`,publicOrigin);return copyRequest(request,next,request.headers)};var failure=(status,error,headers={})=>Response.json({error},{headers,status});var isRecord=(value)=>typeof value==="object"&&value!==null&&!Array.isArray(value);var readTopics=async(request)=>{try{const body=await request.json();return isRecord(body)&&Array.isArray(body.topics)?body.topics:null}catch{return null}};var readTicket=(value)=>isRecord(value)&&typeof value.ticket==="string"&&typeof value.expiresAt==="string"?{expiresAt:value.expiresAt,ticket:value.ticket}:null;var isCrossSite=(request)=>{const origin=request.headers.get("origin");return request.headers.get("sec-fetch-site")==="cross-site"||origin!==null&&origin!==new URL(request.url).origin};var accessToken=async(auth,request)=>{try{const token=await auth.getAccessToken?.(request)??null;return token===null||token===""?{token:null}:{token}}catch(error){if(error instanceof ApplicationUserAuthUnavailableError){return{unavailable:true}}throw error}};var createRealtimeTicketHandler=(options)=>{const tenantUrl=requireHttpsOrigin(options.tenantUrl,"tenantUrl");const host=options.host===undefined?tenantUrl:requireHttpsOrigin(options.host,"realtime.host");const fetch=options.fetch??globalThis.fetch;return async(request)=>{if(request.method!=="POST"){return failure(405,"method_not_allowed",{allow:"POST"})}if(isCrossSite(request)){return failure(403,"forbidden")}if(!(request.headers.get("content-type")??"").startsWith("application/json")){return failure(415,"unsupported_media_type")}const topics=await readTopics(request);if(topics===null){return failure(400,"invalid_request")}const credential=await accessToken(options.auth,request);if("unavailable"in credential){return failure(503,"unavailable")}if(credential.token===null){return failure(401,"unauthenticated")}const headers=new Headers({authorization:`Bearer ${credential.token}`,"content-type":"application/json","x-organization-id":options.organizationId});const correlationId=request.headers.get("x-correlation-id");if(correlationId!==null){headers.set("x-correlation-id",correlationId)}const minted=await fetch(new URL("/application/v1/realtime/tickets",tenantUrl),{body:JSON.stringify({topics}),headers,method:"POST",redirect:"manual"});if(!minted.ok){const forwarded=new Headers({"content-type":minted.headers.get("content-type")??"application/json"});const retryAfter=minted.headers.get("retry-after");if(retryAfter!==null){forwarded.set("retry-after",retryAfter)}return new Response(minted.body,{headers:forwarded,status:minted.status})}const ticket=readTicket(await minted.json());if(ticket===null){return failure(502,"unavailable")}const streamUrl=new URL("/application/v1/realtime/events",host);streamUrl.searchParams.set("ticket",ticket.ticket);const body={expiresAt:ticket.expiresAt,streamUrl:streamUrl.href,ticket:ticket.ticket};return Response.json(body,{headers:{"cache-control":"no-store"}})}};var mountsForCiResources=(auth,resources)=>{const ciOptions={auth,bindings:resources.bindings,organizationId:resources.organizationId,tenantUrl:resources.tenantUrl};if(resources.fetch!==undefined){Object.assign(ciOptions,{fetch:resources.fetch})}if(resources.policy!==undefined){Object.assign(ciOptions,{policy:resources.policy})}return createCiResourceMounts(ciOptions)};var capabilityForwarding=(auth,capabilities)=>{const basePath=capabilities.basePath??"/api/ci";if(capabilities.authentication===undefined){return{...capabilities,basePath,getAccessToken:async(request)=>await auth.getAccessToken?.(request)??null}}return{...capabilities,basePath}};var createExternalApplicationBff=(options)=>{const authBasePath=options.authBasePath??"/api/auth";const capabilities=options.capabilities===undefined?undefined:capabilityForwarding(options.auth,options.capabilities);const ciMounts=options.ciResources===undefined?[]:mountsForCiResources(options.auth,options.ciResources);const realtimeMounts=options.realtime===undefined?[]:[{basePath:`${options.realtime.basePath??"/api"}/realtime/ticket`,handler:createRealtimeTicketHandler({...options.realtime,auth:options.auth})}];const resources=[...realtimeMounts,...ciMounts,...options.resources??[]];return async(request)=>{const publicOrigin=publicOriginFromHeaders(request.headers,options.publicOrigin);const incoming=requestWithPublicOrigin(request,publicOrigin);const{pathname}=new URL(incoming.url);if(pathname===authBasePath||pathname.startsWith(`${authBasePath}/`)){return await options.auth.handler(incoming)}const resource=resources.find((mount)=>pathname===mount.basePath||pathname.startsWith(`${mount.basePath}/`));if(resource!==undefined){return await resource.handler(incoming)}if(capabilities!==undefined){const forwarded=await forwardDedicatedCapability(incoming,capabilities);if(forwarded!==null){return forwarded}}return new Response(null,{status:404})}};var isRecord2=(value)=>value!==null&&Object(value)===value&&!Array.isArray(value);var runIdFromPayload=(payload)=>{if(!isRecord2(payload)){return null}if(typeof payload.runId==="string"){return payload.runId}if(isRecord2(payload.result)&&typeof payload.result.runId==="string"){return payload.result.runId}return null};var unauthenticated2=()=>Response.json({error:"unauthenticated"},{status:401});var forbidden2=()=>Response.json({error:"forbidden"},{status:403});var invalidRequest=()=>Response.json({error:"invalid_request"},{status:400});var authorizeSession=async(request,options)=>{if(options.authorize!==undefined){return await options.authorize(request)}const context=await options.auth.getEntityContext(request,options.resourceId);if(context===null){return unauthenticated2()}const requiredScopes=options.requiredScopes??[];return requiredScopes.every((scope)=>context.scopes.includes(scope))?context:forbidden2()};var accessTokenFrom=async(request,options)=>{if(options.getAccessToken!==undefined){return await options.getAccessToken(request)}return await options.auth.getAccessToken?.(request)??null};var createFixedWorkflowRoute=(options)=>{const tenantUrl=requireHttpsOrigin(options.tenantUrl,"tenantUrl");const hasWorkflowId=options.workflowId!==undefined;const hasWorkflowFqn=options.workflowFqn!==undefined;if(hasWorkflowId===hasWorkflowFqn){throw new TypeError("createFixedWorkflowRoute requires exactly one of workflowId or workflowFqn")}const workflowReference=hasWorkflowId?options.workflowId:options.workflowFqn;if(typeof workflowReference!=="string"||workflowReference.length===0||workflowReference.trim()!==workflowReference){throw new TypeError("createFixedWorkflowRoute requires a non-empty workflow identifier without surrounding whitespace")}return async(request,params)=>{if(request.method!=="POST"){return new Response(null,{status:405})}const incoming=requestWithPublicOrigin(request,publicOriginFromHeaders(request.headers,options.publicOrigin));const context=await authorizeSession(incoming,options);if(context instanceof Response){return context}const accessToken=await accessTokenFrom(incoming,options);if(accessToken===null||accessToken.length===0){return unauthenticated2()}let body;try{body=await incoming.json()}catch{return invalidRequest()}if(isRecord2(body)&&(("workflowId"in body)||("workflowFqn"in body))){return invalidRequest()}let input;try{input=options.validate(body,params)}catch(error){if(error instanceof TypeError){return invalidRequest()}throw error}const headers=new Headers({authorization:`Bearer ${accessToken}`,"content-type":"application/json","x-organization-id":context.organizationId});const idempotencyKey=options.idempotencyKey===undefined?incoming.headers.get("idempotency-key")??incoming.headers.get("x-idempotency-key"):options.idempotencyKey(input,context,incoming);if(idempotencyKey!==null&&idempotencyKey.length>0){headers.set("idempotency-key",idempotencyKey)}const fetch=options.fetch??globalThis.fetch;const response=await fetch(new URL(`/application/v1/workflows/${encodeURIComponent(workflowReference)}/runs`,tenantUrl),{body:JSON.stringify({input}),headers,method:"POST"});if(!response.ok){const contentType=response.headers.get("content-type")??"application/json";return new Response(await response.text(),{headers:{"content-type":contentType},status:response.status})}const runId=runIdFromPayload(await response.json());if(runId===null){return Response.json({error:"invalid_response"},{status:502})}return Response.json({runId})}};var createGatewayWebHandler=(kernel)=>kernel.handle;var{cookies,createCiResourceMounts:createCiResourceMounts2,createExternalApplicationBff:createExternalApplicationBff2,createFixedWorkflowRoute:createFixedWorkflowRoute2,createRealtimeTicketHandler:createRealtimeTicketHandler2,createGatewayWebHandler:createGatewayWebHandler2,headers,publicOriginFromHeaders:publicOriginFromHeaders2,requestWithPublicOrigin:requestWithPublicOrigin2}=exports_web;export{cookies,createCiResourceMounts2 as createCiResourceMounts,createExternalApplicationBff2 as createExternalApplicationBff,createFixedWorkflowRoute2 as createFixedWorkflowRoute,createGatewayWebHandler2 as createGatewayWebHandler,createRealtimeTicketHandler2 as createRealtimeTicketHandler,headers,publicOriginFromHeaders2 as publicOriginFromHeaders,requestWithPublicOrigin2 as requestWithPublicOrigin};
|
|
1
|
+
var __defProp=Object.defineProperty;var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true,configurable:true,set:__exportSetter.bind(all,name)})};var exports_web={};__export(exports_web,{cookies:()=>cookiesFromRequest,createCiResourceMounts:()=>createCiResourceMounts,createExternalApplicationBff:()=>createExternalApplicationBff,createFixedWorkflowRoute:()=>createFixedWorkflowRoute,createGatewayWebHandler:()=>createGatewayWebHandler,createRealtimeTicketHandler:()=>createRealtimeTicketHandler,headers:()=>headersFromRequest,publicOriginFromHeaders:()=>publicOriginFromHeaders,requestWithPublicOrigin:()=>requestWithPublicOrigin});var isAuditSubject=(value)=>value!==null&&value!==undefined&&value.issuer.length>0&&value.subjectId.length>0;import*as Predicate from"effect/Predicate";import*as Redacted from"effect/Redacted";var secretValue=(secret)=>Predicate.isString(secret)?secret:Redacted.value(secret);var resolveCredentials=async(provider)=>("getCredentials"in provider)?await provider.getCredentials():provider;var basicAuthorization=({clientId,clientSecret})=>{const secret=secretValue(clientSecret);if(clientId.length===0||clientId.includes(":")){throw new TypeError("A non-empty clientId without ':' is required")}if(secret.length===0){throw new TypeError("A non-empty clientSecret is required")}return`Basic ${Buffer.from(`${clientId}:${secret}`,"utf-8").toString("base64")}`};var requireHttpsOrigin=(value,name)=>{let url;try{url=new URL(value)}catch{throw new TypeError(`${name} must contain only an HTTPS origin`)}if(url.protocol!=="https:"||url.origin!==value||url.pathname!=="/"||url.search!==""||url.hash!==""||url.username!==""||url.password!==""){throw new TypeError(`${name} must contain only an HTTPS origin`)}return url.origin};var capabilityPath=/^(?:\/context|\/knowledge(?:\/.*)?|\/agents(?:\/.*)?|\/conversations(?:\/.*)?|\/skills(?:\/.*)?|\/workflows(?:\/.*)?|\/runs\/.+)$/u;var identityHeaders=async(request,options)=>{const headers=new Headers;if(options.authentication===undefined){const accessToken=await options.getAccessToken(request);if(accessToken===null||accessToken.length===0){return null}headers.set("authorization",`Bearer ${accessToken}`);const organizationId=request.headers.get("x-organization-id");if(organizationId!==null){headers.set("x-organization-id",organizationId)}return headers}const auditSubject=await options.getAuditSubject(request);if(!isAuditSubject(auditSubject)){return null}const anonymousVisitor=options.caller==="anonymous_visitor";if(anonymousVisitor&&auditSubject.mappedUserId!==undefined){return null}headers.set("authorization",basicAuthorization(await resolveCredentials(options.authentication.credentials)));headers.set("x-organization-id",options.organizationId);headers.set("x-external-audit-issuer",auditSubject.issuer);headers.set("x-external-audit-subject",auditSubject.subjectId);if(anonymousVisitor){headers.set("x-external-caller-kind","anonymous_visitor")}else if(auditSubject.mappedUserId!==undefined){headers.set("x-external-ci-user-id",auditSubject.mappedUserId)}return headers};var forwardDedicatedCapability=async(request,options)=>{const url=new URL(request.url);const{basePath}=options;if(url.pathname!==basePath&&!url.pathname.startsWith(`${basePath}/`)){return null}const rest=url.pathname.slice(basePath.length);if(!capabilityPath.test(rest)){return new Response(null,{status:404})}const headers=await identityHeaders(request,options);if(headers===null){return Response.json({error:"unauthenticated"},{status:401})}const tenantUrl=requireHttpsOrigin(options.tenantUrl,"tenantUrl");const target=new URL(`/application/v1${rest}${url.search}`,tenantUrl);const correlationId=request.headers.get("x-correlation-id");if(correlationId!==null){headers.set("x-correlation-id",correlationId)}const lastEventId=request.headers.get("last-event-id");if(lastEventId!==null){headers.set("last-event-id",lastEventId)}const contentType=request.headers.get("content-type");if(contentType!==null){headers.set("content-type",contentType)}const idempotencyKey=request.headers.get("idempotency-key")??request.headers.get("x-idempotency-key");if(idempotencyKey!==null){headers.set("idempotency-key",idempotencyKey)}const init={headers,method:request.method,redirect:"manual"};if(request.method!=="GET"&&request.method!=="HEAD"){init.body=await request.arrayBuffer()}const fetch=options.fetch??globalThis.fetch;return await fetch(target,init)};var unauthenticated=()=>Response.json({error:"authentication_required"},{headers:{"cache-control":"no-store"},status:401});var forbidden=()=>Response.json({error:"forbidden"},{status:403});var isReadOperation=(operation)=>operation===undefined||operation==="get"||operation==="list"||operation==="list_members";var authorizeWithUserAuth=(auth,policy)=>(resourceId)=>async(request,operation="get")=>{const context=await auth.getEntityContext(request,resourceId);if(context===null){return unauthenticated()}const scope=isReadOperation(operation)?policy.readScope:policy.writeScope;return context.scopes.includes(scope)?context:forbidden()};import{createEntityProtocol}from"@collective-intelligence/external-apps-client-sdk/resources";import*as Effect2 from"effect/Effect";import{createEntityHttpTransport}from"@collective-intelligence/external-apps-client-sdk";import*as Config from"effect/Config";import*as Context from"effect/Context";import*as Effect from"effect/Effect";import*as Layer from"effect/Layer";import*as Schema2 from"effect/Schema";var credential=Symbol.for("@collective-intelligence/external-apps-server-sdk/ci-entity-invocation");var ciEntityAccessToken=(context)=>{if(!Object.hasOwn(context,credential)){return}const bound=context;return bound[credential]?.(context)};var matchesEntityContext=(context,resourceId)=>context?.resourceId===resourceId&&context.applicationId.length>0&&context.user?.kind==="ci_user"&&context.user.id.length>0&&context.user.issuer===context.issuer&&context.user.organizationId===context.organizationId;import*as Predicate2 from"effect/Predicate";import*as Schema from"effect/Schema";import{CiError,CiErrorCode,CiTransportError,FederatedAuthError,FederatedAuthErrorCode}from"@collective-intelligence/external-apps-client-sdk/effect";class GatewayEffectRuntimeError extends Schema.TaggedError()("GatewayEffectRuntimeError",{cause:Schema.Defect()}){constructor(...args){if(args.length===1){super({cause:args[0]})}else{super(args[0],args[1])}}get message(){return"The gateway runtime failed"}}var oauthErrorCodes=["invalid_client","invalid_grant","invalid_request","invalid_scope","invalid_target","temporarily_unavailable","unauthorized_client","unsupported_grant_type"];class MemberSessionExchangeError extends Schema.TaggedError()("MemberSessionExchangeError",{cause:Schema.optional(Schema.Defect()),code:Schema.Literals([...oauthErrorCodes,"invalid_response"]),status:Schema.UndefinedOr(Schema.Int)}){constructor(first,second,options){if(Predicate2.isString(first)){const status=Predicate2.isNumber(second)?second:undefined;super(options?.cause===undefined?{code:first,status}:{cause:options.cause,code:first,status})}else{super(first,Predicate2.isNumber(second)?undefined:second)}}get message(){return`CI refused the member session exchange: ${this.code}`}}class CiEntities extends Context.Service()("@collective-intelligence/external-apps-server-sdk/CiEntities"){}var capability={create:"create",delete:"delete",get:"get",list:"search",list_members:"search",update:"update",upload:"upload"};var tenantOrigin=(tenantUrl)=>{const tenant=new URL(tenantUrl);if(tenant.protocol!=="https:"||tenant.username!==""||tenant.password!==""||tenant.pathname!=="/"||tenant.search!==""||tenant.hash!==""){throw new TypeError("CI entity bindings require an HTTPS tenant origin")}return tenant.origin};var entityTransport=(options,schemaFqn,accessToken)=>createEntityHttpTransport({authentication:{auth:{getAccessToken:()=>accessToken},mode:"federated"},destination:{kind:"ci",organizationId:options.organizationId,schemaFqn,tenantUrl:tenantOrigin(options.tenantUrl)},fetch:options.fetch??globalThis.fetch});var isCiErrorCode=Schema2.is(CiErrorCode);var failure=(error)=>error.code==="transport_error"?new CiTransportError({cause:error}):new CiError({code:isCiErrorCode(error.code)?error.code:"invalid_request",details:error.outcome===undefined?{...error.details,resourceCode:error.code}:{...error.details,outcome:error.outcome,resourceCode:error.code},message:error.message,retryable:error.retryable});var make=(options)=>{const origin=tenantOrigin(options.tenantUrl);const executeResult=Effect.fn("CiEntities.executeResult")(function*executeResult(binding,request,context,callOptions){const{definition,protocol}=binding;const accessToken=ciEntityAccessToken(context);if(!matchesEntityContext(context,definition.id)||context.issuer!==origin||context.organizationId!==options.organizationId||accessToken===undefined){return{correlationId:request.requestId,error:{code:"forbidden",message:"The current CI identity is not authorized for this binding",outcome:"not_dispatched",retryable:false},ok:false}}const decoded=protocol.decodeRequest(request);if(!decoded.ok){return{...decoded,error:{...decoded.error,outcome:"not_dispatched"}}}const{operation}=decoded.value;if(definition.capabilities[capability[operation]]!==true){return{correlationId:request.requestId,error:{code:"capability_not_supported",message:"Resource operation is unsupported",outcome:"not_dispatched",retryable:false},ok:false}}const result=yield*Effect.acquireUseRelease(Effect.sync(()=>entityTransport(options,binding.schemaFqn,accessToken)),(entities)=>Effect.promise(async(signal)=>await entities.execute(decoded.value,{signal:callOptions?.signal===undefined?signal:AbortSignal.any([callOptions.signal,signal])})),(entities)=>Effect.promise(entities.close));const response=protocol.decodeResult(operation,result,request.requestId);return!response.ok&&response.error.details?.phase==="response_contract"?{...response,error:{...response.error,outcome:operation==="get"||operation==="list"||operation==="list_members"?"rejected":"uncertain"}}:response});return CiEntities.of({execute:Effect.fn("CiEntities.execute")(function*execute(binding,request,context){const result=yield*executeResult(binding,request,context);if(result.ok){return result.value}return yield*failure(result.error)}),executeResult})};var requireBinding=(options,schemaFqn)=>{entityTransport(options,schemaFqn,"")};var defineCiEntityResource=(input)=>{const{definition}=input;const options={organizationId:input.organizationId,tenantUrl:input.tenantUrl};if(input.fetch!==undefined){Object.assign(options,{fetch:input.fetch})}const entities=make(options);const binding={definition,protocol:createEntityProtocol(definition),schemaFqn:input.schemaFqn};requireBinding(options,input.schemaFqn);return Object.freeze({definition,execute:(request,context,callOptions)=>Effect2.runPromise(entities.executeResult(binding,request,context,callOptions))})};import{createEntityProtocol as createEntityProtocol2}from"@collective-intelligence/external-apps-client-sdk/resources";var unavailableBrand=Symbol.for("@collective-intelligence/external-apps-server-sdk/ApplicationUserAuthUnavailableError");class ApplicationUserAuthUnavailableError extends Error{[unavailableBrand]=true;code="user_auth_unavailable";static[Symbol.hasInstance](value){return value instanceof Error&&unavailableBrand in value&&value[unavailableBrand]===true&&"code"in value&&value.code==="user_auth_unavailable"}constructor(cause){super("Application user authentication is unavailable",{cause});this.name="ApplicationUserAuthUnavailableError"}}var record=(value)=>typeof value==="object"&&value!==null&&!Array.isArray(value)?Object.fromEntries(Object.entries(value)):null;var json=(body,status,correlationId)=>Response.json(body,{headers:{"cache-control":"no-store","x-correlation-id":correlationId},status});var resourceResult=(result)=>{if(result.ok){return json(result,200,result.correlationId)}let status;switch(result.error.code){case"unauthenticated":{status=401;break}case"forbidden":{status=403;break}case"not_found":{status=404;break}case"conflict":{status=409;break}case"rate_limited":{status=429;break}case"unavailable":case"transport_error":{status=503;break}case"internal":{status=500;break}case"capability_not_supported":case"invalid_request":case"upload_not_supported":{status=400;break}default:{status=500}}return json(result,status,result.correlationId)};var resourceRequest=(request,body,resourceId,externalId,action,correlationId)=>{if(request.method==="POST"&&externalId===undefined&&(action==="scan"||action==="search")){const pagination=record(body.pagination);if(pagination===null||pagination.mode!=="cursor"&&pagination.mode!=="page"){return null}const query=body;return{operation:"list",query,requestId:correlationId,resourceId}}if(request.method==="GET"&&externalId!==undefined&&action===undefined){return{id:externalId,operation:"get",requestId:correlationId,resourceId}}if(request.method==="POST"&&externalId===undefined&&action==="records"){if(typeof body.idempotencyKey!=="string"||!("value"in body)){return null}return{idempotencyKey:body.idempotencyKey,operation:"create",requestId:correlationId,resourceId,value:body.value}}if(externalId===undefined||typeof body.expectedRevision!=="string"){return null}const idempotencyKey=typeof body.idempotencyKey==="string"?{idempotencyKey:body.idempotencyKey}:{};if(request.method==="PATCH"&&action===undefined&&"value"in body){return{expectedRevision:body.expectedRevision,id:externalId,...idempotencyKey,operation:"update",requestId:correlationId,resourceId,value:body.value}}const operation=request.method==="DELETE"&&action===undefined?"hard_delete":request.method==="POST"&&action==="soft-delete"?"soft_delete":request.method==="POST"&&action==="restore"?"restore":null;return operation===null?null:{expectedRevision:body.expectedRevision,id:externalId,...idempotencyKey,operation,requestId:correlationId,resourceId}};var readResourceBody=async(request,maximum)=>{if(Number(request.headers.get("content-length"))>maximum){await request.body?.cancel();return null}const reader=request.body?.getReader();if(reader===undefined){return null}const decoder=new TextDecoder("utf-8",{fatal:true});let size=0;let text="";try{for(;;){const{done,value}=await reader.read();if(done){break}size+=value.byteLength;if(size>maximum){await reader.cancel();return null}text+=decoder.decode(value,{stream:true})}text+=decoder.decode();const parsed=JSON.parse(text);if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){return null}return Object.fromEntries(Object.entries(parsed))}catch{return null}finally{reader.releaseLock()}};var trimTrailingSlash=(value)=>value.endsWith("/")?value.slice(0,-1):value;var matchEntityHttpRoute=(pathname,basePath)=>{const prefix=trimTrailingSlash(basePath);if(!pathname.startsWith(`${prefix}/`)){return null}let parts;try{parts=pathname.slice(prefix.length+1).split("/").map(decodeURIComponent)}catch{return null}const[head,id,action]=parts;if(head==="search"&&parts.length===1){return{kind:"search"}}if(head==="records"&&parts.length===1){return{kind:"collection"}}if(head==="uploads"&&parts.length===1){return{kind:"uploads"}}if(head!=="records"||id===undefined||id.length===0){return null}if(parts.length===2){return{id,kind:"record"}}if(parts.length===3&&action==="soft-delete"){return{id,kind:"soft_delete"}}if(parts.length===4&&action==="relation-members"&&parts[3]==="search"){return{id,kind:"relation_members"}}return null};var decodeEntityRoute=(protocol,input,body)=>{if(input.operation==="list_members"){const{field,...query}=body;return protocol.decodeRequest({...input,field,query})}if(input.operation==="upload"){return protocol.decodeRequest({...body,...input})}if(input.operation!=="list"&&input.operation!=="get"){const allowed=["idempotencyKey"];if(input.operation!=="create"){allowed.push("expectedRevision")}if(input.operation==="create"||input.operation==="update"){allowed.push("value")}if(Object.keys(body).some((key)=>!allowed.includes(key))){return{correlationId:input.requestId,error:{code:"invalid_request",details:{issues:[{field:"",keyword:"additionalProperties"}]},message:"Request contains unsupported entity fields",retryable:false},ok:false}}}return protocol.decodeRequest({...input,operation:input.operation==="soft_delete"?"delete":input.operation})};var readResourceRoute=async(request,basePath,resourceId,requestId,maximum)=>{const invalid=(message)=>resourceResult({correlationId:requestId,error:{code:"invalid_request",message,retryable:false},ok:false});const path=new URL(request.url).pathname;const route=matchEntityHttpRoute(path,basePath);if(route===null){return new Response(null,{status:404})}const body=request.method==="GET"?{}:await readResourceBody(request,maximum);if(body===null){return invalid("Request body is invalid or exceeds its limit")}if(route.kind==="relation_members"){const member={operation:"list_members",parentId:route.id,requestId,resourceId};return request.method==="POST"?{body,input:member}:invalid("Invalid resource route or request")}if(route.kind==="uploads"){const upload={operation:"upload",requestId,resourceId};return request.method==="POST"?{body,input:upload}:invalid("Invalid resource route or request")}let externalId;let action;switch(route.kind){case"search":{action="search";break}case"collection":{action="records";break}case"record":{externalId=route.id;break}case"soft_delete":{action="soft-delete";externalId=route.id;break}default:{break}}const input=resourceRequest(request,body,resourceId,externalId,action,requestId);return input===null?invalid("Invalid resource route or request"):{body,input}};var createResourceHttpHandler=(options)=>{const protocol="executeCrud"in options.resource?null:createEntityProtocol2(options.resource.definition);return async(request)=>{const requestId=request.headers.get("x-correlation-id")?.match(/^[\w.-]{1,128}$/u)?.[0]??crypto.randomUUID();const{resource}=options;const route=await readResourceRoute(request,options.basePath,resource.definition.id,requestId,options.maxBodyBytes??1048576);if(route instanceof Response){return route}const{body,input}=route;const decoded=protocol===null?null:decodeEntityRoute(protocol,input,body);if(decoded!==null&&!decoded.ok){return resourceResult(decoded)}try{const operation=decoded?.ok?decoded.value.operation:input.operation;const authorized=await options.authorize(request,operation);if(authorized instanceof Response){return authorized}if(!matchesEntityContext(authorized,resource.definition.id)){return resourceResult({correlationId:requestId,error:{code:"forbidden",message:"The current identity is not authorized for this resource",retryable:false},ok:false})}if("executeCrud"in resource){return input.operation==="upload"||input.operation==="list_members"?new Response(null,{status:404}):resourceResult(await resource.executeCrud(input,authorized))}if(decoded?.ok){return resourceResult(await resource.execute(decoded.value,authorized,{signal:request.signal}))}throw new TypeError("Entity request was not decoded")}catch(error){return resourceResult({correlationId:requestId,error:{code:error instanceof ApplicationUserAuthUnavailableError?"unavailable":"internal",message:"Resource authorization or execution is unavailable",retryable:false},ok:false})}}};var defaultPolicy={readScope:"knowledge:read",writeScope:"knowledge:write"};var createCiResourceMounts=(options)=>{const authorize=authorizeWithUserAuth(options.auth,options.policy??defaultPolicy);return options.bindings.map((binding)=>{const basePath=`/api/resources/${binding.definition.id}`;const resource=options.fetch===undefined?defineCiEntityResource({definition:binding.definition,organizationId:options.organizationId,schemaFqn:binding.schemaFqn,tenantUrl:options.tenantUrl}):defineCiEntityResource({definition:binding.definition,fetch:options.fetch,organizationId:options.organizationId,schemaFqn:binding.schemaFqn,tenantUrl:options.tenantUrl});return{basePath,handler:createResourceHttpHandler({authorize:authorize(binding.definition.id),basePath,resource})}})};var publicOriginFromHeaders=(headerList,fallbackOrigin)=>{const forwardedHost=headerList.get("x-forwarded-host");const forwardedProto=headerList.get("x-forwarded-proto");if(forwardedHost===null||forwardedHost.length===0){return requireHttpsOrigin(fallbackOrigin,"publicOrigin")}const host=forwardedHost.split(",")[0]?.trim()??"";const protoRaw=forwardedProto?.split(",")[0]?.trim();const proto=(protoRaw===undefined||protoRaw.length===0?"https":protoRaw).toLowerCase();if(host.length===0||proto!=="https"){return requireHttpsOrigin(fallbackOrigin,"publicOrigin")}return requireHttpsOrigin(`https://${host}`,"x-forwarded-host")};var cookiesFromRequest=(request)=>request.headers.get("cookie");var headersFromRequest=(request)=>request.headers;var copyRequest=(request,url,headerList)=>{const{method}=request;const init={headers:headerList,method,redirect:"manual",signal:request.signal};if(method!=="GET"&&method!=="HEAD"&&request.body!==null){Object.assign(init,{body:request.body,duplex:"half"})}return new Request(url,init)};var requestWithPublicOrigin=(request,publicOrigin)=>{const current=new URL(request.url);const next=new URL(`${current.pathname}${current.search}`,publicOrigin);return copyRequest(request,next,request.headers)};var failure2=(status,error,headers={})=>Response.json({error},{headers,status});var isRecord=(value)=>typeof value==="object"&&value!==null&&!Array.isArray(value);var readTopics=async(request)=>{try{const body=await request.json();return isRecord(body)&&Array.isArray(body.topics)?body.topics:null}catch{return null}};var readTicket=(value)=>isRecord(value)&&typeof value.ticket==="string"&&typeof value.expiresAt==="string"?{expiresAt:value.expiresAt,ticket:value.ticket}:null;var isCrossSite=(request)=>{const origin=request.headers.get("origin");return request.headers.get("sec-fetch-site")==="cross-site"||origin!==null&&origin!==new URL(request.url).origin};var accessToken=async(auth,request)=>{try{const token=await auth.getAccessToken?.(request)??null;return token===null||token===""?{token:null}:{token}}catch(error){if(error instanceof ApplicationUserAuthUnavailableError){return{unavailable:true}}throw error}};var createRealtimeTicketHandler=(options)=>{const tenantUrl=requireHttpsOrigin(options.tenantUrl,"tenantUrl");const host=options.host===undefined?tenantUrl:requireHttpsOrigin(options.host,"realtime.host");const fetch=options.fetch??globalThis.fetch;return async(request)=>{if(request.method!=="POST"){return failure2(405,"method_not_allowed",{allow:"POST"})}if(isCrossSite(request)){return failure2(403,"forbidden")}if(!(request.headers.get("content-type")??"").startsWith("application/json")){return failure2(415,"unsupported_media_type")}const topics=await readTopics(request);if(topics===null){return failure2(400,"invalid_request")}const credential=await accessToken(options.auth,request);if("unavailable"in credential){return failure2(503,"unavailable")}if(credential.token===null){return failure2(401,"unauthenticated")}const headers=new Headers({authorization:`Bearer ${credential.token}`,"content-type":"application/json","x-organization-id":options.organizationId});const correlationId=request.headers.get("x-correlation-id");if(correlationId!==null){headers.set("x-correlation-id",correlationId)}const minted=await fetch(new URL("/application/v1/realtime/tickets",tenantUrl),{body:JSON.stringify({topics}),headers,method:"POST",redirect:"manual"});if(!minted.ok){const forwarded=new Headers({"content-type":minted.headers.get("content-type")??"application/json"});const retryAfter=minted.headers.get("retry-after");if(retryAfter!==null){forwarded.set("retry-after",retryAfter)}return new Response(minted.body,{headers:forwarded,status:minted.status})}const ticket=readTicket(await minted.json());if(ticket===null){return failure2(502,"unavailable")}const streamUrl=new URL("/application/v1/realtime/events",host);streamUrl.searchParams.set("ticket",ticket.ticket);const body={expiresAt:ticket.expiresAt,streamUrl:streamUrl.href,ticket:ticket.ticket};return Response.json(body,{headers:{"cache-control":"no-store"}})}};var mountsForCiResources=(auth,resources)=>{const ciOptions={auth,bindings:resources.bindings,organizationId:resources.organizationId,tenantUrl:resources.tenantUrl};if(resources.fetch!==undefined){Object.assign(ciOptions,{fetch:resources.fetch})}if(resources.policy!==undefined){Object.assign(ciOptions,{policy:resources.policy})}return createCiResourceMounts(ciOptions)};var capabilityForwarding=(auth,capabilities)=>{const basePath=capabilities.basePath??"/api/ci";if(capabilities.authentication===undefined){return{...capabilities,basePath,getAccessToken:async(request)=>await auth.getAccessToken?.(request)??null}}return{...capabilities,basePath}};var createExternalApplicationBff=(options)=>{const authBasePath=options.authBasePath??"/api/auth";const capabilities=options.capabilities===undefined?undefined:capabilityForwarding(options.auth,options.capabilities);const ciMounts=options.ciResources===undefined?[]:mountsForCiResources(options.auth,options.ciResources);const realtimeMounts=options.realtime===undefined?[]:[{basePath:`${options.realtime.basePath??"/api"}/realtime/ticket`,handler:createRealtimeTicketHandler({...options.realtime,auth:options.auth})}];const resources=[...realtimeMounts,...ciMounts,...options.resources??[]];return async(request)=>{const publicOrigin=publicOriginFromHeaders(request.headers,options.publicOrigin);const incoming=requestWithPublicOrigin(request,publicOrigin);const{pathname}=new URL(incoming.url);if(pathname===authBasePath||pathname.startsWith(`${authBasePath}/`)){return await options.auth.handler(incoming)}const resource=resources.find((mount)=>pathname===mount.basePath||pathname.startsWith(`${mount.basePath}/`));if(resource!==undefined){return await resource.handler(incoming)}if(capabilities!==undefined){const forwarded=await forwardDedicatedCapability(incoming,capabilities);if(forwarded!==null){return forwarded}}return new Response(null,{status:404})}};var isRecord2=(value)=>value!==null&&Object(value)===value&&!Array.isArray(value);var runIdFromPayload=(payload)=>{if(!isRecord2(payload)){return null}if(typeof payload.runId==="string"){return payload.runId}if(isRecord2(payload.result)&&typeof payload.result.runId==="string"){return payload.result.runId}return null};var unauthenticated2=()=>Response.json({error:"unauthenticated"},{status:401});var forbidden2=()=>Response.json({error:"forbidden"},{status:403});var invalidRequest=()=>Response.json({error:"invalid_request"},{status:400});var authorizeSession=async(request,options)=>{if(options.authorize!==undefined){return await options.authorize(request)}const context=await options.auth.getEntityContext(request,options.resourceId);if(context===null){return unauthenticated2()}const requiredScopes=options.requiredScopes??[];return requiredScopes.every((scope)=>context.scopes.includes(scope))?context:forbidden2()};var accessTokenFrom=async(request,options)=>{if(options.getAccessToken!==undefined){return await options.getAccessToken(request)}return await options.auth.getAccessToken?.(request)??null};var createFixedWorkflowRoute=(options)=>{const tenantUrl=requireHttpsOrigin(options.tenantUrl,"tenantUrl");const hasWorkflowId=options.workflowId!==undefined;const hasWorkflowFqn=options.workflowFqn!==undefined;if(hasWorkflowId===hasWorkflowFqn){throw new TypeError("createFixedWorkflowRoute requires exactly one of workflowId or workflowFqn")}const workflowReference=hasWorkflowId?options.workflowId:options.workflowFqn;if(typeof workflowReference!=="string"||workflowReference.length===0||workflowReference.trim()!==workflowReference){throw new TypeError("createFixedWorkflowRoute requires a non-empty workflow identifier without surrounding whitespace")}return async(request,params)=>{if(request.method!=="POST"){return new Response(null,{status:405})}const incoming=requestWithPublicOrigin(request,publicOriginFromHeaders(request.headers,options.publicOrigin));const context=await authorizeSession(incoming,options);if(context instanceof Response){return context}const accessToken=await accessTokenFrom(incoming,options);if(accessToken===null||accessToken.length===0){return unauthenticated2()}let body;try{body=await incoming.json()}catch{return invalidRequest()}if(isRecord2(body)&&(("workflowId"in body)||("workflowFqn"in body))){return invalidRequest()}let input;try{input=options.validate(body,params)}catch(error){if(error instanceof TypeError){return invalidRequest()}throw error}const headers=new Headers({authorization:`Bearer ${accessToken}`,"content-type":"application/json","x-organization-id":context.organizationId});const idempotencyKey=options.idempotencyKey===undefined?incoming.headers.get("idempotency-key")??incoming.headers.get("x-idempotency-key"):options.idempotencyKey(input,context,incoming);if(idempotencyKey!==null&&idempotencyKey.length>0){headers.set("idempotency-key",idempotencyKey)}const fetch=options.fetch??globalThis.fetch;const response=await fetch(new URL(`/application/v1/workflows/${encodeURIComponent(workflowReference)}/runs`,tenantUrl),{body:JSON.stringify({input}),headers,method:"POST"});if(!response.ok){const contentType=response.headers.get("content-type")??"application/json";return new Response(await response.text(),{headers:{"content-type":contentType},status:response.status})}const runId=runIdFromPayload(await response.json());if(runId===null){return Response.json({error:"invalid_response"},{status:502})}return Response.json({runId})}};var createGatewayWebHandler=(kernel)=>kernel.handle;var{cookies,createCiResourceMounts:createCiResourceMounts2,createExternalApplicationBff:createExternalApplicationBff2,createFixedWorkflowRoute:createFixedWorkflowRoute2,createRealtimeTicketHandler:createRealtimeTicketHandler2,createGatewayWebHandler:createGatewayWebHandler2,headers,publicOriginFromHeaders:publicOriginFromHeaders2,requestWithPublicOrigin:requestWithPublicOrigin2}=exports_web;export{cookies,createCiResourceMounts2 as createCiResourceMounts,createExternalApplicationBff2 as createExternalApplicationBff,createFixedWorkflowRoute2 as createFixedWorkflowRoute,createGatewayWebHandler2 as createGatewayWebHandler,createRealtimeTicketHandler2 as createRealtimeTicketHandler,headers,publicOriginFromHeaders2 as publicOriginFromHeaders,requestWithPublicOrigin2 as requestWithPublicOrigin};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@collective-intelligence/external-apps-server-sdk",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.38",
|
|
4
4
|
"description": "Server-side client and proxy adapters for Collective Intelligence external applications.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -23,6 +23,12 @@
|
|
|
23
23
|
"import": "./dist/effect.js",
|
|
24
24
|
"default": "./dist/effect.js"
|
|
25
25
|
},
|
|
26
|
+
"./next": {
|
|
27
|
+
"ci-source": "./src/entrypoints/next.ts",
|
|
28
|
+
"types": "./dist/next.d.ts",
|
|
29
|
+
"import": "./dist/next.js",
|
|
30
|
+
"default": "./dist/next.js"
|
|
31
|
+
},
|
|
26
32
|
"./admin": {
|
|
27
33
|
"ci-source": "./src/entrypoints/admin.ts",
|
|
28
34
|
"types": "./dist/admin.d.ts",
|
|
@@ -62,8 +68,8 @@
|
|
|
62
68
|
"./persistence/drizzle/effect": {
|
|
63
69
|
"ci-source": "./src/entrypoints/persistence/drizzle-effect.ts",
|
|
64
70
|
"types": "./dist/persistence/drizzle-effect.d.ts",
|
|
65
|
-
"import": "./dist/
|
|
66
|
-
"default": "./dist/
|
|
71
|
+
"import": "./dist/effect.js",
|
|
72
|
+
"default": "./dist/effect.js"
|
|
67
73
|
},
|
|
68
74
|
"./knowledge-sources/payload": {
|
|
69
75
|
"ci-source": "./src/entrypoints/knowledge-sources/payload.ts",
|
|
@@ -98,14 +104,14 @@
|
|
|
98
104
|
"./runtime/next": {
|
|
99
105
|
"ci-source": "./src/entrypoints/runtime/next.ts",
|
|
100
106
|
"types": "./dist/runtime/next.d.ts",
|
|
101
|
-
"import": "./dist/
|
|
102
|
-
"default": "./dist/
|
|
107
|
+
"import": "./dist/next.js",
|
|
108
|
+
"default": "./dist/next.js"
|
|
103
109
|
},
|
|
104
110
|
"./runtime/effect": {
|
|
105
111
|
"ci-source": "./src/entrypoints/runtime/effect.ts",
|
|
106
112
|
"types": "./dist/runtime/effect.d.ts",
|
|
107
|
-
"import": "./dist/
|
|
108
|
-
"default": "./dist/
|
|
113
|
+
"import": "./dist/effect.js",
|
|
114
|
+
"default": "./dist/effect.js"
|
|
109
115
|
},
|
|
110
116
|
"./gateway/contracts": {
|
|
111
117
|
"ci-source": "./src/entrypoints/gateway/contracts.ts",
|
|
@@ -136,18 +142,19 @@
|
|
|
136
142
|
"test": "bun tools/test-postgres.ts && bun tools/test-pack.ts",
|
|
137
143
|
"test:pack": "bun tools/test-pack.ts",
|
|
138
144
|
"test:unit": "bun tools/test-postgres.ts",
|
|
145
|
+
"test:properties": "vitest run --config vitest.config.ts",
|
|
139
146
|
"format": "oxfmt --write .",
|
|
140
147
|
"format:check": "oxfmt --check .",
|
|
141
148
|
"format:check:staged": "oxfmt --check",
|
|
142
149
|
"lint": "node \"../../../.agents/scripts/managed-lint-runner.mjs\" --scope \"packages/public/external-apps-server-sdk\"",
|
|
143
150
|
"lint:staged": "oxlint --no-error-on-unmatched-pattern",
|
|
144
151
|
"prepack": "bun run build",
|
|
145
|
-
"type-check": "bun check",
|
|
152
|
+
"type-check": "bun check && bun check -p tsconfig.type-tests.json",
|
|
146
153
|
"test:postgres": "bun tools/test-postgres.ts src/adapters/persistence/drizzle"
|
|
147
154
|
},
|
|
148
155
|
"dependencies": {
|
|
149
|
-
"@collective-intelligence/extensions-sdk": "0.1.
|
|
150
|
-
"@collective-intelligence/external-apps-client-sdk": "0.1.
|
|
156
|
+
"@collective-intelligence/extensions-sdk": "0.1.31",
|
|
157
|
+
"@collective-intelligence/external-apps-client-sdk": "0.1.37",
|
|
151
158
|
"ajv": "8.20.0",
|
|
152
159
|
"ajv-formats": "3.0.1",
|
|
153
160
|
"jose": "6.2.9"
|
|
@@ -211,6 +218,7 @@
|
|
|
211
218
|
"devDependencies": {
|
|
212
219
|
"@ai-sdk/provider-utils": "5.0.54",
|
|
213
220
|
"@effect/eslint-plugin": "latest",
|
|
221
|
+
"@effect/vitest": "4.1.0",
|
|
214
222
|
"@nestjs/common": "11.2.4",
|
|
215
223
|
"@nestjs/core": "11.2.4",
|
|
216
224
|
"@nestjs/platform-express": "11.2.4",
|
|
@@ -242,7 +250,8 @@
|
|
|
242
250
|
"rxjs": "7.8.2",
|
|
243
251
|
"typescript": "5.9.3",
|
|
244
252
|
"ultracite": "7.10.7",
|
|
253
|
+
"vitest": "5.0.2",
|
|
245
254
|
"zod": "4.4.3"
|
|
246
255
|
},
|
|
247
|
-
"gitHead": "
|
|
256
|
+
"gitHead": "b46c00d8ce76db49b810e7a3f25933ace4f2252f"
|
|
248
257
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var __defProp=Object.defineProperty;var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true,configurable:true,set:__exportSetter.bind(all,name)})};var exports_drizzle_effect={};__export(exports_drizzle_effect,{DrizzlePostgres:()=>DrizzlePostgres,DrizzlePostgresInitializationError:()=>DrizzlePostgresInitializationError,layerFromDatabase:()=>layerFromDatabase,layerNodePostgres:()=>layerNodePostgres});import{drizzle}from"drizzle-orm/node-postgres";import*as Context from"effect/Context";import*as Effect from"effect/Effect";import*as Layer from"effect/Layer";import{Pool}from"pg";import*as Schema from"effect/Schema";class DrizzlePostgresInitializationError extends Schema.TaggedError()("DrizzlePostgresInitializationError",{cause:Schema.Defect()}){}var makeDatabase=(pool)=>drizzle({client:pool});class DrizzlePostgres extends Context.Service()("@collective-intelligence/external-apps-server-sdk/DrizzlePostgres"){}var layerFromDatabase=(value)=>Layer.succeed(DrizzlePostgres,value);var layerNodePostgres=(options)=>Layer.effect(DrizzlePostgres,Effect.acquireRelease(Effect.sync(()=>new Pool(options.connection)),(pool)=>Effect.promise(async()=>{await pool.end()})).pipe(Effect.flatMap((pool)=>{const value=DrizzlePostgres.of({database:makeDatabase(pool),pool});const{migrate}=options;return migrate===undefined?Effect.succeed(value):Effect.tryPromise({catch:(cause)=>new DrizzlePostgresInitializationError({cause}),try:migrate.bind(undefined,value)}).pipe(Effect.as(value))})));var{DrizzlePostgres:DrizzlePostgres2,DrizzlePostgresInitializationError:DrizzlePostgresInitializationError2,layerFromDatabase:layerFromDatabase2,layerNodePostgres:layerNodePostgres2}=exports_drizzle_effect;export{DrizzlePostgres2 as DrizzlePostgres,DrizzlePostgresInitializationError2 as DrizzlePostgresInitializationError,layerFromDatabase2 as layerFromDatabase,layerNodePostgres2 as layerNodePostgres};
|