@superdurable/connector-airtable 0.0.0-stage → 0.1.1

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,639 @@
1
+ import {
2
+ ConfigSchema,
3
+ Connection,
4
+ ConnectorID,
5
+ FieldEqualityFilterSchema,
6
+ GetRecordBranch,
7
+ GetRecordBranchDefect,
8
+ GetRecordBranchFound,
9
+ GetRecordBranchInvalidResponse,
10
+ GetRecordBranchNotFound,
11
+ GetRecordBranchProviderRejected,
12
+ GetRecordDefinition,
13
+ GetRecordInputSchema,
14
+ GetRecordMetadata,
15
+ ListRecordsBranch,
16
+ ListRecordsBranchDefect,
17
+ ListRecordsBranchInvalidResponse,
18
+ ListRecordsBranchListed,
19
+ ListRecordsBranchOffsetExpired,
20
+ ListRecordsBranchProviderRejected,
21
+ ListRecordsDefinition,
22
+ ListRecordsInputSchema,
23
+ ListRecordsMetadata,
24
+ ProviderID,
25
+ RecordPageSchema,
26
+ RecordSchema,
27
+ RecordSortSchema,
28
+ RecordUpdateSchema,
29
+ RecordUpsertSchema,
30
+ UpdateRecordsBranch,
31
+ UpdateRecordsBranchDefect,
32
+ UpdateRecordsBranchInvalidResponse,
33
+ UpdateRecordsBranchNotFound,
34
+ UpdateRecordsBranchProviderRejected,
35
+ UpdateRecordsBranchUpdated,
36
+ UpdateRecordsDefinition,
37
+ UpdateRecordsInputSchema,
38
+ UpdateRecordsMetadata,
39
+ UpdatedRecordsSchema,
40
+ UpsertRecordsBranch,
41
+ UpsertRecordsBranchDefect,
42
+ UpsertRecordsBranchInvalidResponse,
43
+ UpsertRecordsBranchProviderRejected,
44
+ UpsertRecordsBranchUpserted,
45
+ UpsertRecordsDefinition,
46
+ UpsertRecordsInputSchema,
47
+ UpsertRecordsMetadata,
48
+ UpsertedRecordsSchema,
49
+ newConnection,
50
+ newConnectionWithOperations,
51
+ newProjectConnection
52
+ } from "./chunk-T4RPDDJS.js";
53
+
54
+ // src/generated/steps.ts
55
+ import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
56
+ function newListRecordsStep(configuration) {
57
+ const { connection, connectionName, listed, offsetExpired, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
58
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
59
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listRecords(), connection: connection.reference, branches: [
60
+ goToBranch("listed", listed),
61
+ ...offsetExpired ? [goToBranch("offsetExpired", offsetExpired)] : [],
62
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
63
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
64
+ ...defect ? [goToBranch("defect", defect)] : []
65
+ ] });
66
+ }
67
+ function newGetRecordStep(configuration) {
68
+ const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
69
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
70
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.getRecord(), connection: connection.reference, branches: [
71
+ goToBranch("found", found),
72
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
73
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
74
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
75
+ ...defect ? [goToBranch("defect", defect)] : []
76
+ ] });
77
+ }
78
+ function newUpsertRecordsStep(configuration) {
79
+ const { connection, connectionName, upserted, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
80
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
81
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.upsertRecords(), connection: connection.reference, branches: [
82
+ goToBranch("upserted", upserted),
83
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
84
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
85
+ ...defect ? [goToBranch("defect", defect)] : []
86
+ ] });
87
+ }
88
+ function newUpdateRecordsStep(configuration) {
89
+ const { connection, connectionName, updated, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
90
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
91
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.updateRecords(), connection: connection.reference, branches: [
92
+ goToBranch("updated", updated),
93
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
94
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
95
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
96
+ ...defect ? [goToBranch("defect", defect)] : []
97
+ ] });
98
+ }
99
+
100
+ // src/project.ts
101
+ import { SecretString as SecretString2 } from "@superdurable/connectors-sdk";
102
+ import { z } from "zod";
103
+
104
+ // src/client.ts
105
+ import { BodyTooLargeError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
106
+ import { ReauthorizationRequiredError, SecretString } from "@superdurable/connectors-sdk";
107
+
108
+ // src/operations.ts
109
+ import { newMutationBranch, newMutationRetry, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
110
+ var baseIdPattern = /^app[0-9A-Za-z]{14}$/;
111
+ var recordIdPattern = /^rec[0-9A-Za-z]{14}$/;
112
+ var zeroTime = "0001-01-01T00:00:00Z";
113
+ var zeroRecord = { id: "", createdTime: zeroTime, fields: {} };
114
+ var zeroPage = { records: [] };
115
+ var zeroUpserted = { records: [], createdRecordIds: [], updatedRecordIds: [] };
116
+ var zeroUpdated = { records: [] };
117
+ var ListRecordsOperation = class {
118
+ /** Bind one authenticated client. */
119
+ constructor(client) {
120
+ this.client = client;
121
+ }
122
+ client;
123
+ /** Return the manifest definition. */
124
+ definition() {
125
+ return ListRecordsDefinition;
126
+ }
127
+ /** Validate, send, and classify one list attempt. */
128
+ async invoke(call, input) {
129
+ let requestBody;
130
+ try {
131
+ requestBody = buildListRequest(input);
132
+ } catch (error) {
133
+ return queryDefect("listRecords", zeroPage, error);
134
+ }
135
+ const objectId = `${input.baseId}/${input.tableIdOrName}`;
136
+ const result = await this.client.exchange(call, "listRecords", input.baseId, objectId, "POST", `${recordPath(input)}/listRecords`, requestBody);
137
+ if ("outcome" in result) return queryOutcome(result.outcome, zeroPage, "providerRejected");
138
+ try {
139
+ const body = decodeObject(result.response.body);
140
+ if (!Array.isArray(body.records) || body.records.length > Number(requestBody.pageSize) || !body.records.every(isObject)) throw new Error("Airtable returned an invalid record page");
141
+ const offset = body.offset === void 0 ? "" : requireString(body.offset);
142
+ if (Buffer.byteLength(offset, "utf8") > 1024) throw new Error("Airtable returned an oversized offset");
143
+ const records = body.records.map(decodeRecord);
144
+ const output = { records, ...offset ? { offset } : {}, ...requestBody.filterByFormula ? { filterFormula: String(requestBody.filterByFormula) } : {} };
145
+ return newQueryBranch("listed", output, this.client.receipt(call, objectId));
146
+ } catch {
147
+ return queryFailure("listRecords", "invalidResponse", "PROTOCOL", zeroPage, this.client.receipt(call, objectId));
148
+ }
149
+ }
150
+ };
151
+ var GetRecordOperation = class {
152
+ /** Bind one authenticated client. */
153
+ constructor(client) {
154
+ this.client = client;
155
+ }
156
+ client;
157
+ /** Return the manifest definition. */
158
+ definition() {
159
+ return GetRecordDefinition;
160
+ }
161
+ /** Validate, send, and classify one record read. */
162
+ async invoke(call, input) {
163
+ try {
164
+ validateBaseAndTable(input.baseId, input.tableIdOrName);
165
+ if (!recordIdPattern.test(input.recordId)) throw new Error("recordId must be an Airtable record ID");
166
+ } catch (error) {
167
+ return queryDefect("getRecord", zeroRecord, error);
168
+ }
169
+ const result = await this.client.exchange(call, "getRecord", input.baseId, input.recordId, "GET", `${recordPath(input)}/${encodeURIComponent(input.recordId)}`);
170
+ if ("outcome" in result) return queryOutcome(result.outcome, zeroRecord, "providerRejected", "notFound");
171
+ try {
172
+ const record = decodeRecord(decodeObject(result.response.body));
173
+ if (record.id !== input.recordId) throw new Error("record ID mismatch");
174
+ return newQueryBranch("found", record, this.client.receipt(call, input.recordId));
175
+ } catch {
176
+ return queryFailure("getRecord", "invalidResponse", "PROTOCOL", zeroRecord, this.client.receipt(call, input.recordId));
177
+ }
178
+ }
179
+ };
180
+ var UpsertRecordsOperation = class {
181
+ /** Bind one authenticated client. */
182
+ constructor(client) {
183
+ this.client = client;
184
+ }
185
+ client;
186
+ /** Return the manifest definition. */
187
+ definition() {
188
+ return UpsertRecordsDefinition;
189
+ }
190
+ /** Reuse the Dex Call ID; Airtable does not accept an idempotency header. */
191
+ idempotencyKey(callId) {
192
+ return callId;
193
+ }
194
+ /** Validate and send one repeat-safe merge-field upsert. */
195
+ async invoke(call, input) {
196
+ let requestBody;
197
+ try {
198
+ requestBody = buildUpsertRequest(input);
199
+ } catch (error) {
200
+ return mutationDefect("upsertRecords", zeroUpserted, error);
201
+ }
202
+ const objectId = `${input.baseId}/${input.tableIdOrName}`;
203
+ const result = await this.client.exchange(call, "upsertRecords", input.baseId, objectId, "PATCH", recordPath(input), requestBody);
204
+ if ("outcome" in result) return mutationOutcome(result.outcome, zeroUpserted, "providerRejected");
205
+ try {
206
+ const body = decodeObject(result.response.body);
207
+ if (!Array.isArray(body.records) || body.records.length !== input.records?.length || !Array.isArray(body.createdRecords) || !Array.isArray(body.updatedRecords)) throw new Error("invalid upsert response");
208
+ const records = body.records.map(decodeRecord);
209
+ const createdRecordIds = body.createdRecords.map(requireString);
210
+ const updatedRecordIds = body.updatedRecords.map(requireString);
211
+ const writtenIds = new Set(records.map((record) => record.id));
212
+ if ([...createdRecordIds, ...updatedRecordIds].some((id) => !writtenIds.has(id)) || createdRecordIds.some((id) => updatedRecordIds.includes(id))) throw new Error("invalid upsert IDs");
213
+ const partialSuccessReasons = decodePartialSuccessReasons(body.details);
214
+ return newMutationBranch("upserted", { records, createdRecordIds, updatedRecordIds, ...partialSuccessReasons.length ? { partialSuccessReasons } : {} }, this.client.receipt(call, objectId));
215
+ } catch {
216
+ return mutationFailure("upsertRecords", "invalidResponse", "PROTOCOL", zeroUpserted, this.client.receipt(call, objectId));
217
+ }
218
+ }
219
+ };
220
+ var UpdateRecordsOperation = class {
221
+ /** Bind one authenticated client. */
222
+ constructor(client) {
223
+ this.client = client;
224
+ }
225
+ client;
226
+ /** Return the manifest definition. */
227
+ definition() {
228
+ return UpdateRecordsDefinition;
229
+ }
230
+ /** Reuse the Dex Call ID; absolute replacement makes retries safe. */
231
+ idempotencyKey(callId) {
232
+ return callId;
233
+ }
234
+ /** Validate and send one repeat-safe update by record ID. */
235
+ async invoke(call, input) {
236
+ let requestBody;
237
+ try {
238
+ requestBody = buildUpdateRequest(input);
239
+ } catch (error) {
240
+ return mutationDefect("updateRecords", zeroUpdated, error);
241
+ }
242
+ const objectId = `${input.baseId}/${input.tableIdOrName}`;
243
+ const result = await this.client.exchange(call, "updateRecords", input.baseId, objectId, "PATCH", recordPath(input), requestBody);
244
+ if ("outcome" in result) return mutationOutcome(result.outcome, zeroUpdated, "providerRejected", "notFound");
245
+ try {
246
+ const body = decodeObject(result.response.body);
247
+ if (!Array.isArray(body.records) || body.records.length !== input.records?.length) throw new Error("invalid update response");
248
+ const records = body.records.map(decodeRecord);
249
+ const requestedIds = new Set(input.records.map((record) => record.id));
250
+ if (records.some((record) => !requestedIds.has(record.id))) throw new Error("unexpected updated record");
251
+ const partialSuccessReasons = decodePartialSuccessReasons(body.details);
252
+ return newMutationBranch("updated", { records, ...partialSuccessReasons.length ? { partialSuccessReasons } : {} }, this.client.receipt(call, objectId));
253
+ } catch {
254
+ return mutationFailure("updateRecords", "invalidResponse", "PROTOCOL", zeroUpdated, this.client.receipt(call, objectId));
255
+ }
256
+ }
257
+ };
258
+ function queryOutcome(outcome, zero, rejectedBranch, notFoundBranch = rejectedBranch) {
259
+ if (outcome.disposition === "retry") return newQueryRetry(outcome.failure, outcome.retryAfterMs);
260
+ const branch = outcome.disposition === "notFound" ? notFoundBranch : outcome.disposition === "offsetExpired" ? "offsetExpired" : outcome.disposition === "rejected" ? rejectedBranch : outcome.disposition;
261
+ return newQueryBranch(branch, zero, outcome.receipt, outcome.failure);
262
+ }
263
+ function mutationOutcome(outcome, zero, rejectedBranch, notFoundBranch = rejectedBranch) {
264
+ if (outcome.disposition === "retry") return newMutationRetry(outcome.failure, outcome.retryAfterMs);
265
+ const branch = outcome.disposition === "notFound" ? notFoundBranch : outcome.disposition === "rejected" || outcome.disposition === "offsetExpired" ? rejectedBranch : outcome.disposition;
266
+ return newMutationBranch(branch, zero, outcome.receipt, outcome.failure);
267
+ }
268
+ function queryDefect(operation, zero, error) {
269
+ return queryFailure(operation, "defect", "VALIDATION", zero, {}, error);
270
+ }
271
+ function mutationDefect(operation, zero, error) {
272
+ return mutationFailure(operation, "defect", "VALIDATION", zero, {}, error);
273
+ }
274
+ function queryFailure(operation, branch, kind, zero, receipt, error) {
275
+ return newQueryBranch(branch, zero, receipt, { kind, provider: "airtable", operation, message: error instanceof Error ? error.message : "Airtable response is invalid" });
276
+ }
277
+ function mutationFailure(operation, branch, kind, zero, receipt, error) {
278
+ return newMutationBranch(branch, zero, receipt, { kind, provider: "airtable", operation, message: error instanceof Error ? error.message : "Airtable response is invalid" });
279
+ }
280
+ function validateIdentifier(label, value) {
281
+ if (!value) throw new Error(`${label} is required`);
282
+ if (Buffer.byteLength(value, "utf8") > 1e3 || /[\p{Cc}\p{Cf}]/u.test(value)) throw new Error(`${label} is invalid`);
283
+ }
284
+ function validateBaseAndTable(baseId, table) {
285
+ if (!baseIdPattern.test(baseId)) throw new Error("baseId must be an Airtable base ID");
286
+ validateIdentifier("tableIdOrName", table);
287
+ }
288
+ function recordPath(input) {
289
+ return `/v0/${encodeURIComponent(input.baseId)}/${encodeURIComponent(input.tableIdOrName)}`;
290
+ }
291
+ function buildListRequest(input) {
292
+ validateBaseAndTable(input.baseId, input.tableIdOrName);
293
+ const pageSize = input.pageSize || 100;
294
+ if (!Number.isInteger(pageSize) || pageSize < 1 || pageSize > 100) throw new Error("pageSize must be between 1 and 100");
295
+ if (Buffer.byteLength(input.offset ?? "", "utf8") > 1024) throw new Error("offset is too long");
296
+ const filterByFormula = buildFilterFormula(input.filters ?? [], input.formula ?? "");
297
+ if ((input.fields?.length ?? 0) > 500) throw new Error("too many fields");
298
+ const fields = uniqueIdentifiers("fields", input.fields ?? []);
299
+ if ((input.sort?.length ?? 0) > 10) throw new Error("too many sort entries");
300
+ input.sort?.forEach((sort, index) => {
301
+ validateIdentifier(`sort[${index}].field`, sort.field);
302
+ if (sort.direction && sort.direction !== "asc" && sort.direction !== "desc") throw new Error("sort direction is invalid");
303
+ });
304
+ if (input.viewIdOrName) validateIdentifier("viewIdOrName", input.viewIdOrName);
305
+ return {
306
+ pageSize,
307
+ ...input.offset ? { offset: input.offset } : {},
308
+ ...filterByFormula ? { filterByFormula } : {},
309
+ ...fields.length ? { fields } : {},
310
+ ...input.sort?.length ? { sort: input.sort.map((sort) => ({ field: sort.field, ...sort.direction ? { direction: sort.direction } : {} })) } : {},
311
+ ...input.viewIdOrName ? { view: input.viewIdOrName } : {}
312
+ };
313
+ }
314
+ function buildFilterFormula(filters, rawFormula) {
315
+ if (filters.length > 25 || Buffer.byteLength(rawFormula, "utf8") > 16e3) throw new Error("filter formula is too long");
316
+ const conditions = filters.map(filterCondition);
317
+ if (rawFormula.trim()) conditions.push(`(${rawFormula})`);
318
+ const formula = conditions.length === 0 ? "" : conditions.length === 1 ? conditions[0] : `AND(${conditions.join(", ")})`;
319
+ if (Buffer.byteLength(formula, "utf8") > 16e3) throw new Error("filter formula is too long");
320
+ return formula;
321
+ }
322
+ function filterCondition(filter) {
323
+ validateIdentifier("field", filter.field);
324
+ if (/[{}\\]/.test(filter.field)) throw new Error("field name cannot contain braces or a backslash");
325
+ const selected = [filter.text !== void 0, filter.number !== void 0, filter.checkbox !== void 0].filter(Boolean).length;
326
+ if (selected !== 1) throw new Error("exactly one filter value is required");
327
+ const field = `{${filter.field}}`;
328
+ if (filter.text !== void 0) {
329
+ if (/[\\\p{Cc}\p{Cf}]/u.test(filter.text)) throw new Error("text filter is invalid");
330
+ return `${field} = "${filter.text.replaceAll('"', '\\"')}"`;
331
+ }
332
+ if (filter.number !== void 0) {
333
+ if (!Number.isFinite(filter.number)) throw new Error("number filter must be finite");
334
+ return `${field} = ${filter.number}`;
335
+ }
336
+ return filter.checkbox ? `${field} = TRUE()` : `NOT(${field})`;
337
+ }
338
+ function uniqueIdentifiers(label, values) {
339
+ values.forEach((value, index) => validateIdentifier(`${label}[${index}]`, value));
340
+ return [...new Set(values)];
341
+ }
342
+ function validateWrittenFields(label, fields) {
343
+ if (!fields || Object.keys(fields).length < 1 || Object.keys(fields).length > 500) throw new Error(`${label} needs 1 to 500 fields`);
344
+ for (const key of Object.keys(fields)) {
345
+ validateIdentifier("field name", key);
346
+ if (fields[key] === void 0) throw new Error(`${label} has an undefined cell value`);
347
+ try {
348
+ JSON.stringify(fields[key]);
349
+ } catch {
350
+ throw new Error(`${label} has an invalid cell value`);
351
+ }
352
+ }
353
+ }
354
+ function buildUpsertRequest(input) {
355
+ validateBaseAndTable(input.baseId, input.tableIdOrName);
356
+ if (!input.fieldsToMergeOn || input.fieldsToMergeOn.length < 1 || input.fieldsToMergeOn.length > 3) throw new Error("fieldsToMergeOn must name 1 to 3 fields");
357
+ const mergeFields = uniqueIdentifiers("fieldsToMergeOn", input.fieldsToMergeOn);
358
+ if (mergeFields.length !== input.fieldsToMergeOn.length) throw new Error("fieldsToMergeOn cannot repeat a field");
359
+ if (!input.records || input.records.length < 1 || input.records.length > 10) throw new Error("records must hold 1 to 10 records");
360
+ const seen = /* @__PURE__ */ new Set();
361
+ const records = input.records.map((record, index) => {
362
+ const fields = record.fields;
363
+ validateWrittenFields(`records[${index}]`, fields);
364
+ const key = mergeFields.map((field) => {
365
+ if (!(field in fields) || fields[field] === null) throw new Error("merge field needs a non-null value");
366
+ return JSON.stringify(fields[field]);
367
+ }).join("\0");
368
+ if (seen.has(key)) throw new Error("records repeat merge values");
369
+ seen.add(key);
370
+ return { fields };
371
+ });
372
+ return { performUpsert: { fieldsToMergeOn: mergeFields }, records, ...input.typecast ? { typecast: true } : {} };
373
+ }
374
+ function buildUpdateRequest(input) {
375
+ validateBaseAndTable(input.baseId, input.tableIdOrName);
376
+ if (!input.records || input.records.length < 1 || input.records.length > 10) throw new Error("records must hold 1 to 10 records");
377
+ const seen = /* @__PURE__ */ new Set();
378
+ const records = input.records.map((record, index) => {
379
+ if (!recordIdPattern.test(record.id) || seen.has(record.id)) throw new Error("record ID is invalid or repeated");
380
+ seen.add(record.id);
381
+ validateWrittenFields(`records[${index}]`, record.fields);
382
+ return { id: record.id, fields: record.fields };
383
+ });
384
+ return { records, ...input.typecast ? { typecast: true } : {} };
385
+ }
386
+ function decodeObject(body) {
387
+ const document = JSON.parse(Buffer.from(body).toString("utf8"));
388
+ if (!isObject(document)) throw new Error("response is not an object");
389
+ return document;
390
+ }
391
+ function isObject(value) {
392
+ return value !== null && typeof value === "object" && !Array.isArray(value);
393
+ }
394
+ function requireString(value) {
395
+ if (typeof value !== "string") throw new Error("expected string");
396
+ return value;
397
+ }
398
+ function decodeRecord(value) {
399
+ if (!isObject(value) || typeof value.id !== "string" || !recordIdPattern.test(value.id) || typeof value.createdTime !== "string") throw new Error("record is invalid");
400
+ const timestamp = Date.parse(value.createdTime);
401
+ if (!Number.isFinite(timestamp)) throw new Error("createdTime is invalid");
402
+ const fields = value.fields === void 0 || value.fields === null ? {} : value.fields;
403
+ if (!isObject(fields)) throw new Error("fields are invalid");
404
+ const createdTime = new Date(timestamp).toISOString().replace(/\.000Z$/, "Z");
405
+ return { id: value.id, createdTime, fields };
406
+ }
407
+ function decodePartialSuccessReasons(value) {
408
+ if (!isObject(value) || value.message !== "partialSuccess" || !Array.isArray(value.reasons)) return [];
409
+ const allowed = /* @__PURE__ */ new Set(["attachmentsFailedUploading", "attachmentUploadRateIsTooHigh"]);
410
+ return [...new Set(value.reasons.filter((reason) => typeof reason === "string" && allowed.has(reason)))];
411
+ }
412
+
413
+ // src/client.ts
414
+ var defaultEndpoint = "https://api.airtable.com";
415
+ var defaultMaxResponseBytes = 4194304;
416
+ var requestTimeoutMs = 25e3;
417
+ var rateLimitCooldownMs = 3e4;
418
+ var AirtableClient = class {
419
+ endpoint;
420
+ maxResponseBytes;
421
+ credentials;
422
+ send;
423
+ now;
424
+ nextRequestAt = /* @__PURE__ */ new Map();
425
+ /** Construct one client without contacting Airtable. */
426
+ constructor(config, credentials, options = {}) {
427
+ if (!credentials) throw new TypeError("Airtable credential provider is required");
428
+ this.endpoint = validateBaseURL(config.endpoint || defaultEndpoint);
429
+ this.maxResponseBytes = config.maxResponseBytes || defaultMaxResponseBytes;
430
+ if (!Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0) throw new TypeError("Airtable maxResponseBytes must be positive");
431
+ this.credentials = credentials;
432
+ this.send = options.send ?? sendProviderRequest;
433
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
434
+ }
435
+ /** Bind the list query. */
436
+ listRecords() {
437
+ return new ListRecordsOperation(this);
438
+ }
439
+ /** Bind the record query. */
440
+ getRecord() {
441
+ return new GetRecordOperation(this);
442
+ }
443
+ /** Bind the upsert mutation. */
444
+ upsertRecords() {
445
+ return new UpsertRecordsOperation(this);
446
+ }
447
+ /** Bind the update mutation. */
448
+ updateRecords() {
449
+ return new UpdateRecordsOperation(this);
450
+ }
451
+ /** Produce one safe receipt after an exchange. */
452
+ receipt(call, objectId) {
453
+ return {
454
+ callId: call.id,
455
+ provider: "airtable",
456
+ observedAt: this.now().toISOString(),
457
+ ...call.idempotencyKey ? { idempotencyKey: call.idempotencyKey } : {},
458
+ ...objectId ? { providerObjectId: objectId } : {}
459
+ };
460
+ }
461
+ /** Resolve credentials, pace one base, send a bounded request, and classify non-2xx responses. */
462
+ async exchange(call, operation, baseId, objectId, method, path, body) {
463
+ const slot = this.reserveRequestSlot(baseId);
464
+ if (slot > 2e3) return { outcome: this.failure("retry", operation, "RATE_LIMIT", "Airtable requests to this base are paced to its rate limit", {}, slot) };
465
+ if (slot > 0) {
466
+ try {
467
+ await waitForSlot(slot, call.context.cancellationSignal);
468
+ } catch {
469
+ return { outcome: this.failure("retry", operation, "AVAILABILITY", "the Step ended while waiting for an Airtable request slot") };
470
+ }
471
+ }
472
+ let token;
473
+ try {
474
+ const credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
475
+ if (!(credentials.personalAccessToken instanceof SecretString)) throw new TypeError("invalid Airtable token");
476
+ token = credentials.personalAccessToken.reveal();
477
+ if (!isHeaderSafeCredential(token)) throw new TypeError("invalid Airtable token");
478
+ } catch (error) {
479
+ if (error instanceof ReauthorizationRequiredError) return { outcome: this.failure("rejected", operation, "AUTHENTICATION", "the Airtable connection must be authorized again") };
480
+ return { outcome: this.failure("defect", operation, "AUTHENTICATION", "Airtable connection credentials are unavailable") };
481
+ }
482
+ let encoded;
483
+ try {
484
+ if (body !== void 0) encoded = Buffer.from(JSON.stringify(body), "utf8");
485
+ } catch {
486
+ return { outcome: this.failure("defect", operation, "LOCAL_DEFECT", `${operation} request could not be encoded`) };
487
+ }
488
+ const receipt = this.receipt(call, objectId);
489
+ let response;
490
+ try {
491
+ response = await this.send({
492
+ url: this.endpoint + path,
493
+ method,
494
+ headers: { Accept: "application/json", Authorization: `Bearer ${token}`, ...encoded ? { "Content-Type": "application/json" } : {} },
495
+ ...encoded ? { body: encoded } : {},
496
+ maxResponseBytes: this.maxResponseBytes,
497
+ addressPolicy: this.endpoint === defaultEndpoint ? "publicHTTPS" : "privateNetworkHTTP",
498
+ timeoutMs: requestTimeoutMs,
499
+ signal: call.context.cancellationSignal
500
+ });
501
+ } catch (error) {
502
+ if (error instanceof BodyTooLargeError) return { outcome: this.failure("invalidResponse", operation, "RESPONSE_TOO_LARGE", "Airtable response exceeds the configured size limit", receipt) };
503
+ return { outcome: this.failure("retry", operation, "TRANSPORT", "Airtable did not return a complete response", receipt) };
504
+ }
505
+ if (response.status >= 200 && response.status < 300) return { response };
506
+ return { outcome: this.classifyResponse(operation, baseId, response, receipt) };
507
+ }
508
+ reserveRequestSlot(baseId) {
509
+ const now = this.now().getTime();
510
+ const slot = Math.max(now, this.nextRequestAt.get(baseId) ?? now);
511
+ const delay = slot - now;
512
+ if (delay <= 2e3) this.nextRequestAt.set(baseId, slot + 200);
513
+ return delay;
514
+ }
515
+ classifyResponse(operation, baseId, response, receipt) {
516
+ const status = response.status;
517
+ const retryAfterMs = parseRetryAfter(header(response, "retry-after"), this.now());
518
+ if (status === 429) {
519
+ this.nextRequestAt.set(baseId, Math.max(this.nextRequestAt.get(baseId) ?? 0, this.now().getTime() + rateLimitCooldownMs));
520
+ return this.failure("retry", operation, "RATE_LIMIT", "Airtable rate limited requests to this base", receipt, Math.max(retryAfterMs, rateLimitCooldownMs));
521
+ }
522
+ if (status === 408 || status >= 500 && status !== 501) return this.failure("retry", operation, "AVAILABILITY", "Airtable is temporarily unavailable", receipt, retryAfterMs);
523
+ const errorType = readErrorType(response.body);
524
+ if (status === 422 && errorType === "LIST_RECORDS_ITERATOR_NOT_AVAILABLE") return this.failure("offsetExpired", operation, "NOT_FOUND", "Airtable no longer recognizes the list offset", receipt);
525
+ if (status === 404) return this.failure("notFound", operation, "NOT_FOUND", "Airtable found no such record or route", receipt);
526
+ if (status === 401) return this.failure("rejected", operation, "AUTHENTICATION", "Airtable rejected the personal access token", receipt);
527
+ if (status === 403) return this.failure("rejected", operation, "AUTHORIZATION", "Airtable denied access", receipt);
528
+ if (status === 400 || status === 413 || status === 422) return this.failure("rejected", operation, "VALIDATION", "Airtable rejected the request as invalid", receipt);
529
+ if (status >= 300 && status < 400) return this.failure("rejected", operation, "PROTOCOL", "Airtable redirected the request", receipt);
530
+ return this.failure("rejected", operation, "PROVIDER_REJECTION", "Airtable rejected the request", receipt);
531
+ }
532
+ failure(disposition, operation, kind, message, receipt = {}, retryAfterMs = 0) {
533
+ return { disposition, failure: { kind, provider: "airtable", operation, message }, receipt, retryAfterMs };
534
+ }
535
+ };
536
+ function header(response, name) {
537
+ const value = response.headers[name];
538
+ return Array.isArray(value) ? value[0] ?? "" : value ?? "";
539
+ }
540
+ function readErrorType(body) {
541
+ if (body.length > 65536) return "";
542
+ try {
543
+ const decoded = JSON.parse(Buffer.from(body).toString("utf8"));
544
+ if (!decoded || typeof decoded !== "object" || !("error" in decoded)) return "";
545
+ const value = decoded.error;
546
+ const candidate = typeof value === "string" ? value : value && typeof value === "object" && "type" in value ? value.type : void 0;
547
+ return typeof candidate === "string" && /^[A-Z][A-Z0-9_]{1,63}$/.test(candidate) ? candidate : "";
548
+ } catch {
549
+ return "";
550
+ }
551
+ }
552
+ function waitForSlot(delayMs, signal) {
553
+ return new Promise((resolve, reject) => {
554
+ const timer = setTimeout(resolve, delayMs);
555
+ signal?.addEventListener("abort", () => {
556
+ clearTimeout(timer);
557
+ reject(new Error("cancelled"));
558
+ }, { once: true });
559
+ });
560
+ }
561
+
562
+ // src/project.ts
563
+ function newProjectConnection2(project, connectionName) {
564
+ return newProjectConnection(project, connectionName, (loadedProject, name) => {
565
+ const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "airtable" && entry.connectionName === name);
566
+ if (!selected) throw new TypeError("Airtable project connection is not configured");
567
+ const config = z.object({ endpoint: z.string().optional(), maxResponseBytes: z.number().int().optional() }).parse(selected.configuration);
568
+ const credentials = {
569
+ async resolve(call, signal) {
570
+ void call;
571
+ const fields = await loadedProject.resolveCredential("airtable", name, signal);
572
+ const decoded = z.object({ personal_access_token: z.string().min(1) }).parse(fields);
573
+ return { personalAccessToken: new SecretString2(decoded.personal_access_token) };
574
+ }
575
+ };
576
+ return new AirtableClient(config, credentials);
577
+ });
578
+ }
579
+ export {
580
+ AirtableClient,
581
+ ConfigSchema,
582
+ Connection,
583
+ ConnectorID,
584
+ FieldEqualityFilterSchema,
585
+ GetRecordBranch,
586
+ GetRecordBranchDefect,
587
+ GetRecordBranchFound,
588
+ GetRecordBranchInvalidResponse,
589
+ GetRecordBranchNotFound,
590
+ GetRecordBranchProviderRejected,
591
+ GetRecordDefinition,
592
+ GetRecordInputSchema,
593
+ GetRecordMetadata,
594
+ GetRecordOperation,
595
+ ListRecordsBranch,
596
+ ListRecordsBranchDefect,
597
+ ListRecordsBranchInvalidResponse,
598
+ ListRecordsBranchListed,
599
+ ListRecordsBranchOffsetExpired,
600
+ ListRecordsBranchProviderRejected,
601
+ ListRecordsDefinition,
602
+ ListRecordsInputSchema,
603
+ ListRecordsMetadata,
604
+ ListRecordsOperation,
605
+ ProviderID,
606
+ RecordPageSchema,
607
+ RecordSchema,
608
+ RecordSortSchema,
609
+ RecordUpdateSchema,
610
+ RecordUpsertSchema,
611
+ UpdateRecordsBranch,
612
+ UpdateRecordsBranchDefect,
613
+ UpdateRecordsBranchInvalidResponse,
614
+ UpdateRecordsBranchNotFound,
615
+ UpdateRecordsBranchProviderRejected,
616
+ UpdateRecordsBranchUpdated,
617
+ UpdateRecordsDefinition,
618
+ UpdateRecordsInputSchema,
619
+ UpdateRecordsMetadata,
620
+ UpdateRecordsOperation,
621
+ UpdatedRecordsSchema,
622
+ UpsertRecordsBranch,
623
+ UpsertRecordsBranchDefect,
624
+ UpsertRecordsBranchInvalidResponse,
625
+ UpsertRecordsBranchProviderRejected,
626
+ UpsertRecordsBranchUpserted,
627
+ UpsertRecordsDefinition,
628
+ UpsertRecordsInputSchema,
629
+ UpsertRecordsMetadata,
630
+ UpsertRecordsOperation,
631
+ UpsertedRecordsSchema,
632
+ newConnection,
633
+ newConnectionWithOperations,
634
+ newGetRecordStep,
635
+ newListRecordsStep,
636
+ newProjectConnection2 as newProjectConnection,
637
+ newUpdateRecordsStep,
638
+ newUpsertRecordsStep
639
+ };