@superdurable/connector-elasticsearch 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,208 @@
1
+ import { D as DeleteDocumentInput, a as DeletedDocument, C as Connection, I as IndexDocumentInput, b as IndexedDocument, S as SearchDocumentsInput, c as SearchPage, d as Config, e as Credentials, O as Operations } from './connection-BpzhI70A.js';
2
+ export { f as ConfigSchema, g as CredentialSource, h as DeleteDocumentInputSchema, i as DeletedDocumentSchema, j as IndexDocumentInputSchema, k as IndexedDocumentSchema, l as SearchDocumentsInputSchema, m as SearchHit, n as SearchHitSchema, o as SearchPageSchema, p as decodeCredentials, q as newConnection, r as newConnectionWithOperations } from './connection-BpzhI70A.js';
3
+ import * as _superdurable_connectors_sdk from '@superdurable/connectors-sdk';
4
+ import { MutationDefinition, QueryDefinition, MutationStepConfig, Mutation, MutationResult, QueryStepConfig, Query, QueryResult, MutationStep, QueryStep, CredentialProvider, Call, MutationAttempt, QueryAttempt } from '@superdurable/connectors-sdk';
5
+ import { StepTarget } from '@superdurable/dex';
6
+ import { LoadedProject } from '@superdurable/connectors-sdk/projectconfig';
7
+ import { ProviderRequest, ProviderResponse } from '@superdurable/connectors-sdk/providerhttp';
8
+ import 'zod';
9
+
10
+ /** Stable connector identity. */
11
+ declare const ConnectorID = "elasticsearch";
12
+ /** Provider identity for named connections. */
13
+ declare const ProviderID = "elasticsearch";
14
+ /** Branch IDs for indexDocument. */
15
+ declare const IndexDocumentBranch: {
16
+ readonly Indexed: "indexed";
17
+ readonly ProviderRejected: "providerRejected";
18
+ readonly Defect: "defect";
19
+ };
20
+ /** Elasticsearch stored the requested document at the stable ID. */
21
+ declare const IndexDocumentBranchIndexed: "indexed";
22
+ /** Elasticsearch conclusively rejected the document replacement. */
23
+ declare const IndexDocumentBranchProviderRejected: "providerRejected";
24
+ /** Local document input or credentials are invalid. */
25
+ declare const IndexDocumentBranchDefect: "defect";
26
+ /** Manifest definition for indexDocument. */
27
+ declare const IndexDocumentDefinition: MutationDefinition;
28
+ /** Manifest metadata for indexDocument. */
29
+ declare const IndexDocumentMetadata: {
30
+ readonly kind: "mutation";
31
+ readonly idempotency: "required";
32
+ readonly authorization: "required";
33
+ };
34
+ /** Branch IDs for deleteDocument. */
35
+ declare const DeleteDocumentBranch: {
36
+ readonly Absent: "absent";
37
+ readonly IndexNotFound: "indexNotFound";
38
+ readonly ProviderRejected: "providerRejected";
39
+ readonly Defect: "defect";
40
+ };
41
+ /** The document is absent, whether deleted now or already missing. */
42
+ declare const DeleteDocumentBranchAbsent: "absent";
43
+ /** The requested index does not exist. */
44
+ declare const DeleteDocumentBranchIndexNotFound: "indexNotFound";
45
+ /** Elasticsearch conclusively rejected the deletion. */
46
+ declare const DeleteDocumentBranchProviderRejected: "providerRejected";
47
+ /** Local document ID or credentials are invalid. */
48
+ declare const DeleteDocumentBranchDefect: "defect";
49
+ /** Manifest definition for deleteDocument. */
50
+ declare const DeleteDocumentDefinition: MutationDefinition;
51
+ /** Manifest metadata for deleteDocument. */
52
+ declare const DeleteDocumentMetadata: {
53
+ readonly kind: "mutation";
54
+ readonly idempotency: "required";
55
+ readonly authorization: "required";
56
+ };
57
+ /** Branch IDs for searchDocuments. */
58
+ declare const SearchDocumentsBranch: {
59
+ readonly Found: "found";
60
+ readonly IndexNotFound: "indexNotFound";
61
+ readonly ProviderRejected: "providerRejected";
62
+ readonly InvalidResponse: "invalidResponse";
63
+ readonly Defect: "defect";
64
+ };
65
+ /** Elasticsearch returned a search page, possibly empty. */
66
+ declare const SearchDocumentsBranchFound: "found";
67
+ /** The requested index does not exist. */
68
+ declare const SearchDocumentsBranchIndexNotFound: "indexNotFound";
69
+ /** Elasticsearch conclusively rejected the search. */
70
+ declare const SearchDocumentsBranchProviderRejected: "providerRejected";
71
+ /** Elasticsearch returned malformed or oversized search data. */
72
+ declare const SearchDocumentsBranchInvalidResponse: "invalidResponse";
73
+ /** Local input or credentials are invalid. */
74
+ declare const SearchDocumentsBranchDefect: "defect";
75
+ /** Manifest definition for searchDocuments. */
76
+ declare const SearchDocumentsDefinition: QueryDefinition;
77
+ /** Manifest metadata for searchDocuments. */
78
+ declare const SearchDocumentsMetadata: {
79
+ readonly kind: "query";
80
+ readonly idempotency: "none";
81
+ readonly authorization: "required";
82
+ };
83
+
84
+ /** Configuration for the indexDocument connector Step. */
85
+ interface IndexDocumentStepConfig<StepInput, OperationInput = IndexDocumentInput, OperationOutput = IndexedDocument> extends Omit<MutationStepConfig<StepInput, OperationInput, OperationOutput>, 'operation' | 'connection' | 'branches'> {
86
+ /** Named connection supplying this operation. */
87
+ connection: Connection<{
88
+ indexDocument(): Mutation<OperationInput, OperationOutput>;
89
+ }>;
90
+ /** Name matching the bound connection. */
91
+ connectionName: string;
92
+ /** Elasticsearch stored the requested document at the stable ID. */
93
+ indexed: StepTarget<MutationResult<OperationOutput>>;
94
+ /** Elasticsearch conclusively rejected the document replacement. */
95
+ providerRejected?: StepTarget<MutationResult<OperationOutput>>;
96
+ /** Local document input or credentials are invalid. */
97
+ defect?: StepTarget<MutationResult<OperationOutput>>;
98
+ }
99
+ /** Build the indexDocument Step from a named connection. */
100
+ declare function newIndexDocumentStep<StepInput, OperationInput = IndexDocumentInput, OperationOutput = IndexedDocument>(configuration: IndexDocumentStepConfig<StepInput, OperationInput, OperationOutput>): MutationStep<StepInput, OperationInput, OperationOutput>;
101
+ /** Configuration for the deleteDocument connector Step. */
102
+ interface DeleteDocumentStepConfig<StepInput, OperationInput = DeleteDocumentInput, OperationOutput = DeletedDocument> extends Omit<MutationStepConfig<StepInput, OperationInput, OperationOutput>, 'operation' | 'connection' | 'branches'> {
103
+ /** Named connection supplying this operation. */
104
+ connection: Connection<{
105
+ deleteDocument(): Mutation<OperationInput, OperationOutput>;
106
+ }>;
107
+ /** Name matching the bound connection. */
108
+ connectionName: string;
109
+ /** The document is absent, whether deleted now or already missing. */
110
+ absent: StepTarget<MutationResult<OperationOutput>>;
111
+ /** The requested index does not exist. */
112
+ indexNotFound?: StepTarget<MutationResult<OperationOutput>>;
113
+ /** Elasticsearch conclusively rejected the deletion. */
114
+ providerRejected?: StepTarget<MutationResult<OperationOutput>>;
115
+ /** Local document ID or credentials are invalid. */
116
+ defect?: StepTarget<MutationResult<OperationOutput>>;
117
+ }
118
+ /** Build the deleteDocument Step from a named connection. */
119
+ declare function newDeleteDocumentStep<StepInput, OperationInput = DeleteDocumentInput, OperationOutput = DeletedDocument>(configuration: DeleteDocumentStepConfig<StepInput, OperationInput, OperationOutput>): MutationStep<StepInput, OperationInput, OperationOutput>;
120
+ /** Configuration for the searchDocuments connector Step. */
121
+ interface SearchDocumentsStepConfig<StepInput, OperationInput = SearchDocumentsInput, OperationOutput = SearchPage> extends Omit<QueryStepConfig<StepInput, OperationInput, OperationOutput>, 'operation' | 'connection' | 'branches'> {
122
+ /** Named connection supplying this operation. */
123
+ connection: Connection<{
124
+ searchDocuments(): Query<OperationInput, OperationOutput>;
125
+ }>;
126
+ /** Name matching the bound connection. */
127
+ connectionName: string;
128
+ /** Elasticsearch returned a search page, possibly empty. */
129
+ found: StepTarget<QueryResult<OperationOutput>>;
130
+ /** The requested index does not exist. */
131
+ indexNotFound?: StepTarget<QueryResult<OperationOutput>>;
132
+ /** Elasticsearch conclusively rejected the search. */
133
+ providerRejected?: StepTarget<QueryResult<OperationOutput>>;
134
+ /** Elasticsearch returned malformed or oversized search data. */
135
+ invalidResponse?: StepTarget<QueryResult<OperationOutput>>;
136
+ /** Local input or credentials are invalid. */
137
+ defect?: StepTarget<QueryResult<OperationOutput>>;
138
+ }
139
+ /** Build the searchDocuments Step from a named connection. */
140
+ declare function newSearchDocumentsStep<StepInput, OperationInput = SearchDocumentsInput, OperationOutput = SearchPage>(configuration: SearchDocumentsStepConfig<StepInput, OperationInput, OperationOutput>): QueryStep<StepInput, OperationInput, OperationOutput>;
141
+
142
+ /** Injectable HTTP sender and clock for provider replay. */
143
+ interface ElasticsearchClientOptions {
144
+ /** Provider sender; omitted uses the SDK's redirect-safe transport. */
145
+ send?: (request: ProviderRequest) => Promise<ProviderResponse>;
146
+ /** Clock for Retry-After dates. */
147
+ now?: () => Date;
148
+ }
149
+ /** One bounded provider outcome without credential-bearing request data. */
150
+ interface ElasticsearchExchange {
151
+ /** HTTP status, or zero without a response. */ status: number;
152
+ /** Complete bounded response body. */ body: Uint8Array;
153
+ /** Retry-After delay in milliseconds. */ retryAfterMs: number;
154
+ /** Safe transport or response classification. */ error?: 'request' | 'tooLarge';
155
+ }
156
+ /** Elasticsearch REST client with call-time Basic credentials. */
157
+ declare class ElasticsearchClient {
158
+ /** Validated cluster URL without a trailing slash. */ readonly clusterUrl: string;
159
+ /** Maximum complete document request size in bytes. */ readonly maxDocumentBytes: number;
160
+ private readonly timeoutMs;
161
+ private readonly maxResponseBytes;
162
+ private readonly credentials;
163
+ private readonly send;
164
+ private readonly now;
165
+ /** Validate cluster settings without contacting Elasticsearch. */
166
+ constructor(config: Config, credentials: CredentialProvider<Credentials>, options?: ElasticsearchClientOptions);
167
+ /** Bind the absolute replacement Mutation. */ indexDocument(): IndexDocumentOperation;
168
+ /** Bind the stable-ID deletion Mutation. */ deleteDocument(): DeleteDocumentOperation;
169
+ /** Bind the bounded search Query. */ searchDocuments(): SearchDocumentsOperation;
170
+ /** Resolve Basic authorization without returning credentials in failures. */
171
+ authorization(call: Call): Promise<string | undefined>;
172
+ /** Send one bounded request without automatic redirects. */
173
+ exchange(call: Call, method: 'GET' | 'PUT' | 'DELETE', url: string, headers: Record<string, string>, body?: Uint8Array): Promise<ElasticsearchExchange>;
174
+ private retryAfter;
175
+ }
176
+ /** Fully replace one document under a stable caller-selected ID. */
177
+ declare class IndexDocumentOperation implements Mutation<IndexDocumentInput, IndexedDocument> {
178
+ private readonly client;
179
+ /** Bind the provider client. */ constructor(client: ElasticsearchClient);
180
+ /** Return the generated Mutation contract. */ definition(): _superdurable_connectors_sdk.QueryDefinition;
181
+ /** Use stable Dex call identity; absolute PUT is safe to retry. */
182
+ idempotencyKey(callId: string): string;
183
+ /** Retry unconfirmed responses with the same absolute document source. */
184
+ invoke(call: Call, input: IndexDocumentInput): Promise<MutationAttempt<IndexedDocument>>;
185
+ }
186
+ /** Ensure one stable document ID is absent. */
187
+ declare class DeleteDocumentOperation implements Mutation<DeleteDocumentInput, DeletedDocument> {
188
+ private readonly client;
189
+ /** Bind the provider client. */ constructor(client: ElasticsearchClient);
190
+ /** Return the generated Mutation contract. */ definition(): _superdurable_connectors_sdk.QueryDefinition;
191
+ /** Use stable Dex call identity; repeating DELETE is safe. */
192
+ idempotencyKey(callId: string): string;
193
+ /** Treat both deleted and already absent as success. */
194
+ invoke(call: Call, input: DeleteDocumentInput): Promise<MutationAttempt<DeletedDocument>>;
195
+ }
196
+ /** Search one Elasticsearch index with bounded query-string pagination. */
197
+ declare class SearchDocumentsOperation implements Query<SearchDocumentsInput, SearchPage> {
198
+ private readonly client;
199
+ /** Bind the provider client. */ constructor(client: ElasticsearchClient);
200
+ /** Return the generated Query contract. */ definition(): _superdurable_connectors_sdk.QueryDefinition;
201
+ /** Reject partial results and retry timed-out or shard-failed searches. */
202
+ invoke(call: Call, input: SearchDocumentsInput): Promise<QueryAttempt<SearchPage>>;
203
+ }
204
+
205
+ /** Bind one named Elasticsearch connection declared in a Dex project. */
206
+ declare function newProjectConnection(project: LoadedProject, connectionName: string, options?: ElasticsearchClientOptions): Connection<Operations>;
207
+
208
+ export { Config, Connection, ConnectorID, Credentials, DeleteDocumentBranch, DeleteDocumentBranchAbsent, DeleteDocumentBranchDefect, DeleteDocumentBranchIndexNotFound, DeleteDocumentBranchProviderRejected, DeleteDocumentDefinition, DeleteDocumentInput, DeleteDocumentMetadata, DeleteDocumentOperation, type DeleteDocumentStepConfig, DeletedDocument, ElasticsearchClient, type ElasticsearchClientOptions, IndexDocumentBranch, IndexDocumentBranchDefect, IndexDocumentBranchIndexed, IndexDocumentBranchProviderRejected, IndexDocumentDefinition, IndexDocumentInput, IndexDocumentMetadata, IndexDocumentOperation, type IndexDocumentStepConfig, IndexedDocument, ProviderID, SearchDocumentsBranch, SearchDocumentsBranchDefect, SearchDocumentsBranchFound, SearchDocumentsBranchIndexNotFound, SearchDocumentsBranchInvalidResponse, SearchDocumentsBranchProviderRejected, SearchDocumentsDefinition, SearchDocumentsInput, SearchDocumentsMetadata, SearchDocumentsOperation, type SearchDocumentsStepConfig, SearchPage, newDeleteDocumentStep, newIndexDocumentStep, newProjectConnection, newSearchDocumentsStep };
package/dist/index.js ADDED
@@ -0,0 +1,473 @@
1
+ import {
2
+ ConfigSchema,
3
+ Connection,
4
+ ConnectorID,
5
+ DeleteDocumentBranch,
6
+ DeleteDocumentBranchAbsent,
7
+ DeleteDocumentBranchDefect,
8
+ DeleteDocumentBranchIndexNotFound,
9
+ DeleteDocumentBranchProviderRejected,
10
+ DeleteDocumentDefinition,
11
+ DeleteDocumentInputSchema,
12
+ DeleteDocumentMetadata,
13
+ DeletedDocumentSchema,
14
+ IndexDocumentBranch,
15
+ IndexDocumentBranchDefect,
16
+ IndexDocumentBranchIndexed,
17
+ IndexDocumentBranchProviderRejected,
18
+ IndexDocumentDefinition,
19
+ IndexDocumentInputSchema,
20
+ IndexDocumentMetadata,
21
+ IndexedDocumentSchema,
22
+ ProviderID,
23
+ SearchDocumentsBranch,
24
+ SearchDocumentsBranchDefect,
25
+ SearchDocumentsBranchFound,
26
+ SearchDocumentsBranchIndexNotFound,
27
+ SearchDocumentsBranchInvalidResponse,
28
+ SearchDocumentsBranchProviderRejected,
29
+ SearchDocumentsDefinition,
30
+ SearchDocumentsInputSchema,
31
+ SearchDocumentsMetadata,
32
+ SearchHitSchema,
33
+ SearchPageSchema,
34
+ decodeCredentials,
35
+ newConnection,
36
+ newConnectionWithOperations,
37
+ newProjectConnection
38
+ } from "./chunk-S7BMYXLB.js";
39
+
40
+ // src/generated/steps.ts
41
+ import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
42
+ function newIndexDocumentStep(configuration) {
43
+ const { connection, connectionName, indexed, providerRejected, defect, ...stepConfiguration } = configuration;
44
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
45
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.indexDocument(), connection: connection.reference, branches: [
46
+ goToBranch("indexed", indexed),
47
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
48
+ ...defect ? [goToBranch("defect", defect)] : []
49
+ ] });
50
+ }
51
+ function newDeleteDocumentStep(configuration) {
52
+ const { connection, connectionName, absent, indexNotFound, providerRejected, defect, ...stepConfiguration } = configuration;
53
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
54
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.deleteDocument(), connection: connection.reference, branches: [
55
+ goToBranch("absent", absent),
56
+ ...indexNotFound ? [goToBranch("indexNotFound", indexNotFound)] : [],
57
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
58
+ ...defect ? [goToBranch("defect", defect)] : []
59
+ ] });
60
+ }
61
+ function newSearchDocumentsStep(configuration) {
62
+ const { connection, connectionName, found, indexNotFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
63
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
64
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.searchDocuments(), connection: connection.reference, branches: [
65
+ goToBranch("found", found),
66
+ ...indexNotFound ? [goToBranch("indexNotFound", indexNotFound)] : [],
67
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
68
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
69
+ ...defect ? [goToBranch("defect", defect)] : []
70
+ ] });
71
+ }
72
+
73
+ // src/project.ts
74
+ import { z } from "zod";
75
+
76
+ // src/client.ts
77
+ import {
78
+ newMutationBranch,
79
+ newMutationRetry,
80
+ newQueryBranch,
81
+ newQueryRetry
82
+ } from "@superdurable/connectors-sdk";
83
+ import {
84
+ BodyTooLargeError,
85
+ ProviderTransportError,
86
+ parseRetryAfter,
87
+ sendProviderRequest,
88
+ validateBaseURL
89
+ } from "@superdurable/connectors-sdk/providerhttp";
90
+ var indexPattern = /^[a-z0-9.][a-z0-9._-]*$/;
91
+ var emptyIndexed = { index: "", id: "" };
92
+ var emptyDeleted = { index: "", id: "", wasDeleted: false };
93
+ var emptyPage = { total: 0, relation: "", hits: [] };
94
+ var ElasticsearchClient = class {
95
+ /** Validated cluster URL without a trailing slash. */
96
+ clusterUrl;
97
+ /** Maximum complete document request size in bytes. */
98
+ maxDocumentBytes;
99
+ timeoutMs;
100
+ maxResponseBytes;
101
+ credentials;
102
+ send;
103
+ now;
104
+ /** Validate cluster settings without contacting Elasticsearch. */
105
+ constructor(config, credentials, options = {}) {
106
+ if (!config || !credentials) throw new TypeError("Elasticsearch configuration and credentials are required");
107
+ this.clusterUrl = validateBaseURL(config.clusterUrl);
108
+ this.timeoutMs = config.timeoutMs ?? 15e3;
109
+ this.maxResponseBytes = config.maxResponseBytes ?? 4194304;
110
+ this.maxDocumentBytes = config.maxDocumentBytes ?? 1048576;
111
+ if (![this.timeoutMs, this.maxResponseBytes, this.maxDocumentBytes].every((value) => Number.isSafeInteger(value) && value > 0))
112
+ throw new TypeError("Elasticsearch request limits must be positive integers");
113
+ this.credentials = credentials;
114
+ this.send = options.send ?? sendProviderRequest;
115
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
116
+ }
117
+ /** Bind the absolute replacement Mutation. */
118
+ indexDocument() {
119
+ return new IndexDocumentOperation(this);
120
+ }
121
+ /** Bind the stable-ID deletion Mutation. */
122
+ deleteDocument() {
123
+ return new DeleteDocumentOperation(this);
124
+ }
125
+ /** Bind the bounded search Query. */
126
+ searchDocuments() {
127
+ return new SearchDocumentsOperation(this);
128
+ }
129
+ /** Resolve Basic authorization without returning credentials in failures. */
130
+ async authorization(call) {
131
+ try {
132
+ const credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
133
+ const username = credentials.username;
134
+ const password = credentials.password.reveal();
135
+ if (!username || /[:\r\n\0]/.test(username) || !password || /[\r\n\0]/.test(password)) return void 0;
136
+ return `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`;
137
+ } catch {
138
+ return void 0;
139
+ }
140
+ }
141
+ /** Send one bounded request without automatic redirects. */
142
+ async exchange(call, method, url, headers, body) {
143
+ const request = {
144
+ url,
145
+ method,
146
+ headers,
147
+ maxResponseBytes: this.maxResponseBytes,
148
+ timeoutMs: this.timeoutMs,
149
+ addressPolicy: url.startsWith("https://") ? "publicHTTPS" : "privateNetworkHTTP",
150
+ signal: call.context.cancellationSignal,
151
+ ...body ? { body } : {}
152
+ };
153
+ try {
154
+ const response = await this.send(request);
155
+ return {
156
+ status: response.status,
157
+ body: response.body,
158
+ retryAfterMs: this.retryAfter(response.headers)
159
+ };
160
+ } catch (error) {
161
+ if (error instanceof BodyTooLargeError)
162
+ return {
163
+ status: error.status ?? 0,
164
+ body: new Uint8Array(),
165
+ retryAfterMs: this.retryAfter(error.headers ?? {}),
166
+ error: "tooLarge"
167
+ };
168
+ if (error instanceof ProviderTransportError)
169
+ return { status: 0, body: new Uint8Array(), retryAfterMs: 0, error: "request" };
170
+ return { status: 0, body: new Uint8Array(), retryAfterMs: 0, error: "request" };
171
+ }
172
+ }
173
+ retryAfter(headers) {
174
+ const value = Object.entries(headers).find(([name]) => name.toLowerCase() === "retry-after")?.[1];
175
+ return parseRetryAfter(Array.isArray(value) ? value[0] ?? "" : value ?? "", this.now());
176
+ }
177
+ };
178
+ var IndexDocumentOperation = class {
179
+ /** Bind the provider client. */
180
+ constructor(client) {
181
+ this.client = client;
182
+ }
183
+ client;
184
+ /** Return the generated Mutation contract. */
185
+ definition() {
186
+ return IndexDocumentDefinition;
187
+ }
188
+ /** Use stable Dex call identity; absolute PUT is safe to retry. */
189
+ idempotencyKey(callId) {
190
+ return callId;
191
+ }
192
+ /** Retry unconfirmed responses with the same absolute document source. */
193
+ async invoke(call, input) {
194
+ if (!input || !validIndex(input.index) || !validDocumentID(input.documentId) || !isRecord(input.source))
195
+ return indexFailure("defect", "VALIDATION");
196
+ let body;
197
+ try {
198
+ body = Buffer.from(JSON.stringify(input.source));
199
+ } catch {
200
+ return indexFailure("defect", "VALIDATION");
201
+ }
202
+ if (body.byteLength > this.client.maxDocumentBytes) return indexFailure("defect", "VALIDATION");
203
+ const authorization = await this.client.authorization(call);
204
+ if (!authorization) return indexFailure("defect", "AUTHENTICATION");
205
+ const exchange = await this.client.exchange(
206
+ call,
207
+ "PUT",
208
+ documentURL(this.client.clusterUrl, input.index, input.documentId),
209
+ { Accept: "application/json", "Content-Type": "application/json", Authorization: authorization },
210
+ body
211
+ );
212
+ const retry = documentRetry(exchange, "indexDocument");
213
+ if (retry) return retry;
214
+ if (exchange.status === 200 || exchange.status === 201) {
215
+ const result = parseJSON(exchange.body);
216
+ if (!isRecord(result) || result._index !== input.index || result._id !== input.documentId || result.result !== "created" && result.result !== "updated") return indexRetry("PROTOCOL");
217
+ return newMutationBranch("indexed", { index: input.index, id: input.documentId });
218
+ }
219
+ return indexFailure("providerRejected", rejectionKind(exchange.status));
220
+ }
221
+ };
222
+ var DeleteDocumentOperation = class {
223
+ /** Bind the provider client. */
224
+ constructor(client) {
225
+ this.client = client;
226
+ }
227
+ client;
228
+ /** Return the generated Mutation contract. */
229
+ definition() {
230
+ return DeleteDocumentDefinition;
231
+ }
232
+ /** Use stable Dex call identity; repeating DELETE is safe. */
233
+ idempotencyKey(callId) {
234
+ return callId;
235
+ }
236
+ /** Treat both deleted and already absent as success. */
237
+ async invoke(call, input) {
238
+ if (!input || !validIndex(input.index) || !validDocumentID(input.documentId))
239
+ return deleteFailure("defect", "VALIDATION");
240
+ const authorization = await this.client.authorization(call);
241
+ if (!authorization) return deleteFailure("defect", "AUTHENTICATION");
242
+ const exchange = await this.client.exchange(
243
+ call,
244
+ "DELETE",
245
+ documentURL(this.client.clusterUrl, input.index, input.documentId),
246
+ { Accept: "application/json", Authorization: authorization }
247
+ );
248
+ const retry = documentRetry(exchange, "deleteDocument");
249
+ if (retry) return retry;
250
+ if (exchange.status === 200 || exchange.status === 404) {
251
+ const result = parseJSON(exchange.body);
252
+ if (!isRecord(result)) return deleteRetry("PROTOCOL");
253
+ const error = result.error;
254
+ if (exchange.status === 404 && isRecord(error) && error.type === "index_not_found_exception")
255
+ return deleteFailure("indexNotFound", "NOT_FOUND");
256
+ if (result._index !== input.index || result._id !== input.documentId || result.result !== "deleted" && result.result !== "not_found") return deleteRetry("PROTOCOL");
257
+ return newMutationBranch("absent", {
258
+ index: input.index,
259
+ id: input.documentId,
260
+ wasDeleted: result.result === "deleted"
261
+ });
262
+ }
263
+ return deleteFailure("providerRejected", rejectionKind(exchange.status));
264
+ }
265
+ };
266
+ var SearchDocumentsOperation = class {
267
+ /** Bind the provider client. */
268
+ constructor(client) {
269
+ this.client = client;
270
+ }
271
+ client;
272
+ /** Return the generated Query contract. */
273
+ definition() {
274
+ return SearchDocumentsDefinition;
275
+ }
276
+ /** Reject partial results and retry timed-out or shard-failed searches. */
277
+ async invoke(call, input) {
278
+ const size = input?.size || 10;
279
+ const from = input?.from ?? 0;
280
+ if (!input || !validIndex(input.index) || typeof input.query !== "string" || !input.query.trim() || Buffer.byteLength(input.query) > 4096 || !Number.isSafeInteger(size) || size < 1 || size > 100 || !Number.isSafeInteger(from) || from < 0 || from + size > 1e4)
281
+ return searchFailure("defect", "VALIDATION");
282
+ const authorization = await this.client.authorization(call);
283
+ if (!authorization) return searchFailure("defect", "AUTHENTICATION");
284
+ const query = new URLSearchParams({
285
+ q: input.query,
286
+ size: String(size),
287
+ from: String(from),
288
+ allow_partial_search_results: "false"
289
+ });
290
+ const exchange = await this.client.exchange(
291
+ call,
292
+ "GET",
293
+ `${this.client.clusterUrl}/${input.index}/_search?${query}`,
294
+ { Accept: "application/json", Authorization: authorization }
295
+ );
296
+ if (exchange.error === "request") return searchRetry("AVAILABILITY");
297
+ if (exchange.status === 429) return searchRetry("RATE_LIMIT", exchange.retryAfterMs);
298
+ if (exchange.status === 408 || exchange.status === 409 || exchange.status >= 500)
299
+ return searchRetry("AVAILABILITY", exchange.retryAfterMs);
300
+ if (exchange.status === 404) return searchFailure("indexNotFound", "NOT_FOUND");
301
+ if (exchange.status !== 200) return searchFailure("providerRejected", rejectionKind(exchange.status));
302
+ if (exchange.error === "tooLarge") return searchFailure("invalidResponse", "RESPONSE_TOO_LARGE");
303
+ const body = parseJSON(exchange.body);
304
+ if (!isRecord(body) || typeof body.timed_out !== "boolean" || !isRecord(body._shards))
305
+ return searchFailure("invalidResponse", "PROTOCOL");
306
+ if (body.timed_out || typeof body._shards.failed === "number" && body._shards.failed > 0)
307
+ return searchRetry("AVAILABILITY");
308
+ const hitsRoot = body.hits;
309
+ const total = isRecord(hitsRoot) ? hitsRoot.total : void 0;
310
+ const hits = isRecord(hitsRoot) ? hitsRoot.hits : void 0;
311
+ if (!isRecord(total) || !Number.isSafeInteger(total.value) || total.value < 0 || total.relation !== "eq" && total.relation !== "gte" || !Array.isArray(hits))
312
+ return searchFailure("invalidResponse", "PROTOCOL");
313
+ const parsedHits = [];
314
+ for (const hit of hits) {
315
+ if (!isRecord(hit) || typeof hit._index !== "string" || !hit._index || typeof hit._id !== "string" || !hit._id || !Object.hasOwn(hit, "_source") || hit._score !== void 0 && hit._score !== null && typeof hit._score !== "number")
316
+ return searchFailure("invalidResponse", "PROTOCOL");
317
+ parsedHits.push({
318
+ index: hit._index,
319
+ id: hit._id,
320
+ source: hit._source,
321
+ ...typeof hit._score === "number" ? { score: hit._score } : {}
322
+ });
323
+ }
324
+ return newQueryBranch("found", { total: total.value, relation: total.relation, hits: parsedHits });
325
+ }
326
+ };
327
+ function validIndex(index) {
328
+ return typeof index === "string" && index.length <= 255 && indexPattern.test(index) && index !== "." && index !== "..";
329
+ }
330
+ function validDocumentID(id) {
331
+ return typeof id === "string" && !!id && Buffer.byteLength(id) <= 512 && !/[\r\n\0]/.test(id);
332
+ }
333
+ function documentURL(clusterUrl, index, documentId) {
334
+ return `${clusterUrl}/${index}/_doc/${encodeURIComponent(documentId)}`;
335
+ }
336
+ function parseJSON(body) {
337
+ try {
338
+ return JSON.parse(Buffer.from(body).toString("utf8"));
339
+ } catch {
340
+ return void 0;
341
+ }
342
+ }
343
+ function isRecord(value) {
344
+ return typeof value === "object" && value !== null && !Array.isArray(value);
345
+ }
346
+ function rejectionKind(status) {
347
+ return status === 401 ? "AUTHENTICATION" : status === 403 ? "AUTHORIZATION" : "PROVIDER_REJECTION";
348
+ }
349
+ function failure(operation, kind) {
350
+ return { kind, provider: "elasticsearch", operation, message: "Elasticsearch provider operation failed" };
351
+ }
352
+ function documentRetry(exchange, operation) {
353
+ if (exchange.status === 429) return newMutationRetry(failure(operation, "RATE_LIMIT"), exchange.retryAfterMs);
354
+ if (exchange.status === 408 || exchange.status === 409 || exchange.status >= 500)
355
+ return newMutationRetry(failure(operation, "AVAILABILITY"), exchange.retryAfterMs);
356
+ if (exchange.error === "tooLarge") return newMutationRetry(failure(operation, "RESPONSE_TOO_LARGE"));
357
+ if (exchange.error) return newMutationRetry(failure(operation, "TRANSPORT"));
358
+ return void 0;
359
+ }
360
+ function indexFailure(branch, kind) {
361
+ return newMutationBranch(branch, emptyIndexed, {}, failure("indexDocument", kind));
362
+ }
363
+ function indexRetry(kind) {
364
+ return newMutationRetry(failure("indexDocument", kind));
365
+ }
366
+ function deleteFailure(branch, kind) {
367
+ return newMutationBranch(branch, emptyDeleted, {}, failure("deleteDocument", kind));
368
+ }
369
+ function deleteRetry(kind) {
370
+ return newMutationRetry(failure("deleteDocument", kind));
371
+ }
372
+ function searchFailure(branch, kind) {
373
+ return newQueryBranch(branch, emptyPage, {}, failure("searchDocuments", kind));
374
+ }
375
+ function searchRetry(kind, after = 0) {
376
+ return newQueryRetry(failure("searchDocuments", kind), after);
377
+ }
378
+
379
+ // src/project.ts
380
+ var settingsSchema = z.strictObject({
381
+ clusterUrl: z.string(),
382
+ timeout: z.union([z.string(), z.number().int()]).optional(),
383
+ maxResponseBytes: z.number().int().optional(),
384
+ maxDocumentBytes: z.number().int().optional()
385
+ });
386
+ function newProjectConnection2(project, connectionName, options = {}) {
387
+ return newProjectConnection(project, connectionName, (loadedProject, name) => {
388
+ const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "elasticsearch" && entry.connectionName === name);
389
+ if (!selected) throw new TypeError("Elasticsearch project connection is not configured");
390
+ const settings = settingsSchema.parse(selected.configuration);
391
+ const timeoutMs = typeof settings.timeout === "number" ? Math.ceil(settings.timeout / 1e6) : settings.timeout !== void 0 ? parseDurationMilliseconds(settings.timeout) : void 0;
392
+ const config = {
393
+ clusterUrl: settings.clusterUrl,
394
+ ...timeoutMs !== void 0 ? { timeoutMs } : {},
395
+ ...settings.maxResponseBytes !== void 0 ? { maxResponseBytes: settings.maxResponseBytes } : {},
396
+ ...settings.maxDocumentBytes !== void 0 ? { maxDocumentBytes: settings.maxDocumentBytes } : {}
397
+ };
398
+ const credentials = {
399
+ async resolve(call, signal) {
400
+ void call;
401
+ return decodeCredentials(await loadedProject.resolveCredential("elasticsearch", name, signal));
402
+ }
403
+ };
404
+ return new ElasticsearchClient(config, credentials, options);
405
+ });
406
+ }
407
+ function parseDurationMilliseconds(value) {
408
+ let remaining = value;
409
+ let milliseconds = 0;
410
+ const units = {
411
+ ns: 1e-6,
412
+ us: 1e-3,
413
+ "\xB5s": 1e-3,
414
+ ms: 1,
415
+ s: 1e3,
416
+ m: 6e4,
417
+ h: 36e5
418
+ };
419
+ while (remaining) {
420
+ const component = /^(\d+(?:\.\d+)?)(ns|us|µs|ms|s|m|h)/.exec(remaining);
421
+ if (!component) throw new TypeError("Elasticsearch timeout must be a positive Go duration");
422
+ milliseconds += Number(component[1]) * (units[component[2] ?? ""] ?? NaN);
423
+ remaining = remaining.slice(component[0].length);
424
+ }
425
+ if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0)
426
+ throw new TypeError("Elasticsearch timeout must resolve to positive whole milliseconds");
427
+ return milliseconds;
428
+ }
429
+ export {
430
+ ConfigSchema,
431
+ Connection,
432
+ ConnectorID,
433
+ DeleteDocumentBranch,
434
+ DeleteDocumentBranchAbsent,
435
+ DeleteDocumentBranchDefect,
436
+ DeleteDocumentBranchIndexNotFound,
437
+ DeleteDocumentBranchProviderRejected,
438
+ DeleteDocumentDefinition,
439
+ DeleteDocumentInputSchema,
440
+ DeleteDocumentMetadata,
441
+ DeleteDocumentOperation,
442
+ DeletedDocumentSchema,
443
+ ElasticsearchClient,
444
+ IndexDocumentBranch,
445
+ IndexDocumentBranchDefect,
446
+ IndexDocumentBranchIndexed,
447
+ IndexDocumentBranchProviderRejected,
448
+ IndexDocumentDefinition,
449
+ IndexDocumentInputSchema,
450
+ IndexDocumentMetadata,
451
+ IndexDocumentOperation,
452
+ IndexedDocumentSchema,
453
+ ProviderID,
454
+ SearchDocumentsBranch,
455
+ SearchDocumentsBranchDefect,
456
+ SearchDocumentsBranchFound,
457
+ SearchDocumentsBranchIndexNotFound,
458
+ SearchDocumentsBranchInvalidResponse,
459
+ SearchDocumentsBranchProviderRejected,
460
+ SearchDocumentsDefinition,
461
+ SearchDocumentsInputSchema,
462
+ SearchDocumentsMetadata,
463
+ SearchDocumentsOperation,
464
+ SearchHitSchema,
465
+ SearchPageSchema,
466
+ decodeCredentials,
467
+ newConnection,
468
+ newConnectionWithOperations,
469
+ newDeleteDocumentStep,
470
+ newIndexDocumentStep,
471
+ newProjectConnection2 as newProjectConnection,
472
+ newSearchDocumentsStep
473
+ };