@superdurable/connector-buffer 0.0.0-stage → 0.2.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.
package/dist/index.js ADDED
@@ -0,0 +1,1114 @@
1
+ import {
2
+ ChannelProfileSchema,
3
+ ChannelsListSchema,
4
+ ConfigSchema,
5
+ Connection,
6
+ ConnectorID,
7
+ CreateIdeaBranch,
8
+ CreateIdeaBranchCreated,
9
+ CreateIdeaBranchDefect,
10
+ CreateIdeaBranchProviderRejected,
11
+ CreateIdeaBranchUncertain,
12
+ CreateIdeaDefinition,
13
+ CreateIdeaInputSchema,
14
+ CreateIdeaMetadata,
15
+ CreatePostBranch,
16
+ CreatePostBranchCreated,
17
+ CreatePostBranchDefect,
18
+ CreatePostBranchProviderRejected,
19
+ CreatePostBranchUncertain,
20
+ CreatePostDefinition,
21
+ CreatePostInputSchema,
22
+ CreatePostMetadata,
23
+ CreateScheduledPostBranch,
24
+ CreateScheduledPostBranchCreated,
25
+ CreateScheduledPostBranchDefect,
26
+ CreateScheduledPostBranchProviderRejected,
27
+ CreateScheduledPostBranchUncertain,
28
+ CreateScheduledPostDefinition,
29
+ CreateScheduledPostInputSchema,
30
+ CreateScheduledPostMetadata,
31
+ CredentialMaterialError,
32
+ DeletePostBranch,
33
+ DeletePostBranchDefect,
34
+ DeletePostBranchDeleted,
35
+ DeletePostBranchInvalidResponse,
36
+ DeletePostBranchProviderRejected,
37
+ DeletePostDefinition,
38
+ DeletePostInputSchema,
39
+ DeletePostMetadata,
40
+ EditPostBranch,
41
+ EditPostBranchDefect,
42
+ EditPostBranchInvalidResponse,
43
+ EditPostBranchProviderRejected,
44
+ EditPostBranchUpdated,
45
+ EditPostDefinition,
46
+ EditPostInputSchema,
47
+ EditPostMetadata,
48
+ GetChannelBranch,
49
+ GetChannelBranchDefect,
50
+ GetChannelBranchFound,
51
+ GetChannelBranchInvalidResponse,
52
+ GetChannelBranchNotFound,
53
+ GetChannelBranchProviderRejected,
54
+ GetChannelDefinition,
55
+ GetChannelInputSchema,
56
+ GetChannelMetadata,
57
+ GetPostBranch,
58
+ GetPostBranchDefect,
59
+ GetPostBranchFound,
60
+ GetPostBranchInvalidResponse,
61
+ GetPostBranchNotFound,
62
+ GetPostBranchProviderRejected,
63
+ GetPostDefinition,
64
+ GetPostInputSchema,
65
+ GetPostMetadata,
66
+ IdeaProfileSchema,
67
+ IdeasPageSchema,
68
+ ListChannelsBranch,
69
+ ListChannelsBranchDefect,
70
+ ListChannelsBranchInvalidResponse,
71
+ ListChannelsBranchListed,
72
+ ListChannelsBranchProviderRejected,
73
+ ListChannelsDefinition,
74
+ ListChannelsInputSchema,
75
+ ListChannelsMetadata,
76
+ ListIdeasBranch,
77
+ ListIdeasBranchDefect,
78
+ ListIdeasBranchInvalidResponse,
79
+ ListIdeasBranchListed,
80
+ ListIdeasBranchProviderRejected,
81
+ ListIdeasDefinition,
82
+ ListIdeasInputSchema,
83
+ ListIdeasMetadata,
84
+ ListOrganizationsBranch,
85
+ ListOrganizationsBranchDefect,
86
+ ListOrganizationsBranchInvalidResponse,
87
+ ListOrganizationsBranchListed,
88
+ ListOrganizationsBranchProviderRejected,
89
+ ListOrganizationsDefinition,
90
+ ListOrganizationsInputSchema,
91
+ ListOrganizationsMetadata,
92
+ ListPostsBranch,
93
+ ListPostsBranchDefect,
94
+ ListPostsBranchInvalidResponse,
95
+ ListPostsBranchListed,
96
+ ListPostsBranchProviderRejected,
97
+ ListPostsDefinition,
98
+ ListPostsInputSchema,
99
+ ListPostsMetadata,
100
+ OrganizationIdentitySchema,
101
+ OrganizationsListSchema,
102
+ PostAssetSchema,
103
+ PostDeleteResultSchema,
104
+ PostProfileSchema,
105
+ PostsListSchema,
106
+ ProviderID,
107
+ PublishPostNowBranch,
108
+ PublishPostNowBranchCreated,
109
+ PublishPostNowBranchDefect,
110
+ PublishPostNowBranchProviderRejected,
111
+ PublishPostNowBranchUncertain,
112
+ PublishPostNowDefinition,
113
+ PublishPostNowInputSchema,
114
+ PublishPostNowMetadata,
115
+ decodeCredentials,
116
+ decodeSignedInteger,
117
+ exactIntegerJSONCodec,
118
+ isCredentialMaterialError,
119
+ newConnection,
120
+ newConnectionWithOperations,
121
+ newProjectConnection,
122
+ parseExactIntegerJSON,
123
+ parseJSONNumberTokens
124
+ } from "./chunk-Q62AX6CW.js";
125
+
126
+ // src/generated/steps.ts
127
+ import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
128
+ function newCreateIdeaStep(configuration) {
129
+ const { connection, connectionName, created, providerRejected, uncertain, defect, ...stepConfiguration } = configuration;
130
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
131
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.createIdea(), connection: connection.reference, branches: [
132
+ goToBranch("created", created),
133
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
134
+ ...uncertain ? [goToBranch("uncertain", uncertain)] : [],
135
+ ...defect ? [goToBranch("defect", defect)] : []
136
+ ] });
137
+ }
138
+ function newListIdeasStep(configuration) {
139
+ const { connection, connectionName, listed, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
140
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
141
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listIdeas(), connection: connection.reference, branches: [
142
+ goToBranch("listed", listed),
143
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
144
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
145
+ ...defect ? [goToBranch("defect", defect)] : []
146
+ ] });
147
+ }
148
+ function newListOrganizationsStep(configuration) {
149
+ const { connection, connectionName, listed, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
150
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
151
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listOrganizations(), connection: connection.reference, branches: [
152
+ goToBranch("listed", listed),
153
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
154
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
155
+ ...defect ? [goToBranch("defect", defect)] : []
156
+ ] });
157
+ }
158
+ function newListChannelsStep(configuration) {
159
+ const { connection, connectionName, listed, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
160
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
161
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listChannels(), connection: connection.reference, branches: [
162
+ goToBranch("listed", listed),
163
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
164
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
165
+ ...defect ? [goToBranch("defect", defect)] : []
166
+ ] });
167
+ }
168
+ function newGetPostStep(configuration) {
169
+ const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
170
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
171
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.getPost(), connection: connection.reference, branches: [
172
+ goToBranch("found", found),
173
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
174
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
175
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
176
+ ...defect ? [goToBranch("defect", defect)] : []
177
+ ] });
178
+ }
179
+ function newListPostsStep(configuration) {
180
+ const { connection, connectionName, listed, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
181
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
182
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listPosts(), connection: connection.reference, branches: [
183
+ goToBranch("listed", listed),
184
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
185
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
186
+ ...defect ? [goToBranch("defect", defect)] : []
187
+ ] });
188
+ }
189
+ function newCreatePostStep(configuration) {
190
+ const { connection, connectionName, created, providerRejected, uncertain, defect, ...stepConfiguration } = configuration;
191
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
192
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.createPost(), connection: connection.reference, branches: [
193
+ goToBranch("created", created),
194
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
195
+ ...uncertain ? [goToBranch("uncertain", uncertain)] : [],
196
+ ...defect ? [goToBranch("defect", defect)] : []
197
+ ] });
198
+ }
199
+ function newCreateScheduledPostStep(configuration) {
200
+ const { connection, connectionName, created, providerRejected, uncertain, defect, ...stepConfiguration } = configuration;
201
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
202
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.createScheduledPost(), connection: connection.reference, branches: [
203
+ goToBranch("created", created),
204
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
205
+ ...uncertain ? [goToBranch("uncertain", uncertain)] : [],
206
+ ...defect ? [goToBranch("defect", defect)] : []
207
+ ] });
208
+ }
209
+ function newPublishPostNowStep(configuration) {
210
+ const { connection, connectionName, created, providerRejected, uncertain, defect, ...stepConfiguration } = configuration;
211
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
212
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.publishPostNow(), connection: connection.reference, branches: [
213
+ goToBranch("created", created),
214
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
215
+ ...uncertain ? [goToBranch("uncertain", uncertain)] : [],
216
+ ...defect ? [goToBranch("defect", defect)] : []
217
+ ] });
218
+ }
219
+ function newEditPostStep(configuration) {
220
+ const { connection, connectionName, updated, providerRejected, invalidResponse, defect, maxSends, ...stepConfiguration } = configuration;
221
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
222
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.editPost(), connection: connection.reference, branches: [
223
+ goToBranch("updated", updated),
224
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
225
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
226
+ ...defect ? [goToBranch("defect", defect)] : []
227
+ ] });
228
+ }
229
+ function newDeletePostStep(configuration) {
230
+ const { connection, connectionName, deleted, providerRejected, invalidResponse, defect, maxSends, ...stepConfiguration } = configuration;
231
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
232
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.deletePost(), connection: connection.reference, branches: [
233
+ goToBranch("deleted", deleted),
234
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
235
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
236
+ ...defect ? [goToBranch("defect", defect)] : []
237
+ ] });
238
+ }
239
+ function newGetChannelStep(configuration) {
240
+ const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
241
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
242
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.getChannel(), connection: connection.reference, branches: [
243
+ goToBranch("found", found),
244
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
245
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
246
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
247
+ ...defect ? [goToBranch("defect", defect)] : []
248
+ ] });
249
+ }
250
+
251
+ // src/project.ts
252
+ import { SecretString as SecretString2 } from "@superdurable/connectors-sdk";
253
+ import { z } from "zod";
254
+
255
+ // src/client.ts
256
+ import { SecretString, newQueryBranch as newQueryBranch2, newQueryRetry as newQueryRetry2 } from "@superdurable/connectors-sdk";
257
+ import { BodyTooLargeError, ProviderStalledError, ProviderTransportError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
258
+
259
+ // src/operations.ts
260
+ import {
261
+ definitionMaxSends,
262
+ newMutationBranch,
263
+ newMutationRetry,
264
+ newMutationUncertain,
265
+ newQueryBranch,
266
+ newQueryRetry
267
+ } from "@superdurable/connectors-sdk";
268
+ import { newFence } from "@superdurable/connectors-sdk/singledispatch";
269
+ var getPostQuery = "query GetPost($input: PostInput!) { post(input: $input) { id text channelId } }";
270
+ var listOrganizationsQuery = "query ListOrganizations { account { organizations { id name } } }";
271
+ var listChannelsQuery = "query ListChannels($input: ChannelsInput!) { channels(input: $input) { id name service } }";
272
+ var listPostsQuery = "query ListPosts($input: PostsInput!, $first: Int, $after: String) { posts(input: $input, first: $first, after: $after) { pageInfo { endCursor hasNextPage } edges { node { id text channelId } } } }";
273
+ var listIdeasQuery = "query ListIdeas($input: IdeasInput!, $first: Int, $after: String) { ideas(input: $input, first: $first, after: $after) { pageInfo { endCursor hasNextPage } edges { node { id content { title text } } } } }";
274
+ var createIdeaMutation = "mutation CreateIdea($input: CreateIdeaInput!) { createIdea(input: $input) { ... on Idea { id content { title text } } } }";
275
+ var createPostMutation = "mutation CreatePost($input: CreatePostInput!) { createPost(input: $input) { __typename ... on PostActionSuccess { post { id text channelId } } } }";
276
+ var editPostMutation = "mutation EditPost($input: EditPostInput!) { editPost(input: $input) { __typename ... on PostActionSuccess { post { id text channelId } } } }";
277
+ var deletePostMutation = "mutation DeletePost($input: DeletePostInput!) { deletePost(input: $input) { __typename } }";
278
+ var emptyPost = { id: "", text: "", channelId: "" };
279
+ var emptyIdea = { id: "", title: "", text: "" };
280
+ var BufferQuery = class {
281
+ /** Bind the authenticated Buffer client. */
282
+ constructor(client) {
283
+ this.client = client;
284
+ }
285
+ client;
286
+ /** Return the manifest operation contract. */
287
+ definition() {
288
+ return this.contract;
289
+ }
290
+ };
291
+ var BufferMutation = class {
292
+ /** Bind the authenticated Buffer client. */
293
+ constructor(client) {
294
+ this.client = client;
295
+ }
296
+ client;
297
+ /** Return the manifest operation contract. */
298
+ definition() {
299
+ return this.contract;
300
+ }
301
+ /** Use the stable Dex call ID across attempts. */
302
+ idempotencyKey(callID) {
303
+ return callID;
304
+ }
305
+ };
306
+ var ListOrganizationsOperation = class extends BufferQuery {
307
+ contract = ListOrganizationsDefinition;
308
+ async invoke(call) {
309
+ return query(
310
+ this.client,
311
+ call,
312
+ "listOrganizations",
313
+ listOrganizationsQuery,
314
+ {},
315
+ { organizations: [] },
316
+ "listed",
317
+ (data) => ({ organizations: records(record(data.account).organizations).map(organization) })
318
+ );
319
+ }
320
+ };
321
+ var ListChannelsOperation = class extends BufferQuery {
322
+ contract = ListChannelsDefinition;
323
+ /** Read channel IDs, names, and services. */
324
+ async invoke(call, input) {
325
+ const empty = { channels: [] };
326
+ if (!isValidGraphQLID(input.organizationId)) return queryFailure("listChannels", "defect", empty, "VALIDATION");
327
+ return query(
328
+ this.client,
329
+ call,
330
+ "listChannels",
331
+ listChannelsQuery,
332
+ { input: { organizationId: input.organizationId } },
333
+ empty,
334
+ "listed",
335
+ (data) => ({ channels: records(data.channels).map(channel) })
336
+ );
337
+ }
338
+ };
339
+ var GetPostOperation = class extends BufferQuery {
340
+ contract = GetPostDefinition;
341
+ /** Read the post and validate its identity. */
342
+ async invoke(call, input) {
343
+ if (!isValidGraphQLID(input.postId)) return queryFailure("getPost", "defect", emptyPost, "VALIDATION");
344
+ return query(this.client, call, "getPost", getPostQuery, { input: { id: input.postId } }, emptyPost, "found", (data) => {
345
+ if (data.post == null) return void 0;
346
+ const result = post(record(data.post));
347
+ if (result.id !== input.postId) throw new TypeError("unexpected post ID");
348
+ return result;
349
+ }, true);
350
+ }
351
+ };
352
+ var ListPostsOperation = class extends BufferQuery {
353
+ contract = ListPostsDefinition;
354
+ /** Read post summaries and their cursor. */
355
+ async invoke(call, input) {
356
+ return queryPage(this.client, call, "listPosts", listPostsQuery, input, { posts: [], hasNextPage: false }, (data) => {
357
+ const { nodes, ...info } = page(data.posts);
358
+ return { posts: nodes.map(post), ...info };
359
+ });
360
+ }
361
+ };
362
+ var ListIdeasOperation = class extends BufferQuery {
363
+ contract = ListIdeasDefinition;
364
+ /** Read idea summaries and their cursor. */
365
+ async invoke(call, input) {
366
+ return queryPage(this.client, call, "listIdeas", listIdeasQuery, input, { ideas: [], hasNextPage: false }, (data) => {
367
+ const { nodes, ...info } = page(data.ideas);
368
+ return { ideas: nodes.map(idea), ...info };
369
+ });
370
+ }
371
+ };
372
+ var CreateIdeaOperation = class extends BufferMutation {
373
+ contract = CreateIdeaDefinition;
374
+ /** Create an idea with the requested title and text. */
375
+ async invoke(call, input) {
376
+ const operation = "createIdea";
377
+ if (!isValidGraphQLID(input.organizationId) || !input.title.trim() || !input.text.trim()) {
378
+ return mutationFailure(operation, "defect", emptyIdea, "VALIDATION");
379
+ }
380
+ const result = await dispatch(
381
+ this.client,
382
+ call,
383
+ this.contract,
384
+ operation,
385
+ createIdeaMutation,
386
+ { organizationId: input.organizationId, content: { title: input.title, text: input.text } },
387
+ emptyIdea,
388
+ unconfirmedIdea
389
+ );
390
+ if ("kind" in result) return result;
391
+ let created;
392
+ try {
393
+ const document = envelope(result.body);
394
+ if (errors(document).length) throw new TypeError("GraphQL rejected the idea");
395
+ created = idea(payload(document, operation));
396
+ } catch {
397
+ return mutationFailure(operation, "providerRejected", emptyIdea, "PROVIDER_REJECTION");
398
+ }
399
+ if (created.title !== input.title || created.text !== input.text) {
400
+ return mutationFailure(operation, "providerRejected", emptyIdea, "PROTOCOL");
401
+ }
402
+ return newMutationBranch("created", created);
403
+ }
404
+ };
405
+ var CreatePostOperation = class extends BufferMutation {
406
+ contract = CreatePostDefinition;
407
+ /** Queue the post with automatic scheduling. */
408
+ async invoke(call, input) {
409
+ return createPost(this.client, call, this.contract, "createPost", input, "addToQueue");
410
+ }
411
+ };
412
+ var CreateScheduledPostOperation = class extends BufferMutation {
413
+ contract = CreateScheduledPostDefinition;
414
+ /** Queue one post at the supplied RFC 3339 timestamp. */
415
+ async invoke(call, input) {
416
+ return createPost(this.client, call, this.contract, "createScheduledPost", input, "customScheduled");
417
+ }
418
+ };
419
+ var PublishPostNowOperation = class extends BufferMutation {
420
+ contract = PublishPostNowDefinition;
421
+ /** Submit the post for immediate publishing. */
422
+ async invoke(call, input) {
423
+ return createPost(this.client, call, this.contract, "publishPostNow", input, "shareNow");
424
+ }
425
+ };
426
+ var EditPostOperation = class extends BufferMutation {
427
+ contract = EditPostDefinition;
428
+ /** Replace the selected post's content. */
429
+ async invoke(call, input) {
430
+ const operation = "editPost";
431
+ let fields;
432
+ try {
433
+ fields = postFields("id", input.postId, input.text, input.assets);
434
+ } catch {
435
+ return mutationFailure(operation, "defect", emptyPost, "VALIDATION");
436
+ }
437
+ const response = await this.client.executeGraphQL(call, editPostMutation, { input: fields });
438
+ return writeFailure(call, response, operation, emptyPost) ?? postResult(response, operation, operation, "updated");
439
+ }
440
+ };
441
+ var DeletePostOperation = class extends BufferMutation {
442
+ contract = DeletePostDefinition;
443
+ /** Remove the post and report the confirmed ID. */
444
+ async invoke(call, input) {
445
+ const operation = "deletePost";
446
+ const empty = { id: "" };
447
+ if (!isValidGraphQLID(input.postId)) return mutationFailure(operation, "defect", empty, "VALIDATION");
448
+ const response = await this.client.executeGraphQL(call, deletePostMutation, { input: { id: input.postId } });
449
+ const failure3 = writeFailure(call, response, operation, empty);
450
+ if (failure3) return failure3;
451
+ try {
452
+ const document = envelope(response.body);
453
+ if (errors(document).length || payload(document, operation).__typename !== "DeletePostSuccess") {
454
+ throw new TypeError("unconfirmed delete");
455
+ }
456
+ } catch {
457
+ return writeRetry(operation, "PROTOCOL");
458
+ }
459
+ return newMutationBranch("deleted", { id: input.postId });
460
+ }
461
+ };
462
+ async function queryPage(client, call, operation, statement, input, empty, decode) {
463
+ const first = input.first ?? 0;
464
+ const after = input.after ?? "";
465
+ if (!isValidGraphQLID(input.organizationId) || !Number.isInteger(first) || first < 0 || first > 100 || Buffer.byteLength(after) > 512) {
466
+ return queryFailure(operation, "defect", empty, "VALIDATION");
467
+ }
468
+ return query(
469
+ client,
470
+ call,
471
+ operation,
472
+ statement,
473
+ { input: { organizationId: input.organizationId }, first: first || 20, after },
474
+ empty,
475
+ "listed",
476
+ decode
477
+ );
478
+ }
479
+ async function query(client, call, operation, statement, variables, empty, branch, decode, hasNotFound = false) {
480
+ const response = await client.executeGraphQL(call, statement, variables);
481
+ const { status, error, retryAfterMs } = response;
482
+ if (error === "credential") return queryFailure(operation, "defect", empty, "AUTHENTICATION");
483
+ if (error === "request") return newQueryRetry(failure(operation, "TRANSPORT"));
484
+ if (status === 429) return newQueryRetry(failure(operation, "RATE_LIMIT"), retryAfterMs);
485
+ if (status === 408 || status >= 500) return newQueryRetry(failure(operation, "AVAILABILITY"), retryAfterMs);
486
+ if (status !== 200) return queryFailure(operation, "providerRejected", empty, "PROVIDER_REJECTION");
487
+ if (error === "tooLarge") return queryFailure(operation, "invalidResponse", empty, "RESPONSE_TOO_LARGE");
488
+ if (error) return newQueryRetry(failure(operation, "TRANSPORT"));
489
+ try {
490
+ const document = envelope(response.body);
491
+ const reported = errors(document);
492
+ if (reported.length) {
493
+ const outcome = classifyGraphQLErrors(reported);
494
+ if (outcome === "graphQLNotFound" && hasNotFound) return queryFailure(operation, "notFound", empty, "NOT_FOUND");
495
+ if (outcome === "rateLimited") return newQueryRetry(failure(operation, "RATE_LIMIT"), retryAfterMs);
496
+ if (outcome === "unavailable") return newQueryRetry(failure(operation, "AVAILABILITY"), retryAfterMs);
497
+ return queryFailure(operation, "providerRejected", empty, "PROVIDER_REJECTION");
498
+ }
499
+ const value = decode(record(document.data));
500
+ if (value === void 0) return queryFailure(operation, "notFound", empty, "NOT_FOUND");
501
+ return newQueryBranch(branch, value);
502
+ } catch {
503
+ return queryFailure(operation, "invalidResponse", empty, "PROTOCOL");
504
+ }
505
+ }
506
+ async function createPost(client, call, definition, operation, input, mode) {
507
+ let fields;
508
+ try {
509
+ fields = postFields("channelId", input.channelId, input.text, input.assets);
510
+ if (mode === "customScheduled") fields.dueAt = utcTimestamp(input.dueAt);
511
+ } catch {
512
+ return mutationFailure(operation, "defect", emptyPost, "VALIDATION");
513
+ }
514
+ const response = await dispatch(
515
+ client,
516
+ call,
517
+ definition,
518
+ operation,
519
+ createPostMutation,
520
+ { ...fields, mode, schedulingType: "automatic" },
521
+ emptyPost,
522
+ unconfirmedPost
523
+ );
524
+ if ("kind" in response) return response;
525
+ return postResult(response, operation, "createPost", "created", input.channelId);
526
+ }
527
+ async function dispatch(client, call, definition, operation, statement, fields, empty, unconfirmed) {
528
+ const defaultMaxSends = definitionMaxSends(definition);
529
+ const maxSends = call.maxSendsOverride ?? defaultMaxSends;
530
+ let fence;
531
+ try {
532
+ fence = newFence(call, definition.stepDefaults.executeMethodTimeoutMs, { maxSends: defaultMaxSends });
533
+ } catch {
534
+ return mutationFailure(operation, "defect", empty, "LOCAL_DEFECT");
535
+ }
536
+ const decision = fence.decide();
537
+ if (decision.kind === "failClosed") return writeRetry(operation, "TRANSPORT");
538
+ if (decision.kind === "readBackRequired") return newMutationUncertain(empty, failure(operation, "TRANSPORT"));
539
+ let response;
540
+ try {
541
+ response = await fence.dispatch((signal) => client.executeGraphQL(call, statement, { input: fields }, signal));
542
+ } catch {
543
+ return writeRetry(operation, "AVAILABILITY");
544
+ }
545
+ const { status, error, retryAfterMs } = response;
546
+ if (status === 429 || status === 503) {
547
+ try {
548
+ await fence.recordCanResend();
549
+ } catch {
550
+ return writeRetry(operation, "AVAILABILITY");
551
+ }
552
+ return writeRetry(operation, status === 429 ? "RATE_LIMIT" : "AVAILABILITY", retryAfterMs);
553
+ }
554
+ const priorSends = decision.priorSendUpperBound ?? 0;
555
+ if (error || status === 408 || status >= 500 || status === 200 && unconfirmed(response.body)) {
556
+ return priorSends + 1 >= maxSends ? newMutationUncertain(empty, failure(operation, "TRANSPORT")) : writeRetry(operation, "TRANSPORT");
557
+ }
558
+ if (definiteRefusal(response)) {
559
+ if (priorSends) return writeRetry(operation, "TRANSPORT");
560
+ try {
561
+ await fence.recordCanResend();
562
+ } catch {
563
+ return writeRetry(operation, "AVAILABILITY");
564
+ }
565
+ }
566
+ return writeFailure(call, response, operation, empty) ?? response;
567
+ }
568
+ function writeFailure(call, response, operation, empty) {
569
+ const { status, error, retryAfterMs } = response;
570
+ if (error === "credential") return call.context.attempt > 1 ? writeRetry(operation, "TRANSPORT") : mutationFailure(operation, "defect", empty, "AUTHENTICATION");
571
+ if (error === "request") return writeRetry(operation, "TRANSPORT");
572
+ if (status === 429) return writeRetry(operation, "RATE_LIMIT", retryAfterMs);
573
+ if (status === 408 || status >= 500) return writeRetry(operation, "AVAILABILITY", retryAfterMs);
574
+ if (status !== 200) return call.context.attempt === 1 && definiteRefusal(response) ? mutationFailure(operation, "providerRejected", empty, "PROVIDER_REJECTION") : writeRetry(operation, "TRANSPORT");
575
+ if (error) return writeRetry(operation, error === "tooLarge" ? "RESPONSE_TOO_LARGE" : "TRANSPORT");
576
+ return void 0;
577
+ }
578
+ var definiteStatuses = /* @__PURE__ */ new Set([400, 401, 403, 404, 411, 413, 414, 415, 422]);
579
+ function definiteRefusal(response) {
580
+ if (!definiteStatuses.has(response.status)) return false;
581
+ try {
582
+ const document = envelope(response.body);
583
+ if (document.success === true || ["data", "result", "results"].some((key) => nonempty(document[key]))) return false;
584
+ return ["code", "message", "error", "errors", "errorInfo"].some((key) => document[key] !== "" && nonempty(document[key]));
585
+ } catch {
586
+ return false;
587
+ }
588
+ }
589
+ function nonempty(value) {
590
+ return value != null && (typeof value !== "object" || Object.keys(value).length > 0);
591
+ }
592
+ function postResult(response, operation, field, branch, channelID = "") {
593
+ try {
594
+ const document = envelope(response.body);
595
+ if (errors(document).length) throw new TypeError("unconfirmed GraphQL result");
596
+ const result = payload(document, field);
597
+ if (result.__typename !== "PostActionSuccess") throw new TypeError("unconfirmed post");
598
+ const created = post(record(result.post));
599
+ if (channelID && channelID !== created.channelId) throw new TypeError("unexpected channel ID");
600
+ return newMutationBranch(branch, created);
601
+ } catch {
602
+ return writeRetry(operation, "PROTOCOL");
603
+ }
604
+ }
605
+ function unconfirmedPost(body) {
606
+ try {
607
+ const document = envelope(body);
608
+ if (errors(document).length) return false;
609
+ const result = payload(document, "createPost");
610
+ if (requiredText(result, "__typename") === "PostActionSuccess") post(record(result.post));
611
+ return false;
612
+ } catch {
613
+ return true;
614
+ }
615
+ }
616
+ function unconfirmedIdea(body) {
617
+ try {
618
+ const document = envelope(body);
619
+ if (errors(document).length) return false;
620
+ requiredText(payload(document, "createIdea"), "id");
621
+ return false;
622
+ } catch {
623
+ return true;
624
+ }
625
+ }
626
+ function postFields(idField, id, text2, assets) {
627
+ if (!isValidGraphQLID(id) || !text2.trim() && !assets?.length) throw new TypeError("ID and text or assets are required");
628
+ return { [idField]: id, text: text2, ...assets ? { assets: assets.map(assetInput) } : {} };
629
+ }
630
+ function assetInput(asset) {
631
+ const url = mediaURL(asset.url);
632
+ const offset = asset.thumbnailOffsetMs;
633
+ if (asset.type === "image" && !asset.title && offset == null) {
634
+ return { image: { url, ...asset.thumbnailUrl ? { thumbnailUrl: mediaURL(asset.thumbnailUrl) } : {} } };
635
+ }
636
+ if (asset.type === "video" && !asset.title && !asset.thumbnailUrl) {
637
+ if (offset == null) return { video: { url } };
638
+ const offsetMs = decodeSignedInteger(offset);
639
+ if (BigInt(typeof offsetMs === "number" ? offsetMs : offsetMs.rawJSON) >= 0n) {
640
+ return { video: { url, metadata: { thumbnailOffset: offsetMs } } };
641
+ }
642
+ }
643
+ if (asset.type === "document" && asset.title?.trim() && offset == null) {
644
+ return { document: { url, title: asset.title, thumbnailUrl: mediaURL(asset.thumbnailUrl ?? "") } };
645
+ }
646
+ throw new TypeError("invalid media asset fields");
647
+ }
648
+ function mediaURL(value) {
649
+ const url = new URL(value);
650
+ if (!/^https:\/\/[^/]/i.test(value) || !url.host || /^https:\/\/[^/?#]*@/i.test(value) || url.username || url.password || url.search || url.hash || /[\r\n]/.test(value)) {
651
+ throw new TypeError("invalid public media URL");
652
+ }
653
+ return value;
654
+ }
655
+ function utcTimestamp(value) {
656
+ const parts = /^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})(?:[.,](\d+))?(Z|[+-]\d{2}:\d{2})$/.exec(value);
657
+ if (!parts) throw new TypeError("invalid timestamp");
658
+ const local = `${parts[1]}T${parts[2]}`;
659
+ const localTime = /* @__PURE__ */ new Date(local + "Z");
660
+ if (Number.isNaN(localTime.valueOf()) || localTime.toISOString().slice(0, 19) !== local) throw new TypeError("invalid date");
661
+ const utc = new Date(local + parts[4]).toISOString().split(".")[0];
662
+ const fraction = (parts[3] ?? "").slice(0, 9).replace(/0+$/, "");
663
+ if (utc === "0001-01-01T00:00:00" && !fraction) throw new TypeError("invalid zero timestamp");
664
+ return utc + (fraction ? `.${fraction}` : "") + "Z";
665
+ }
666
+ function page(value) {
667
+ const data = record(value);
668
+ const info = record(data.pageInfo ?? {});
669
+ const end = text(info, "endCursor");
670
+ const hasNextPage = info.hasNextPage ?? false;
671
+ if (typeof hasNextPage !== "boolean" || hasNextPage && !end) throw new TypeError("invalid page info");
672
+ return { nodes: records(data.edges).map((edge) => record(edge.node)), ...end ? { endCursor: end } : {}, hasNextPage };
673
+ }
674
+ function organization(value) {
675
+ return { id: requiredText(value, "id"), name: requiredText(value, "name") };
676
+ }
677
+ function channel(value) {
678
+ return { ...organization(value), service: requiredText(value, "service") };
679
+ }
680
+ function post(value) {
681
+ return { id: requiredText(value, "id"), text: text(value, "text"), channelId: requiredText(value, "channelId") };
682
+ }
683
+ function idea(value) {
684
+ const content = record(value.content ?? {});
685
+ return { id: requiredText(value, "id"), title: text(content, "title"), text: text(content, "text") };
686
+ }
687
+ function envelope(body) {
688
+ return record(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(body)));
689
+ }
690
+ function payload(document, field) {
691
+ return record(record(document.data)[field]);
692
+ }
693
+ function errors(document) {
694
+ const values = document.errors ?? [];
695
+ if (!Array.isArray(values)) throw new TypeError("invalid GraphQL errors");
696
+ return values;
697
+ }
698
+ function record(value) {
699
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError("expected an object");
700
+ return value;
701
+ }
702
+ function records(value) {
703
+ if (!Array.isArray(value)) throw new TypeError("expected an array");
704
+ return value.map(record);
705
+ }
706
+ function text(value, field) {
707
+ const item = value[field] ?? "";
708
+ if (typeof item !== "string") throw new TypeError("expected text");
709
+ return item;
710
+ }
711
+ function requiredText(value, field) {
712
+ const item = text(value, field);
713
+ if (!item) throw new TypeError("required text is empty");
714
+ return item;
715
+ }
716
+ function failure(operation, kind) {
717
+ return { provider: "buffer", operation, kind, message: `Buffer ${operation} failed with ${kind}` };
718
+ }
719
+ function queryFailure(operation, branch, empty, kind) {
720
+ return newQueryBranch(branch, empty, {}, failure(operation, kind));
721
+ }
722
+ function mutationFailure(operation, branch, empty, kind) {
723
+ return newMutationBranch(branch, empty, {}, failure(operation, kind));
724
+ }
725
+ function writeRetry(operation, kind, delay = 0) {
726
+ return newMutationRetry(failure(operation, kind), delay);
727
+ }
728
+
729
+ // src/client.ts
730
+ var emptyChannel = () => ({ id: "", name: "", service: "" });
731
+ var getChannelGraphQL = "query GetChannel($id: ChannelId!) { channel(input: {id: $id}) { id name service } }";
732
+ var BufferClient = class {
733
+ /** Validate provider configuration without contacting Buffer. */
734
+ constructor(config, credentials, options = {}) {
735
+ this.credentials = credentials;
736
+ if (!config || !credentials) throw new TypeError("Buffer configuration and credentials are required");
737
+ this.baseURL = validateBaseURL(config.baseUrl ?? "https://api.buffer.com").replace(/\/$/, "");
738
+ this.timeoutMs = config.timeoutMs ?? 15e3;
739
+ this.maxResponseBytes = config.maxResponseBytes ?? 1048576;
740
+ if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs <= 0 || !Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0)
741
+ throw new TypeError("Buffer request limits must be positive integers");
742
+ this.send = options.send ?? sendProviderRequest;
743
+ }
744
+ credentials;
745
+ baseURL;
746
+ timeoutMs;
747
+ maxResponseBytes;
748
+ send;
749
+ /** Bind the getChannel Query. */
750
+ getChannel() {
751
+ return new GetChannelOperation(this);
752
+ }
753
+ /** Bind the create idea operation. */
754
+ createIdea() {
755
+ return new CreateIdeaOperation(this);
756
+ }
757
+ /** Bind the list ideas operation. */
758
+ listIdeas() {
759
+ return new ListIdeasOperation(this);
760
+ }
761
+ /** Bind the list organizations operation. */
762
+ listOrganizations() {
763
+ return new ListOrganizationsOperation(this);
764
+ }
765
+ /** Bind the list channels operation. */
766
+ listChannels() {
767
+ return new ListChannelsOperation(this);
768
+ }
769
+ /** Bind the get post operation. */
770
+ getPost() {
771
+ return new GetPostOperation(this);
772
+ }
773
+ /** Bind the list posts operation. */
774
+ listPosts() {
775
+ return new ListPostsOperation(this);
776
+ }
777
+ /** Bind the create post operation. */
778
+ createPost() {
779
+ return new CreatePostOperation(this);
780
+ }
781
+ /** Bind the create scheduled post operation. */
782
+ createScheduledPost() {
783
+ return new CreateScheduledPostOperation(this);
784
+ }
785
+ /** Bind the publish post now operation. */
786
+ publishPostNow() {
787
+ return new PublishPostNowOperation(this);
788
+ }
789
+ /** Bind the edit post operation. */
790
+ editPost() {
791
+ return new EditPostOperation(this);
792
+ }
793
+ /** Bind the delete post operation. */
794
+ deletePost() {
795
+ return new DeletePostOperation(this);
796
+ }
797
+ /** Resolve credentials and send one bounded channel lookup. */
798
+ async get(call, input) {
799
+ return this.executeGraphQL(call, getChannelGraphQL, { id: input.channelId });
800
+ }
801
+ /** Send one authenticated GraphQL request with a bounded response and optional write deadline. */
802
+ async executeGraphQL(call, query2, variables, signal = call.context.cancellationSignal) {
803
+ let apiKey;
804
+ try {
805
+ const credentials = await this.credentials.resolve(call, signal);
806
+ apiKey = credentials.apiKey instanceof SecretString ? credentials.apiKey.reveal() : "";
807
+ } catch {
808
+ return emptyExchange("credential");
809
+ }
810
+ if (!isHeaderSafeCredential(apiKey)) return emptyExchange("credential");
811
+ const url = new URL(`${this.baseURL}/`);
812
+ const request = {
813
+ url: url.toString(),
814
+ method: "POST",
815
+ headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: `Bearer ${apiKey}` },
816
+ body: new TextEncoder().encode(JSON.stringify({ query: query2, variables })),
817
+ maxResponseBytes: this.maxResponseBytes,
818
+ timeoutMs: this.timeoutMs,
819
+ addressPolicy: this.baseURL.startsWith("https://") ? "publicHTTPS" : "privateNetworkHTTP",
820
+ signal
821
+ };
822
+ let response;
823
+ let isTooLarge = false;
824
+ try {
825
+ response = await this.send(request);
826
+ } catch (error) {
827
+ if (error instanceof BodyTooLargeError && error.status !== void 0) {
828
+ response = { status: error.status, headers: error.headers ?? {}, body: new Uint8Array() };
829
+ isTooLarge = true;
830
+ } else if ((error instanceof ProviderTransportError || error instanceof ProviderStalledError) && error.status !== void 0) {
831
+ return {
832
+ status: error.status,
833
+ body: new Uint8Array(),
834
+ retryAfterMs: parseRetryAfter(header(error.headers ?? {}, "retry-after")),
835
+ error: "interrupted"
836
+ };
837
+ } else return emptyExchange("request");
838
+ }
839
+ const retryAfterMs = parseRetryAfter(header(response.headers, "retry-after"));
840
+ if (isTooLarge || response.body.length > this.maxResponseBytes)
841
+ return { status: response.status, body: new Uint8Array(), retryAfterMs, error: "tooLarge" };
842
+ return { status: response.status, body: response.body, retryAfterMs };
843
+ }
844
+ };
845
+ var GetChannelOperation = class {
846
+ /** Bind the provider client. */
847
+ constructor(client) {
848
+ this.client = client;
849
+ }
850
+ client;
851
+ /** Return the generated Query definition. */
852
+ definition() {
853
+ return GetChannelDefinition;
854
+ }
855
+ /** Classify provider outcomes consistently with Go. */
856
+ async invoke(call, input) {
857
+ if (!isValidGraphQLID(input?.channelId))
858
+ return terminal("defect", "VALIDATION", "channelId must contain 1\u2013128 printable characters");
859
+ const exchange = await this.client.get(call, input);
860
+ if (exchange.error === "credential") return terminal("defect", "AUTHENTICATION", "Buffer credentials are unavailable or invalid");
861
+ if (exchange.error === "request") return retry("TRANSPORT", "Buffer request failed");
862
+ if (exchange.status === 429) return retry("RATE_LIMIT", "Buffer rate limited the request", exchange.retryAfterMs);
863
+ if (exchange.status === 408 || exchange.status >= 500) return retry("AVAILABILITY", "Buffer is temporarily unavailable", exchange.retryAfterMs);
864
+ if (exchange.status !== 200) return terminal("providerRejected", "PROVIDER_REJECTION", `Buffer rejected HTTP ${exchange.status}`);
865
+ if (exchange.error === "tooLarge") return terminal("invalidResponse", "RESPONSE_TOO_LARGE", "Buffer response exceeded the configured limit");
866
+ if (exchange.error === "interrupted") return retry("TRANSPORT", "Buffer response was interrupted");
867
+ const channel2 = decodeChannel(exchange.body, input.channelId);
868
+ if (channel2 === "rejected") return terminal("providerRejected", "PROVIDER_REJECTION", "Buffer rejected the GraphQL query");
869
+ if (channel2 === "unavailable") return retry("AVAILABILITY", "Buffer reported an unexpected server error", exchange.retryAfterMs);
870
+ if (channel2 === "rateLimited") return retry("RATE_LIMIT", "Buffer rate limited the request", exchange.retryAfterMs);
871
+ if (channel2 === "graphQLNotFound") return terminal("notFound", "NOT_FOUND", "Buffer did not find the channel");
872
+ if (channel2 === void 0) return terminal("invalidResponse", "PROTOCOL", "Buffer returned invalid channel JSON");
873
+ if (channel2 === null) return terminal("notFound", "NOT_FOUND", "Buffer did not expose the channel");
874
+ return newQueryBranch2("found", channel2);
875
+ }
876
+ };
877
+ function isValidGraphQLID(value) {
878
+ return typeof value === "string" && value.length > 0 && value.trim() === value && new TextEncoder().encode(value).length <= 128 && ![...value].some((character) => character.codePointAt(0) < 32 || character.codePointAt(0) === 127) && !/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF])/.test(value);
879
+ }
880
+ function emptyExchange(error) {
881
+ return { status: 0, body: new Uint8Array(), retryAfterMs: 0, error };
882
+ }
883
+ function failure2(kind, message) {
884
+ return { provider: "buffer", operation: "getChannel", kind, message };
885
+ }
886
+ function terminal(branch, kind, message) {
887
+ return newQueryBranch2(branch, emptyChannel(), {}, failure2(kind, message));
888
+ }
889
+ function retry(kind, message, delay = 0) {
890
+ return newQueryRetry2(failure2(kind, message), delay);
891
+ }
892
+ function header(headers, name) {
893
+ const entry = Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1];
894
+ return Array.isArray(entry) ? entry[0] ?? "" : entry ?? "";
895
+ }
896
+ function isObject(value) {
897
+ return typeof value === "object" && value !== null && !Array.isArray(value);
898
+ }
899
+ function classifyGraphQLErrors(errors2) {
900
+ const precedence = ["graphQLNotFound", "rateLimited", "unavailable"];
901
+ let outcome = 0;
902
+ for (const error of errors2) {
903
+ const extensions = isObject(error) ? error.extensions : void 0;
904
+ if (extensions !== void 0 && extensions !== null && !isObject(extensions)) return "rejected";
905
+ const code = isObject(extensions) ? extensions.code : void 0;
906
+ if (code === "NOT_FOUND") continue;
907
+ if (code === "RATE_LIMIT_EXCEEDED") outcome = Math.max(outcome, 1);
908
+ else if (code === "UNEXPECTED") outcome = Math.max(outcome, 2);
909
+ else return "rejected";
910
+ }
911
+ return precedence[outcome];
912
+ }
913
+ function decodeChannel(body, channelID) {
914
+ let raw;
915
+ try {
916
+ raw = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(body));
917
+ } catch {
918
+ return void 0;
919
+ }
920
+ if (!isObject(raw)) return void 0;
921
+ if (raw.errors !== void 0 && raw.errors !== null && !Array.isArray(raw.errors)) return void 0;
922
+ if (Array.isArray(raw.errors) && raw.errors.length > 0) return classifyGraphQLErrors(raw.errors);
923
+ if (!isObject(raw.data)) return void 0;
924
+ const channel2 = raw.data.channel;
925
+ if (channel2 === null) return null;
926
+ if (!isObject(channel2)) return void 0;
927
+ if (channel2.id !== channelID || typeof channel2.name !== "string" || !channel2.name || typeof channel2.service !== "string" || !channel2.service) return void 0;
928
+ return { id: channel2.id, name: channel2.name, service: channel2.service };
929
+ }
930
+
931
+ // src/project.ts
932
+ function newProjectConnection2(project, connectionName) {
933
+ return newProjectConnection(project, connectionName, (loadedProject, name) => {
934
+ const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "buffer" && entry.connectionName === name);
935
+ if (!selected) throw new TypeError("Buffer project connection is not configured");
936
+ const fields = z.strictObject({ baseUrl: z.string().optional(), timeout: z.union([z.string(), z.number().int()]).optional(), maxResponseBytes: z.number().int().optional() }).parse(selected.configuration);
937
+ const timeoutMs = typeof fields.timeout === "number" ? Math.ceil(fields.timeout / 1e6) : fields.timeout ? parseDurationMilliseconds(fields.timeout) : void 0;
938
+ const config = {
939
+ ...fields.baseUrl ? { baseUrl: fields.baseUrl } : {},
940
+ ...timeoutMs !== void 0 ? { timeoutMs } : {},
941
+ ...fields.maxResponseBytes !== void 0 ? { maxResponseBytes: fields.maxResponseBytes } : {}
942
+ };
943
+ const credentials = {
944
+ async resolve(_call, signal) {
945
+ const privateFields = await loadedProject.resolveCredential("buffer", name, signal);
946
+ if (typeof privateFields.apiKey !== "string") throw new TypeError("Buffer credentials are unavailable");
947
+ return { apiKey: new SecretString2(privateFields.apiKey) };
948
+ }
949
+ };
950
+ return new BufferClient(config, credentials);
951
+ });
952
+ }
953
+ function parseDurationMilliseconds(value) {
954
+ let remaining = value;
955
+ let milliseconds = 0;
956
+ const units = { ns: 1e-6, us: 1e-3, "\xB5s": 1e-3, ms: 1, s: 1e3, m: 6e4, h: 36e5 };
957
+ while (remaining) {
958
+ const part = /^(\d+(?:\.\d+)?)(ns|us|µs|ms|s|m|h)/.exec(remaining);
959
+ if (!part) throw new TypeError("Buffer timeout must be a positive Go duration");
960
+ milliseconds += Number(part[1]) * (units[part[2] ?? ""] ?? NaN);
961
+ remaining = remaining.slice(part[0].length);
962
+ }
963
+ if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) throw new TypeError("Buffer timeout must resolve to positive whole milliseconds");
964
+ return milliseconds;
965
+ }
966
+ export {
967
+ BufferClient,
968
+ ChannelProfileSchema,
969
+ ChannelsListSchema,
970
+ ConfigSchema,
971
+ Connection,
972
+ ConnectorID,
973
+ CreateIdeaBranch,
974
+ CreateIdeaBranchCreated,
975
+ CreateIdeaBranchDefect,
976
+ CreateIdeaBranchProviderRejected,
977
+ CreateIdeaBranchUncertain,
978
+ CreateIdeaDefinition,
979
+ CreateIdeaInputSchema,
980
+ CreateIdeaMetadata,
981
+ CreateIdeaOperation,
982
+ CreatePostBranch,
983
+ CreatePostBranchCreated,
984
+ CreatePostBranchDefect,
985
+ CreatePostBranchProviderRejected,
986
+ CreatePostBranchUncertain,
987
+ CreatePostDefinition,
988
+ CreatePostInputSchema,
989
+ CreatePostMetadata,
990
+ CreatePostOperation,
991
+ CreateScheduledPostBranch,
992
+ CreateScheduledPostBranchCreated,
993
+ CreateScheduledPostBranchDefect,
994
+ CreateScheduledPostBranchProviderRejected,
995
+ CreateScheduledPostBranchUncertain,
996
+ CreateScheduledPostDefinition,
997
+ CreateScheduledPostInputSchema,
998
+ CreateScheduledPostMetadata,
999
+ CreateScheduledPostOperation,
1000
+ CredentialMaterialError,
1001
+ DeletePostBranch,
1002
+ DeletePostBranchDefect,
1003
+ DeletePostBranchDeleted,
1004
+ DeletePostBranchInvalidResponse,
1005
+ DeletePostBranchProviderRejected,
1006
+ DeletePostDefinition,
1007
+ DeletePostInputSchema,
1008
+ DeletePostMetadata,
1009
+ DeletePostOperation,
1010
+ EditPostBranch,
1011
+ EditPostBranchDefect,
1012
+ EditPostBranchInvalidResponse,
1013
+ EditPostBranchProviderRejected,
1014
+ EditPostBranchUpdated,
1015
+ EditPostDefinition,
1016
+ EditPostInputSchema,
1017
+ EditPostMetadata,
1018
+ EditPostOperation,
1019
+ GetChannelBranch,
1020
+ GetChannelBranchDefect,
1021
+ GetChannelBranchFound,
1022
+ GetChannelBranchInvalidResponse,
1023
+ GetChannelBranchNotFound,
1024
+ GetChannelBranchProviderRejected,
1025
+ GetChannelDefinition,
1026
+ GetChannelInputSchema,
1027
+ GetChannelMetadata,
1028
+ GetChannelOperation,
1029
+ GetPostBranch,
1030
+ GetPostBranchDefect,
1031
+ GetPostBranchFound,
1032
+ GetPostBranchInvalidResponse,
1033
+ GetPostBranchNotFound,
1034
+ GetPostBranchProviderRejected,
1035
+ GetPostDefinition,
1036
+ GetPostInputSchema,
1037
+ GetPostMetadata,
1038
+ GetPostOperation,
1039
+ IdeaProfileSchema,
1040
+ IdeasPageSchema,
1041
+ ListChannelsBranch,
1042
+ ListChannelsBranchDefect,
1043
+ ListChannelsBranchInvalidResponse,
1044
+ ListChannelsBranchListed,
1045
+ ListChannelsBranchProviderRejected,
1046
+ ListChannelsDefinition,
1047
+ ListChannelsInputSchema,
1048
+ ListChannelsMetadata,
1049
+ ListChannelsOperation,
1050
+ ListIdeasBranch,
1051
+ ListIdeasBranchDefect,
1052
+ ListIdeasBranchInvalidResponse,
1053
+ ListIdeasBranchListed,
1054
+ ListIdeasBranchProviderRejected,
1055
+ ListIdeasDefinition,
1056
+ ListIdeasInputSchema,
1057
+ ListIdeasMetadata,
1058
+ ListIdeasOperation,
1059
+ ListOrganizationsBranch,
1060
+ ListOrganizationsBranchDefect,
1061
+ ListOrganizationsBranchInvalidResponse,
1062
+ ListOrganizationsBranchListed,
1063
+ ListOrganizationsBranchProviderRejected,
1064
+ ListOrganizationsDefinition,
1065
+ ListOrganizationsInputSchema,
1066
+ ListOrganizationsMetadata,
1067
+ ListOrganizationsOperation,
1068
+ ListPostsBranch,
1069
+ ListPostsBranchDefect,
1070
+ ListPostsBranchInvalidResponse,
1071
+ ListPostsBranchListed,
1072
+ ListPostsBranchProviderRejected,
1073
+ ListPostsDefinition,
1074
+ ListPostsInputSchema,
1075
+ ListPostsMetadata,
1076
+ ListPostsOperation,
1077
+ OrganizationIdentitySchema,
1078
+ OrganizationsListSchema,
1079
+ PostAssetSchema,
1080
+ PostDeleteResultSchema,
1081
+ PostProfileSchema,
1082
+ PostsListSchema,
1083
+ ProviderID,
1084
+ PublishPostNowBranch,
1085
+ PublishPostNowBranchCreated,
1086
+ PublishPostNowBranchDefect,
1087
+ PublishPostNowBranchProviderRejected,
1088
+ PublishPostNowBranchUncertain,
1089
+ PublishPostNowDefinition,
1090
+ PublishPostNowInputSchema,
1091
+ PublishPostNowMetadata,
1092
+ PublishPostNowOperation,
1093
+ decodeCredentials,
1094
+ decodeSignedInteger,
1095
+ exactIntegerJSONCodec,
1096
+ isCredentialMaterialError,
1097
+ newConnection,
1098
+ newConnectionWithOperations,
1099
+ newCreateIdeaStep,
1100
+ newCreatePostStep,
1101
+ newCreateScheduledPostStep,
1102
+ newDeletePostStep,
1103
+ newEditPostStep,
1104
+ newGetChannelStep,
1105
+ newGetPostStep,
1106
+ newListChannelsStep,
1107
+ newListIdeasStep,
1108
+ newListOrganizationsStep,
1109
+ newListPostsStep,
1110
+ newProjectConnection2 as newProjectConnection,
1111
+ newPublishPostNowStep,
1112
+ parseExactIntegerJSON,
1113
+ parseJSONNumberTokens
1114
+ };