@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/dist/next.d.ts ADDED
@@ -0,0 +1,358 @@
1
+ // Generated by dts-bundle-generator v9.5.1
2
+
3
+ import { DatasetDefinition, DatasetProviderCapabilities, DatasetProviderResult, DatasetResultPage, OperationDomainDeclaration, PackageSchemaProjection, PortableOperationDeclaration, QueryInput } from '@collective-intelligence/extensions-sdk';
4
+ import { EntityOperation, EntityOperationResult, EntityRequest, ResourceDefinition, ResourceResult, ResourceTransportRequest } from '@collective-intelligence/external-apps-client-sdk/resources';
5
+ import * as Redacted from 'effect/Redacted';
6
+
7
+ /** Application login identities are separate from gateway machine callers. */
8
+ export type ApplicationUserIdentity = Readonly<{
9
+ kind: "local_user";
10
+ id: string;
11
+ email: string;
12
+ name: string | null;
13
+ } | {
14
+ kind: "ci_user";
15
+ id: string;
16
+ email: string | null;
17
+ name: string | null;
18
+ issuer: string;
19
+ organizationId: string;
20
+ }>;
21
+ export type ApplicationUserSession = Readonly<{
22
+ identity: ApplicationUserIdentity;
23
+ expiresAt: Date;
24
+ }>;
25
+ /** Constructed only after user/app/organization authorization at server ingress.
26
+ * Canonical identities survive proxy hops and scope mutation receipts; credentials
27
+ * and request/correlation IDs are deliberately not part of that logical identity.
28
+ */
29
+ export type EntityInvocationContext = Readonly<{
30
+ /** The App Permissions of the user's effective roles on the app. */
31
+ appPermissions: readonly string[];
32
+ applicationId: string;
33
+ issuer: string;
34
+ organizationId: string;
35
+ resourceId: string;
36
+ /** The user's effective roles on the app, read from CI at this lookup. */
37
+ roles: readonly string[];
38
+ scopes: readonly string[];
39
+ user: ApplicationUserIdentity;
40
+ }>;
41
+ export type ApplicationUserAuth = Readonly<{
42
+ mode: "federated" | "local";
43
+ handler: (request: Request) => Promise<Response>;
44
+ /** Returns null only when the request has no valid application session. */
45
+ getSession: (request: Request) => Promise<ApplicationUserSession | null>;
46
+ /** Server-only current CI authority. The host still owns resource/operation policy.
47
+ * Null means no valid CI session, including a user without a role on the app.
48
+ */
49
+ getEntityContext: (request: Request, resourceId: string) => Promise<EntityInvocationContext | null>;
50
+ /** Server-only Delegated access token. Absent for local application login. */
51
+ getAccessToken?: (request: Request) => Promise<string | null>;
52
+ }>;
53
+ export interface ExternalApplicationExternalAuditSubject {
54
+ readonly issuer: string;
55
+ readonly mappedUserId?: string;
56
+ readonly subjectId: string;
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> {
64
+ readonly clientId: string;
65
+ readonly clientSecret: Secret;
66
+ }
67
+ export interface RotatingConfidentialCredentialProvider {
68
+ readonly getCredentials: () => ConfidentialCredentials | Promise<ConfidentialCredentials>;
69
+ }
70
+ export type ConfidentialCredentialProvider<Secret extends ClientSecret = string> = ConfidentialCredentials<Secret> | RotatingConfidentialCredentialProvider;
71
+ export type ServiceServerAuthentication<Secret extends ClientSecret = string> = Readonly<{
72
+ credentials: ConfidentialCredentialProvider<Secret>;
73
+ mode: "service";
74
+ }>;
75
+ /** Application credentials authorize each call for a required Audit subject in one configured organization. */
76
+ export type ServiceCapabilityAuthorization = Readonly<{
77
+ authentication: ServiceServerAuthentication;
78
+ /**
79
+ * Who makes each forwarded call; defaults to `"service"`. `"anonymous_visitor"`
80
+ * marks each call as made by the anonymous visitor the Audit subject names:
81
+ * the backend then runs only the Agent's own bindings and never the
82
+ * application's service authority. A visitor is never a CI user, so an Audit
83
+ * subject carrying `mappedUserId` is refused with `401`.
84
+ */
85
+ caller?: "anonymous_visitor" | "service";
86
+ getAuditSubject: (request: Request) => Promise<ExternalApplicationExternalAuditSubject | null>;
87
+ organizationId: string;
88
+ }>;
89
+ export type UserAuthScopePolicy = Readonly<{
90
+ readScope: string;
91
+ writeScope: string;
92
+ }>;
93
+ export type CiResourceBinding<Value = unknown, Create = Value, Patch = Partial<Value>> = Readonly<{
94
+ definition: ResourceDefinition<Value, Create, Patch>;
95
+ schemaFqn: string;
96
+ }>;
97
+ export type CiResourcesOptions = Readonly<{
98
+ auth: Pick<ApplicationUserAuth, "getEntityContext">;
99
+ bindings: readonly CiResourceBinding[];
100
+ fetch?: typeof globalThis.fetch;
101
+ organizationId: string;
102
+ policy?: UserAuthScopePolicy;
103
+ tenantUrl: string;
104
+ }>;
105
+ export type RealtimeTicketOptions = Readonly<{
106
+ auth: Pick<ApplicationUserAuth, "getAccessToken">;
107
+ /** The CI organization the signed-in users belong to. */
108
+ organizationId: string;
109
+ /** The CI origin that mints tickets. */
110
+ tenantUrl: string;
111
+ /** The origin the browser opens the event stream on; defaults to `tenantUrl`. */
112
+ host?: string;
113
+ fetch?: typeof globalThis.fetch;
114
+ }>;
115
+ /** The ticket route answer: a single-use ticket and the stream it opens. */
116
+ export type RealtimeTicketResponse = Readonly<{
117
+ ticket: string;
118
+ expiresAt: string;
119
+ streamUrl: string;
120
+ }>;
121
+ export type BffResourceMount = Readonly<{
122
+ basePath: string;
123
+ handler: (request: Request) => Promise<Response>;
124
+ }>;
125
+ /** Dedicated Capability forwarding: the user's delegated token by default, or service credentials with an Audit subject. */
126
+ export type ExternalApplicationBffCapabilities = Readonly<{
127
+ basePath?: string;
128
+ fetch?: typeof globalThis.fetch;
129
+ tenantUrl: string;
130
+ }> & (Readonly<{
131
+ authentication?: never;
132
+ }> | ServiceCapabilityAuthorization);
133
+ /** The realtime ticket route `POST {basePath}/realtime/ticket`; `basePath` defaults to `/api`. */
134
+ export type ExternalApplicationBffRealtime = Omit<RealtimeTicketOptions, "auth"> & Readonly<{
135
+ basePath?: string;
136
+ }>;
137
+ export type ExternalApplicationBffOptions = Readonly<{
138
+ auth: ApplicationUserAuth;
139
+ authBasePath?: string;
140
+ capabilities?: ExternalApplicationBffCapabilities;
141
+ ciResources?: Omit<CiResourcesOptions, "auth">;
142
+ publicOrigin: string;
143
+ realtime?: ExternalApplicationBffRealtime;
144
+ resources?: readonly BffResourceMount[];
145
+ }>;
146
+ export type ExternalApplicationBff = (request: Request) => Promise<Response>;
147
+ export type PrincipalKind = "detached_user" | "service_principal";
148
+ export type DelegatedSubjectPolicy = "allowed" | "forbidden" | "required";
149
+ export type AuthorizationRequirement = Readonly<{
150
+ delegatedSubject?: DelegatedSubjectPolicy;
151
+ organization: "required";
152
+ principalKinds: readonly PrincipalKind[];
153
+ scopes: readonly string[];
154
+ }>;
155
+ export type ExternalAuditSubject = Readonly<{
156
+ issuer: string;
157
+ mappedCiUserId?: string;
158
+ subject: string;
159
+ }>;
160
+ export type GatewayCallerIdentity = Readonly<{
161
+ audience: readonly string[];
162
+ binding: string;
163
+ expiresAt: number;
164
+ installationId: string;
165
+ issuer: string;
166
+ organizationId: string;
167
+ principalKind: PrincipalKind;
168
+ requestId: string;
169
+ scopes: readonly string[];
170
+ subject: string;
171
+ }>;
172
+ export type GatewayInvocationContext = Readonly<{
173
+ caller: GatewayCallerIdentity;
174
+ correlationId: string;
175
+ externalAuditSubject?: ExternalAuditSubject;
176
+ organizationId: string;
177
+ }>;
178
+ /** Full inventory only: no filters, text search or caller-selected ordering.
179
+ * Continue consecutive pages with the first watermark. A conflict requires restart.
180
+ */
181
+ export type ResourceInventoryRequest = Readonly<{
182
+ page: number;
183
+ pageSize: number;
184
+ watermark?: string;
185
+ }>;
186
+ /** A configured local or CI-backed binding; no storage policy is exposed to browsers. */
187
+ export type EntityResourceDefinition<Value = unknown, Create = Value, Patch = Partial<Value>> = Readonly<{
188
+ definition: ResourceDefinition<Value, Create, Patch>;
189
+ execute: (request: EntityRequest<Create, Patch>, context: EntityInvocationContext, options?: Readonly<{
190
+ signal?: AbortSignal;
191
+ }>) => Promise<ResourceResult<EntityOperationResult<Value, EntityOperation>>>;
192
+ }>;
193
+ export type GatewayResourceOperation = ResourceTransportRequest["operation"];
194
+ export type GatewayResourceAuthorization = Readonly<Partial<Record<GatewayResourceOperation, AuthorizationRequirement>>>;
195
+ export type GatewayResourceDefinition<Entity = unknown, Create = Entity, Update = Partial<Entity>> = Readonly<{
196
+ authorization: GatewayResourceAuthorization;
197
+ definition: ResourceDefinition<Entity, Create, Update>;
198
+ execute: (request: ResourceTransportRequest, context: GatewayInvocationContext, options?: Readonly<{
199
+ signal?: AbortSignal;
200
+ }>) => Promise<ResourceResult<unknown>>;
201
+ scan?: (request: ResourceInventoryRequest & Readonly<{
202
+ requestId: string;
203
+ resourceId: string;
204
+ }>, context: GatewayInvocationContext, options?: Readonly<{
205
+ signal?: AbortSignal;
206
+ }>) => Promise<ResourceResult<unknown>>;
207
+ changes?: (request: Readonly<{
208
+ cursor?: string;
209
+ limit: number;
210
+ requestId: string;
211
+ resourceId: string;
212
+ }>, context: GatewayInvocationContext, options?: Readonly<{
213
+ signal?: AbortSignal;
214
+ }>) => Promise<ResourceResult<unknown>>;
215
+ }>;
216
+ export type CrudResource<Entity = unknown, Create = Entity, Update = Partial<Entity>> = GatewayResourceDefinition<Entity, Create, Update> & Readonly<{
217
+ executeCrud: (request: ResourceTransportRequest, context: EntityInvocationContext) => Promise<ResourceResult<unknown>>;
218
+ }>;
219
+ export type ResourceHttpHandlerOptions<Value = unknown, Create = Value, Patch = Partial<Value>> = Readonly<{
220
+ resource: CrudResource<Value, Create, Patch> | EntityResourceDefinition<Value, Create, Patch>;
221
+ /** Mount path including the entity name, e.g. /api/leads. */
222
+ basePath: string;
223
+ /** Host verifies the current CI session and resource policy; no browser identity is trusted. */
224
+ authorize: (request: Request, operation: ResourceTransportRequest["operation"] | EntityOperation) => Promise<EntityInvocationContext | Response>;
225
+ maxBodyBytes?: number;
226
+ }>;
227
+ /**
228
+ * Runtime dispatch validates the declared input schema before invoking a
229
+ * handler. The bivariant call signature lets domains retain heterogeneous,
230
+ * strongly typed handlers while exposing one erased operation collection.
231
+ */
232
+ export type GatewayOperationHandler<Input = unknown, Output = unknown> = {
233
+ bivarianceHack(request: Readonly<{
234
+ context: GatewayInvocationContext;
235
+ /** Validated caller key; the handler owns durable replay storage. */
236
+ idempotencyKey?: string;
237
+ input: Input;
238
+ signal: AbortSignal;
239
+ }>): Promise<Output>;
240
+ }["bivarianceHack"];
241
+ export type GatewayOperationDefinition<Input = unknown, Output = unknown> = Omit<PortableOperationDeclaration, "input" | "output"> & Readonly<{
242
+ handler: GatewayOperationHandler<Input, Output>;
243
+ input: PackageSchemaProjection;
244
+ output: PackageSchemaProjection;
245
+ }>;
246
+ export type GatewayOperationManifest = Omit<GatewayOperationDefinition, "handler"> & Readonly<{
247
+ canonicalReference: string;
248
+ }>;
249
+ export type GatewayOperationDomainDefinition = OperationDomainDeclaration<GatewayOperationDefinition>;
250
+ export type GatewayOperationDomainManifest = OperationDomainDeclaration<GatewayOperationManifest>;
251
+ /** CI destination marker only; source records are shared across all connections. */
252
+ export type OrganizationBinding = Readonly<{
253
+ mode: "installed_organization";
254
+ }>;
255
+ export type GatewayKnowledgeResourceExposure = Readonly<{
256
+ resource: GatewayResourceDefinition;
257
+ access: "read" | "read_write";
258
+ }>;
259
+ export type GatewayDatasetBinding = Readonly<{
260
+ id: string;
261
+ title: string;
262
+ definition: DatasetDefinition;
263
+ authorization: AuthorizationRequirement;
264
+ providerFqn: string;
265
+ query: (input: QueryInput, context: GatewayInvocationContext, options: Readonly<{
266
+ signal: AbortSignal;
267
+ }>) => Promise<DatasetProviderResult<DatasetResultPage>>;
268
+ }>;
269
+ export type GatewayDatasetManifest = Omit<GatewayDatasetBinding, "query"> & Readonly<{
270
+ capabilities: DatasetProviderCapabilities;
271
+ }>;
272
+ export type GatewayDefinitionInput = Readonly<{
273
+ knowledge?: readonly GatewayKnowledgeResourceExposure[];
274
+ datasets?: readonly GatewayDatasetBinding[];
275
+ id: string;
276
+ operationDomains: readonly GatewayOperationDomainDefinition[];
277
+ organizationBinding?: OrganizationBinding;
278
+ protocolVersion?: "2";
279
+ version: string;
280
+ }>;
281
+ export type GatewayManifest = Readonly<{
282
+ capabilities: Readonly<{
283
+ resources: boolean;
284
+ }>;
285
+ datasets: readonly GatewayDatasetManifest[];
286
+ knowledge: readonly Readonly<{
287
+ id: string;
288
+ access: "read" | "read_write";
289
+ definition: GatewayResourceDefinition["definition"];
290
+ fullInventory: boolean;
291
+ incrementalChanges: boolean;
292
+ }>[];
293
+ contentHash: string;
294
+ id: string;
295
+ operationDomains: readonly GatewayOperationDomainManifest[];
296
+ organizationBinding: OrganizationBinding;
297
+ protocolVersion: "2";
298
+ revision: string;
299
+ version: string;
300
+ }>;
301
+ export type GatewayProposal = Readonly<{
302
+ gatewayId: string;
303
+ gatewayVersion: string;
304
+ knowledge: GatewayManifest["knowledge"];
305
+ operationDomains: readonly GatewayOperationDomainManifest[];
306
+ revision: string;
307
+ }>;
308
+ export interface DefinedGateway {
309
+ readonly input: GatewayDefinitionInput;
310
+ readonly resource: (id: string) => GatewayResourceDefinition | undefined;
311
+ readonly dataset: (id: string) => GatewayDatasetBinding | undefined;
312
+ readonly manifest: GatewayManifest;
313
+ readonly proposal: GatewayProposal;
314
+ }
315
+ export interface GatewayKernel {
316
+ readonly handle: (request: Request) => Promise<Response>;
317
+ readonly manifest: DefinedGateway["manifest"];
318
+ }
319
+ export type WorkflowTarget = Readonly<{
320
+ workflowId: string;
321
+ workflowFqn?: never;
322
+ }> | Readonly<{
323
+ workflowFqn: string;
324
+ workflowId?: never;
325
+ }>;
326
+ export type FixedWorkflowRouteOptions<Input, Params = Record<string, never>> = Readonly<{
327
+ auth: Pick<ApplicationUserAuth, "getAccessToken" | "getEntityContext">;
328
+ fetch?: typeof globalThis.fetch;
329
+ publicOrigin: string;
330
+ tenantUrl: string;
331
+ validate: (body: unknown, params: Params) => Input;
332
+ resourceId: string;
333
+ requiredScopes?: readonly string[];
334
+ idempotencyKey?: (input: Input, context: EntityInvocationContext, request: Request) => string | null;
335
+ authorize?: (request: Request) => Promise<EntityInvocationContext | Response>;
336
+ getAccessToken?: (request: Request) => Promise<string | null>;
337
+ }> & WorkflowTarget;
338
+ export type GatewayWebHandler = (request: Request) => Promise<Response>;
339
+ export type GatewayRuntimeKernel = Pick<GatewayKernel, "handle">;
340
+ export type GatewayNextRouteHandlers = Readonly<{
341
+ DELETE: GatewayWebHandler;
342
+ GET: GatewayWebHandler;
343
+ PATCH: GatewayWebHandler;
344
+ POST: GatewayWebHandler;
345
+ PUT: GatewayWebHandler;
346
+ }>;
347
+ export type ResourceNextRouteHandlers = Readonly<{
348
+ DELETE: GatewayWebHandler;
349
+ GET: GatewayWebHandler;
350
+ PATCH: GatewayWebHandler;
351
+ POST: GatewayWebHandler;
352
+ }>;
353
+ export declare const cookies: (request: Request) => string | null, createCiResourceMounts: (options: CiResourcesOptions) => {
354
+ basePath: string;
355
+ handler: (request: Request) => Promise<Response>;
356
+ }[], createExternalApplicationBff: (options: ExternalApplicationBffOptions) => ExternalApplicationBff, createExternalApplicationBffNextHandlers: (options: ExternalApplicationBffOptions) => GatewayNextRouteHandlers, createFixedWorkflowRoute: <Input, Params = Record<string, never>>(options: FixedWorkflowRouteOptions<Input, Params>) => ((request: Request, params: Params) => Promise<Response>), createRealtimeTicketHandler: (options: RealtimeTicketOptions) => ((request: Request) => Promise<Response>), createGatewayNextRouteHandlers: (kernel: GatewayRuntimeKernel) => GatewayNextRouteHandlers, createResourceNextRouteHandlers: <Value, Create = Value, Patch = Partial<Value>>(options: ResourceHttpHandlerOptions<Value, Create, Patch>) => ResourceNextRouteHandlers, headers: (request: Request) => Headers, publicOriginFromHeaders: (headerList: Headers, fallbackOrigin: string) => string, requestWithPublicOrigin: (request: Request, publicOrigin: string) => Request;
357
+
358
+ export {};
package/dist/next.js ADDED
@@ -0,0 +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_next={};__export(exports_next,{cookies:()=>cookiesFromRequest,createCiResourceMounts:()=>createCiResourceMounts,createExternalApplicationBff:()=>createExternalApplicationBff,createExternalApplicationBffNextHandlers:()=>createExternalApplicationBffNextHandlers,createFixedWorkflowRoute:()=>createFixedWorkflowRoute,createGatewayNextRouteHandlers:()=>createGatewayNextRouteHandlers,createRealtimeTicketHandler:()=>createRealtimeTicketHandler,createResourceNextRouteHandlers:()=>createResourceNextRouteHandlers,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 createGatewayNextRouteHandlers=(kernel)=>{const handle=createGatewayWebHandler(kernel);return{DELETE:handle,GET:handle,PATCH:handle,POST:handle,PUT:handle}};var createResourceNextRouteHandlers=(options)=>{const handle=createResourceHttpHandler(options);return{DELETE:handle,GET:handle,PATCH:handle,POST:handle}};var createExternalApplicationBffNextHandlers=(options)=>createGatewayNextRouteHandlers({handle:createExternalApplicationBff(options)});var{cookies,createCiResourceMounts:createCiResourceMounts2,createExternalApplicationBff:createExternalApplicationBff2,createExternalApplicationBffNextHandlers:createExternalApplicationBffNextHandlers2,createFixedWorkflowRoute:createFixedWorkflowRoute2,createRealtimeTicketHandler:createRealtimeTicketHandler2,createGatewayNextRouteHandlers:createGatewayNextRouteHandlers2,createResourceNextRouteHandlers:createResourceNextRouteHandlers2,headers,publicOriginFromHeaders:publicOriginFromHeaders2,requestWithPublicOrigin:requestWithPublicOrigin2}=exports_next;export{cookies,createCiResourceMounts2 as createCiResourceMounts,createExternalApplicationBff2 as createExternalApplicationBff,createExternalApplicationBffNextHandlers2 as createExternalApplicationBffNextHandlers,createFixedWorkflowRoute2 as createFixedWorkflowRoute,createGatewayNextRouteHandlers2 as createGatewayNextRouteHandlers,createRealtimeTicketHandler2 as createRealtimeTicketHandler,createResourceNextRouteHandlers2 as createResourceNextRouteHandlers,headers,publicOriginFromHeaders2 as publicOriginFromHeaders,requestWithPublicOrigin2 as requestWithPublicOrigin};
@@ -1,6 +1,8 @@
1
1
  // Generated by dts-bundle-generator v9.5.1
2
2
 
3
+ import * as DrizzleNodePostgres from 'drizzle-orm/node-postgres';
3
4
  import * as Context from 'effect/Context';
5
+ import * as Effect from 'effect/Effect';
4
6
  import * as Layer from 'effect/Layer';
5
7
  import * as Schema from 'effect/Schema';
6
8
  import { Pool, PoolConfig } from 'pg';
@@ -10,9 +12,10 @@ declare const DrizzlePostgresInitializationError_base: Schema.Class<DrizzlePostg
10
12
  }>, import("effect/Cause").YieldableError>;
11
13
  declare class DrizzlePostgresInitializationError extends DrizzlePostgresInitializationError_base {
12
14
  }
13
- declare const makeDatabase: (pool: Pool) => import("drizzle-orm/node-postgres").NodePgDatabase<import("drizzle-orm").EmptyRelations> & {
15
+ declare const makeDatabase: (drizzle: typeof DrizzleNodePostgres.drizzle, pool: Pool) => DrizzleNodePostgres.NodePgDatabase<import("drizzle-orm").EmptyRelations> & {
14
16
  $client: Pool;
15
17
  };
18
+ /** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/effect`. */
16
19
  export type DrizzlePostgresValue = Readonly<{
17
20
  database: ReturnType<typeof makeDatabase>;
18
21
  pool: Pool;
@@ -23,16 +26,32 @@ declare const DrizzlePostgres_base: Context.ServiceClass<DrizzlePostgres, "@coll
23
26
  }>>;
24
27
  declare class DrizzlePostgres extends DrizzlePostgres_base {
25
28
  }
29
+ /** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/effect`. */
26
30
  export type NodePostgresLayerOptions = Readonly<{
27
31
  connection: PoolConfig;
28
32
  /** Explicit host-selected migration hook. The SDK never discovers or runs DDL implicitly. */
29
33
  migrate?: (value: DrizzlePostgresValue) => Promise<void>;
30
34
  }>;
31
- declare const DrizzlePostgres$1: typeof DrizzlePostgres, DrizzlePostgresInitializationError$1: typeof DrizzlePostgresInitializationError, layerFromDatabase: (value: DrizzlePostgresValue) => import("effect/Layer").Layer<DrizzlePostgres, never, never>, layerNodePostgres: (options: NodePostgresLayerOptions) => import("effect/Layer").Layer<DrizzlePostgres, DrizzlePostgresInitializationError, never>;
35
+ declare const DrizzlePostgres$1: typeof DrizzlePostgres;
36
+ type DrizzlePostgres$1 = DrizzlePostgres;
37
+ declare const DrizzlePostgresInitializationError$1: typeof DrizzlePostgresInitializationError;
38
+ type DrizzlePostgresInitializationError$1 = DrizzlePostgresInitializationError;
39
+ /** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/effect`. */
40
+ declare const DrizzlePostgres$2: typeof DrizzlePostgres;
41
+ /** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/effect`. */
42
+ type DrizzlePostgres$2 = DrizzlePostgres$1;
43
+ /** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/effect`. */
44
+ declare const DrizzlePostgresInitializationError$2: typeof DrizzlePostgresInitializationError;
45
+ /** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/effect`. */
46
+ type DrizzlePostgresInitializationError$2 = DrizzlePostgresInitializationError$1;
47
+ /** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/effect`. */
48
+ export declare const layerFromDatabase: (value: DrizzlePostgresValue) => import("effect/Layer").Layer<DrizzlePostgres, never, never>;
49
+ /** @deprecated Import it from `@collective-intelligence/external-apps-server-sdk/effect`. */
50
+ export declare const layerNodePostgres: (options: NodePostgresLayerOptions) => import("effect/Layer").Layer<DrizzlePostgres, DrizzlePostgresInitializationError, never>;
32
51
 
33
52
  export {
34
- DrizzlePostgres$1 as DrizzlePostgres,
35
- DrizzlePostgresInitializationError$1 as DrizzlePostgresInitializationError,
53
+ DrizzlePostgres$2 as DrizzlePostgres,
54
+ DrizzlePostgresInitializationError$2 as DrizzlePostgresInitializationError,
36
55
  };
37
56
 
38
57
  export {};