@superdurable/connector-buffer 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Super Durable
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,3 @@
1
- # Temporary Holding Version
1
+ # Buffer TypeScript connector
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Implements `getChannel`, returning one channel ID, name, and service. Go-recorded conformance checks exact requests, branches, retries, and outputs. Configure secret `apiKey` using the [connection guide](../README.md). See the [runnable Dex Flow](examples/channel-read/README.md). Live provider authorization remains unverified.
@@ -0,0 +1,65 @@
1
+ {
2
+ "connectorId": "buffer",
3
+ "releaseTag": "connectors/buffer/go/v0.1.0",
4
+ "package": {
5
+ "ecosystem": "npm",
6
+ "name": "@superdurable/connector-buffer",
7
+ "version": "0.1.0"
8
+ },
9
+ "factories": [
10
+ {
11
+ "name": "newGetChannelStep",
12
+ "kind": "query",
13
+ "operationId": "getChannel",
14
+ "inputType": "GetChannelInput",
15
+ "description": "Return a connected channel's ID, name, and service.",
16
+ "fields": {
17
+ "stepType": "stepType",
18
+ "annotations": "annotations",
19
+ "connectionName": "connectionName",
20
+ "resultAttribute": "resultAttribute"
21
+ },
22
+ "branches": [
23
+ {
24
+ "id": "found",
25
+ "field": "found",
26
+ "optional": false
27
+ },
28
+ {
29
+ "id": "notFound",
30
+ "field": "notFound",
31
+ "optional": true
32
+ },
33
+ {
34
+ "id": "providerRejected",
35
+ "field": "providerRejected",
36
+ "optional": true
37
+ },
38
+ {
39
+ "id": "invalidResponse",
40
+ "field": "invalidResponse",
41
+ "optional": true
42
+ },
43
+ {
44
+ "id": "defect",
45
+ "field": "defect",
46
+ "optional": true
47
+ }
48
+ ],
49
+ "inputSchema": {
50
+ "additionalProperties": false,
51
+ "description": "GetChannelInput selects a connected Buffer channel by opaque ID.",
52
+ "properties": {
53
+ "channelId": {
54
+ "description": "ChannelID is the ID returned by Buffer channel queries.",
55
+ "type": "string"
56
+ }
57
+ },
58
+ "required": [
59
+ "channelId"
60
+ ],
61
+ "type": "object"
62
+ }
63
+ }
64
+ ]
65
+ }
@@ -0,0 +1,106 @@
1
+ // src/generated/models.ts
2
+ import { z } from "zod";
3
+ import { SecretString } from "@superdurable/connectors-sdk";
4
+ var ConfigSchema = z.object({
5
+ "baseUrl": z.string().optional(),
6
+ "timeoutMs": z.number().int().optional(),
7
+ "maxResponseBytes": z.number().int().optional()
8
+ });
9
+ function decodeCredentials(value) {
10
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("credential fields are invalid");
11
+ const fields = value;
12
+ const allowed = /* @__PURE__ */ new Set(["apiKey"]);
13
+ if (Object.keys(fields).some((key) => !allowed.has(key))) throw new TypeError("stored credential does not match the connector credential fields");
14
+ if (fields["apiKey"] != null && !(typeof fields["apiKey"] === "string")) throw new TypeError("credential apiKey has an invalid type");
15
+ const credentials = {};
16
+ if (!fields["apiKey"]) throw new TypeError("credential apiKey is required");
17
+ credentials.apiKey = new SecretString(fields["apiKey"] ?? "");
18
+ return credentials;
19
+ }
20
+ var GetChannelInputSchema = z.strictObject({
21
+ "channelId": z.string()
22
+ });
23
+ var ChannelProfileSchema = z.strictObject({
24
+ "id": z.string(),
25
+ "name": z.string(),
26
+ "service": z.string()
27
+ });
28
+
29
+ // src/generated/definitions.ts
30
+ var ConnectorID = "buffer";
31
+ var ProviderID = "buffer";
32
+ var GetChannelBranch = {
33
+ Found: "found",
34
+ NotFound: "notFound",
35
+ ProviderRejected: "providerRejected",
36
+ InvalidResponse: "invalidResponse",
37
+ Defect: "defect"
38
+ };
39
+ var GetChannelBranchFound = GetChannelBranch.Found;
40
+ var GetChannelBranchNotFound = GetChannelBranch.NotFound;
41
+ var GetChannelBranchProviderRejected = GetChannelBranch.ProviderRejected;
42
+ var GetChannelBranchInvalidResponse = GetChannelBranch.InvalidResponse;
43
+ var GetChannelBranchDefect = GetChannelBranch.Defect;
44
+ var GetChannelDefinition = {
45
+ operation: { connectorId: ConnectorID, operationId: "getChannel" },
46
+ branches: [
47
+ { id: "found", description: "Buffer returned the channel." },
48
+ { id: "notFound", description: "Buffer did not expose a channel for this ID.", optional: true },
49
+ { id: "providerRejected", description: "Buffer returned a definite GraphQL or HTTP rejection.", optional: true },
50
+ { id: "invalidResponse", description: "Buffer returned malformed or oversized JSON.", optional: true },
51
+ { id: "defect", description: "Local input or credentials are invalid.", optional: true }
52
+ ],
53
+ stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "async" }
54
+ };
55
+ var GetChannelMetadata = { kind: "query", idempotency: "none", authorization: "required" };
56
+
57
+ // src/generated/connection.ts
58
+ import { ConnectionRefSchema } from "@superdurable/connectors-sdk";
59
+ var Connection = class {
60
+ /** Stable provider and connection name. */
61
+ reference;
62
+ /** Bound provider operations. */
63
+ operations;
64
+ /** Validate a reference and bind operations. */
65
+ constructor(reference, operations) {
66
+ this.reference = ConnectionRefSchema.parse(reference);
67
+ if (this.reference.provider !== ProviderID) throw new TypeError("connection provider differs from the manifest");
68
+ if (!operations) throw new TypeError("connector operations are required");
69
+ this.operations = operations;
70
+ }
71
+ };
72
+ function newConnection(client, reference) {
73
+ if (!client) throw new TypeError("connector client is required");
74
+ return new Connection(reference, client);
75
+ }
76
+ function newConnectionWithOperations(operations, reference) {
77
+ return new Connection(reference, operations);
78
+ }
79
+ function newProjectConnection(project, connectionName, createClient) {
80
+ if (!project) throw new TypeError("loaded project is required");
81
+ const reference = ConnectionRefSchema.parse({ provider: ProviderID, name: connectionName });
82
+ const selected = project.configuration.connections.find((entry) => entry.connectorId === ConnectorID && entry.connectionName === connectionName);
83
+ if (!selected || selected.provider !== ProviderID) throw new TypeError("project connection is not configured");
84
+ return newConnection(createClient(project, connectionName), reference);
85
+ }
86
+
87
+ export {
88
+ ConfigSchema,
89
+ decodeCredentials,
90
+ GetChannelInputSchema,
91
+ ChannelProfileSchema,
92
+ ConnectorID,
93
+ ProviderID,
94
+ GetChannelBranch,
95
+ GetChannelBranchFound,
96
+ GetChannelBranchNotFound,
97
+ GetChannelBranchProviderRejected,
98
+ GetChannelBranchInvalidResponse,
99
+ GetChannelBranchDefect,
100
+ GetChannelDefinition,
101
+ GetChannelMetadata,
102
+ Connection,
103
+ newConnection,
104
+ newConnectionWithOperations,
105
+ newProjectConnection
106
+ };
@@ -0,0 +1,72 @@
1
+ import { SecretString, CredentialProvider, Query, ConnectionRef } from '@superdurable/connectors-sdk';
2
+ import { z } from 'zod';
3
+
4
+ /** Connector configuration; omitted fields use manifest defaults. */
5
+ interface Config {
6
+ /** Buffer GraphQL HTTPS endpoint. Blank uses the displayed production URL; override only for a trusted test gateway. Do not append a path or credentials. */
7
+ baseUrl?: string;
8
+ /** Maximum duration of one channel query as a positive Go duration. Blank uses the displayed default; increase only for slow responses. Runtime value in milliseconds. */
9
+ timeoutMs?: number;
10
+ /** Maximum complete GraphQL JSON response in bytes as a positive integer. Blank uses the displayed default; increase only for large responses. */
11
+ maxResponseBytes?: number;
12
+ }
13
+ /** Runtime schema for manifest configuration. */
14
+ declare const ConfigSchema: z.ZodObject<{
15
+ baseUrl: z.ZodOptional<z.ZodString>;
16
+ timeoutMs: z.ZodOptional<z.ZodNumber>;
17
+ maxResponseBytes: z.ZodOptional<z.ZodNumber>;
18
+ }, z.core.$strip>;
19
+ /** Private connector credentials resolved by the host. */
20
+ interface Credentials {
21
+ /** Secret account API key from Buffer > Settings > API > Create a new API key. Copy the complete key; blank prevents calls. Dex sends it as a Bearer credential, never in Flow data. Rotate it on the same page if exposed. */
22
+ apiKey: SecretString;
23
+ }
24
+ /** Decode private credential fields for the connector. */
25
+ declare function decodeCredentials(value: unknown): Credentials;
26
+ /** Host-owned source of private connector credentials. */
27
+ type CredentialSource = CredentialProvider<Credentials>;
28
+ /** GetChannelInput selects a connected Buffer channel by opaque ID. */
29
+ interface GetChannelInput {
30
+ /** ChannelID is the ID returned by Buffer channel queries. */
31
+ "channelId": string;
32
+ }
33
+ /** ChannelProfile contains public metadata for one connected channel. */
34
+ interface ChannelProfile {
35
+ /** ID is the Buffer channel ID. */
36
+ "id": string;
37
+ /** Name is the connected channel name. */
38
+ "name": string;
39
+ /** Service is the social platform identifier. */
40
+ "service": string;
41
+ }
42
+ /** Runtime validator for GetChannelInput. */
43
+ declare const GetChannelInputSchema: z.ZodObject<{
44
+ channelId: z.ZodString;
45
+ }, z.core.$strict>;
46
+ /** Runtime validator for ChannelProfile. */
47
+ declare const ChannelProfileSchema: z.ZodObject<{
48
+ id: z.ZodString;
49
+ name: z.ZodString;
50
+ service: z.ZodString;
51
+ }, z.core.$strict>;
52
+
53
+ /** Typed operations supplied by a client or mock. */
54
+ interface Operations {
55
+ /** Invoke getChannel through this connection. */
56
+ getChannel(): Query<GetChannelInput, ChannelProfile>;
57
+ }
58
+ /** Named connector connection kept outside Flow state. */
59
+ declare class Connection<BoundOperations = Operations> {
60
+ /** Stable provider and connection name. */
61
+ readonly reference: ConnectionRef;
62
+ /** Bound provider operations. */
63
+ readonly operations: BoundOperations;
64
+ /** Validate a reference and bind operations. */
65
+ constructor(reference: ConnectionRef, operations: BoundOperations);
66
+ }
67
+ /** Bind a client to a named connection. */
68
+ declare function newConnection(client: Operations, reference: ConnectionRef): Connection;
69
+ /** Bind scripted operations to a named connection. */
70
+ declare function newConnectionWithOperations(operations: Operations, reference: ConnectionRef): Connection;
71
+
72
+ export { type ChannelProfile as C, type GetChannelInput as G, type Operations as O, Connection as a, type Config as b, type Credentials as c, ChannelProfileSchema as d, ConfigSchema as e, type CredentialSource as f, GetChannelInputSchema as g, decodeCredentials as h, newConnectionWithOperations as i, newConnection as n };
@@ -0,0 +1,97 @@
1
+ import { G as GetChannelInput, C as ChannelProfile, a as Connection, O as Operations, b as Config, c as Credentials } from './connection-BRLi-NI_.js';
2
+ export { d as ChannelProfileSchema, e as ConfigSchema, f as CredentialSource, g as GetChannelInputSchema, h as decodeCredentials, n as newConnection, i as newConnectionWithOperations } from './connection-BRLi-NI_.js';
3
+ import { QueryDefinition, QueryStepConfig, Query, QueryResult, QueryStep, CredentialProvider, Call, QueryAttempt } from '@superdurable/connectors-sdk';
4
+ import { StepTarget } from '@superdurable/dex';
5
+ import { LoadedProject } from '@superdurable/connectors-sdk/projectconfig';
6
+ import { ProviderRequest, ProviderResponse } from '@superdurable/connectors-sdk/providerhttp';
7
+ import 'zod';
8
+
9
+ /** Stable connector identity. */
10
+ declare const ConnectorID = "buffer";
11
+ /** Provider identity for named connections. */
12
+ declare const ProviderID = "buffer";
13
+ /** Branch IDs for getChannel. */
14
+ declare const GetChannelBranch: {
15
+ readonly Found: "found";
16
+ readonly NotFound: "notFound";
17
+ readonly ProviderRejected: "providerRejected";
18
+ readonly InvalidResponse: "invalidResponse";
19
+ readonly Defect: "defect";
20
+ };
21
+ /** Buffer returned the channel. */
22
+ declare const GetChannelBranchFound: "found";
23
+ /** Buffer did not expose a channel for this ID. */
24
+ declare const GetChannelBranchNotFound: "notFound";
25
+ /** Buffer returned a definite GraphQL or HTTP rejection. */
26
+ declare const GetChannelBranchProviderRejected: "providerRejected";
27
+ /** Buffer returned malformed or oversized JSON. */
28
+ declare const GetChannelBranchInvalidResponse: "invalidResponse";
29
+ /** Local input or credentials are invalid. */
30
+ declare const GetChannelBranchDefect: "defect";
31
+ /** Manifest definition for getChannel. */
32
+ declare const GetChannelDefinition: QueryDefinition;
33
+ /** Manifest metadata for getChannel. */
34
+ declare const GetChannelMetadata: {
35
+ readonly kind: "query";
36
+ readonly idempotency: "none";
37
+ readonly authorization: "required";
38
+ };
39
+
40
+ /** Configuration for the getChannel connector Step. */
41
+ interface GetChannelStepConfig<StepInput, OperationInput = GetChannelInput, OperationOutput = ChannelProfile> extends Omit<QueryStepConfig<StepInput, OperationInput, OperationOutput>, 'operation' | 'connection' | 'branches'> {
42
+ /** Named connection supplying this operation. */
43
+ connection: Connection<{
44
+ getChannel(): Query<OperationInput, OperationOutput>;
45
+ }>;
46
+ /** Name matching the bound connection. */
47
+ connectionName: string;
48
+ /** Buffer returned the channel. */
49
+ found: StepTarget<QueryResult<OperationOutput>>;
50
+ /** Buffer did not expose a channel for this ID. */
51
+ notFound?: StepTarget<QueryResult<OperationOutput>>;
52
+ /** Buffer returned a definite GraphQL or HTTP rejection. */
53
+ providerRejected?: StepTarget<QueryResult<OperationOutput>>;
54
+ /** Buffer returned malformed or oversized JSON. */
55
+ invalidResponse?: StepTarget<QueryResult<OperationOutput>>;
56
+ /** Local input or credentials are invalid. */
57
+ defect?: StepTarget<QueryResult<OperationOutput>>;
58
+ }
59
+ /** Build the getChannel Step from a named connection. */
60
+ declare function newGetChannelStep<StepInput, OperationInput = GetChannelInput, OperationOutput = ChannelProfile>(configuration: GetChannelStepConfig<StepInput, OperationInput, OperationOutput>): QueryStep<StepInput, OperationInput, OperationOutput>;
61
+
62
+ /** Open one named Buffer connection from Dex project configuration. */
63
+ declare function newProjectConnection(project: LoadedProject, connectionName: string): Connection<Operations>;
64
+
65
+ /** Injectable provider sender for tests and local applications. */
66
+ interface BufferClientOptions {
67
+ /** Provider sender; omitted uses the SDK transport. */ send?: (request: ProviderRequest) => Promise<ProviderResponse>;
68
+ }
69
+ interface Exchange {
70
+ status: number;
71
+ body: Uint8Array;
72
+ retryAfterMs: number;
73
+ error?: 'credential' | 'request' | 'tooLarge';
74
+ }
75
+ /** Authenticated Buffer GraphQL client for channel lookups. */
76
+ declare class BufferClient {
77
+ private readonly credentials;
78
+ private readonly baseURL;
79
+ private readonly timeoutMs;
80
+ private readonly maxResponseBytes;
81
+ private readonly send;
82
+ /** Validate provider configuration without contacting Buffer. */
83
+ constructor(config: Config, credentials: CredentialProvider<Credentials>, options?: BufferClientOptions);
84
+ /** Bind the getChannel Query. */ getChannel(): GetChannelOperation;
85
+ /** Resolve credentials and send one bounded channel lookup. */
86
+ get(call: Call, input: GetChannelInput): Promise<Exchange>;
87
+ }
88
+ /** Read one channel by its Buffer GraphQL ID. */
89
+ declare class GetChannelOperation implements Query<GetChannelInput, ChannelProfile> {
90
+ private readonly client;
91
+ /** Bind the provider client. */ constructor(client: BufferClient);
92
+ /** Return the generated Query definition. */ definition(): QueryDefinition;
93
+ /** Classify provider outcomes consistently with Go. */
94
+ invoke(call: Call, input: GetChannelInput): Promise<QueryAttempt<ChannelProfile>>;
95
+ }
96
+
97
+ export { BufferClient, type BufferClientOptions, ChannelProfile, Config, Connection, ConnectorID, Credentials, GetChannelBranch, GetChannelBranchDefect, GetChannelBranchFound, GetChannelBranchInvalidResponse, GetChannelBranchNotFound, GetChannelBranchProviderRejected, GetChannelDefinition, GetChannelInput, GetChannelMetadata, GetChannelOperation, type GetChannelStepConfig, ProviderID, newGetChannelStep, newProjectConnection };
package/dist/index.js ADDED
@@ -0,0 +1,245 @@
1
+ import {
2
+ ChannelProfileSchema,
3
+ ConfigSchema,
4
+ Connection,
5
+ ConnectorID,
6
+ GetChannelBranch,
7
+ GetChannelBranchDefect,
8
+ GetChannelBranchFound,
9
+ GetChannelBranchInvalidResponse,
10
+ GetChannelBranchNotFound,
11
+ GetChannelBranchProviderRejected,
12
+ GetChannelDefinition,
13
+ GetChannelInputSchema,
14
+ GetChannelMetadata,
15
+ ProviderID,
16
+ decodeCredentials,
17
+ newConnection,
18
+ newConnectionWithOperations,
19
+ newProjectConnection
20
+ } from "./chunk-VOOXKNLI.js";
21
+
22
+ // src/generated/steps.ts
23
+ import { goToBranch, newQueryStep } from "@superdurable/connectors-sdk";
24
+ function newGetChannelStep(configuration) {
25
+ const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
26
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
27
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.getChannel(), connection: connection.reference, branches: [
28
+ goToBranch("found", found),
29
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
30
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
31
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
32
+ ...defect ? [goToBranch("defect", defect)] : []
33
+ ] });
34
+ }
35
+
36
+ // src/project.ts
37
+ import { SecretString as SecretString2 } from "@superdurable/connectors-sdk";
38
+ import { z } from "zod";
39
+
40
+ // src/client.ts
41
+ import { SecretString, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
42
+ import { BodyTooLargeError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
43
+ var emptyChannel = () => ({ id: "", name: "", service: "" });
44
+ var getChannelGraphQL = "query GetChannel($id: ChannelId!) { channel(input: {id: $id}) { id name service } }";
45
+ var BufferClient = class {
46
+ /** Validate provider configuration without contacting Buffer. */
47
+ constructor(config, credentials, options = {}) {
48
+ this.credentials = credentials;
49
+ if (!config || !credentials) throw new TypeError("Buffer configuration and credentials are required");
50
+ this.baseURL = validateBaseURL(config.baseUrl ?? "https://api.buffer.com").replace(/\/$/, "");
51
+ this.timeoutMs = config.timeoutMs ?? 15e3;
52
+ this.maxResponseBytes = config.maxResponseBytes ?? 1048576;
53
+ if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs <= 0 || !Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0)
54
+ throw new TypeError("Buffer request limits must be positive integers");
55
+ this.send = options.send ?? sendProviderRequest;
56
+ }
57
+ credentials;
58
+ baseURL;
59
+ timeoutMs;
60
+ maxResponseBytes;
61
+ send;
62
+ /** Bind the getChannel Query. */
63
+ getChannel() {
64
+ return new GetChannelOperation(this);
65
+ }
66
+ /** Resolve credentials and send one bounded channel lookup. */
67
+ async get(call, input) {
68
+ let apiKey;
69
+ try {
70
+ const credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
71
+ apiKey = credentials.apiKey instanceof SecretString ? credentials.apiKey.reveal() : "";
72
+ } catch {
73
+ return emptyExchange("credential");
74
+ }
75
+ if (!isHeaderSafeCredential(apiKey)) return emptyExchange("credential");
76
+ const url = new URL(`${this.baseURL}/`);
77
+ const request = {
78
+ url: url.toString(),
79
+ method: "POST",
80
+ headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: `Bearer ${apiKey}` },
81
+ body: new TextEncoder().encode(JSON.stringify({ query: getChannelGraphQL, variables: { id: input.channelId } })),
82
+ maxResponseBytes: this.maxResponseBytes,
83
+ timeoutMs: this.timeoutMs,
84
+ addressPolicy: this.baseURL.startsWith("https://") ? "publicHTTPS" : "privateNetworkHTTP",
85
+ signal: call.context.cancellationSignal
86
+ };
87
+ let response;
88
+ let isTooLarge = false;
89
+ try {
90
+ response = await this.send(request);
91
+ } catch (error) {
92
+ if (error instanceof BodyTooLargeError && error.status !== void 0) {
93
+ response = { status: error.status, headers: error.headers ?? {}, body: new Uint8Array() };
94
+ isTooLarge = true;
95
+ } else return emptyExchange("request");
96
+ }
97
+ const retryAfterMs = parseRetryAfter(header(response.headers, "retry-after"));
98
+ if (isTooLarge || response.body.length > this.maxResponseBytes)
99
+ return { status: response.status, body: new Uint8Array(), retryAfterMs, error: "tooLarge" };
100
+ return { status: response.status, body: response.body, retryAfterMs };
101
+ }
102
+ };
103
+ var GetChannelOperation = class {
104
+ /** Bind the provider client. */
105
+ constructor(client) {
106
+ this.client = client;
107
+ }
108
+ client;
109
+ /** Return the generated Query definition. */
110
+ definition() {
111
+ return GetChannelDefinition;
112
+ }
113
+ /** Classify provider outcomes consistently with Go. */
114
+ async invoke(call, input) {
115
+ if (!isValidGraphQLID(input?.channelId))
116
+ return terminal("defect", "VALIDATION", "channelId must contain 1\u2013128 printable characters");
117
+ const exchange = await this.client.get(call, input);
118
+ if (exchange.error === "credential") return terminal("defect", "AUTHENTICATION", "Buffer credentials are unavailable or invalid");
119
+ if (exchange.error === "request") return retry("TRANSPORT", "Buffer request failed");
120
+ if (exchange.status === 429) return retry("RATE_LIMIT", "Buffer rate limited the request", exchange.retryAfterMs);
121
+ if (exchange.status === 408 || exchange.status >= 500) return retry("AVAILABILITY", "Buffer is temporarily unavailable", exchange.retryAfterMs);
122
+ if (exchange.status !== 200) return terminal("providerRejected", "PROVIDER_REJECTION", `Buffer rejected HTTP ${exchange.status}`);
123
+ if (exchange.error === "tooLarge") return terminal("invalidResponse", "RESPONSE_TOO_LARGE", "Buffer response exceeded the configured limit");
124
+ const channel = decodeChannel(exchange.body, input.channelId);
125
+ if (channel === "rejected") return terminal("providerRejected", "PROVIDER_REJECTION", "Buffer rejected the GraphQL query");
126
+ if (channel === "unavailable") return retry("AVAILABILITY", "Buffer reported an unexpected server error", exchange.retryAfterMs);
127
+ if (channel === "rateLimited") return retry("RATE_LIMIT", "Buffer rate limited the request", exchange.retryAfterMs);
128
+ if (channel === "graphQLNotFound") return terminal("notFound", "NOT_FOUND", "Buffer did not find the channel");
129
+ if (channel === void 0) return terminal("invalidResponse", "PROTOCOL", "Buffer returned invalid channel JSON");
130
+ if (channel === null) return terminal("notFound", "NOT_FOUND", "Buffer did not expose the channel");
131
+ return newQueryBranch("found", channel);
132
+ }
133
+ };
134
+ function isValidGraphQLID(value) {
135
+ 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);
136
+ }
137
+ function emptyExchange(error) {
138
+ return { status: 0, body: new Uint8Array(), retryAfterMs: 0, error };
139
+ }
140
+ function failure(kind, message) {
141
+ return { provider: "buffer", operation: "getChannel", kind, message };
142
+ }
143
+ function terminal(branch, kind, message) {
144
+ return newQueryBranch(branch, emptyChannel(), {}, failure(kind, message));
145
+ }
146
+ function retry(kind, message, delay = 0) {
147
+ return newQueryRetry(failure(kind, message), delay);
148
+ }
149
+ function header(headers, name) {
150
+ const entry = Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1];
151
+ return Array.isArray(entry) ? entry[0] ?? "" : entry ?? "";
152
+ }
153
+ function isObject(value) {
154
+ return typeof value === "object" && value !== null && !Array.isArray(value);
155
+ }
156
+ function classifyGraphQLErrors(errors) {
157
+ const precedence = ["graphQLNotFound", "rateLimited", "unavailable"];
158
+ let outcome = 0;
159
+ for (const error of errors) {
160
+ const extensions = isObject(error) ? error.extensions : void 0;
161
+ if (extensions !== void 0 && extensions !== null && !isObject(extensions)) return "rejected";
162
+ const code = isObject(extensions) ? extensions.code : void 0;
163
+ if (code === "NOT_FOUND") continue;
164
+ if (code === "RATE_LIMIT_EXCEEDED") outcome = Math.max(outcome, 1);
165
+ else if (code === "UNEXPECTED") outcome = Math.max(outcome, 2);
166
+ else return "rejected";
167
+ }
168
+ return precedence[outcome];
169
+ }
170
+ function decodeChannel(body, channelID) {
171
+ let raw;
172
+ try {
173
+ raw = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(body));
174
+ } catch {
175
+ return void 0;
176
+ }
177
+ if (!isObject(raw)) return void 0;
178
+ if (raw.errors !== void 0 && raw.errors !== null && !Array.isArray(raw.errors)) return void 0;
179
+ if (Array.isArray(raw.errors) && raw.errors.length > 0) return classifyGraphQLErrors(raw.errors);
180
+ if (!isObject(raw.data)) return void 0;
181
+ const channel = raw.data.channel;
182
+ if (channel === null) return null;
183
+ if (!isObject(channel)) return void 0;
184
+ if (channel.id !== channelID || typeof channel.name !== "string" || !channel.name || typeof channel.service !== "string" || !channel.service) return void 0;
185
+ return { id: channel.id, name: channel.name, service: channel.service };
186
+ }
187
+
188
+ // src/project.ts
189
+ function newProjectConnection2(project, connectionName) {
190
+ return newProjectConnection(project, connectionName, (loadedProject, name) => {
191
+ const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "buffer" && entry.connectionName === name);
192
+ if (!selected) throw new TypeError("Buffer project connection is not configured");
193
+ 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);
194
+ const timeoutMs = typeof fields.timeout === "number" ? Math.ceil(fields.timeout / 1e6) : fields.timeout ? parseDurationMilliseconds(fields.timeout) : void 0;
195
+ const config = {
196
+ ...fields.baseUrl ? { baseUrl: fields.baseUrl } : {},
197
+ ...timeoutMs !== void 0 ? { timeoutMs } : {},
198
+ ...fields.maxResponseBytes !== void 0 ? { maxResponseBytes: fields.maxResponseBytes } : {}
199
+ };
200
+ const credentials = {
201
+ async resolve(_call, signal) {
202
+ const privateFields = await loadedProject.resolveCredential("buffer", name, signal);
203
+ if (typeof privateFields.apiKey !== "string") throw new TypeError("Buffer credentials are unavailable");
204
+ return { apiKey: new SecretString2(privateFields.apiKey) };
205
+ }
206
+ };
207
+ return new BufferClient(config, credentials);
208
+ });
209
+ }
210
+ function parseDurationMilliseconds(value) {
211
+ let remaining = value;
212
+ let milliseconds = 0;
213
+ const units = { ns: 1e-6, us: 1e-3, "\xB5s": 1e-3, ms: 1, s: 1e3, m: 6e4, h: 36e5 };
214
+ while (remaining) {
215
+ const part = /^(\d+(?:\.\d+)?)(ns|us|µs|ms|s|m|h)/.exec(remaining);
216
+ if (!part) throw new TypeError("Buffer timeout must be a positive Go duration");
217
+ milliseconds += Number(part[1]) * (units[part[2] ?? ""] ?? NaN);
218
+ remaining = remaining.slice(part[0].length);
219
+ }
220
+ if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) throw new TypeError("Buffer timeout must resolve to positive whole milliseconds");
221
+ return milliseconds;
222
+ }
223
+ export {
224
+ BufferClient,
225
+ ChannelProfileSchema,
226
+ ConfigSchema,
227
+ Connection,
228
+ ConnectorID,
229
+ GetChannelBranch,
230
+ GetChannelBranchDefect,
231
+ GetChannelBranchFound,
232
+ GetChannelBranchInvalidResponse,
233
+ GetChannelBranchNotFound,
234
+ GetChannelBranchProviderRejected,
235
+ GetChannelDefinition,
236
+ GetChannelInputSchema,
237
+ GetChannelMetadata,
238
+ GetChannelOperation,
239
+ ProviderID,
240
+ decodeCredentials,
241
+ newConnection,
242
+ newConnectionWithOperations,
243
+ newGetChannelStep,
244
+ newProjectConnection2 as newProjectConnection
245
+ };
package/dist/mock.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ import { MockQuery, Case } from '@superdurable/connectors-sdk/connectormock';
2
+ import { Failure } from '@superdurable/connectors-sdk';
3
+ import { O as Operations, a as Connection, G as GetChannelInput, C as ChannelProfile } from './connection-BRLi-NI_.js';
4
+ import 'zod';
5
+
6
+ /** Go zero value for GetChannelInput in scripted cases. */
7
+ declare const emptyGetChannelInput: GetChannelInput;
8
+ /** Go zero value for ChannelProfile in scripted cases. */
9
+ declare const emptyChannelProfile: ChannelProfile;
10
+ /** Script the found branch. */
11
+ declare function getChannelFound(value: ChannelProfile, failure?: Failure): Case<ChannelProfile>;
12
+ /** Script the notFound branch. */
13
+ declare function getChannelNotFound(value: ChannelProfile, failure?: Failure): Case<ChannelProfile>;
14
+ /** Script the providerRejected branch. */
15
+ declare function getChannelProviderRejected(value: ChannelProfile, failure?: Failure): Case<ChannelProfile>;
16
+ /** Script the invalidResponse branch. */
17
+ declare function getChannelInvalidResponse(value: ChannelProfile, failure?: Failure): Case<ChannelProfile>;
18
+ /** Script the defect branch. */
19
+ declare function getChannelDefect(value: ChannelProfile, failure?: Failure): Case<ChannelProfile>;
20
+ /** Script a safe retry of getChannel. */
21
+ declare function getChannelRetry(failure: Failure, retryAfterMs?: number): Case<ChannelProfile>;
22
+ /** Manifest scenario foundDefault for getChannel. */
23
+ declare function getChannelFoundDefault(): Case<ChannelProfile>;
24
+ /** Default getChannel scenario. */
25
+ declare function getChannelDefault(): Case<ChannelProfile>;
26
+ /** Scripted operations and manifest defaults for this connector. */
27
+ declare class GeneratedMock implements Operations {
28
+ #private;
29
+ constructor(connectionName: string);
30
+ connection(): Connection;
31
+ getChannel(): MockQuery<GetChannelInput, ChannelProfile>;
32
+ assertNoFailures(): void;
33
+ }
34
+
35
+ export { GeneratedMock, GeneratedMock as Mock, emptyChannelProfile, emptyGetChannelInput, getChannelDefault, getChannelDefect, getChannelFound, getChannelFoundDefault, getChannelInvalidResponse, getChannelNotFound, getChannelProviderRejected, getChannelRetry };
package/dist/mock.js ADDED
@@ -0,0 +1,74 @@
1
+ import {
2
+ ChannelProfileSchema,
3
+ GetChannelDefinition,
4
+ GetChannelInputSchema,
5
+ ProviderID,
6
+ newConnectionWithOperations
7
+ } from "./chunk-VOOXKNLI.js";
8
+
9
+ // src/generated/mock.ts
10
+ import { branchCase, retryCase, newQuery } from "@superdurable/connectors-sdk/connectormock";
11
+ var emptyGetChannelInput = GetChannelInputSchema.parse({
12
+ "channelId": ""
13
+ });
14
+ var emptyChannelProfile = ChannelProfileSchema.parse({
15
+ "id": "",
16
+ "name": "",
17
+ "service": ""
18
+ });
19
+ function getChannelFound(value, failure) {
20
+ return branchCase("found", value, failure);
21
+ }
22
+ function getChannelNotFound(value, failure) {
23
+ return branchCase("notFound", value, failure);
24
+ }
25
+ function getChannelProviderRejected(value, failure) {
26
+ return branchCase("providerRejected", value, failure);
27
+ }
28
+ function getChannelInvalidResponse(value, failure) {
29
+ return branchCase("invalidResponse", value, failure);
30
+ }
31
+ function getChannelDefect(value, failure) {
32
+ return branchCase("defect", value, failure);
33
+ }
34
+ function getChannelRetry(failure, retryAfterMs = 0) {
35
+ return retryCase(failure, retryAfterMs);
36
+ }
37
+ function getChannelFoundDefault() {
38
+ const value = ChannelProfileSchema.parse({ "id": "channel-1", "name": "Example Channel", "service": "instagram" });
39
+ return branchCase("found", value);
40
+ }
41
+ function getChannelDefault() {
42
+ return getChannelFoundDefault();
43
+ }
44
+ var GeneratedMock = class {
45
+ #getChannel;
46
+ #connection;
47
+ constructor(connectionName) {
48
+ this.#getChannel = newQuery(GetChannelDefinition).default(getChannelDefault());
49
+ this.#connection = newConnectionWithOperations(this, { provider: ProviderID, name: connectionName });
50
+ }
51
+ connection() {
52
+ return this.#connection;
53
+ }
54
+ getChannel() {
55
+ return this.#getChannel;
56
+ }
57
+ assertNoFailures() {
58
+ this.#getChannel.assertNoFailures();
59
+ }
60
+ };
61
+ export {
62
+ GeneratedMock,
63
+ GeneratedMock as Mock,
64
+ emptyChannelProfile,
65
+ emptyGetChannelInput,
66
+ getChannelDefault,
67
+ getChannelDefect,
68
+ getChannelFound,
69
+ getChannelFoundDefault,
70
+ getChannelInvalidResponse,
71
+ getChannelNotFound,
72
+ getChannelProviderRejected,
73
+ getChannelRetry
74
+ };
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@superdurable/connector-buffer",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "license": "MIT",
5
+ "description": "Buffer connector for Dex TypeScript applications",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/superdurable/dex-connectors-library.git",
9
+ "directory": "connectors/buffer/typescript"
10
+ },
11
+ "type": "module",
12
+ "engines": {
13
+ "node": "^22.0.0 || ^24.0.0"
14
+ },
15
+ "module": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js"
21
+ },
22
+ "./mock": {
23
+ "types": "./dist/mock.d.ts",
24
+ "import": "./dist/mock.js"
25
+ },
26
+ "./dex-connector.json": "./dex-connector.json"
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "README.md",
31
+ "LICENSE",
32
+ "dex-connector.json"
33
+ ],
34
+ "scripts": {
35
+ "prepack": "npm run build",
36
+ "build": "tsup src/index.ts src/mock.ts --format esm --dts --clean",
37
+ "typecheck": "tsc --noEmit",
38
+ "lint": "eslint src test examples",
39
+ "test": "vitest run --exclude test/integration/**",
40
+ "test:integration": "vitest run test/integration/*.integration.test.ts",
41
+ "example:worker": "tsx examples/channel-read/worker.ts",
42
+ "example:start": "tsx examples/channel-read/start.ts",
43
+ "check": "npm run typecheck && npm run lint && npm test && npm run build"
44
+ },
45
+ "dependencies": {
46
+ "@superdurable/connectors-sdk": "0.1.1",
47
+ "@superdurable/dex": ">=1.28.0",
48
+ "zod": "^4.1.0"
49
+ },
50
+ "devDependencies": {
51
+ "@eslint/js": "^9.0.0",
52
+ "@types/node": "^22.0.0",
53
+ "eslint": "^9.0.0",
54
+ "tsup": "^8.0.0",
55
+ "tsx": "^4.23.15",
56
+ "typescript": "^5.9.0",
57
+ "typescript-eslint": "^8.0.0",
58
+ "vitest": "^3.0.0",
59
+ "yaml": "^2.9.1"
60
+ }
61
+ }