@zapier/zapier-sdk 0.77.2 → 0.78.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.mjs CHANGED
@@ -50,6 +50,7 @@ function canonicalInputSchema(schema) {
50
50
  function buildRegistry({
51
51
  sdk,
52
52
  meta,
53
+ formatters,
53
54
  packageFilter
54
55
  }) {
55
56
  const definitionsByKey = /* @__PURE__ */ new Map();
@@ -90,7 +91,7 @@ function buildRegistry({
90
91
  (c) => typeof c === "string" ? c : c.key
91
92
  ),
92
93
  resolvers: m.resolvers,
93
- formatter: m.formatter,
94
+ formatter: formatters?.[key],
94
95
  experimental: m.experimental,
95
96
  packages: m.packages,
96
97
  confirm: m.confirm ?? (m.type === "delete" ? "delete" : void 0),
@@ -516,8 +517,8 @@ function normalizeError(error, adaptError) {
516
517
  );
517
518
  }
518
519
  function createFunction(coreFn, options) {
519
- const { sdk, schema } = options;
520
- const functionName = coreFn.name;
520
+ const { sdk, schema, name } = options;
521
+ const functionName = name || coreFn.name;
521
522
  const namedFunctions = {
522
523
  [functionName]: async function(callOptions) {
523
524
  return runInMethodScope(async () => {
@@ -692,9 +693,6 @@ function createPaginatedFunction(coreFn, options) {
692
693
  };
693
694
  return namedFunctions[functionName];
694
695
  }
695
- function definePlugin(fn) {
696
- return fn;
697
- }
698
696
  function createPluginMethod(sdk, config) {
699
697
  const { name, inputSchema, handler, ...metaFields } = config;
700
698
  const namedHandlers = {
@@ -763,8 +761,7 @@ function splitPluginContribution(result) {
763
761
  }
764
762
  var RESERVED_ROOT_KEYS = /* @__PURE__ */ new Set([
765
763
  "context",
766
- "getRegistry",
767
- "addPlugin"
764
+ "getRegistry"
768
765
  ]);
769
766
  function hasOwn(obj, key) {
770
767
  return Object.prototype.hasOwnProperty.call(obj, key);
@@ -778,15 +775,28 @@ function setOwn(target, key, value) {
778
775
  });
779
776
  }
780
777
  function checkCollisions(target, source, kind, callerLabel, override) {
778
+ if (kind === "root key") {
779
+ checkRootKeyCollisions(target, Object.keys(source), override, callerLabel);
780
+ return;
781
+ }
781
782
  for (const key of Object.keys(source)) {
782
- if (kind === "root key" && RESERVED_ROOT_KEYS.has(key)) {
783
+ if (!override && hasOwn(target, key)) {
784
+ throw new Error(
785
+ `${callerLabel}: duplicate ${kind} "${key}". If the override is intentional, pass { override: true } in the options.`
786
+ );
787
+ }
788
+ }
789
+ }
790
+ function checkRootKeyCollisions(target, keys, override, callerLabel) {
791
+ for (const key of keys) {
792
+ if (RESERVED_ROOT_KEYS.has(key)) {
783
793
  throw new Error(
784
794
  `${callerLabel}: plugin attempted to register reserved root key "${key}". The SDK uses this key for its own accessor; rename the plugin's method.`
785
795
  );
786
796
  }
787
797
  if (!override && hasOwn(target, key)) {
788
798
  throw new Error(
789
- `${callerLabel}: duplicate ${kind} "${key}". If the override is intentional, pass { override: true } in the options.`
799
+ `${callerLabel}: duplicate root key "${key}". If the override is intentional, pass { override: true } in the options.`
790
800
  );
791
801
  }
792
802
  }
@@ -837,7 +847,7 @@ function mergeContribution(propertiesTarget, contextTarget, contribution, option
837
847
  function applyPluginContribution(acc, contribution, options) {
838
848
  mergeContribution(acc.view, acc.context, contribution, options);
839
849
  }
840
- function wrapAsSdk(properties, context, opts) {
850
+ function wrapAsSdk(properties, context) {
841
851
  const sdk = {
842
852
  ...properties,
843
853
  context,
@@ -849,9 +859,6 @@ function wrapAsSdk(properties, context, opts) {
849
859
  });
850
860
  }
851
861
  };
852
- if (opts?.addPlugin !== void 0) {
853
- sdk.addPlugin = opts.addPlugin;
854
- }
855
862
  return sdk;
856
863
  }
857
864
  function wrapAccumulatorAsSdk(acc) {
@@ -870,126 +877,92 @@ function applyPluginToSdk(sdk, plugin, options) {
870
877
  callerLabel: "addPlugin",
871
878
  override: options.override === true
872
879
  });
880
+ return contribution;
873
881
  }
874
- function buildStackAccumulator(head, callerLabel) {
875
- const ordered = [];
882
+ function resolveStack(head) {
883
+ const entries = [];
876
884
  let node = head;
877
885
  while (node) {
878
- ordered.unshift(node);
886
+ entries.unshift({ apply: node.entry, override: node.override });
879
887
  node = node.prev;
880
888
  }
881
- const acc = createPluginAccumulator();
882
- for (const { plugin, override } of ordered) {
883
- const contribution = splitPluginContribution(
884
- plugin(acc.view)
885
- );
886
- applyPluginContribution(acc, contribution, { callerLabel, override });
887
- }
888
- return acc;
889
- }
890
- function addPlugin(sdk, plugin, options) {
891
- applyPluginToSdk(
892
- sdk,
893
- plugin,
894
- options ?? {}
895
- );
889
+ return entries;
890
+ }
891
+ function composeStackHooks(hooks) {
892
+ let composed = {};
893
+ for (const h of hooks) composed = buildHooks(composed, h);
894
+ return composed;
895
+ }
896
+ function collapseStackEntries(entries, callerLabel) {
897
+ return (outerSdk) => {
898
+ const { context: outerContext, ...outerProperties } = outerSdk ?? {};
899
+ const viewAcc = createPluginAccumulator(outerProperties, outerContext);
900
+ const contribsAcc = createPluginAccumulator();
901
+ const hooks = [];
902
+ for (const { apply, override } of entries) {
903
+ const contribution = splitPluginContribution(
904
+ apply(viewAcc.view)
905
+ );
906
+ const hookless = { ...contribution, hooks: {} };
907
+ applyPluginContribution(viewAcc, hookless, { callerLabel, override });
908
+ applyPluginContribution(contribsAcc, hookless, { callerLabel, override });
909
+ hooks.push(contribution.hooks);
910
+ }
911
+ const stackHooks = composeStackHooks(hooks);
912
+ viewAcc.context.hooks = buildHooks(viewAcc.context.hooks, stackHooks);
913
+ contribsAcc.context.hooks = stackHooks;
914
+ const { context: _ignored, ...contributedRoot } = contribsAcc.view;
915
+ return {
916
+ ...contributedRoot,
917
+ context: contribsAcc.context
918
+ };
919
+ };
896
920
  }
897
- function buildSdk(properties, context) {
898
- const addPlugin2 = (plugin, options) => {
899
- logDeprecation(
900
- "sdk.addPlugin(plugin) (the chain-style extension) is deprecated. Build the SDK in one pass with createPluginStack().use(...).toSdk() instead \u2014 each .toSdk() produces fresh plugin closures and avoids the closure-sharing semantics that caused this to be deprecated."
901
- );
921
+ function buildStackAccumulator(head, callerLabel) {
922
+ const entries = resolveStack(head);
923
+ const acc = createPluginAccumulator();
924
+ const hooks = [];
925
+ for (const { apply, override } of entries) {
902
926
  const contribution = splitPluginContribution(
903
- plugin({ ...properties, context })
927
+ apply(acc.view)
904
928
  );
905
- const mergedProperties = { ...properties };
906
- const mergedContext = {
907
- ...context,
908
- meta: { ...context.meta },
909
- hooks: { ...context.hooks }
910
- };
911
- mergeContribution(mergedProperties, mergedContext, contribution, {
912
- callerLabel: "addPlugin",
913
- override: options?.override === true
914
- });
915
- return buildSdk(
916
- mergedProperties,
917
- mergedContext
929
+ applyPluginContribution(
930
+ acc,
931
+ { ...contribution, hooks: {} },
932
+ { callerLabel, override }
918
933
  );
919
- };
920
- return wrapAsSdk(properties, context, { addPlugin: addPlugin2 });
921
- }
922
- function withDeprecatedAddPlugin(sdk) {
923
- const initialProperties = {};
924
- for (const key of Object.keys(sdk)) {
925
- if (key === "context" || key === "getRegistry" || key === "addPlugin") {
926
- continue;
927
- }
928
- initialProperties[key] = sdk[key];
934
+ hooks.push(contribution.hooks);
929
935
  }
930
- const initialContext = sdk.context;
931
- return buildSdk(
932
- initialProperties,
933
- initialContext
934
- );
936
+ acc.context.hooks = composeStackHooks(hooks);
937
+ return acc;
935
938
  }
936
939
  function composePlugins(...plugins) {
937
940
  logDeprecation(
938
- "composePlugins(...) is deprecated. Use createPluginStack().use(a).use(b).use(c).toPlugin() instead. The stack carries the same collision-detection and hook-composition behavior, supports per-step { override: true } for intentional duplicates, and progressively narrows types so dependency mistakes surface at the specific .use call."
939
- );
940
- let stack = buildPluginStack(
941
- null,
942
- "composePlugins"
941
+ "composePlugins(...) is deprecated. Use createPluginStack().use(a).use(b).use(c).toPlugin({ name }) instead. The stack carries the same collision-detection and hook-composition behavior and supports per-step { override: true } for intentional duplicates."
943
942
  );
943
+ let head = null;
944
944
  for (const plugin of plugins) {
945
- stack = stack.use(plugin);
945
+ head = { entry: plugin, override: false, prev: head };
946
946
  }
947
- return stack.toPlugin();
947
+ const entries = resolveStack(head);
948
+ return collapseStackEntries(entries, "composePlugins");
948
949
  }
949
950
  function createPluginStack() {
950
951
  return buildPluginStack(null, "createPluginStack");
951
952
  }
952
953
  function buildPluginStack(head, callerLabel) {
953
- return {
954
+ const stack = {
954
955
  use(plugin, options) {
955
956
  const next = {
956
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
957
- plugin,
957
+ entry: plugin,
958
958
  override: options?.override === true,
959
959
  prev: head
960
960
  };
961
961
  return buildPluginStack(next, callerLabel);
962
962
  },
963
963
  toPlugin() {
964
- const ordered = [];
965
- let node = head;
966
- while (node) {
967
- ordered.unshift(node);
968
- node = node.prev;
969
- }
970
- return (outerSdk) => {
971
- const { context: outerContext, ...outerProperties } = outerSdk ?? {};
972
- const viewAcc = createPluginAccumulator(outerProperties, outerContext);
973
- const contribsAcc = createPluginAccumulator();
974
- for (const { plugin: subPlugin, override } of ordered) {
975
- const contribution = splitPluginContribution(
976
- subPlugin(viewAcc.view)
977
- );
978
- applyPluginContribution(viewAcc, contribution, {
979
- callerLabel,
980
- override
981
- });
982
- applyPluginContribution(contribsAcc, contribution, {
983
- callerLabel,
984
- override
985
- });
986
- }
987
- const { context: _ignored, ...contributedRoot } = contribsAcc.view;
988
- return {
989
- ...contributedRoot,
990
- context: contribsAcc.context
991
- };
992
- };
964
+ const entries = resolveStack(head);
965
+ return collapseStackEntries(entries, callerLabel);
993
966
  },
994
967
  toSdk() {
995
968
  return wrapAccumulatorAsSdk(
@@ -997,419 +970,1304 @@ function buildPluginStack(head, callerLabel) {
997
970
  );
998
971
  }
999
972
  };
973
+ return stack;
974
+ }
975
+ function parseId(id) {
976
+ const at = id.lastIndexOf("/");
977
+ return at === -1 ? { name: id, namespace: void 0 } : { name: id.slice(at + 1), namespace: id.slice(0, at) };
978
+ }
979
+ function makeId(name, namespace, kind = "leaf") {
980
+ validateName(name, kind);
981
+ if (namespace !== void 0) validateNamespace(namespace);
982
+ return namespace ? `${namespace}/${name}` : name;
983
+ }
984
+ var NAME_RE = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
985
+ var SEGMENT_RE = /^@?[A-Za-z0-9._-]+$/;
986
+ function validateName(name, kind) {
987
+ if (name === "") throw new Error("Plugin name must not be empty.");
988
+ if (kind === "leaf") {
989
+ if (!NAME_RE.test(name)) {
990
+ throw new Error(
991
+ `Plugin name "${name}" must be a valid JS identifier (it is the binding name).`
992
+ );
993
+ }
994
+ } else if (!SEGMENT_RE.test(name)) {
995
+ throw new Error(
996
+ `Plugin name "${name}" must be package-like (letters, digits, ".", "_", "-", optional leading "@") with no "/".`
997
+ );
998
+ }
1000
999
  }
1001
- function createCorePlugin(options) {
1002
- return () => ({
1003
- context: {
1004
- core: options
1000
+ function validateNamespace(namespace) {
1001
+ if (namespace === "") throw new Error("Plugin namespace must not be empty.");
1002
+ for (const segment of namespace.split("/")) {
1003
+ if (!SEGMENT_RE.test(segment)) {
1004
+ throw new Error(
1005
+ `Plugin namespace "${namespace}" is invalid: each "/"-separated segment must be package-like (letters, digits, ".", "_", "-", optional leading "@").`
1006
+ );
1005
1007
  }
1006
- });
1008
+ }
1007
1009
  }
1008
- function withPositional(schema) {
1009
- Object.assign(schema._zod.def, {
1010
- positionalMeta: { positional: true }
1011
- });
1012
- return schema;
1010
+ var LEAF_META_KEYS = [
1011
+ "description",
1012
+ "categories",
1013
+ "type",
1014
+ "itemType",
1015
+ "returnType",
1016
+ "outputSchema",
1017
+ "inputParameters",
1018
+ "packages",
1019
+ "experimental",
1020
+ "confirm",
1021
+ "deprecation",
1022
+ "aliases",
1023
+ "supportsJsonOutput"
1024
+ ];
1025
+ function normalizeImports(deps) {
1026
+ if (!deps) return { plugins: [], bindings: [] };
1027
+ const seen = /* @__PURE__ */ new Map();
1028
+ const bindings = [];
1029
+ const add = (binding, id) => {
1030
+ const priorId = seen.get(binding);
1031
+ if (priorId !== void 0 && priorId !== id) {
1032
+ throw new Error(
1033
+ `Import binding "${binding}" is declared twice. Two different plugins ("${priorId}" and "${id}") bind the same name; wrap one in selectExports to rename it.`
1034
+ );
1035
+ }
1036
+ if (priorId === void 0) {
1037
+ seen.set(binding, id);
1038
+ bindings.push({ binding, id });
1039
+ }
1040
+ };
1041
+ for (const plugin of deps) {
1042
+ if (plugin.pluginType === "aggregate") {
1043
+ for (const [binding, child] of Object.entries(plugin.exports)) {
1044
+ add(binding, child.id);
1045
+ }
1046
+ } else {
1047
+ add(plugin.name, plugin.id);
1048
+ }
1049
+ }
1050
+ return { plugins: deps, bindings };
1013
1051
  }
1014
- function schemaHasPositionalMeta(schema) {
1015
- return "positionalMeta" in schema._zod.def;
1052
+ function collectLeafMeta(config) {
1053
+ let meta;
1054
+ for (const key of LEAF_META_KEYS) {
1055
+ if (config[key] !== void 0) (meta ?? (meta = {}))[key] = config[key];
1056
+ }
1057
+ return meta;
1016
1058
  }
1017
- function isPositional(schema) {
1018
- if (schemaHasPositionalMeta(schema) && schema._zod.def.positionalMeta?.positional) {
1019
- return true;
1059
+ function defineMethod(config) {
1060
+ const deps = normalizeImports(config.imports);
1061
+ return {
1062
+ pluginType: "method",
1063
+ name: config.name,
1064
+ namespace: config.namespace,
1065
+ id: makeId(config.name, config.namespace),
1066
+ imports: deps.plugins,
1067
+ importBindings: deps.bindings,
1068
+ inputSchema: config.inputSchema,
1069
+ meta: collectLeafMeta(config),
1070
+ resolvers: config.resolvers,
1071
+ formatter: config.formatter,
1072
+ output: config.output,
1073
+ positional: config.positional,
1074
+ setup: config.setup,
1075
+ run: config.run
1076
+ };
1077
+ }
1078
+ function defineFormatter(config) {
1079
+ const deps = normalizeImports(config.imports);
1080
+ return {
1081
+ imports: deps.plugins,
1082
+ importBindings: deps.bindings,
1083
+ fetchContext: config.fetchContext,
1084
+ format: config.format
1085
+ };
1086
+ }
1087
+ function declareMethod(config) {
1088
+ const { name, namespace } = parseId(config.id);
1089
+ const id = makeId(name, namespace);
1090
+ return {
1091
+ pluginType: "method",
1092
+ name,
1093
+ namespace,
1094
+ id,
1095
+ standIn: true,
1096
+ imports: [],
1097
+ importBindings: [],
1098
+ run: () => {
1099
+ throw new Error(
1100
+ `Plugin "${id}" is a stand-in (declareMethod) with no implementation. Register the real plugin under this id.`
1101
+ );
1102
+ }
1103
+ };
1104
+ }
1105
+ function defineProperty(config) {
1106
+ const deps = normalizeImports(config.imports);
1107
+ return {
1108
+ pluginType: "property",
1109
+ name: config.name,
1110
+ namespace: config.namespace,
1111
+ id: makeId(config.name, config.namespace),
1112
+ imports: deps.plugins,
1113
+ importBindings: deps.bindings,
1114
+ setup: config.setup,
1115
+ value: config.value,
1116
+ get: config.get,
1117
+ meta: collectLeafMeta(config)
1118
+ };
1119
+ }
1120
+ function declareProperty(config) {
1121
+ const { name, namespace } = parseId(config.id);
1122
+ return {
1123
+ pluginType: "property",
1124
+ name,
1125
+ namespace,
1126
+ id: makeId(name, namespace),
1127
+ standIn: true,
1128
+ imports: [],
1129
+ importBindings: []
1130
+ };
1131
+ }
1132
+ function definePlugin(fnOrConfig) {
1133
+ if (typeof fnOrConfig === "function") return fnOrConfig;
1134
+ const config = fnOrConfig;
1135
+ const deps = normalizeImports(config.imports);
1136
+ return {
1137
+ pluginType: "aggregate",
1138
+ name: config.name,
1139
+ namespace: config.namespace,
1140
+ id: makeId(config.name, config.namespace, "aggregate"),
1141
+ imports: deps.plugins,
1142
+ importBindings: deps.bindings,
1143
+ exports: normalizeExports(config.exports),
1144
+ middleware: config.middleware
1145
+ };
1146
+ }
1147
+ function normalizeExports(exports) {
1148
+ if (!exports) return {};
1149
+ const out = {};
1150
+ const add = (binding, leaf) => {
1151
+ const existing = out[binding];
1152
+ if (existing && existing.id !== leaf.id) {
1153
+ throw new Error(
1154
+ `definePlugin: duplicate export binding "${binding}". Two different plugins ("${existing.id}" and "${leaf.id}") bind the same name; wrap one in selectExports to rename it.`
1155
+ );
1156
+ }
1157
+ out[binding] = leaf;
1158
+ };
1159
+ for (const element of exports) {
1160
+ if (element.pluginType === "aggregate") {
1161
+ for (const [binding, child] of Object.entries(element.exports)) {
1162
+ add(binding, child);
1163
+ }
1164
+ } else {
1165
+ add(element.name, element);
1166
+ }
1020
1167
  }
1021
- if (schema instanceof z.ZodOptional) {
1022
- return isPositional(schema._zod.def.innerType);
1168
+ return out;
1169
+ }
1170
+ function fromFunctionPlugin(fn, config) {
1171
+ return {
1172
+ pluginType: "legacy",
1173
+ name: config.name,
1174
+ namespace: config.namespace,
1175
+ id: makeId(config.name, config.namespace, "aggregate"),
1176
+ imports: [],
1177
+ importBindings: [],
1178
+ run: fn
1179
+ };
1180
+ }
1181
+ function defineLegacyMerge(args) {
1182
+ return {
1183
+ pluginType: "legacy-merge",
1184
+ name: args.name,
1185
+ namespace: args.namespace,
1186
+ id: makeId(args.name, args.namespace, "aggregate"),
1187
+ legacy: fromFunctionPlugin(args.legacy, {
1188
+ name: args.name,
1189
+ namespace: args.namespace
1190
+ }),
1191
+ plugin: args.plugin
1192
+ };
1193
+ }
1194
+ function legacyGraphEntry(name, value, pluginMeta) {
1195
+ const { inputSchema, ...rest } = pluginMeta ?? {};
1196
+ const meta = Object.keys(rest).length ? rest : void 0;
1197
+ if (typeof value === "function") {
1198
+ return {
1199
+ pluginType: "method",
1200
+ name,
1201
+ value,
1202
+ chain: [],
1203
+ ...inputSchema ? { inputSchema } : {},
1204
+ ...meta ? { meta } : {}
1205
+ };
1023
1206
  }
1024
- if (schema instanceof z.ZodDefault) {
1025
- return isPositional(schema._zod.def.innerType);
1207
+ return { pluginType: "property", name, value, ...meta ? { meta } : {} };
1208
+ }
1209
+ function adaptLegacyFormatter(legacy, sdk) {
1210
+ const legacyFetch = legacy.fetch;
1211
+ return {
1212
+ fetchContext: legacyFetch ? async ({ items, input, context }) => {
1213
+ let ctx = context;
1214
+ for (const item of items) {
1215
+ ctx = await legacyFetch(sdk, input, item, ctx);
1216
+ }
1217
+ return ctx;
1218
+ } : void 0,
1219
+ format: ({ item, context }) => legacy.format(item, context)
1220
+ };
1221
+ }
1222
+ function normalizeFormatter(entry, sdk) {
1223
+ if (entry.pluginType !== "method") return void 0;
1224
+ if (entry.formatter) return entry.formatter;
1225
+ const legacy = entry.meta?.formatter;
1226
+ return legacy ? adaptLegacyFormatter(legacy, sdk) : void 0;
1227
+ }
1228
+ function pluginEntryMeta(entry) {
1229
+ if (entry.pluginType === "method" && entry.meta) {
1230
+ return entry.inputSchema ? { ...entry.meta, inputSchema: entry.inputSchema } : entry.meta;
1026
1231
  }
1027
- return false;
1232
+ if (entry.pluginType === "property" && entry.meta) return entry.meta;
1233
+ return void 0;
1028
1234
  }
1029
-
1030
- // src/constants.ts
1031
- var ZAPIER_BASE_URL = globalThis.process?.env?.ZAPIER_BASE_URL || "https://zapier.com";
1032
- function getZapierSdkService() {
1033
- return globalThis.process?.env?.ZAPIER_SDK_SERVICE;
1235
+ function buildSurfaceRegistry(context, packageFilter) {
1236
+ const meta = {};
1237
+ const surface = {};
1238
+ const entries = {};
1239
+ for (const [binding, id] of Object.entries(context.surface)) {
1240
+ const entry = context.plugins[id];
1241
+ if (!entry || entry.pluginType === "aggregate") continue;
1242
+ surface[binding] = entry.value;
1243
+ entries[binding] = entry;
1244
+ const m = pluginEntryMeta(entry);
1245
+ if (m) meta[binding] = m;
1246
+ }
1247
+ const formatters = {};
1248
+ for (const [binding, entry] of Object.entries(entries)) {
1249
+ const f = normalizeFormatter(entry, surface);
1250
+ if (f) formatters[binding] = f;
1251
+ }
1252
+ return buildRegistry({ sdk: surface, meta, formatters, packageFilter });
1253
+ }
1254
+ var dangerousContextPlugin = {
1255
+ pluginType: "property",
1256
+ name: "context",
1257
+ namespace: "kitcore",
1258
+ id: "kitcore/context",
1259
+ imports: [],
1260
+ importBindings: [],
1261
+ privileged: true
1262
+ };
1263
+ defineMethod({
1264
+ name: "getRegistry",
1265
+ namespace: "kitcore",
1266
+ imports: [dangerousContextPlugin],
1267
+ inputSchema: z.object({ package: z.string().optional() }).optional(),
1268
+ run: ({ imports, input }) => buildSurfaceRegistry(imports.context, input?.package)
1269
+ });
1270
+ function normalizeOutput(output) {
1271
+ if (output === void 0) return { type: "raw" };
1272
+ if (typeof output === "string") return { type: output };
1273
+ return output;
1034
1274
  }
1035
- var MAX_PAGE_LIMIT = 1e4;
1036
- var DEFAULT_PAGE_SIZE = 100;
1037
- var DEFAULT_ACTION_TIMEOUT_MS = 18e4;
1038
- function parseIntEnvVar(name) {
1039
- const value = globalThis.process?.env?.[name];
1040
- if (value === void 0) return void 0;
1041
- const parsed = parseInt(value, 10);
1042
- if (isNaN(parsed)) {
1043
- console.warn(
1044
- `[zapier-sdk] Invalid value for ${name}: "${value}" (expected integer)`
1045
- );
1046
- return void 0;
1275
+ var CONTEXT = Symbol("kitcore.context");
1276
+ function getContext(sdk) {
1277
+ return sdk[CONTEXT];
1278
+ }
1279
+ function isResolverRef(value) {
1280
+ return "ref" in value;
1281
+ }
1282
+ function nestedResolvers(resolver) {
1283
+ const out = [];
1284
+ if (resolver.type === "object") {
1285
+ for (const field of Object.values(resolver.properties ?? {})) {
1286
+ if (!isResolverRef(field.resolver)) out.push(field.resolver);
1287
+ }
1288
+ out.push(...Object.values(resolver.definitions ?? {}));
1289
+ } else if (resolver.type === "array") {
1290
+ if (!isResolverRef(resolver.items)) out.push(resolver.items);
1291
+ out.push(...Object.values(resolver.definitions ?? {}));
1047
1292
  }
1048
- return parsed;
1293
+ return out;
1049
1294
  }
1050
- var ZAPIER_MAX_NETWORK_RETRIES = parseIntEnvVar("ZAPIER_MAX_NETWORK_RETRIES") ?? 3;
1051
- var ZAPIER_MAX_NETWORK_RETRY_DELAY_MS = parseIntEnvVar("ZAPIER_MAX_NETWORK_RETRY_DELAY_MS") ?? 6e4;
1052
- var MAX_CONCURRENCY_LIMIT = 1e4;
1053
- function parseConcurrencyEnvVar(name) {
1054
- const value = globalThis.process?.env?.[name];
1055
- if (!value) return void 0;
1056
- if (value === "Infinity") return Infinity;
1057
- if (/^[1-9]\d*$/.test(value)) {
1058
- const parsed = parseInt(value, 10);
1059
- if (parsed <= MAX_CONCURRENCY_LIMIT) return parsed;
1295
+ function resolverImportEdges(resolver) {
1296
+ const out = [...resolver.imports];
1297
+ for (const child of nestedResolvers(resolver)) {
1298
+ out.push(...resolverImportEdges(child));
1060
1299
  }
1061
- console.warn(
1062
- `[zapier-sdk] Invalid value for ${name}: "${value}" (expected positive integer 1-${MAX_CONCURRENCY_LIMIT} or "Infinity")`
1063
- );
1064
- return void 0;
1300
+ return out;
1065
1301
  }
1066
- var ZAPIER_MAX_CONCURRENT_REQUESTS = parseConcurrencyEnvVar("ZAPIER_MAX_CONCURRENT_REQUESTS") ?? 200;
1067
- function getZapierApprovalMode() {
1068
- const value = globalThis.process?.env?.ZAPIER_APPROVAL_MODE;
1069
- if (value === "disabled" || value === "poll" || value === "throw")
1070
- return value;
1071
- return void 0;
1302
+ function methodAttachmentEdges(plugin) {
1303
+ const out = [];
1304
+ if (plugin.resolvers) {
1305
+ for (const resolver of Object.values(plugin.resolvers)) {
1306
+ out.push(...resolverImportEdges(resolver));
1307
+ }
1308
+ }
1309
+ if (plugin.formatter) out.push(...plugin.formatter.imports);
1310
+ return out;
1072
1311
  }
1073
- function getZapierOpenAutoModeApprovalsInBrowser() {
1074
- const value = globalThis.process?.env?.ZAPIER_OPEN_AUTO_MODE_APPROVALS_IN_BROWSER;
1075
- if (value === void 0) return void 0;
1076
- return value === "true";
1312
+ function edgesOf(plugin) {
1313
+ if (plugin.pluginType === "aggregate") {
1314
+ return [...Object.values(plugin.exports), ...plugin.imports];
1315
+ }
1316
+ if (plugin.pluginType === "method") {
1317
+ return [...plugin.imports, ...methodAttachmentEdges(plugin)];
1318
+ }
1319
+ return plugin.imports;
1077
1320
  }
1078
- function getZapierDefaultApprovalMode() {
1079
- const isInteractive = !!globalThis.process?.stdin?.isTTY && !!globalThis.process?.stdout?.isTTY;
1080
- return isInteractive ? "poll" : "throw";
1321
+ function isStandIn(plugin) {
1322
+ return (plugin.pluginType === "method" || plugin.pluginType === "property" || plugin.pluginType === "aggregate") && plugin.standIn === true;
1081
1323
  }
1082
- var DEFAULT_APPROVAL_TIMEOUT_MS = 10 * 60 * 1e3;
1083
- var DEFAULT_MAX_APPROVAL_RETRIES = 2;
1084
-
1085
- // src/types/properties.ts
1086
- var AppKeyPropertySchema = withPositional(
1087
- z.string().min(1).describe("App key (e.g., 'SlackCLIAPI' or slug like 'github')")
1088
- );
1089
- var AppPropertySchema = withPositional(
1090
- z.string().min(1).describe(
1091
- "App slug (e.g., 'github'), implementation name (e.g., 'SlackCLIAPI'), or versioned ID (e.g., 'github@1.2.3')"
1092
- )
1093
- );
1094
- var ActionTypePropertySchema = z.enum([
1095
- "read",
1096
- "read_bulk",
1097
- "write",
1098
- "run",
1099
- "search",
1100
- "search_or_write",
1101
- "search_and_write",
1102
- "filter"
1103
- ]).describe("Action type that matches the action's defined type");
1104
- var ActionKeyPropertySchema = z.string().min(1).describe("Action key to execute");
1105
- var ActionPropertySchema = withPositional(
1106
- z.string().min(1).describe("Action key (e.g., 'send_message' or 'find_row')")
1107
- );
1108
- var InputFieldPropertySchema = withPositional(
1109
- z.string().min(1).describe("Input field key to get choices for")
1110
- );
1111
- var ConnectionIdPropertySchema = z.union([z.string(), z.number().int().positive()]).describe("Connection ID to use for this action");
1112
- var AuthenticationIdPropertySchema = ConnectionIdPropertySchema.meta({
1113
- deprecated: true
1114
- });
1115
- var ConnectionPropertySchema = z.union([z.string(), z.number().int().positive()]).describe(
1116
- "Connection alias or connection ID (UUID or positive integer). Strings that match a key in the connections map are resolved against it; otherwise the value is used as a connection ID directly."
1117
- );
1118
- var InputsPropertySchema = z.record(z.string(), z.unknown()).describe("Input parameters for the action");
1119
- var LimitPropertySchema = z.number().int().min(1).max(MAX_PAGE_LIMIT).default(50).describe("Maximum number of items to return");
1120
- var OffsetPropertySchema = z.number().int().min(0).default(0).describe("Number of items to skip for pagination");
1121
- var OutputPropertySchema = z.string().describe("Output file path");
1122
- var DebugPropertySchema = z.boolean().default(false).describe("Enable debug logging");
1123
- var ParamsPropertySchema = z.record(z.string(), z.unknown()).describe("Additional parameters");
1124
- var ActionTimeoutMsPropertySchema = z.number().min(1e3).optional().describe(
1125
- `Maximum time to wait for action completion in milliseconds (default: ${DEFAULT_ACTION_TIMEOUT_MS})`
1126
- );
1127
- var TablePropertySchema = withPositional(
1128
- z.string().regex(/^[A-Z0-9]{26}$/, "Table ID must be a valid ULID").describe("The unique identifier of the table")
1129
- );
1130
- var RecordPropertySchema = withPositional(
1131
- z.string().regex(/^[A-Z0-9]{26}$/, "Record ID must be a valid ULID").describe("The unique identifier of the record")
1132
- );
1133
- var RecordsPropertySchema = z.array(z.string().regex(/^[A-Z0-9]{26}$/, "Record ID must be a valid ULID")).min(1).max(100).describe("Record IDs to operate on");
1134
- var FieldsPropertySchema = z.array(z.union([z.string(), z.number()])).describe(
1135
- 'Fields to operate on. Accepts field names (e.g., "Email") or IDs (e.g., "f6", "6", or 6).'
1136
- );
1137
- var AppsPropertySchema = z.array(z.string()).describe("Filter by app keys (e.g., 'SlackCLIAPI' or slug like 'github')");
1138
- var TablesPropertySchema = z.array(z.string()).describe("Filter by specific table IDs");
1139
- var ConnectionsPropertySchema = z.array(z.string()).describe("List of connection IDs to filter by");
1140
- var TriggerInboxPropertySchema = withPositional(
1141
- z.string().min(1).describe(
1142
- "Trigger inbox identifier \u2014 UUID or name. Non-UUID values are resolved by name via the inbox list endpoint."
1143
- )
1144
- );
1145
- var TriggerInboxNamePropertySchema = z.string().min(1).max(100).describe(
1146
- "Inbox name; unique per (user, account). Enables get-or-create on createTriggerInbox."
1147
- );
1148
- var LeasePropertySchema = z.string().min(1).describe("Lease ID returned from leaseTriggerInboxMessages");
1149
- var LeaseSecondsPropertySchema = z.number().int().min(1).max(3600).describe(
1150
- "Seconds until the lease expires; messages return to available if not acked. API default is 300 (5 minutes)."
1151
- );
1152
- var LeaseLimitPropertySchema = z.number().int().min(1).max(100).describe("Maximum messages to lease in a single batch (1-100)");
1153
-
1154
- // src/types/errors.ts
1155
- var _a, _b;
1156
- var ZapierError = class extends (_b = Error, _a = CORE_ERROR_SYMBOL, _b) {
1157
- constructor(message, options = {}) {
1158
- super(message);
1159
- this[_a] = true;
1160
- this.name = "ZapierError";
1161
- this.code = "ZAPIER_ERROR";
1162
- if (options.statusCode !== void 0) this.statusCode = options.statusCode;
1163
- if (options.errors !== void 0) this.errors = options.errors;
1164
- if (options.cause !== void 0) this.cause = options.cause;
1165
- if (options.response !== void 0) this.response = options.response;
1166
- Object.setPrototypeOf(this, new.target.prototype);
1167
- }
1168
- };
1169
- var ZapierValidationError = class extends ZapierError {
1170
- constructor(message, options = {}) {
1171
- super(message, options);
1172
- this.name = "ZapierValidationError";
1173
- this.code = "ZAPIER_VALIDATION_ERROR";
1174
- this.details = options.details;
1324
+ function topoOrder(descriptors) {
1325
+ const order = [];
1326
+ const visited = /* @__PURE__ */ new Set();
1327
+ const visit = (id) => {
1328
+ if (visited.has(id)) return;
1329
+ visited.add(id);
1330
+ const descriptor = descriptors.get(id);
1331
+ if (descriptor) for (const edge of edgesOf(descriptor)) visit(edge.id);
1332
+ order.push(id);
1333
+ };
1334
+ for (const id of descriptors.keys()) visit(id);
1335
+ return order;
1336
+ }
1337
+ function collectPlugins(root, materialized = /* @__PURE__ */ new Set()) {
1338
+ const byId = /* @__PURE__ */ new Map();
1339
+ const visit = (plugin) => {
1340
+ if (materialized.has(plugin.id)) return;
1341
+ const existing = byId.get(plugin.id);
1342
+ if (existing === plugin) return;
1343
+ if (existing) {
1344
+ const bothReal = !isStandIn(existing) && !isStandIn(plugin);
1345
+ if (bothReal) {
1346
+ throw new Error(
1347
+ `createSdk: duplicate plugin id "${plugin.id}". Two different plugins registered under the same id.`
1348
+ );
1349
+ }
1350
+ if (isStandIn(existing) && !isStandIn(plugin)) {
1351
+ byId.set(plugin.id, plugin);
1352
+ for (const edge of edgesOf(plugin)) visit(edge);
1353
+ }
1354
+ return;
1355
+ }
1356
+ byId.set(plugin.id, plugin);
1357
+ for (const edge of edgesOf(plugin)) visit(edge);
1358
+ };
1359
+ visit(root);
1360
+ for (const [id, plugin] of byId) {
1361
+ if (isStandIn(plugin)) {
1362
+ throw new Error(
1363
+ `createSdk: missing dependency "${id}". A plugin depends on it (via a stand-in) but no implementation was registered.`
1364
+ );
1365
+ }
1175
1366
  }
1176
- };
1177
- var ZapierUnknownError = class extends ZapierError {
1178
- constructor() {
1179
- super(...arguments);
1180
- this.name = "ZapierUnknownError";
1181
- this.code = "ZAPIER_UNKNOWN_ERROR";
1367
+ return byId;
1368
+ }
1369
+ function bindValue(target, key, entry) {
1370
+ if (entry.pluginType === "property" && entry.getValue) {
1371
+ Object.defineProperty(target, key, {
1372
+ get: entry.getValue,
1373
+ enumerable: true,
1374
+ configurable: true
1375
+ });
1376
+ } else {
1377
+ Object.defineProperty(target, key, {
1378
+ value: entry.value,
1379
+ writable: true,
1380
+ enumerable: true,
1381
+ configurable: true
1382
+ });
1182
1383
  }
1183
- };
1184
- var ZapierAuthenticationError = class extends ZapierError {
1185
- constructor() {
1186
- super(...arguments);
1187
- this.name = "ZapierAuthenticationError";
1188
- this.code = "ZAPIER_AUTHENTICATION_ERROR";
1384
+ }
1385
+ function buildSurface(context, ...maps) {
1386
+ const sdk = {};
1387
+ for (const map of maps) {
1388
+ Object.defineProperties(sdk, Object.getOwnPropertyDescriptors(map));
1189
1389
  }
1190
- };
1191
- var zapierAdaptError = (options) => {
1192
- switch (options.code) {
1193
- case CoreErrorCode.Validation:
1194
- return new ZapierValidationError(options.message, {
1195
- cause: options.cause,
1196
- details: options.details
1197
- });
1198
- case CoreErrorCode.Unknown:
1199
- return new ZapierUnknownError(options.message, {
1200
- cause: options.cause
1201
- });
1202
- default:
1203
- return new ZapierError(options.message, { cause: options.cause });
1390
+ sdk.context = context;
1391
+ sdk[CONTEXT] = context;
1392
+ return sdk;
1393
+ }
1394
+ function buildImports(plugins, importBindings) {
1395
+ const imports = {};
1396
+ for (const { binding, id } of importBindings) {
1397
+ bindValue(imports, binding, plugins[id]);
1204
1398
  }
1205
- };
1206
- var ZapierApiError = class extends ZapierError {
1207
- constructor(message, options = {}) {
1208
- super(message, options);
1209
- this.name = "ZapierApiError";
1210
- this.code = "ZAPIER_API_ERROR";
1399
+ return imports;
1400
+ }
1401
+ function mirrorLegacyRootKeys(context, rootKeys, meta) {
1402
+ const exports = {};
1403
+ for (const [name, value] of Object.entries(rootKeys)) {
1404
+ context.plugins[name] = legacyGraphEntry(name, value, meta[name]);
1405
+ exports[name] = value;
1211
1406
  }
1212
- };
1213
- var ZapierAppNotFoundError = class extends ZapierError {
1214
- constructor(message, options = {}) {
1215
- super(message, options);
1216
- this.name = "ZapierAppNotFoundError";
1217
- this.code = "ZAPIER_APP_NOT_FOUND_ERROR";
1218
- this.appKey = options.appKey;
1407
+ return exports;
1408
+ }
1409
+ function recordExportSurface(context, exports) {
1410
+ for (const [binding, child] of Object.entries(exports)) {
1411
+ context.surface[binding] = child.id;
1219
1412
  }
1220
- };
1221
- var ZapierNotFoundError = class extends ZapierError {
1222
- constructor(message, options = {}) {
1223
- super(message, options);
1224
- this.name = "ZapierNotFoundError";
1225
- this.code = "ZAPIER_NOT_FOUND_ERROR";
1413
+ }
1414
+ function materialize(descriptors, context) {
1415
+ const states = /* @__PURE__ */ new Map();
1416
+ runLegacyPass(descriptors, context);
1417
+ buildMethodEntries(descriptors, context, states);
1418
+ buildEagerArtifacts(descriptors, context, states);
1419
+ bindAttachments(descriptors, context);
1420
+ resolveAggregates(descriptors, context);
1421
+ assembleMiddleware(descriptors, context);
1422
+ return context.plugins;
1423
+ }
1424
+ function bindResolver(resolver, plugins) {
1425
+ switch (resolver.type) {
1426
+ case "static":
1427
+ return {
1428
+ type: "static",
1429
+ requireParams: resolver.requireParams,
1430
+ requireCapabilities: resolver.requireCapabilities,
1431
+ inputType: resolver.inputType,
1432
+ placeholder: resolver.placeholder
1433
+ };
1434
+ case "constant":
1435
+ return {
1436
+ type: "constant",
1437
+ value: resolver.value,
1438
+ requireParams: resolver.requireParams,
1439
+ requireCapabilities: resolver.requireCapabilities
1440
+ };
1441
+ case "info":
1442
+ return { type: "info", text: resolver.text };
1443
+ case "object": {
1444
+ const imports = buildImports(plugins, resolver.importBindings);
1445
+ const bound = {
1446
+ type: "object",
1447
+ requireParams: resolver.requireParams,
1448
+ requireCapabilities: resolver.requireCapabilities
1449
+ };
1450
+ if (resolver.properties)
1451
+ bound.properties = bindFields(resolver.properties, plugins);
1452
+ if (resolver.definitions)
1453
+ bound.definitions = bindDefinitions(resolver.definitions, plugins);
1454
+ const { fetch: fetch2 } = resolver;
1455
+ if (fetch2) bound.fetch = ({ params }) => fetch2({ imports, params });
1456
+ return bound;
1457
+ }
1458
+ case "array": {
1459
+ const bound = {
1460
+ type: "array",
1461
+ requireParams: resolver.requireParams,
1462
+ requireCapabilities: resolver.requireCapabilities,
1463
+ minItems: resolver.minItems,
1464
+ maxItems: resolver.maxItems,
1465
+ items: isResolverRef(resolver.items) ? resolver.items : bindResolver(resolver.items, plugins)
1466
+ };
1467
+ if (resolver.definitions)
1468
+ bound.definitions = bindDefinitions(resolver.definitions, plugins);
1469
+ return bound;
1470
+ }
1471
+ default: {
1472
+ const imports = buildImports(plugins, resolver.importBindings);
1473
+ const bound = {
1474
+ type: "dynamic",
1475
+ requireParams: resolver.requireParams,
1476
+ requireCapabilities: resolver.requireCapabilities,
1477
+ inputType: resolver.inputType,
1478
+ placeholder: resolver.placeholder,
1479
+ prompt: resolver.prompt
1480
+ };
1481
+ const { fetch: fetch2, tryResolveWithoutPrompt } = resolver;
1482
+ if (fetch2)
1483
+ bound.fetch = ({ params, search }) => fetch2({ imports, params, search });
1484
+ if (tryResolveWithoutPrompt) {
1485
+ bound.tryResolveWithoutPrompt = ({ params }) => tryResolveWithoutPrompt({ imports, params });
1486
+ }
1487
+ return bound;
1488
+ }
1226
1489
  }
1227
- };
1228
- var ZapierResourceNotFoundError = class extends ZapierNotFoundError {
1229
- constructor(message, options = {}) {
1230
- super(message, options);
1231
- this.name = "ZapierResourceNotFoundError";
1232
- this.code = "ZAPIER_RESOURCE_NOT_FOUND_ERROR";
1233
- this.resourceType = options.resourceType;
1234
- this.resourceId = options.resourceId;
1490
+ }
1491
+ function bindFields(fields, plugins) {
1492
+ const out = {};
1493
+ for (const [key, field] of Object.entries(fields)) {
1494
+ out[key] = {
1495
+ ...field,
1496
+ resolver: isResolverRef(field.resolver) ? field.resolver : bindResolver(field.resolver, plugins)
1497
+ };
1235
1498
  }
1236
- };
1237
- var ZapierConfigurationError = class extends ZapierError {
1238
- constructor(message, options = {}) {
1239
- super(message, options);
1240
- this.name = "ZapierConfigurationError";
1241
- this.code = "ZAPIER_CONFIGURATION_ERROR";
1242
- this.configType = options.configType;
1499
+ return out;
1500
+ }
1501
+ function bindDefinitions(definitions, plugins) {
1502
+ const out = {};
1503
+ for (const [key, def] of Object.entries(definitions)) {
1504
+ out[key] = bindResolver(def, plugins);
1243
1505
  }
1244
- };
1245
- var ZapierBundleError = class extends ZapierError {
1246
- constructor(message, options = {}) {
1247
- super(message, options);
1248
- this.name = "ZapierBundleError";
1249
- this.code = "ZAPIER_BUNDLE_ERROR";
1250
- this.buildErrors = options.buildErrors;
1506
+ return out;
1507
+ }
1508
+ function bindFormatter(formatter, plugins) {
1509
+ const imports = buildImports(plugins, formatter.importBindings);
1510
+ const bound = { format: formatter.format };
1511
+ const { fetchContext } = formatter;
1512
+ if (fetchContext)
1513
+ bound.fetchContext = ({ items, input, context }) => fetchContext({ imports, items, input, context });
1514
+ return bound;
1515
+ }
1516
+ function bindAttachments(descriptors, context) {
1517
+ const plugins = context.plugins;
1518
+ for (const [id, descriptor] of descriptors) {
1519
+ if (descriptor.pluginType !== "method") continue;
1520
+ const entry = plugins[id];
1521
+ if (!entry || entry.pluginType !== "method") continue;
1522
+ if (descriptor.resolvers) {
1523
+ const bound = {};
1524
+ for (const [param, resolver] of Object.entries(descriptor.resolvers)) {
1525
+ bound[param] = bindResolver(resolver, plugins);
1526
+ }
1527
+ entry.resolvers = bound;
1528
+ }
1529
+ if (descriptor.formatter) {
1530
+ entry.formatter = bindFormatter(descriptor.formatter, plugins);
1531
+ }
1251
1532
  }
1252
- };
1253
- var ZapierTimeoutError = class extends ZapierError {
1254
- constructor(message, options = {}) {
1255
- super(message, options);
1256
- this.name = "ZapierTimeoutError";
1257
- this.code = "ZAPIER_TIMEOUT_ERROR";
1258
- this.attempts = options.attempts;
1259
- this.maxAttempts = options.maxAttempts;
1533
+ }
1534
+ function runLegacyPass(descriptors, context) {
1535
+ const plugins = context.plugins;
1536
+ const compatView = new Proxy(
1537
+ {},
1538
+ {
1539
+ get: (_target, prop) => {
1540
+ if (prop === "context") return context;
1541
+ const entry = plugins[prop];
1542
+ return entry?.value;
1543
+ }
1544
+ }
1545
+ );
1546
+ for (const id of topoOrder(descriptors)) {
1547
+ const descriptor = descriptors.get(id);
1548
+ if (!descriptor || descriptor.pluginType !== "legacy") continue;
1549
+ const { rootKeys, meta, hooks, contextRest } = splitPluginContribution(
1550
+ descriptor.run(compatView)
1551
+ );
1552
+ Object.assign(context.meta, meta);
1553
+ Object.assign(context, contextRest);
1554
+ context.hooks = buildHooks(context.hooks, hooks);
1555
+ const exports = mirrorLegacyRootKeys(context, rootKeys, meta);
1556
+ if (!("getRegistry" in exports)) {
1557
+ let getRegistry2 = function(options) {
1558
+ const sdk = this ?? exports;
1559
+ const meta2 = {};
1560
+ const formatters = {};
1561
+ for (const [binding, id2] of Object.entries(context.surface)) {
1562
+ const entry = context.plugins[id2];
1563
+ if (!entry || entry.pluginType === "aggregate") continue;
1564
+ const m = pluginEntryMeta(entry);
1565
+ if (m) meta2[binding] = m;
1566
+ const f = normalizeFormatter(entry, sdk);
1567
+ if (f) formatters[binding] = f;
1568
+ }
1569
+ Object.assign(meta2, context.meta);
1570
+ return buildRegistry({
1571
+ sdk,
1572
+ meta: meta2,
1573
+ formatters,
1574
+ packageFilter: options?.package
1575
+ });
1576
+ };
1577
+ exports.getRegistry = getRegistry2;
1578
+ plugins.getRegistry = {
1579
+ pluginType: "method",
1580
+ name: "getRegistry",
1581
+ value: getRegistry2,
1582
+ chain: []
1583
+ };
1584
+ }
1585
+ plugins[id] = { pluginType: "aggregate", name: descriptor.name, exports };
1586
+ }
1587
+ }
1588
+ function buildMethodEntries(descriptors, context, states) {
1589
+ const plugins = context.plugins;
1590
+ for (const [id, descriptor] of descriptors) {
1591
+ if (descriptor.pluginType !== "method") continue;
1592
+ const out = normalizeOutput(descriptor.output);
1593
+ const entry = {
1594
+ pluginType: "method",
1595
+ name: descriptor.name,
1596
+ chain: [],
1597
+ inputSchema: descriptor.inputSchema,
1598
+ // Derive the presentation type from the output mode when the author did
1599
+ // not set one; an explicit meta.type (e.g. "create") still wins.
1600
+ meta: out.type === "raw" || descriptor.meta?.type ? descriptor.meta : { ...descriptor.meta, type: out.type },
1601
+ output: out,
1602
+ // Replaced below; never called.
1603
+ value: () => void 0
1604
+ };
1605
+ const callRun = (input) => descriptor.run({
1606
+ imports: buildImports(plugins, descriptor.importBindings),
1607
+ state: states.get(id),
1608
+ input
1609
+ });
1610
+ const fold = (coreFn) => (input) => {
1611
+ let next = coreFn;
1612
+ for (const wrap of entry.chain) {
1613
+ const inner = next;
1614
+ next = (i) => wrap.run({
1615
+ imports: buildImports(plugins, wrap.owner.importBindings),
1616
+ next: inner,
1617
+ input: i
1618
+ });
1619
+ }
1620
+ return next(input);
1621
+ };
1622
+ const sdk = { context };
1623
+ if (out.type === "list") {
1624
+ entry.value = createPaginatedFunction(
1625
+ fold(callRun),
1626
+ {
1627
+ sdk,
1628
+ schema: descriptor.inputSchema,
1629
+ name: descriptor.name,
1630
+ defaultPageSize: out.defaultPageSize,
1631
+ adaptPage: out.adaptPage
1632
+ }
1633
+ );
1634
+ } else if (out.type === "item") {
1635
+ const itemCore = async (input) => ({
1636
+ data: await callRun(input)
1637
+ });
1638
+ entry.value = createFunction(
1639
+ fold(itemCore),
1640
+ { sdk, schema: descriptor.inputSchema, name: descriptor.name }
1641
+ );
1642
+ } else {
1643
+ entry.value = (rawInput) => {
1644
+ const input = descriptor.inputSchema ? descriptor.inputSchema.parse(rawInput) : rawInput;
1645
+ return fold(callRun)(input);
1646
+ };
1647
+ }
1648
+ if (descriptor.positional) {
1649
+ const names = descriptor.positional;
1650
+ const canonicalValue = entry.value;
1651
+ entry.value = (...args) => {
1652
+ const packed = {};
1653
+ names.forEach((name, i) => {
1654
+ if (i < args.length) packed[name] = args[i];
1655
+ });
1656
+ return canonicalValue(packed);
1657
+ };
1658
+ entry.positional = names;
1659
+ }
1660
+ plugins[id] = entry;
1260
1661
  }
1261
- };
1262
- var ZapierActionError = class extends ZapierError {
1263
- constructor(message, options = {}) {
1264
- super(message, options);
1265
- this.name = "ZapierActionError";
1266
- this.code = "ZAPIER_ACTION_ERROR";
1267
- this.appKey = options.appKey;
1268
- this.actionKey = options.actionKey;
1662
+ }
1663
+ function buildEagerArtifacts(descriptors, context, states) {
1664
+ const plugins = context.plugins;
1665
+ const built = /* @__PURE__ */ new Set();
1666
+ const building = /* @__PURE__ */ new Set();
1667
+ const ensureBuilt = (id) => {
1668
+ if (built.has(id)) return;
1669
+ const descriptor = descriptors.get(id);
1670
+ if (!descriptor || descriptor.pluginType === "aggregate" || descriptor.pluginType === "legacy") {
1671
+ built.add(id);
1672
+ return;
1673
+ }
1674
+ if (building.has(id)) {
1675
+ throw new Error(`createSdk: dependency cycle at "${id}".`);
1676
+ }
1677
+ building.add(id);
1678
+ for (const { id: depId } of descriptor.importBindings) ensureBuilt(depId);
1679
+ if (descriptor.pluginType === "method") {
1680
+ states.set(
1681
+ id,
1682
+ descriptor.setup ? descriptor.setup({
1683
+ imports: buildImports(plugins, descriptor.importBindings)
1684
+ }) : void 0
1685
+ );
1686
+ } else {
1687
+ states.set(
1688
+ id,
1689
+ descriptor.setup ? descriptor.setup({
1690
+ imports: buildImports(plugins, descriptor.importBindings)
1691
+ }) : void 0
1692
+ );
1693
+ if (descriptor.privileged) {
1694
+ plugins[id] = {
1695
+ pluginType: "property",
1696
+ name: descriptor.name,
1697
+ value: context,
1698
+ meta: descriptor.meta
1699
+ };
1700
+ } else if (descriptor.get) {
1701
+ const get = descriptor.get;
1702
+ const importBindings = descriptor.importBindings;
1703
+ plugins[id] = {
1704
+ pluginType: "property",
1705
+ name: descriptor.name,
1706
+ getValue: () => get({
1707
+ imports: buildImports(plugins, importBindings),
1708
+ state: states.get(id)
1709
+ }),
1710
+ meta: descriptor.meta
1711
+ };
1712
+ } else {
1713
+ plugins[id] = {
1714
+ pluginType: "property",
1715
+ name: descriptor.name,
1716
+ value: descriptor.value,
1717
+ meta: descriptor.meta
1718
+ };
1719
+ }
1720
+ }
1721
+ building.delete(id);
1722
+ built.add(id);
1723
+ };
1724
+ for (const id of descriptors.keys()) ensureBuilt(id);
1725
+ }
1726
+ function resolveAggregates(descriptors, context) {
1727
+ const plugins = context.plugins;
1728
+ for (const [id, descriptor] of descriptors) {
1729
+ if (descriptor.pluginType !== "aggregate") continue;
1730
+ const exports = {};
1731
+ for (const [binding, child] of Object.entries(descriptor.exports)) {
1732
+ bindValue(exports, binding, plugins[child.id]);
1733
+ }
1734
+ plugins[id] = { pluginType: "aggregate", name: descriptor.name, exports };
1269
1735
  }
1270
- // Legacy accessor for backward compatibility
1271
- get actionErrors() {
1272
- return this.errors;
1736
+ }
1737
+ function assembleMiddleware(descriptors, context) {
1738
+ const plugins = context.plugins;
1739
+ for (const id of topoOrder(descriptors)) {
1740
+ const descriptor = descriptors.get(id);
1741
+ if (!descriptor || descriptor.pluginType !== "aggregate" || !descriptor.middleware) {
1742
+ continue;
1743
+ }
1744
+ for (const [targetBinding, fn] of Object.entries(descriptor.middleware)) {
1745
+ const edge = descriptor.importBindings.find(
1746
+ (b) => b.binding === targetBinding
1747
+ );
1748
+ if (!edge) {
1749
+ throw new Error(
1750
+ `createSdk: middleware target "${targetBinding}" in plugin "${id}" is not a direct dependency. A middleware target must be a declared dependency of the wrapping plugin.`
1751
+ );
1752
+ }
1753
+ const target = plugins[edge.id];
1754
+ if (!target || target.pluginType !== "method") {
1755
+ throw new Error(
1756
+ `createSdk: middleware target "${targetBinding}" in plugin "${id}" does not resolve to a method.`
1757
+ );
1758
+ }
1759
+ if (target.output?.type === "list") {
1760
+ throw new Error(
1761
+ `createSdk: middleware target "${targetBinding}" in plugin "${id}" resolves to a list-output method, which does not support middleware yet.`
1762
+ );
1763
+ }
1764
+ target.chain.push({ run: fn, owner: descriptor });
1765
+ }
1273
1766
  }
1274
- };
1275
- var ZapierConflictError = class extends ZapierError {
1276
- constructor(message, options = {}) {
1277
- super(message, options);
1278
- this.name = "ZapierConflictError";
1279
- this.code = "ZAPIER_CONFLICT_ERROR";
1280
- this.resourceType = options.resourceType;
1767
+ }
1768
+ function createSdk(root) {
1769
+ const context = { plugins: {}, meta: {}, hooks: {}, surface: {} };
1770
+ if (root.pluginType === "legacy-merge") {
1771
+ const { legacy, plugin } = root;
1772
+ const collectRoot = {
1773
+ pluginType: "aggregate",
1774
+ name: root.name,
1775
+ id: `${root.id}:merge`,
1776
+ imports: [legacy, plugin],
1777
+ importBindings: [],
1778
+ exports: {}
1779
+ };
1780
+ const plugins2 = materialize(collectPlugins(collectRoot), context);
1781
+ const legacyExports = plugins2[legacy.id].exports;
1782
+ let pluginSurface;
1783
+ if (plugin.pluginType === "aggregate") {
1784
+ pluginSurface = plugins2[plugin.id].exports;
1785
+ } else {
1786
+ pluginSurface = {};
1787
+ bindValue(pluginSurface, plugin.name, plugins2[plugin.id]);
1788
+ }
1789
+ for (const key of Object.keys(legacyExports)) context.surface[key] = key;
1790
+ if (plugin.pluginType === "aggregate") {
1791
+ recordExportSurface(context, plugin.exports);
1792
+ } else {
1793
+ context.surface[plugin.name] = plugin.id;
1794
+ }
1795
+ return buildSurface(context, legacyExports, pluginSurface);
1796
+ }
1797
+ const plugins = materialize(collectPlugins(root), context);
1798
+ if (root.pluginType === "method" || root.pluginType === "property") {
1799
+ context.surface[root.name] = root.id;
1800
+ const sdk = buildSurface(context);
1801
+ bindValue(sdk, root.name, plugins[root.id]);
1802
+ return sdk;
1803
+ }
1804
+ if (root.pluginType === "aggregate")
1805
+ recordExportSurface(context, root.exports);
1806
+ return buildSurface(context, plugins[root.id].exports);
1807
+ }
1808
+ function addModelPlugin(sdk, plugin, options = {}) {
1809
+ const override = options.override === true;
1810
+ const context = getContext(sdk);
1811
+ const surfaceKeys = plugin.pluginType === "aggregate" ? Object.keys(plugin.exports) : [plugin.name];
1812
+ checkRootKeyCollisions(sdk, surfaceKeys, override, "addPlugin");
1813
+ const materialized = new Set(Object.keys(context.plugins));
1814
+ if (override && materialized.has(plugin.id)) {
1815
+ throw new Error(
1816
+ `addPlugin: cannot override already-materialized plugin "${plugin.id}" on the incremental path. Rebuild the SDK with the replacement via createSdk.`
1817
+ );
1281
1818
  }
1282
- };
1283
- var ZapierRateLimitError = class extends ZapierError {
1284
- constructor(message, options = {}) {
1285
- super(message, options);
1286
- this.name = "ZapierRateLimitError";
1287
- this.code = "ZAPIER_RATE_LIMIT_ERROR";
1288
- this.rateLimit = options.rateLimit ?? {};
1289
- this.retries = options.retries ?? 0;
1819
+ materialize(collectPlugins(plugin, materialized), context);
1820
+ const entry = context.plugins[plugin.id];
1821
+ if (entry.pluginType === "aggregate") {
1822
+ Object.defineProperties(
1823
+ sdk,
1824
+ Object.getOwnPropertyDescriptors(entry.exports)
1825
+ );
1826
+ for (const [binding, child] of Object.entries(
1827
+ plugin.exports
1828
+ )) {
1829
+ context.surface[binding] = child.id;
1830
+ }
1831
+ } else {
1832
+ bindValue(sdk, plugin.name, entry);
1833
+ context.surface[plugin.name] = plugin.id;
1290
1834
  }
1291
- };
1292
- var ZapierApprovalError = class extends ZapierError {
1293
- constructor(message, options = {}) {
1294
- super(message, options);
1295
- this.name = "ZapierApprovalError";
1296
- this.code = "ZAPIER_APPROVAL_ERROR";
1297
- this.approvalId = options.approvalId;
1298
- this.approvalStatus = options.status;
1299
- this.approvalUrl = options.approvalUrl;
1300
- this.pollUrl = options.pollUrl;
1301
- this.streamUrl = options.streamUrl;
1302
- this.reason = options.reason;
1835
+ }
1836
+ function addPlugin(sdk, plugin, options) {
1837
+ if (typeof plugin === "function") {
1838
+ const record = sdk;
1839
+ const contribution = applyPluginToSdk(
1840
+ record,
1841
+ plugin,
1842
+ options ?? {}
1843
+ );
1844
+ const context = record[CONTEXT];
1845
+ if (context) {
1846
+ mirrorLegacyRootKeys(context, contribution.rootKeys, contribution.meta);
1847
+ for (const name of Object.keys(contribution.rootKeys)) {
1848
+ context.surface[name] = name;
1849
+ }
1850
+ }
1851
+ return;
1303
1852
  }
1304
- };
1305
- var ZapierRelayError = class extends ZapierError {
1306
- constructor(message, options = {}) {
1307
- super(message, options);
1308
- this.name = "ZapierRelayError";
1309
- this.code = "ZAPIER_RELAY_ERROR";
1310
- }
1311
- };
1312
- function formatErrorMessage(error) {
1313
- let message = error.message;
1314
- if (error.errors && error.errors.length > 0) {
1315
- const additionalErrors = error.errors.slice(1);
1316
- if (additionalErrors.length > 0) {
1317
- const errorDetails = additionalErrors.map((err) => ` \u2022 ${err.detail || err.title || err.code}`).join("\n");
1318
- message += "\n\nAdditional errors:\n" + errorDetails;
1853
+ addModelPlugin(
1854
+ sdk,
1855
+ plugin,
1856
+ options ?? {}
1857
+ );
1858
+ }
1859
+ function createCorePlugin(options) {
1860
+ return () => ({
1861
+ context: {
1862
+ core: options
1319
1863
  }
1864
+ });
1865
+ }
1866
+ function withPositional(schema) {
1867
+ Object.assign(schema._zod.def, {
1868
+ positionalMeta: { positional: true }
1869
+ });
1870
+ return schema;
1871
+ }
1872
+ function schemaHasPositionalMeta(schema) {
1873
+ return "positionalMeta" in schema._zod.def;
1874
+ }
1875
+ function isPositional(schema) {
1876
+ if (schemaHasPositionalMeta(schema) && schema._zod.def.positionalMeta?.positional) {
1877
+ return true;
1320
1878
  }
1321
- if (error instanceof ZapierAppNotFoundError && error.appKey) {
1322
- message += `
1323
- App key: ${error.appKey}`;
1324
- }
1325
- if (error instanceof ZapierActionError && (error.appKey || error.actionKey)) {
1326
- const context = [];
1327
- if (error.appKey) context.push(`App: ${error.appKey}`);
1328
- if (error.actionKey) context.push(`Action: ${error.actionKey}`);
1329
- message += `
1330
- ${context.join(", ")}`;
1331
- }
1332
- if (error instanceof ZapierResourceNotFoundError && (error.resourceType || error.resourceId)) {
1333
- const context = [];
1334
- if (error.resourceType) context.push(`Type: ${error.resourceType}`);
1335
- if (error.resourceId) context.push(`ID: ${error.resourceId}`);
1336
- message += `
1337
- ${context.join(", ")}`;
1338
- }
1339
- if (error instanceof ZapierConflictError && error.resourceType) {
1340
- message += `
1341
- Type: ${error.resourceType}`;
1342
- }
1343
- if (error instanceof ZapierTimeoutError && (error.attempts || error.maxAttempts)) {
1344
- const context = [];
1345
- if (error.attempts) context.push(`Attempts: ${error.attempts}`);
1346
- if (error.maxAttempts) context.push(`Max attempts: ${error.maxAttempts}`);
1347
- message += `
1348
- ${context.join(", ")}`;
1349
- }
1350
- if (error instanceof ZapierBundleError && error.buildErrors && error.buildErrors.length > 0) {
1351
- message += "\n\nBuild errors:\n" + error.buildErrors.map((err) => ` \u2022 ${err}`).join("\n");
1879
+ if (schema instanceof z.ZodOptional) {
1880
+ return isPositional(schema._zod.def.innerType);
1352
1881
  }
1353
- if (error instanceof ZapierApprovalError && error.approvalUrl) {
1354
- message += `
1355
- Approval URL: ${error.approvalUrl}`;
1882
+ if (schema instanceof z.ZodDefault) {
1883
+ return isPositional(schema._zod.def.innerType);
1356
1884
  }
1357
- if (error instanceof ZapierRateLimitError) {
1358
- const { limit, remaining, retryAfterMs } = error.rateLimit;
1359
- const parts = [];
1360
- if (limit !== void 0) {
1361
- const used = remaining !== void 0 ? limit - remaining : limit;
1362
- parts.push(`${used}/${limit} used`);
1363
- }
1364
- if (retryAfterMs !== void 0 && retryAfterMs > 0) {
1365
- parts.push(`retry in ${formatDuration(retryAfterMs)}`);
1366
- }
1367
- if (error.retries > 0) {
1368
- parts.push(
1369
- `after ${error.retries} retr${error.retries === 1 ? "y" : "ies"}`
1370
- );
1371
- }
1372
- if (parts.length > 0) {
1373
- message += `
1374
- ${parts.join(", ")}`;
1375
- }
1885
+ return false;
1886
+ }
1887
+
1888
+ // src/constants.ts
1889
+ var ZAPIER_BASE_URL = globalThis.process?.env?.ZAPIER_BASE_URL || "https://zapier.com";
1890
+ function getZapierSdkService() {
1891
+ return globalThis.process?.env?.ZAPIER_SDK_SERVICE;
1892
+ }
1893
+ var MAX_PAGE_LIMIT = 1e4;
1894
+ var DEFAULT_PAGE_SIZE = 100;
1895
+ var DEFAULT_ACTION_TIMEOUT_MS = 18e4;
1896
+ function parseIntEnvVar(name) {
1897
+ const value = globalThis.process?.env?.[name];
1898
+ if (value === void 0) return void 0;
1899
+ const parsed = parseInt(value, 10);
1900
+ if (isNaN(parsed)) {
1901
+ console.warn(
1902
+ `[zapier-sdk] Invalid value for ${name}: "${value}" (expected integer)`
1903
+ );
1904
+ return void 0;
1376
1905
  }
1377
- if (error.statusCode && !message.includes(`${error.statusCode}`)) {
1378
- message += `
1379
- HTTP Status: ${error.statusCode}`;
1906
+ return parsed;
1907
+ }
1908
+ var ZAPIER_MAX_NETWORK_RETRIES = parseIntEnvVar("ZAPIER_MAX_NETWORK_RETRIES") ?? 3;
1909
+ var ZAPIER_MAX_NETWORK_RETRY_DELAY_MS = parseIntEnvVar("ZAPIER_MAX_NETWORK_RETRY_DELAY_MS") ?? 6e4;
1910
+ var MAX_CONCURRENCY_LIMIT = 1e4;
1911
+ function parseConcurrencyEnvVar(name) {
1912
+ const value = globalThis.process?.env?.[name];
1913
+ if (!value) return void 0;
1914
+ if (value === "Infinity") return Infinity;
1915
+ if (/^[1-9]\d*$/.test(value)) {
1916
+ const parsed = parseInt(value, 10);
1917
+ if (parsed <= MAX_CONCURRENCY_LIMIT) return parsed;
1380
1918
  }
1381
- return message;
1919
+ console.warn(
1920
+ `[zapier-sdk] Invalid value for ${name}: "${value}" (expected positive integer 1-${MAX_CONCURRENCY_LIMIT} or "Infinity")`
1921
+ );
1922
+ return void 0;
1382
1923
  }
1383
- function formatDuration(ms) {
1384
- const seconds = Math.round(ms / 1e3);
1385
- if (seconds < 60) return `${seconds}s`;
1386
- const minutes = Math.round(seconds / 60);
1387
- if (minutes < 60) return `${minutes}m`;
1388
- const hours = Math.round(minutes / 60);
1389
- if (hours < 24) return `${hours}h`;
1390
- const days = Math.round(hours / 24);
1391
- return `${days}d`;
1924
+ var ZAPIER_MAX_CONCURRENT_REQUESTS = parseConcurrencyEnvVar("ZAPIER_MAX_CONCURRENT_REQUESTS") ?? 200;
1925
+ function getZapierApprovalMode() {
1926
+ const value = globalThis.process?.env?.ZAPIER_APPROVAL_MODE;
1927
+ if (value === "disabled" || value === "poll" || value === "throw")
1928
+ return value;
1929
+ return void 0;
1930
+ }
1931
+ function getZapierOpenAutoModeApprovalsInBrowser() {
1932
+ const value = globalThis.process?.env?.ZAPIER_OPEN_AUTO_MODE_APPROVALS_IN_BROWSER;
1933
+ if (value === void 0) return void 0;
1934
+ return value === "true";
1392
1935
  }
1936
+ function getZapierDefaultApprovalMode() {
1937
+ const isInteractive = !!globalThis.process?.stdin?.isTTY && !!globalThis.process?.stdout?.isTTY;
1938
+ return isInteractive ? "poll" : "throw";
1939
+ }
1940
+ var DEFAULT_APPROVAL_TIMEOUT_MS = 10 * 60 * 1e3;
1941
+ var DEFAULT_MAX_APPROVAL_RETRIES = 2;
1393
1942
 
1394
- // src/types/signals.ts
1395
- var ZapierSignal = class extends Error {
1396
- constructor(message) {
1943
+ // src/types/properties.ts
1944
+ var AppKeyPropertySchema = withPositional(
1945
+ z.string().min(1).describe("App key (e.g., 'SlackCLIAPI' or slug like 'github')")
1946
+ );
1947
+ var AppPropertySchema = withPositional(
1948
+ z.string().min(1).describe(
1949
+ "App slug (e.g., 'github'), implementation name (e.g., 'SlackCLIAPI'), or versioned ID (e.g., 'github@1.2.3')"
1950
+ )
1951
+ );
1952
+ var ActionTypePropertySchema = z.enum([
1953
+ "read",
1954
+ "read_bulk",
1955
+ "write",
1956
+ "run",
1957
+ "search",
1958
+ "search_or_write",
1959
+ "search_and_write",
1960
+ "filter"
1961
+ ]).describe("Action type that matches the action's defined type");
1962
+ var ActionKeyPropertySchema = z.string().min(1).describe("Action key to execute");
1963
+ var ActionPropertySchema = withPositional(
1964
+ z.string().min(1).describe("Action key (e.g., 'send_message' or 'find_row')")
1965
+ );
1966
+ var InputFieldPropertySchema = withPositional(
1967
+ z.string().min(1).describe("Input field key to get choices for")
1968
+ );
1969
+ var ConnectionIdPropertySchema = z.union([z.string(), z.number().int().positive()]).describe("Connection ID to use for this action");
1970
+ var AuthenticationIdPropertySchema = ConnectionIdPropertySchema.meta({
1971
+ deprecated: true
1972
+ });
1973
+ var ConnectionPropertySchema = z.union([z.string(), z.number().int().positive()]).describe(
1974
+ "Connection alias or connection ID (UUID or positive integer). Strings that match a key in the connections map are resolved against it; otherwise the value is used as a connection ID directly."
1975
+ );
1976
+ var InputsPropertySchema = z.record(z.string(), z.unknown()).describe("Input parameters for the action");
1977
+ var LimitPropertySchema = z.number().int().min(1).max(MAX_PAGE_LIMIT).default(50).describe("Maximum number of items to return");
1978
+ var OffsetPropertySchema = z.number().int().min(0).default(0).describe("Number of items to skip for pagination");
1979
+ var OutputPropertySchema = z.string().describe("Output file path");
1980
+ var DebugPropertySchema = z.boolean().default(false).describe("Enable debug logging");
1981
+ var ParamsPropertySchema = z.record(z.string(), z.unknown()).describe("Additional parameters");
1982
+ var ActionTimeoutMsPropertySchema = z.number().min(1e3).optional().describe(
1983
+ `Maximum time to wait for action completion in milliseconds (default: ${DEFAULT_ACTION_TIMEOUT_MS})`
1984
+ );
1985
+ var TablePropertySchema = withPositional(
1986
+ z.string().regex(/^[A-Z0-9]{26}$/, "Table ID must be a valid ULID").describe("The unique identifier of the table")
1987
+ );
1988
+ var RecordPropertySchema = withPositional(
1989
+ z.string().regex(/^[A-Z0-9]{26}$/, "Record ID must be a valid ULID").describe("The unique identifier of the record")
1990
+ );
1991
+ var RecordsPropertySchema = z.array(z.string().regex(/^[A-Z0-9]{26}$/, "Record ID must be a valid ULID")).min(1).max(100).describe("Record IDs to operate on");
1992
+ var FieldsPropertySchema = z.array(z.union([z.string(), z.number()])).describe(
1993
+ 'Fields to operate on. Accepts field names (e.g., "Email") or IDs (e.g., "f6", "6", or 6).'
1994
+ );
1995
+ var AppsPropertySchema = z.array(z.string()).describe("Filter by app keys (e.g., 'SlackCLIAPI' or slug like 'github')");
1996
+ var TablesPropertySchema = z.array(z.string()).describe("Filter by specific table IDs");
1997
+ var ConnectionsPropertySchema = z.array(z.string()).describe("List of connection IDs to filter by");
1998
+ var TriggerInboxPropertySchema = withPositional(
1999
+ z.string().min(1).describe(
2000
+ "Trigger inbox identifier \u2014 UUID or name. Non-UUID values are resolved by name via the inbox list endpoint."
2001
+ )
2002
+ );
2003
+ var TriggerInboxNamePropertySchema = z.string().min(1).max(100).describe(
2004
+ "Inbox name; unique per (user, account). Enables get-or-create on createTriggerInbox."
2005
+ );
2006
+ var LeasePropertySchema = z.string().min(1).describe("Lease ID returned from leaseTriggerInboxMessages");
2007
+ var LeaseSecondsPropertySchema = z.number().int().min(1).max(3600).describe(
2008
+ "Seconds until the lease expires; messages return to available if not acked. API default is 300 (5 minutes)."
2009
+ );
2010
+ var LeaseLimitPropertySchema = z.number().int().min(1).max(100).describe("Maximum messages to lease in a single batch (1-100)");
2011
+
2012
+ // src/types/errors.ts
2013
+ var _a, _b;
2014
+ var ZapierError = class extends (_b = Error, _a = CORE_ERROR_SYMBOL, _b) {
2015
+ constructor(message, options = {}) {
1397
2016
  super(message);
2017
+ this[_a] = true;
2018
+ this.name = "ZapierError";
2019
+ this.code = "ZAPIER_ERROR";
2020
+ if (options.statusCode !== void 0) this.statusCode = options.statusCode;
2021
+ if (options.errors !== void 0) this.errors = options.errors;
2022
+ if (options.cause !== void 0) this.cause = options.cause;
2023
+ if (options.response !== void 0) this.response = options.response;
1398
2024
  Object.setPrototypeOf(this, new.target.prototype);
1399
2025
  }
1400
2026
  };
1401
- var ZapierReleaseTriggerMessageSignal = class extends ZapierSignal {
1402
- constructor() {
1403
- super(...arguments);
1404
- this.name = "ZapierReleaseTriggerMessageSignal";
1405
- this.code = "ZAPIER_RELEASE_TRIGGER_MESSAGE_SIGNAL";
2027
+ var ZapierValidationError = class extends ZapierError {
2028
+ constructor(message, options = {}) {
2029
+ super(message, options);
2030
+ this.name = "ZapierValidationError";
2031
+ this.code = "ZAPIER_VALIDATION_ERROR";
2032
+ this.details = options.details;
1406
2033
  }
1407
2034
  };
1408
- var ZapierAbortDrainSignal = class extends ZapierSignal {
2035
+ var ZapierUnknownError = class extends ZapierError {
1409
2036
  constructor() {
1410
2037
  super(...arguments);
1411
- this.name = "ZapierAbortDrainSignal";
1412
- this.code = "ZAPIER_ABORT_DRAIN_SIGNAL";
2038
+ this.name = "ZapierUnknownError";
2039
+ this.code = "ZAPIER_UNKNOWN_ERROR";
2040
+ }
2041
+ };
2042
+ var ZapierAuthenticationError = class extends ZapierError {
2043
+ constructor() {
2044
+ super(...arguments);
2045
+ this.name = "ZapierAuthenticationError";
2046
+ this.code = "ZAPIER_AUTHENTICATION_ERROR";
2047
+ }
2048
+ };
2049
+ var zapierAdaptError = (options) => {
2050
+ switch (options.code) {
2051
+ case CoreErrorCode.Validation:
2052
+ return new ZapierValidationError(options.message, {
2053
+ cause: options.cause,
2054
+ details: options.details
2055
+ });
2056
+ case CoreErrorCode.Unknown:
2057
+ return new ZapierUnknownError(options.message, {
2058
+ cause: options.cause
2059
+ });
2060
+ default:
2061
+ return new ZapierError(options.message, { cause: options.cause });
2062
+ }
2063
+ };
2064
+ var ZapierApiError = class extends ZapierError {
2065
+ constructor(message, options = {}) {
2066
+ super(message, options);
2067
+ this.name = "ZapierApiError";
2068
+ this.code = "ZAPIER_API_ERROR";
2069
+ }
2070
+ };
2071
+ var ZapierAppNotFoundError = class extends ZapierError {
2072
+ constructor(message, options = {}) {
2073
+ super(message, options);
2074
+ this.name = "ZapierAppNotFoundError";
2075
+ this.code = "ZAPIER_APP_NOT_FOUND_ERROR";
2076
+ this.appKey = options.appKey;
2077
+ }
2078
+ };
2079
+ var ZapierNotFoundError = class extends ZapierError {
2080
+ constructor(message, options = {}) {
2081
+ super(message, options);
2082
+ this.name = "ZapierNotFoundError";
2083
+ this.code = "ZAPIER_NOT_FOUND_ERROR";
2084
+ }
2085
+ };
2086
+ var ZapierResourceNotFoundError = class extends ZapierNotFoundError {
2087
+ constructor(message, options = {}) {
2088
+ super(message, options);
2089
+ this.name = "ZapierResourceNotFoundError";
2090
+ this.code = "ZAPIER_RESOURCE_NOT_FOUND_ERROR";
2091
+ this.resourceType = options.resourceType;
2092
+ this.resourceId = options.resourceId;
2093
+ }
2094
+ };
2095
+ var ZapierConfigurationError = class extends ZapierError {
2096
+ constructor(message, options = {}) {
2097
+ super(message, options);
2098
+ this.name = "ZapierConfigurationError";
2099
+ this.code = "ZAPIER_CONFIGURATION_ERROR";
2100
+ this.configType = options.configType;
2101
+ }
2102
+ };
2103
+ var ZapierBundleError = class extends ZapierError {
2104
+ constructor(message, options = {}) {
2105
+ super(message, options);
2106
+ this.name = "ZapierBundleError";
2107
+ this.code = "ZAPIER_BUNDLE_ERROR";
2108
+ this.buildErrors = options.buildErrors;
2109
+ }
2110
+ };
2111
+ var ZapierTimeoutError = class extends ZapierError {
2112
+ constructor(message, options = {}) {
2113
+ super(message, options);
2114
+ this.name = "ZapierTimeoutError";
2115
+ this.code = "ZAPIER_TIMEOUT_ERROR";
2116
+ this.attempts = options.attempts;
2117
+ this.maxAttempts = options.maxAttempts;
2118
+ }
2119
+ };
2120
+ var ZapierActionError = class extends ZapierError {
2121
+ constructor(message, options = {}) {
2122
+ super(message, options);
2123
+ this.name = "ZapierActionError";
2124
+ this.code = "ZAPIER_ACTION_ERROR";
2125
+ this.appKey = options.appKey;
2126
+ this.actionKey = options.actionKey;
2127
+ }
2128
+ // Legacy accessor for backward compatibility
2129
+ get actionErrors() {
2130
+ return this.errors;
2131
+ }
2132
+ };
2133
+ var ZapierConflictError = class extends ZapierError {
2134
+ constructor(message, options = {}) {
2135
+ super(message, options);
2136
+ this.name = "ZapierConflictError";
2137
+ this.code = "ZAPIER_CONFLICT_ERROR";
2138
+ this.resourceType = options.resourceType;
2139
+ }
2140
+ };
2141
+ var ZapierRateLimitError = class extends ZapierError {
2142
+ constructor(message, options = {}) {
2143
+ super(message, options);
2144
+ this.name = "ZapierRateLimitError";
2145
+ this.code = "ZAPIER_RATE_LIMIT_ERROR";
2146
+ this.rateLimit = options.rateLimit ?? {};
2147
+ this.retries = options.retries ?? 0;
2148
+ }
2149
+ };
2150
+ var ZapierApprovalError = class extends ZapierError {
2151
+ constructor(message, options = {}) {
2152
+ super(message, options);
2153
+ this.name = "ZapierApprovalError";
2154
+ this.code = "ZAPIER_APPROVAL_ERROR";
2155
+ this.approvalId = options.approvalId;
2156
+ this.approvalStatus = options.status;
2157
+ this.approvalUrl = options.approvalUrl;
2158
+ this.pollUrl = options.pollUrl;
2159
+ this.streamUrl = options.streamUrl;
2160
+ this.reason = options.reason;
2161
+ }
2162
+ };
2163
+ var ZapierRelayError = class extends ZapierError {
2164
+ constructor(message, options = {}) {
2165
+ super(message, options);
2166
+ this.name = "ZapierRelayError";
2167
+ this.code = "ZAPIER_RELAY_ERROR";
2168
+ }
2169
+ };
2170
+ function formatErrorMessage(error) {
2171
+ let message = error.message;
2172
+ if (error.errors && error.errors.length > 0) {
2173
+ const additionalErrors = error.errors.slice(1);
2174
+ if (additionalErrors.length > 0) {
2175
+ const errorDetails = additionalErrors.map((err) => ` \u2022 ${err.detail || err.title || err.code}`).join("\n");
2176
+ message += "\n\nAdditional errors:\n" + errorDetails;
2177
+ }
2178
+ }
2179
+ if (error instanceof ZapierAppNotFoundError && error.appKey) {
2180
+ message += `
2181
+ App key: ${error.appKey}`;
2182
+ }
2183
+ if (error instanceof ZapierActionError && (error.appKey || error.actionKey)) {
2184
+ const context = [];
2185
+ if (error.appKey) context.push(`App: ${error.appKey}`);
2186
+ if (error.actionKey) context.push(`Action: ${error.actionKey}`);
2187
+ message += `
2188
+ ${context.join(", ")}`;
2189
+ }
2190
+ if (error instanceof ZapierResourceNotFoundError && (error.resourceType || error.resourceId)) {
2191
+ const context = [];
2192
+ if (error.resourceType) context.push(`Type: ${error.resourceType}`);
2193
+ if (error.resourceId) context.push(`ID: ${error.resourceId}`);
2194
+ message += `
2195
+ ${context.join(", ")}`;
2196
+ }
2197
+ if (error instanceof ZapierConflictError && error.resourceType) {
2198
+ message += `
2199
+ Type: ${error.resourceType}`;
2200
+ }
2201
+ if (error instanceof ZapierTimeoutError && (error.attempts || error.maxAttempts)) {
2202
+ const context = [];
2203
+ if (error.attempts) context.push(`Attempts: ${error.attempts}`);
2204
+ if (error.maxAttempts) context.push(`Max attempts: ${error.maxAttempts}`);
2205
+ message += `
2206
+ ${context.join(", ")}`;
2207
+ }
2208
+ if (error instanceof ZapierBundleError && error.buildErrors && error.buildErrors.length > 0) {
2209
+ message += "\n\nBuild errors:\n" + error.buildErrors.map((err) => ` \u2022 ${err}`).join("\n");
2210
+ }
2211
+ if (error instanceof ZapierApprovalError && error.approvalUrl) {
2212
+ message += `
2213
+ Approval URL: ${error.approvalUrl}`;
2214
+ }
2215
+ if (error instanceof ZapierRateLimitError) {
2216
+ const { limit, remaining, retryAfterMs } = error.rateLimit;
2217
+ const parts = [];
2218
+ if (limit !== void 0) {
2219
+ const used = remaining !== void 0 ? limit - remaining : limit;
2220
+ parts.push(`${used}/${limit} used`);
2221
+ }
2222
+ if (retryAfterMs !== void 0 && retryAfterMs > 0) {
2223
+ parts.push(`retry in ${formatDuration(retryAfterMs)}`);
2224
+ }
2225
+ if (error.retries > 0) {
2226
+ parts.push(
2227
+ `after ${error.retries} retr${error.retries === 1 ? "y" : "ies"}`
2228
+ );
2229
+ }
2230
+ if (parts.length > 0) {
2231
+ message += `
2232
+ ${parts.join(", ")}`;
2233
+ }
2234
+ }
2235
+ if (error.statusCode && !message.includes(`${error.statusCode}`)) {
2236
+ message += `
2237
+ HTTP Status: ${error.statusCode}`;
2238
+ }
2239
+ return message;
2240
+ }
2241
+ function formatDuration(ms) {
2242
+ const seconds = Math.round(ms / 1e3);
2243
+ if (seconds < 60) return `${seconds}s`;
2244
+ const minutes = Math.round(seconds / 60);
2245
+ if (minutes < 60) return `${minutes}m`;
2246
+ const hours = Math.round(minutes / 60);
2247
+ if (hours < 24) return `${hours}h`;
2248
+ const days = Math.round(hours / 24);
2249
+ return `${days}d`;
2250
+ }
2251
+
2252
+ // src/types/signals.ts
2253
+ var ZapierSignal = class extends Error {
2254
+ constructor(message) {
2255
+ super(message);
2256
+ Object.setPrototypeOf(this, new.target.prototype);
2257
+ }
2258
+ };
2259
+ var ZapierReleaseTriggerMessageSignal = class extends ZapierSignal {
2260
+ constructor() {
2261
+ super(...arguments);
2262
+ this.name = "ZapierReleaseTriggerMessageSignal";
2263
+ this.code = "ZAPIER_RELEASE_TRIGGER_MESSAGE_SIGNAL";
2264
+ }
2265
+ };
2266
+ var ZapierAbortDrainSignal = class extends ZapierSignal {
2267
+ constructor() {
2268
+ super(...arguments);
2269
+ this.name = "ZapierAbortDrainSignal";
2270
+ this.code = "ZAPIER_ABORT_DRAIN_SIGNAL";
1413
2271
  }
1414
2272
  };
1415
2273
  var TriggerInboxCommandBaseSchema = z.object({
@@ -4896,7 +5754,7 @@ var actionResultItemFormatter = {
4896
5754
  id: getStringProperty(obj, "id"),
4897
5755
  key: getStringProperty(obj, "key"),
4898
5756
  description: getStringProperty(obj, "description"),
4899
- data: item,
5757
+ raw: item,
4900
5758
  details: []
4901
5759
  };
4902
5760
  }
@@ -5645,8 +6503,10 @@ var UserProfileItemSchema = z.object({
5645
6503
  });
5646
6504
 
5647
6505
  // src/formatters/userProfile.ts
5648
- var userProfileItemFormatter = {
5649
- format: (item) => {
6506
+ var userProfileItemFormatter = defineFormatter({
6507
+ format: ({
6508
+ item
6509
+ }) => {
5650
6510
  const details = [];
5651
6511
  if (item.email) {
5652
6512
  details.push({ text: item.email, style: "dim" });
@@ -5659,41 +6519,38 @@ var userProfileItemFormatter = {
5659
6519
  }
5660
6520
  return {
5661
6521
  title: item.full_name,
5662
- id: item.id,
6522
+ hint: item.id,
5663
6523
  details
5664
6524
  };
5665
6525
  }
5666
- };
6526
+ });
5667
6527
 
5668
6528
  // src/plugins/getProfile/index.ts
5669
- var getProfilePlugin = definePlugin(
5670
- (sdk) => createPluginMethod(sdk, {
5671
- name: "getProfile",
5672
- categories: ["account"],
5673
- type: "item",
5674
- itemType: "Profile",
5675
- inputSchema: GetProfileSchema,
5676
- outputSchema: UserProfileItemSchema,
5677
- formatter: userProfileItemFormatter,
5678
- handler: async ({ sdk: sdk2 }) => {
5679
- const profile = await sdk2.context.api.get(
5680
- "/zapier/api/v4/profile/",
5681
- { authRequired: true }
5682
- );
5683
- return {
5684
- data: {
5685
- id: String(profile.public_id ?? profile.id),
5686
- first_name: profile.first_name,
5687
- last_name: profile.last_name,
5688
- full_name: `${profile.first_name} ${profile.last_name}`,
5689
- email: profile.email,
5690
- email_confirmed: profile.email_confirmed,
5691
- timezone: profile.timezone
5692
- }
5693
- };
5694
- }
5695
- })
5696
- );
6529
+ var getProfilePlugin = defineMethod({
6530
+ name: "getProfile",
6531
+ imports: [dangerousContextPlugin],
6532
+ inputSchema: GetProfileSchema,
6533
+ output: "item",
6534
+ formatter: userProfileItemFormatter,
6535
+ categories: ["account"],
6536
+ itemType: "Profile",
6537
+ outputSchema: UserProfileItemSchema,
6538
+ run: async ({ imports }) => {
6539
+ const api = imports.context.api;
6540
+ const profile = await api.get("/zapier/api/v4/profile/", {
6541
+ authRequired: true
6542
+ });
6543
+ return {
6544
+ id: String(profile.public_id ?? profile.id),
6545
+ first_name: profile.first_name,
6546
+ last_name: profile.last_name,
6547
+ full_name: `${profile.first_name} ${profile.last_name}`,
6548
+ email: profile.email,
6549
+ email_confirmed: profile.email_confirmed,
6550
+ timezone: profile.timezone
6551
+ };
6552
+ }
6553
+ });
5697
6554
 
5698
6555
  // src/api/auth.ts
5699
6556
  function isJwt(token) {
@@ -6995,7 +7852,7 @@ function parseApprovalReviewStreamPayload(parsed, toolNames) {
6995
7852
  }
6996
7853
 
6997
7854
  // src/sdk-version.ts
6998
- var SDK_VERSION = (typeof process !== "undefined" && process.env ? "0.77.2" : void 0) || "unknown";
7855
+ var SDK_VERSION = (typeof process !== "undefined" && process.env ? "0.78.0" : void 0) || "unknown";
6999
7856
 
7000
7857
  // src/utils/open-url.ts
7001
7858
  var nodePrefix = "node:";
@@ -8240,182 +9097,401 @@ var apiPlugin = definePlugin(
8240
9097
  }
8241
9098
  );
8242
9099
 
8243
- // src/utils/batch-utils.ts
8244
- var DEFAULT_CONCURRENCY = 10;
8245
- var BATCH_START_DELAY_MS = 25;
8246
- var DEFAULT_BATCH_TIMEOUT_MS = 18e4;
8247
- async function batch(tasks, options = {}) {
8248
- const {
8249
- concurrency = DEFAULT_CONCURRENCY,
8250
- retry = true,
8251
- batchDelay = BATCH_START_DELAY_MS,
8252
- timeoutMs = DEFAULT_BATCH_TIMEOUT_MS,
8253
- taskTimeoutMs
8254
- } = options;
8255
- if (concurrency <= 0) {
8256
- throw new Error("Concurrency must be greater than 0");
8257
- }
8258
- if (timeoutMs <= 0) {
8259
- throw new Error("Timeout must be greater than 0");
8260
- }
8261
- if (taskTimeoutMs !== void 0 && taskTimeoutMs <= 0) {
8262
- throw new Error("Task timeout must be greater than 0");
8263
- }
8264
- if (tasks.length === 0) {
8265
- return [];
8266
- }
8267
- const startTime = Date.now();
8268
- const results = new Array(tasks.length);
8269
- const taskQueue = tasks.map((task, index) => ({
8270
- index,
8271
- task,
8272
- errorCount: 0
8273
- }));
8274
- async function executeTask(taskState) {
8275
- const { index, task, errorCount } = taskState;
8276
- try {
8277
- let result;
8278
- if (taskTimeoutMs !== void 0) {
8279
- const timeoutPromise = sleep(taskTimeoutMs).then(() => {
9100
+ // src/core-stack.ts
9101
+ var zapierCorePlugin = createCorePlugin({
9102
+ adaptError: zapierAdaptError
9103
+ });
9104
+ function createZapierCoreStack() {
9105
+ return createPluginStack().use(zapierCorePlugin);
9106
+ }
9107
+ var GetConnectionStartUrlSchema = z.object({
9108
+ app: AppPropertySchema
9109
+ }).describe(
9110
+ "Mint a short-lived URL that begins an SDK-initiated connection flow. The URL is signed by zapier.com and bound to the current user/account \u2014 opening it in a different browser session will fail the binding check. Returns the URL as data so the caller decides what to do with it.\n\nUse this directly (rather than the higher-level `create-connection`) when you want either of: (a) hand off the URL and *not* block waiting for completion \u2014 call this alone, skip `wait-for-new-connection` entirely, or (b) do something custom between minting the URL and waiting for the connection \u2014 call this, then email or DM the URL, render it as a QR code for mobile sign-in, etc., then call `wait-for-new-connection`. For the common case where you'd just print and poll back-to-back, `create-connection` is one call.\n\nPair with `wait-for-new-connection` to detect completion: pass the `startedAt` returned here straight through (it's the server's mint time, so polling isn't affected by client clock skew). Example (JS):\n\n```ts\nconst { data: { url, app, startedAt } } = await zapier.getConnectionStartUrl({ app: 'slack' });\n// hand `url` off \u2014 print it, DM it, email it, render a button, whatever\nconst { data: conn } = await zapier.waitForNewConnection({ app, startedAt });\n```"
9111
+ );
9112
+ var GetConnectionStartUrlItemSchema = z.object({
9113
+ url: z.string().describe(
9114
+ "URL the user should open in their browser to complete the auth flow. Single-use, time-limited."
9115
+ ),
9116
+ expiresAt: z.number().describe(
9117
+ "Unix timestamp (seconds) after which the URL's signature is rejected by zapier.com."
9118
+ ),
9119
+ startedAt: z.number().describe(
9120
+ "Unix timestamp (seconds) when the server minted the URL. Use it as the `startedAt` for `wait-for-new-connection` so polling is anchored to server time rather than a possibly-skewed client clock."
9121
+ ),
9122
+ app: z.string().describe(
9123
+ "Versionless app key the URL was minted for (e.g., 'SlackCLIAPI'). Useful for downstream filtering."
9124
+ )
9125
+ }).describe(
9126
+ "The signed start-URL plus metadata needed to poll for completion."
9127
+ );
9128
+
9129
+ // src/plugins/getConnectionStartUrl/index.ts
9130
+ var START_PATH = "/zapier/api/authentications/v1/sdk/connections/start";
9131
+ var getConnectionStartUrlPlugin = definePlugin(
9132
+ (sdk) => createPluginMethod(sdk, {
9133
+ name: "getConnectionStartUrl",
9134
+ categories: ["connection"],
9135
+ type: "create",
9136
+ itemType: "ConnectionStartUrl",
9137
+ inputSchema: GetConnectionStartUrlSchema,
9138
+ outputSchema: GetConnectionStartUrlItemSchema,
9139
+ resolvers: { app: appKeyResolver },
9140
+ handler: async ({
9141
+ sdk: inner,
9142
+ options
9143
+ }) => {
9144
+ const versionedKey = await inner.context.getVersionedImplementationId(
9145
+ options.app
9146
+ );
9147
+ const selectedApi = versionedKey ? versionedKey.split("@")[0] : options.app;
9148
+ setMethodMetadata({ selectedApi });
9149
+ const response = await inner.context.api.post(
9150
+ START_PATH,
9151
+ { selected_api: selectedApi },
9152
+ { authRequired: true }
9153
+ );
9154
+ return {
9155
+ data: GetConnectionStartUrlItemSchema.parse({
9156
+ url: response.url,
9157
+ expiresAt: response.expires_at,
9158
+ startedAt: response.started_at,
9159
+ app: selectedApi
9160
+ })
9161
+ };
9162
+ }
9163
+ })
9164
+ );
9165
+ var WaitForNewConnectionSchema = z.object({
9166
+ app: AppPropertySchema,
9167
+ startedAt: z.number().int().nonnegative().describe(
9168
+ "Unix timestamp (seconds). Only connections whose `date` is at or after this value count as 'new'. Prefer the `startedAt` returned by `get-connection-start-url` \u2014 it's server-stamped, so the comparison isn't thrown off by client clock skew. If you mint the timestamp yourself, capture it *before* showing the start URL so a fast OAuth completion isn't missed."
9169
+ ),
9170
+ timeoutMs: z.number().int().positive().optional().describe(
9171
+ "How long to wait before giving up. Default 5 minutes (300_000)."
9172
+ ),
9173
+ pollIntervalMs: z.number().int().positive().optional().describe(
9174
+ "Delay before the first poll request, in ms. Default 3 seconds (3_000). Subsequent polling cadence is managed by the SDK's polling primitive (backoff with sane defaults)."
9175
+ )
9176
+ }).describe(
9177
+ "Wait for a new connection to appear for the given app. Polls `/api/v0/connections` with server-side `ordering=-date` until the most recent matching row's `date` is at or after the started-at timestamp, then returns it. Pair with `get-connection-start-url` \u2014 that mints the URL the user opens, this waits for the resulting connection to land. Errors with a timeout after the configured timeout (default 5 min). Example (JS):\n\n```ts\nconst { data: { url, app, startedAt } } = await zapier.getConnectionStartUrl({ app: 'slack' });\n// show `url` to the user via the channel they're reading from\nconst { data: conn } = await zapier.waitForNewConnection({ app, startedAt });\n```"
9178
+ );
9179
+ var WaitForNewConnectionItemSchema = z.object({
9180
+ id: z.string().describe(
9181
+ "The new connection's ID. Public UUID when available, falling back to the numeric ID."
9182
+ ),
9183
+ app: z.string().describe(
9184
+ "Versionless app key the connection was created for (e.g., 'SlackCLIAPI')."
9185
+ ),
9186
+ title: z.string().nullable().optional().describe(
9187
+ "Human-readable connection title set by the auth flow, when available."
9188
+ )
9189
+ }).describe("The new connection that was detected.");
9190
+
9191
+ // src/plugins/waitForNewConnection/index.ts
9192
+ var CONNECTIONS_PATH = "/api/v0/connections";
9193
+ var waitForNewConnectionPlugin = definePlugin(
9194
+ (sdk) => createPluginMethod(sdk, {
9195
+ name: "waitForNewConnection",
9196
+ categories: ["connection"],
9197
+ type: "item",
9198
+ itemType: "Connection",
9199
+ inputSchema: WaitForNewConnectionSchema,
9200
+ outputSchema: WaitForNewConnectionItemSchema,
9201
+ resolvers: { app: appKeyResolver },
9202
+ handler: async ({
9203
+ sdk: inner,
9204
+ options
9205
+ }) => {
9206
+ const versionedKey = await inner.context.getVersionedImplementationId(
9207
+ options.app
9208
+ );
9209
+ const appKey = versionedKey ? versionedKey.split("@")[0] : options.app;
9210
+ setMethodMetadata({ selectedApi: appKey });
9211
+ try {
9212
+ const top = await inner.context.api.poll(
9213
+ CONNECTIONS_PATH,
9214
+ {
9215
+ searchParams: {
9216
+ app_key: appKey,
9217
+ // Scope to the current user's own connections. The connection
9218
+ // we're waiting on is by definition owned by the caller; without
9219
+ // this the one-row head-check could match a teammate's freshly
9220
+ // created connection for the same app.
9221
+ owner: "me",
9222
+ is_expired: "false",
9223
+ ordering: "-date",
9224
+ page_size: "1"
9225
+ },
9226
+ authRequired: true,
9227
+ timeoutMs: options.timeoutMs ?? 3e5,
9228
+ initialDelay: options.pollIntervalMs ?? 3e3,
9229
+ isPending: (body) => {
9230
+ const rows = body.data ?? [];
9231
+ const head = rows[0];
9232
+ if (!head?.date) return true;
9233
+ const created = Math.floor(new Date(head.date).getTime() / 1e3);
9234
+ return !Number.isFinite(created) || created < options.startedAt;
9235
+ },
9236
+ resultExtractor: (body) => (
9237
+ // `isPending` guaranteed a fresh row at index 0 before this fires.
9238
+ body.data[0]
9239
+ )
9240
+ }
9241
+ );
9242
+ return {
9243
+ data: WaitForNewConnectionItemSchema.parse({
9244
+ id: String(top.public_id ?? top.id),
9245
+ app: appKey,
9246
+ title: top.title ?? null
9247
+ })
9248
+ };
9249
+ } catch (err) {
9250
+ if (err instanceof ZapierTimeoutError) {
8280
9251
  throw new ZapierTimeoutError(
8281
- `Task timed out after ${taskTimeoutMs}ms`
9252
+ `Timed out waiting for a new "${appKey}" connection. If the user completed the auth flow, retrieve the connection via sdk.getConnection({ id }) with the ID shown on the completion page.`
8282
9253
  );
8283
- });
8284
- result = await Promise.race([task(), timeoutPromise]);
8285
- } else {
8286
- result = await task();
8287
- }
8288
- results[index] = { status: "fulfilled", value: result };
8289
- } catch (error) {
8290
- const newErrorCount = errorCount + 1;
8291
- const isTimeout = error instanceof ZapierTimeoutError;
8292
- if (retry && !isTimeout && newErrorCount < MAX_CONSECUTIVE_ERRORS) {
8293
- const waitTime = calculateErrorBackoffMs(1e3, newErrorCount);
8294
- await sleep(waitTime);
8295
- taskQueue.push({
8296
- index,
8297
- task,
8298
- errorCount: newErrorCount
8299
- });
8300
- } else {
8301
- results[index] = { status: "rejected", reason: error };
9254
+ }
9255
+ throw err;
8302
9256
  }
8303
9257
  }
9258
+ })
9259
+ );
9260
+
9261
+ // src/utils/should-open-browser.ts
9262
+ function shouldOpenBrowser() {
9263
+ if (isCiEnv()) return false;
9264
+ const env = globalThis.process?.env;
9265
+ if (env?.SSH_TTY || env?.SSH_CONNECTION) return false;
9266
+ if (globalThis.process?.platform === "linux" && !env?.DISPLAY && !env?.WAYLAND_DISPLAY) {
9267
+ return false;
8304
9268
  }
8305
- async function worker() {
8306
- while (taskQueue.length > 0) {
8307
- const elapsedTime = Date.now() - startTime;
8308
- if (elapsedTime >= timeoutMs) {
8309
- throw new ZapierTimeoutError(
8310
- `Batch operation timed out after ${Math.floor(elapsedTime / 1e3)}s. ${taskQueue.length} task(s) not completed.`
8311
- );
9269
+ return true;
9270
+ }
9271
+ function isCiEnv() {
9272
+ const env = globalThis.process?.env;
9273
+ return !!(env?.CI || env?.CONTINUOUS_INTEGRATION || env?.GITHUB_ACTIONS || env?.JENKINS_URL || env?.GITLAB_CI || env?.CIRCLECI || env?.TRAVIS || env?.BUILDKITE || env?.DRONE || env?.BITBUCKET_PIPELINES_UUID);
9274
+ }
9275
+ var CreateConnectionSchema = z.object({
9276
+ app: AppPropertySchema,
9277
+ browser: z.enum(["auto", "always", "never"]).default("auto").describe(
9278
+ "When to auto-open the URL in a browser. `auto` (default) opens in local sessions and skips opening in CI / SSH / headless-Linux. `always` forces the open attempt. `never` skips it. The URL is always printed to stderr regardless \u2014 a failed or skipped open degrades gracefully to copy-paste."
9279
+ ),
9280
+ timeoutMs: z.number().int().positive().optional().describe(
9281
+ "How long to wait for the user to complete the connection flow before giving up. Default 5 minutes (300_000)."
9282
+ ),
9283
+ pollIntervalMs: z.number().int().positive().optional().describe(
9284
+ "Delay before the first poll request, in ms. Default 3 seconds (3_000). Subsequent polling cadence is managed by the SDK's polling primitive (backoff with sane defaults)."
9285
+ )
9286
+ }).describe(
9287
+ "Create a new app connection, end-to-end. Mints the start URL via `get-connection-start-url`, prints it to stderr, opportunistically opens it in a browser when it looks safe to do so (skipping CI / SSH / headless-Linux by default \u2014 pass `--browser always` to force, `--browser never` to suppress), then polls via `wait-for-new-connection` until the user completes OAuth and the new connection appears. Returns the connection.\n\nThis is the right command for most callers. Reach for the lower-level building blocks when you want either of: (a) hand off the URL and *not* block on completion \u2014 call `get-connection-start-url` alone, no `wait-for-new-connection` needed, or (b) do something custom between minting the URL and waiting \u2014 call `get-connection-start-url`, do your work (email or DM the URL, render a QR code, etc.), then `wait-for-new-connection`."
9288
+ );
9289
+ var CreateConnectionItemSchema = z.object({
9290
+ id: z.string().describe(
9291
+ "The new connection's ID. Public UUID when available, falling back to the numeric ID."
9292
+ ),
9293
+ app: z.string().describe(
9294
+ "Versionless app key the connection was created for (e.g., 'SlackCLIAPI')."
9295
+ ),
9296
+ title: z.string().nullable().optional().describe(
9297
+ "Human-readable connection title set by the auth flow, when available."
9298
+ )
9299
+ }).describe("The newly created connection.");
9300
+
9301
+ // src/plugins/createConnection/index.ts
9302
+ var createConnectionPlugin = definePlugin(
9303
+ (sdk) => createPluginMethod(sdk, {
9304
+ name: "createConnection",
9305
+ categories: ["connection"],
9306
+ type: "create",
9307
+ itemType: "Connection",
9308
+ inputSchema: CreateConnectionSchema,
9309
+ outputSchema: CreateConnectionItemSchema,
9310
+ resolvers: { app: appKeyResolver },
9311
+ formatter: {
9312
+ format: (item) => ({
9313
+ title: `Connection created: ${item.title || item.id}`,
9314
+ id: item.id,
9315
+ details: [
9316
+ { text: `App: ${item.app}`, style: "normal" },
9317
+ { text: `ID: ${item.id}`, style: "accent" }
9318
+ ]
9319
+ })
9320
+ },
9321
+ handler: async ({
9322
+ sdk: inner,
9323
+ options
9324
+ }) => {
9325
+ const { data: start } = await inner.getConnectionStartUrl({
9326
+ app: options.app
9327
+ });
9328
+ setMethodMetadata({ selectedApi: start.app });
9329
+ console.error(
9330
+ `
9331
+ Open this URL to complete the connection:
9332
+ ${start.url}
9333
+ `
9334
+ );
9335
+ const shouldOpen = options.browser === "always" || options.browser === "auto" && shouldOpenBrowser();
9336
+ if (shouldOpen) {
9337
+ try {
9338
+ await open_url_default(start.url);
9339
+ } catch {
9340
+ }
8312
9341
  }
8313
- const taskState = taskQueue.shift();
8314
- if (!taskState) break;
8315
- await executeTask(taskState);
8316
- if (taskQueue.length > 0 && batchDelay > 0) {
8317
- await sleep(batchDelay);
9342
+ const { data: fresh } = await inner.waitForNewConnection({
9343
+ app: start.app,
9344
+ // Server-stamped mint time: measured on the same clock as a
9345
+ // connection's `date`, so the freshness check is immune to
9346
+ // client/server clock skew.
9347
+ startedAt: start.startedAt,
9348
+ timeoutMs: options.timeoutMs,
9349
+ pollIntervalMs: options.pollIntervalMs
9350
+ });
9351
+ return {
9352
+ data: CreateConnectionItemSchema.parse({
9353
+ id: fresh.id,
9354
+ app: start.app,
9355
+ title: fresh.title ?? null
9356
+ })
9357
+ };
9358
+ }
9359
+ })
9360
+ );
9361
+
9362
+ // src/plugins/deprecated/authentications.ts
9363
+ var listAuthenticationsPlugin = definePlugin(
9364
+ (sdk) => ({
9365
+ listAuthentications: sdk.listConnections,
9366
+ context: {
9367
+ meta: {
9368
+ listAuthentications: {
9369
+ packages: ["cli", "mcp"],
9370
+ categories: ["connection"],
9371
+ deprecation: { message: "Use listConnections instead." },
9372
+ type: "list",
9373
+ itemType: "Connection",
9374
+ inputSchema: ListConnectionsQuerySchema,
9375
+ outputSchema: ConnectionItemSchema,
9376
+ formatter: connectionItemFormatter
9377
+ }
8318
9378
  }
8319
9379
  }
8320
- }
8321
- const workerCount = Math.min(concurrency, tasks.length);
8322
- const workers = [];
8323
- for (let i = 0; i < workerCount; i++) {
8324
- workers.push(worker());
8325
- if (i < workerCount - 1 && batchDelay > 0) {
8326
- await sleep(batchDelay / 10);
9380
+ })
9381
+ );
9382
+ var getAuthenticationPlugin = definePlugin(
9383
+ (sdk) => ({
9384
+ getAuthentication: sdk.getConnection,
9385
+ context: {
9386
+ meta: {
9387
+ getAuthentication: {
9388
+ packages: ["cli", "mcp"],
9389
+ categories: ["connection"],
9390
+ deprecation: { message: "Use getConnection instead." },
9391
+ type: "item",
9392
+ itemType: "Connection",
9393
+ inputSchema: GetConnectionParamSchema,
9394
+ outputSchema: ConnectionItemSchema,
9395
+ formatter: connectionItemFormatter
9396
+ }
9397
+ }
8327
9398
  }
8328
- }
8329
- await Promise.all(workers);
8330
- return results;
8331
- }
8332
-
8333
- // src/plugins/connections/index.ts
8334
- var connectionsPlugin = definePlugin(
8335
- (sdk) => {
8336
- let cachedMap;
8337
- async function loadConnectionsMap() {
8338
- if (cachedMap === void 0) {
8339
- cachedMap = await sdk.context.getManifestConnections() ?? null;
9399
+ })
9400
+ );
9401
+ var findFirstAuthenticationPlugin = definePlugin(
9402
+ (sdk) => ({
9403
+ findFirstAuthentication: sdk.findFirstConnection,
9404
+ context: {
9405
+ meta: {
9406
+ findFirstAuthentication: {
9407
+ packages: ["cli", "mcp"],
9408
+ categories: ["connection"],
9409
+ deprecation: { message: "Use findFirstConnection instead." },
9410
+ type: "item",
9411
+ itemType: "Connection",
9412
+ inputSchema: FindFirstConnectionSchema,
9413
+ outputSchema: ConnectionItemSchema,
9414
+ formatter: connectionItemFormatter
9415
+ }
8340
9416
  }
8341
- return cachedMap;
8342
9417
  }
8343
- return {
8344
- context: {
8345
- resolveConnection: async (name) => {
8346
- const map = await loadConnectionsMap();
8347
- return map?.[name];
8348
- },
8349
- getConnectionsMap: async () => {
8350
- return loadConnectionsMap();
9418
+ })
9419
+ );
9420
+ var findUniqueAuthenticationPlugin = definePlugin(
9421
+ (sdk) => ({
9422
+ findUniqueAuthentication: sdk.findUniqueConnection,
9423
+ context: {
9424
+ meta: {
9425
+ findUniqueAuthentication: {
9426
+ packages: ["cli", "mcp"],
9427
+ categories: ["connection"],
9428
+ deprecation: { message: "Use findUniqueConnection instead." },
9429
+ type: "item",
9430
+ itemType: "Connection",
9431
+ inputSchema: FindUniqueConnectionSchema,
9432
+ outputSchema: ConnectionItemSchema,
9433
+ formatter: connectionItemFormatter
9434
+ }
9435
+ }
9436
+ }
9437
+ })
9438
+ );
9439
+
9440
+ // src/plugins/deprecated/inputFields.ts
9441
+ var listInputFieldsDeprecatedPlugin = definePlugin(
9442
+ (sdk) => ({
9443
+ listInputFields: sdk.listActionInputFields,
9444
+ context: {
9445
+ meta: {
9446
+ listInputFields: {
9447
+ categories: ["action"],
9448
+ deprecation: { message: "Use listActionInputFields instead." },
9449
+ type: "list",
9450
+ itemType: "RootField",
9451
+ inputSchema: ListActionInputFieldsInputSchema,
9452
+ outputSchema: RootFieldItemSchema,
9453
+ formatter: rootFieldItemFormatter,
9454
+ defaultPageSize: DEFAULT_PAGE_SIZE
8351
9455
  }
8352
9456
  }
8353
- };
8354
- }
9457
+ }
9458
+ })
8355
9459
  );
8356
-
8357
- // src/plugins/capabilities/index.ts
8358
- function toDescription(key) {
8359
- const words = key.replace(/^can/, "").replace(/([A-Z])/g, " $1").trim().toLowerCase();
8360
- return `To ${words}`;
8361
- }
8362
- function toEnvVar(key) {
8363
- return "ZAPIER_" + key.replace(/([A-Z])/g, "_$1").toUpperCase();
8364
- }
8365
- function toCliFlag(key) {
8366
- return "--" + key.replace(/([A-Z])/g, "-$1").toLowerCase();
8367
- }
8368
- function buildCapabilityMessage(key) {
8369
- return [
8370
- `${toDescription(key)}, use ${toCliFlag(key)} in the CLI,`,
8371
- `set ${key}: true in SDK options or .zapierrc,`,
8372
- `or set ${toEnvVar(key)}=true.`
8373
- ].join(" ");
8374
- }
8375
- var GATED_FLAGS = [
8376
- "canIncludeSharedConnections",
8377
- "canIncludeSharedTables",
8378
- "canDeleteTables"
8379
- ];
8380
- function isEnabledByEnv(key) {
8381
- const value = globalThis.process?.env?.[toEnvVar(key)];
8382
- if (value === void 0) return void 0;
8383
- if (value === "true" || value === "1") return true;
8384
- if (value === "false" || value === "0") return false;
8385
- return void 0;
8386
- }
8387
- var capabilitiesPlugin = definePlugin(
8388
- (sdk) => {
8389
- const options = sdk.context.options ?? {};
8390
- let cached;
8391
- async function resolveFlags() {
8392
- if (cached) return cached;
8393
- const manifest = await sdk.context.getResolvedManifest();
8394
- cached = {};
8395
- for (const flag of GATED_FLAGS) {
8396
- cached[flag] = Boolean(
8397
- options[flag] ?? isEnabledByEnv(flag) ?? manifest?.[flag]
8398
- );
9460
+ var listInputFieldChoicesDeprecatedPlugin = definePlugin(
9461
+ (sdk) => ({
9462
+ listInputFieldChoices: sdk.listActionInputFieldChoices,
9463
+ context: {
9464
+ meta: {
9465
+ listInputFieldChoices: {
9466
+ categories: ["action"],
9467
+ deprecation: {
9468
+ message: "Use listActionInputFieldChoices instead."
9469
+ },
9470
+ type: "list",
9471
+ itemType: "InputFieldChoiceItem",
9472
+ inputSchema: ListActionInputFieldChoicesInputSchema,
9473
+ outputSchema: InputFieldChoiceItemSchema,
9474
+ formatter: inputFieldChoiceItemFormatter,
9475
+ defaultPageSize: DEFAULT_PAGE_SIZE
9476
+ }
8399
9477
  }
8400
- return cached;
8401
9478
  }
8402
- return {
8403
- context: {
8404
- checkCapability: async (key) => {
8405
- const flags = await resolveFlags();
8406
- if (flags[key]) return;
8407
- throw new ZapierConfigurationError(
8408
- buildCapabilityMessage(key) + " (If you are an AI agent, you MUST NOT retry. Ask the user if they want to enable this.)",
8409
- { configType: key }
8410
- );
8411
- },
8412
- hasCapability: async (key) => {
8413
- const flags = await resolveFlags();
8414
- return flags[key];
9479
+ })
9480
+ );
9481
+ var getInputFieldsSchemaDeprecatedPlugin = definePlugin(
9482
+ (sdk) => ({
9483
+ getInputFieldsSchema: sdk.getActionInputFieldsSchema,
9484
+ context: {
9485
+ meta: {
9486
+ getInputFieldsSchema: {
9487
+ categories: ["action"],
9488
+ deprecation: { message: "Use getActionInputFieldsSchema instead." },
9489
+ type: "function",
9490
+ inputSchema: GetActionInputFieldsSchemaInputSchema
8415
9491
  }
8416
9492
  }
8417
- };
8418
- }
9493
+ }
9494
+ })
8419
9495
  );
8420
9496
  var TableApiItemSchema = z.object({
8421
9497
  id: z.string(),
@@ -8532,256 +9608,67 @@ var listTablesPlugin = definePlugin(
8532
9608
  }
8533
9609
  })
8534
9610
  );
8535
- var GetTableApiResponseSchema = z.object({
8536
- data: TableApiItemSchema
8537
- });
8538
- var GetTableDescription = "Get detailed information about a specific table";
8539
- var GetTableOptionsSchema = z.object({
8540
- table: TablePropertySchema
8541
- }).describe(GetTableDescription).meta({ aliases: { tableId: "table" } });
8542
- var GetTableOptionsSchemaDeprecated = z.object({
8543
- tableId: z.string().regex(/^[A-Z0-9]{26}$/, "Table ID must be a valid ULID").describe("The unique identifier of the table to retrieve")
8544
- });
8545
- var GetTableOptionsInputSchema = z.union([GetTableOptionsSchema, GetTableOptionsSchemaDeprecated]).describe(GetTableDescription);
8546
-
8547
- // src/plugins/tables/getTable/index.ts
8548
- var getTablePlugin = definePlugin(
8549
- (sdk) => createPluginMethod(sdk, {
8550
- ...tablesDefaults,
8551
- name: "getTable",
8552
- type: "item",
8553
- itemType: "Table",
8554
- inputSchema: GetTableOptionsInputSchema,
8555
- outputSchema: TableItemSchema,
8556
- resolvers: { table: tableIdResolver },
8557
- handler: async ({ sdk: sdk2, options }) => {
8558
- const tableId = "table" in options ? options.table : options.tableId;
8559
- const rawResponse = await sdk2.context.api.get(
8560
- `/tables/api/v1/tables/${tableId}`,
8561
- {
8562
- authRequired: true,
8563
- resource: { type: "table", id: tableId }
8564
- }
8565
- );
8566
- const response = GetTableApiResponseSchema.parse(rawResponse);
8567
- return { data: transformTableItem(response.data) };
8568
- }
8569
- })
8570
- );
8571
- var CreateTableApiResponseSchema = z.object({
8572
- data: TableApiItemSchema
8573
- });
8574
- var CreateTableOptionsSchema = z.object({
8575
- name: z.string().min(1).describe("The name for the new table"),
8576
- description: z.string().optional().describe("An optional description of the table")
8577
- }).describe("Create a new table");
8578
-
8579
- // src/plugins/tables/createTable/index.ts
8580
- var createTablePlugin = definePlugin(
8581
- (sdk) => createPluginMethod(sdk, {
8582
- ...tablesDefaults,
8583
- name: "createTable",
8584
- type: "create",
8585
- itemType: "Table",
8586
- inputSchema: CreateTableOptionsSchema,
8587
- outputSchema: TableItemSchema,
8588
- resolvers: { name: tableNameResolver },
8589
- handler: async ({ sdk: sdk2, options }) => {
8590
- const rawResponse = await sdk2.context.api.post(
8591
- "/tables/api/v1/tables",
8592
- { name: options.name, description: options.description },
8593
- { authRequired: true }
8594
- );
8595
- const response = CreateTableApiResponseSchema.parse(rawResponse);
8596
- return { data: transformTableItem(response.data) };
8597
- }
8598
- })
8599
- );
8600
- var DeleteTableDescription = "Delete a table by its ID";
8601
- var DeleteTableOptionsSchema = z.object({
8602
- table: TablePropertySchema
8603
- }).describe(DeleteTableDescription).meta({ aliases: { tableId: "table" } });
8604
- var DeleteTableOptionsSchemaDeprecated = z.object({
8605
- tableId: z.string().regex(/^[A-Z0-9]{26}$/, "Table ID must be a valid ULID").describe("The unique identifier of the table to delete")
8606
- });
8607
- var DeleteTableOptionsInputSchema = z.union([DeleteTableOptionsSchema, DeleteTableOptionsSchemaDeprecated]).describe(DeleteTableDescription);
8608
-
8609
- // src/plugins/tables/deleteTable/index.ts
8610
- var deleteTablePlugin = definePlugin(
8611
- (sdk) => createPluginMethod(sdk, {
8612
- ...tablesDefaults,
8613
- name: "deleteTable",
8614
- type: "delete",
8615
- itemType: "Table",
8616
- inputSchema: DeleteTableOptionsInputSchema,
8617
- resolvers: { table: tableIdResolver },
8618
- confirm: "delete",
8619
- handler: async ({ sdk: sdk2, options }) => {
8620
- await sdk2.context.checkCapability("canDeleteTables");
8621
- const tableId = "table" in options ? options.table : options.tableId;
8622
- await sdk2.context.api.delete(
8623
- `/tables/api/v1/tables/${tableId}`,
8624
- void 0,
8625
- {
8626
- authRequired: true,
8627
- resource: { type: "table", id: tableId }
8628
- }
8629
- );
8630
- return { success: true };
8631
- }
8632
- })
8633
- );
8634
-
8635
- // src/formatters/tableField.ts
8636
- var tableFieldItemFormatter = {
8637
- format: (item) => ({
8638
- title: item.name,
8639
- id: item.id,
8640
- details: [{ text: `Type: ${item.type}`, style: "dim" }]
8641
- })
8642
- };
8643
-
8644
- // src/plugins/tables/listTableFields/index.ts
8645
- var listTableFieldsPlugin = definePlugin(
8646
- (sdk) => createPluginMethod(sdk, {
8647
- ...tablesDefaults,
8648
- name: "listTableFields",
8649
- type: "list",
8650
- itemType: "Field",
8651
- inputSchema: ListTableFieldsOptionsInputSchema,
8652
- outputSchema: FieldItemSchema,
8653
- formatter: tableFieldItemFormatter,
8654
- resolvers: { table: tableIdResolver },
8655
- handler: async ({ sdk: sdk2, options }) => {
8656
- const { api } = sdk2.context;
8657
- const tableId = "table" in options ? options.table : options.tableId;
8658
- const fieldKeys = "fields" in options ? options.fields : options.fieldKeys;
8659
- const searchParams = {};
8660
- if (fieldKeys && fieldKeys.length > 0) {
8661
- const numericIds = await resolveFieldKeys({
8662
- api,
8663
- tableId,
8664
- fieldKeys
8665
- });
8666
- searchParams.field_ids = numericIds.join(",");
8667
- }
8668
- if (options.trash) {
8669
- searchParams.trash = options.trash;
8670
- }
8671
- const rawResponse = await api.get(
8672
- `/tables/api/v1/tables/${tableId}/fields`,
8673
- {
8674
- searchParams: Object.keys(searchParams).length > 0 ? searchParams : void 0,
8675
- authRequired: true,
8676
- resource: { type: "table", id: tableId }
8677
- }
8678
- );
8679
- const response = ListTableFieldsApiResponseSchema.parse(rawResponse);
8680
- return { data: response.data.map(transformFieldItem) };
8681
- }
8682
- })
8683
- );
8684
- var FieldChangesetItemSchema = z.object({
8685
- new: FieldApiItemSchema,
8686
- old: FieldApiItemSchema.nullable(),
8687
- kind: z.enum(["created", "updated", "deleted"])
8688
- });
8689
- var CreateTableFieldsApiResponseSchema = z.object({
8690
- data: z.array(FieldChangesetItemSchema),
8691
- meta: z.object({
8692
- did_change: z.boolean()
8693
- }).optional()
8694
- });
8695
- var NewFieldSchema = z.object({
8696
- type: FieldTypeSchema.describe("The data type of the field"),
8697
- name: z.string().min(1).describe("The display name of the field"),
8698
- options: z.record(z.string(), z.unknown()).optional().describe("Data configuration options for the field"),
8699
- config: z.record(z.string(), z.unknown()).optional().describe("Display configuration for the field")
8700
- });
8701
- var CreateTableFieldsDescription = "Create one or more fields in a table";
8702
- var CreateTableFieldsBase = z.object({
8703
- fields: z.array(NewFieldSchema).min(1).describe("Array of field definitions to create")
9611
+ var GetTableApiResponseSchema = z.object({
9612
+ data: TableApiItemSchema
8704
9613
  });
8705
- var CreateTableFieldsOptionsSchema = z.object({
9614
+ var GetTableDescription = "Get detailed information about a specific table";
9615
+ var GetTableOptionsSchema = z.object({
8706
9616
  table: TablePropertySchema
8707
- }).merge(CreateTableFieldsBase).describe(CreateTableFieldsDescription).meta({ aliases: { tableId: "table" } });
8708
- var CreateTableFieldsOptionsSchemaDeprecated = z.object({
8709
- tableId: z.string().regex(/^[A-Z0-9]{26}$/, "Table ID must be a valid ULID").describe("The unique identifier of the table")
8710
- }).merge(CreateTableFieldsBase);
8711
- var CreateTableFieldsOptionsInputSchema = z.union([
8712
- CreateTableFieldsOptionsSchema,
8713
- CreateTableFieldsOptionsSchemaDeprecated
8714
- ]).describe(CreateTableFieldsDescription);
9617
+ }).describe(GetTableDescription).meta({ aliases: { tableId: "table" } });
9618
+ var GetTableOptionsSchemaDeprecated = z.object({
9619
+ tableId: z.string().regex(/^[A-Z0-9]{26}$/, "Table ID must be a valid ULID").describe("The unique identifier of the table to retrieve")
9620
+ });
9621
+ var GetTableOptionsInputSchema = z.union([GetTableOptionsSchema, GetTableOptionsSchemaDeprecated]).describe(GetTableDescription);
8715
9622
 
8716
- // src/plugins/tables/createTableFields/index.ts
8717
- var createTableFieldsPlugin = definePlugin(
9623
+ // src/plugins/tables/getTable/index.ts
9624
+ var getTablePlugin = definePlugin(
8718
9625
  (sdk) => createPluginMethod(sdk, {
8719
9626
  ...tablesDefaults,
8720
- name: "createTableFields",
8721
- type: "create",
8722
- itemType: "Field",
8723
- returnType: "FieldItem[]",
8724
- inputSchema: CreateTableFieldsOptionsInputSchema,
8725
- outputSchema: FieldItemSchema,
8726
- formatter: tableFieldItemFormatter,
8727
- resolvers: { table: tableIdResolver, fields: tableFieldsResolver },
9627
+ name: "getTable",
9628
+ type: "item",
9629
+ itemType: "Table",
9630
+ inputSchema: GetTableOptionsInputSchema,
9631
+ outputSchema: TableItemSchema,
9632
+ resolvers: { table: tableIdResolver },
8728
9633
  handler: async ({ sdk: sdk2, options }) => {
8729
9634
  const tableId = "table" in options ? options.table : options.tableId;
8730
- const rawResponse = await sdk2.context.api.post(
8731
- `/tables/api/v1/tables/${tableId}/fields`,
8732
- { new_fields: options.fields },
9635
+ const rawResponse = await sdk2.context.api.get(
9636
+ `/tables/api/v1/tables/${tableId}`,
8733
9637
  {
8734
9638
  authRequired: true,
8735
9639
  resource: { type: "table", id: tableId }
8736
9640
  }
8737
9641
  );
8738
- const response = CreateTableFieldsApiResponseSchema.parse(rawResponse);
8739
- return {
8740
- data: response.data.map(
8741
- (changeset) => transformFieldItem(changeset.new)
8742
- )
8743
- };
9642
+ const response = GetTableApiResponseSchema.parse(rawResponse);
9643
+ return { data: transformTableItem(response.data) };
8744
9644
  }
8745
9645
  })
8746
9646
  );
8747
- var DeleteTableFieldsDescription = "Delete one or more fields from a table";
8748
- var DeleteTableFieldsOptionsSchema = z.object({
8749
- table: TablePropertySchema,
8750
- fields: FieldsPropertySchema.min(1)
8751
- }).describe(DeleteTableFieldsDescription).meta({ aliases: { tableId: "table", fieldKeys: "fields" } });
8752
- var DeleteTableFieldsOptionsSchemaDeprecated = z.object({
8753
- tableId: z.string().regex(/^[A-Z0-9]{26}$/, "Table ID must be a valid ULID").describe("The unique identifier of the table"),
8754
- fieldKeys: z.array(z.union([z.string(), z.number()])).min(1).describe(
8755
- 'Fields to delete. Accepts field names (e.g., "Email") or IDs (e.g., "f6", "6", or 6).'
8756
- )
9647
+ var DeleteTableDescription = "Delete a table by its ID";
9648
+ var DeleteTableOptionsSchema = z.object({
9649
+ table: TablePropertySchema
9650
+ }).describe(DeleteTableDescription).meta({ aliases: { tableId: "table" } });
9651
+ var DeleteTableOptionsSchemaDeprecated = z.object({
9652
+ tableId: z.string().regex(/^[A-Z0-9]{26}$/, "Table ID must be a valid ULID").describe("The unique identifier of the table to delete")
8757
9653
  });
8758
- var DeleteTableFieldsOptionsInputSchema = z.union([
8759
- DeleteTableFieldsOptionsSchema,
8760
- DeleteTableFieldsOptionsSchemaDeprecated
8761
- ]).describe(DeleteTableFieldsDescription);
9654
+ var DeleteTableOptionsInputSchema = z.union([DeleteTableOptionsSchema, DeleteTableOptionsSchemaDeprecated]).describe(DeleteTableDescription);
8762
9655
 
8763
- // src/plugins/tables/deleteTableFields/index.ts
8764
- var deleteTableFieldsPlugin = definePlugin(
9656
+ // src/plugins/tables/deleteTable/index.ts
9657
+ var deleteTablePlugin = definePlugin(
8765
9658
  (sdk) => createPluginMethod(sdk, {
8766
9659
  ...tablesDefaults,
8767
- name: "deleteTableFields",
9660
+ name: "deleteTable",
8768
9661
  type: "delete",
8769
- itemType: "Field",
8770
- inputSchema: DeleteTableFieldsOptionsInputSchema,
8771
- resolvers: { table: tableIdResolver, fields: tableFieldIdsResolver },
9662
+ itemType: "Table",
9663
+ inputSchema: DeleteTableOptionsInputSchema,
9664
+ resolvers: { table: tableIdResolver },
8772
9665
  confirm: "delete",
8773
9666
  handler: async ({ sdk: sdk2, options }) => {
8774
- const { api } = sdk2.context;
9667
+ await sdk2.context.checkCapability("canDeleteTables");
8775
9668
  const tableId = "table" in options ? options.table : options.tableId;
8776
- const fieldKeys = "fields" in options ? options.fields : options.fieldKeys;
8777
- const numericFieldIds = await resolveFieldKeys({
8778
- api,
8779
- tableId,
8780
- fieldKeys
8781
- });
8782
- await api.delete(
8783
- `/tables/api/v1/tables/${tableId}/fields`,
8784
- { field_ids: numericFieldIds },
9669
+ await sdk2.context.api.delete(
9670
+ `/tables/api/v1/tables/${tableId}`,
9671
+ void 0,
8785
9672
  {
8786
9673
  authRequired: true,
8787
9674
  resource: { type: "table", id: tableId }
@@ -8791,820 +9678,700 @@ var deleteTableFieldsPlugin = definePlugin(
8791
9678
  }
8792
9679
  })
8793
9680
  );
8794
- var RecordApiItemSchema = z.object({
8795
- id: z.string().regex(/^[A-Z0-9]{26}$/, "Record ID must be a valid ULID"),
8796
- data: z.record(z.string(), z.unknown()),
8797
- created_at: z.string(),
8798
- edited_at: z.string(),
8799
- schema_revision_id: z.number(),
8800
- errors: z.record(z.string(), z.unknown()).nullable().optional(),
8801
- orig_data: z.record(z.string(), z.unknown()).nullable().optional(),
8802
- is_source_record: z.boolean().nullable().optional(),
8803
- deleted_at: z.string().nullable().optional()
8804
- });
8805
- var RecordItemSchema = z.object({
8806
- id: z.string(),
8807
- data: z.record(z.string(), z.unknown()),
8808
- created_at: z.string(),
8809
- edited_at: z.string(),
8810
- deleted_at: z.string().nullable().optional()
8811
- });
8812
- var GetTableRecordApiResponseSchema = z.object({
8813
- data: RecordApiItemSchema
8814
- });
8815
- var GetTableRecordDescription = "Get a single record from a table by ID";
8816
- var GetTableRecordOptionsBaseSchema = z.object({
8817
- keyMode: KeyModeSchema
8818
- });
8819
- var GetTableRecordOptionsSchema = z.object({
8820
- table: TablePropertySchema,
8821
- record: RecordPropertySchema
8822
- }).merge(GetTableRecordOptionsBaseSchema).describe(GetTableRecordDescription).meta({ aliases: { tableId: "table", recordId: "record" } });
8823
- var GetTableRecordOptionsSchemaDeprecated = z.object({
8824
- tableId: z.string().regex(/^[A-Z0-9]{26}$/, "Table ID must be a valid ULID").describe("The unique identifier of the table"),
8825
- recordId: z.string().regex(/^[A-Z0-9]{26}$/, "Record ID must be a valid ULID").describe("The unique identifier of the record")
8826
- }).merge(GetTableRecordOptionsBaseSchema);
8827
- var GetTableRecordOptionsInputSchema = z.union([GetTableRecordOptionsSchema, GetTableRecordOptionsSchemaDeprecated]).describe(GetTableRecordDescription);
8828
-
8829
- // src/formatters/tableRecord.ts
8830
- var tableRecordFormatter = {
8831
- fetch: async (sdk, params, item, context) => {
8832
- if (context) return context;
8833
- const hasFieldIds = Object.keys(item.data).some(isFieldId);
8834
- if (!hasFieldIds) return {};
8835
- const table = params.table ?? params.tableId;
8836
- if (!table) return {};
8837
- const { data: fields } = await sdk.listTableFields({ table });
8838
- return Object.fromEntries(fields.map((f) => [f.id, f.name]));
8839
- },
8840
- format: (item, fieldLabels) => ({
8841
- title: `Record ${item.id}`,
8842
- id: item.id,
8843
- details: Object.entries(item.data).map(([k, v]) => ({
8844
- label: fieldLabels?.[k] ?? k,
8845
- text: formatFieldValue(v),
8846
- style: "normal"
8847
- }))
8848
- })
8849
- };
8850
-
8851
- // src/plugins/tables/getTableRecord/index.ts
8852
- var getTableRecordPlugin = definePlugin(
8853
- (sdk) => createPluginMethod(sdk, {
8854
- ...tablesDefaults,
8855
- name: "getTableRecord",
8856
- type: "item",
8857
- itemType: "Record",
8858
- inputSchema: GetTableRecordOptionsInputSchema,
8859
- outputSchema: RecordItemSchema,
8860
- resolvers: { table: tableIdResolver, record: tableRecordIdResolver },
8861
- formatter: tableRecordFormatter,
8862
- handler: async ({ sdk: sdk2, options }) => {
8863
- const { api } = sdk2.context;
8864
- const tableId = "table" in options ? options.table : options.tableId;
8865
- const recordId = "record" in options ? options.record : options.recordId;
8866
- const rawResponse = await api.get(
8867
- `/tables/api/v1/tables/${tableId}/records/${recordId}`,
8868
- {
8869
- authRequired: true,
8870
- resource: { type: "record", id: recordId }
8871
- }
8872
- );
8873
- const response = GetTableRecordApiResponseSchema.parse(rawResponse);
8874
- const translator = await createFieldKeyTranslator({
8875
- api,
8876
- tableId,
8877
- keyMode: options.keyMode
8878
- });
8879
- return {
8880
- data: {
8881
- ...transformRecordItem(response.data),
8882
- data: translator.translateOutput(response.data.data)
8883
- }
8884
- };
8885
- }
8886
- })
8887
- );
8888
- var ListTableRecordsApiResponseSchema = z.object({
8889
- data: z.array(RecordApiItemSchema),
8890
- meta: z.object({
8891
- pagination: z.object({
8892
- start_cursor: z.string().nullable().optional(),
8893
- end_cursor: z.string().nullable().optional(),
8894
- has_more: z.boolean().optional(),
8895
- has_less: z.boolean().optional()
8896
- }).optional()
8897
- }).optional()
8898
- });
8899
- var FilterOperatorSchema = z.enum([
8900
- "exact",
8901
- "different",
8902
- "contains",
8903
- "icontains",
8904
- "gte",
8905
- "gt",
8906
- "lt",
8907
- "lte",
8908
- "range",
8909
- "in",
8910
- "isnull",
8911
- "startswith",
8912
- "search",
8913
- "is_within"
8914
- ]);
8915
- var FilterConditionSchema = z.object({
8916
- fieldKey: z.string().describe("The field key to filter on (e.g. f1, f2)"),
8917
- operator: FilterOperatorSchema.describe("The comparison operator"),
8918
- value: z.unknown().optional().describe("The value to compare against")
8919
- });
8920
- var SortDirectionSchema = z.enum(["asc", "desc"]);
8921
- var SortConditionSchema = z.object({
8922
- fieldKey: z.string().describe("The field key to sort by"),
8923
- direction: SortDirectionSchema.optional().default("asc").describe("Sort direction")
8924
- });
8925
- var ListTableRecordsDescription = "List records in a table with optional filtering and sorting";
8926
- var ListTableRecordsBase = z.object({
8927
- filters: z.array(FilterConditionSchema).optional().describe("Filter conditions for the query"),
8928
- sort: SortConditionSchema.optional().describe("Sort records by a field"),
8929
- pageSize: z.number().min(1).max(1e3).optional().describe("Number of records per page (max 1000)"),
8930
- maxItems: z.number().min(1).optional().describe("Maximum total items to return across all pages"),
8931
- cursor: z.string().optional().describe("Cursor to start from"),
8932
- keyMode: KeyModeSchema,
8933
- trash: TrashSchema
9681
+ var CreateTableApiResponseSchema = z.object({
9682
+ data: TableApiItemSchema
8934
9683
  });
8935
- var ListTableRecordsOptionsSchema = z.object({
8936
- table: TablePropertySchema
8937
- }).merge(ListTableRecordsBase).describe(ListTableRecordsDescription).meta({ aliases: { tableId: "table" } });
8938
- var ListTableRecordsOptionsSchemaDeprecated = z.object({
8939
- tableId: z.string().regex(/^[A-Z0-9]{26}$/, "Table ID must be a valid ULID").describe("The unique identifier of the table")
8940
- }).merge(ListTableRecordsBase);
8941
- var ListTableRecordsOptionsInputSchema = z.union([
8942
- ListTableRecordsOptionsSchema,
8943
- ListTableRecordsOptionsSchemaDeprecated
8944
- ]).describe(ListTableRecordsDescription);
9684
+ var CreateTableOptionsSchema = z.object({
9685
+ name: z.string().min(1).describe("The name for the new table"),
9686
+ description: z.string().optional().describe("An optional description of the table")
9687
+ }).describe("Create a new table");
8945
9688
 
8946
- // src/plugins/tables/listTableRecords/index.ts
8947
- var listTableRecordsPlugin = definePlugin(
8948
- (sdk) => createPaginatedPluginMethod(sdk, {
9689
+ // src/plugins/tables/createTable/index.ts
9690
+ var createTablePlugin = definePlugin(
9691
+ (sdk) => createPluginMethod(sdk, {
8949
9692
  ...tablesDefaults,
8950
- name: "listTableRecords",
9693
+ name: "createTable",
9694
+ type: "create",
9695
+ itemType: "Table",
9696
+ inputSchema: CreateTableOptionsSchema,
9697
+ outputSchema: TableItemSchema,
9698
+ resolvers: { name: tableNameResolver },
9699
+ handler: async ({ sdk: sdk2, options }) => {
9700
+ const rawResponse = await sdk2.context.api.post(
9701
+ "/tables/api/v1/tables",
9702
+ { name: options.name, description: options.description },
9703
+ { authRequired: true }
9704
+ );
9705
+ const response = CreateTableApiResponseSchema.parse(rawResponse);
9706
+ return { data: transformTableItem(response.data) };
9707
+ }
9708
+ })
9709
+ );
9710
+
9711
+ // src/formatters/tableField.ts
9712
+ var tableFieldItemFormatter = {
9713
+ format: (item) => ({
9714
+ title: item.name,
9715
+ id: item.id,
9716
+ details: [{ text: `Type: ${item.type}`, style: "dim" }]
9717
+ })
9718
+ };
9719
+
9720
+ // src/plugins/tables/listTableFields/index.ts
9721
+ var listTableFieldsPlugin = definePlugin(
9722
+ (sdk) => createPluginMethod(sdk, {
9723
+ ...tablesDefaults,
9724
+ name: "listTableFields",
8951
9725
  type: "list",
8952
- itemType: "Record",
8953
- inputSchema: ListTableRecordsOptionsInputSchema,
8954
- outputSchema: RecordItemSchema,
8955
- defaultPageSize: DEFAULT_PAGE_SIZE,
8956
- resolvers: {
8957
- table: tableIdResolver,
8958
- filters: tableFiltersResolver,
8959
- sort: tableSortResolver
8960
- },
8961
- formatter: tableRecordFormatter,
9726
+ itemType: "Field",
9727
+ inputSchema: ListTableFieldsOptionsInputSchema,
9728
+ outputSchema: FieldItemSchema,
9729
+ formatter: tableFieldItemFormatter,
9730
+ resolvers: { table: tableIdResolver },
8962
9731
  handler: async ({ sdk: sdk2, options }) => {
8963
9732
  const { api } = sdk2.context;
8964
9733
  const tableId = "table" in options ? options.table : options.tableId;
8965
- const translator = await createFieldKeyTranslator({
8966
- api,
8967
- tableId,
8968
- keyMode: options.keyMode
8969
- });
8970
- const body = {};
8971
- if (options.pageSize !== void 0) {
8972
- body.limit = options.pageSize;
8973
- }
8974
- if (options.filters) {
8975
- body.filters = options.filters.map((f) => ({
8976
- key: translator.translateFieldKey(f.fieldKey),
8977
- operator: f.operator,
8978
- value: f.value
8979
- }));
8980
- }
8981
- if (options.sort) {
8982
- body.orders = [
8983
- {
8984
- key: translator.translateFieldKey(options.sort.fieldKey),
8985
- direction: options.sort.direction
8986
- }
8987
- ];
8988
- }
8989
- if (options.cursor) {
8990
- body.cursor_query = {
8991
- query_type: "window",
8992
- start_cursor: options.cursor
8993
- };
9734
+ const fieldKeys = "fields" in options ? options.fields : options.fieldKeys;
9735
+ const searchParams = {};
9736
+ if (fieldKeys && fieldKeys.length > 0) {
9737
+ const numericIds = await resolveFieldKeys({
9738
+ api,
9739
+ tableId,
9740
+ fieldKeys
9741
+ });
9742
+ searchParams.field_ids = numericIds.join(",");
8994
9743
  }
8995
- const searchParams = {
8996
- allow_nested_queries: "true"
8997
- };
8998
9744
  if (options.trash) {
8999
9745
  searchParams.trash = options.trash;
9000
9746
  }
9001
- const rawResponse = await api.post(
9002
- `/tables/api/v1/tables/${tableId}/records/query`,
9003
- body,
9747
+ const rawResponse = await api.get(
9748
+ `/tables/api/v1/tables/${tableId}/fields`,
9004
9749
  {
9005
- searchParams,
9750
+ searchParams: Object.keys(searchParams).length > 0 ? searchParams : void 0,
9006
9751
  authRequired: true,
9007
9752
  resource: { type: "table", id: tableId }
9008
9753
  }
9009
9754
  );
9010
- throwOnResponseErrors(rawResponse);
9011
- const response = ListTableRecordsApiResponseSchema.parse(rawResponse);
9012
- const pagination = response.meta?.pagination;
9013
- const nextCursor = pagination?.has_more && pagination.end_cursor ? pagination.end_cursor : void 0;
9014
- return {
9015
- data: response.data.map((item) => ({
9016
- ...transformRecordItem(item),
9017
- data: translator.translateOutput(item.data)
9018
- })),
9019
- nextCursor
9020
- };
9755
+ const response = ListTableFieldsApiResponseSchema.parse(rawResponse);
9756
+ return { data: response.data.map(transformFieldItem) };
9021
9757
  }
9022
9758
  })
9023
9759
  );
9024
- var RecordChangesetSchema = z.object({
9025
- change_id: z.string(),
9026
- old: RecordApiItemSchema.nullable(),
9027
- new: RecordApiItemSchema,
9028
- changed_field_ids: z.array(z.number()).nullable(),
9029
- record_id: z.string()
9760
+ var FieldChangesetItemSchema = z.object({
9761
+ new: FieldApiItemSchema,
9762
+ old: FieldApiItemSchema.nullable(),
9763
+ kind: z.enum(["created", "updated", "deleted"])
9030
9764
  });
9031
- var CreateTableRecordsApiResponseSchema = z.object({
9032
- data: z.array(RecordChangesetSchema)
9765
+ var CreateTableFieldsApiResponseSchema = z.object({
9766
+ data: z.array(FieldChangesetItemSchema),
9767
+ meta: z.object({
9768
+ did_change: z.boolean()
9769
+ }).optional()
9033
9770
  });
9034
- var NewRecordSchema = z.object({
9035
- data: z.record(z.string(), z.unknown()).describe("The field values for the record, keyed by field ID")
9771
+ var NewFieldSchema = z.object({
9772
+ type: FieldTypeSchema.describe("The data type of the field"),
9773
+ name: z.string().min(1).describe("The display name of the field"),
9774
+ options: z.record(z.string(), z.unknown()).optional().describe("Data configuration options for the field"),
9775
+ config: z.record(z.string(), z.unknown()).optional().describe("Display configuration for the field")
9036
9776
  });
9037
- var CreateTableRecordsDescription = "Create one or more records in a table";
9038
- var CreateTableRecordsBase = z.object({
9039
- records: z.array(NewRecordSchema).min(1).max(100).describe("Array of records to create (max 100)"),
9040
- keyMode: KeyModeSchema
9777
+ var CreateTableFieldsDescription = "Create one or more fields in a table";
9778
+ var CreateTableFieldsBase = z.object({
9779
+ fields: z.array(NewFieldSchema).min(1).describe("Array of field definitions to create")
9041
9780
  });
9042
- var CreateTableRecordsOptionsSchema = z.object({
9781
+ var CreateTableFieldsOptionsSchema = z.object({
9043
9782
  table: TablePropertySchema
9044
- }).merge(CreateTableRecordsBase).describe(CreateTableRecordsDescription).meta({ aliases: { tableId: "table" } });
9045
- var CreateTableRecordsOptionsSchemaDeprecated = z.object({
9783
+ }).merge(CreateTableFieldsBase).describe(CreateTableFieldsDescription).meta({ aliases: { tableId: "table" } });
9784
+ var CreateTableFieldsOptionsSchemaDeprecated = z.object({
9046
9785
  tableId: z.string().regex(/^[A-Z0-9]{26}$/, "Table ID must be a valid ULID").describe("The unique identifier of the table")
9047
- }).merge(CreateTableRecordsBase);
9048
- var CreateTableRecordsOptionsInputSchema = z.union([
9049
- CreateTableRecordsOptionsSchema,
9050
- CreateTableRecordsOptionsSchemaDeprecated
9051
- ]).describe(CreateTableRecordsDescription);
9786
+ }).merge(CreateTableFieldsBase);
9787
+ var CreateTableFieldsOptionsInputSchema = z.union([
9788
+ CreateTableFieldsOptionsSchema,
9789
+ CreateTableFieldsOptionsSchemaDeprecated
9790
+ ]).describe(CreateTableFieldsDescription);
9052
9791
 
9053
- // src/plugins/tables/createTableRecords/index.ts
9054
- var createTableRecordsPlugin = definePlugin(
9792
+ // src/plugins/tables/createTableFields/index.ts
9793
+ var createTableFieldsPlugin = definePlugin(
9055
9794
  (sdk) => createPluginMethod(sdk, {
9056
9795
  ...tablesDefaults,
9057
- name: "createTableRecords",
9796
+ name: "createTableFields",
9058
9797
  type: "create",
9059
- itemType: "Record",
9060
- returnType: "RecordItem[]",
9061
- inputSchema: CreateTableRecordsOptionsInputSchema,
9062
- outputSchema: RecordItemSchema,
9063
- resolvers: { table: tableIdResolver, records: tableRecordsResolver },
9064
- formatter: tableRecordFormatter,
9065
- handler: async ({ sdk: sdk2, options }) => {
9066
- const { api } = sdk2.context;
9067
- const tableId = "table" in options ? options.table : options.tableId;
9068
- const translator = await createFieldKeyTranslator({
9069
- api,
9070
- tableId,
9071
- keyMode: options.keyMode
9072
- });
9073
- const rawResponse = await api.post(
9074
- `/tables/api/v1/tables/${tableId}/records`,
9075
- {
9076
- new_records: options.records.map((record) => ({
9077
- data: translator.translateInput(record.data)
9078
- }))
9079
- },
9080
- { authRequired: true, resource: { type: "table", id: tableId } }
9081
- );
9082
- throwOnResponseErrors(rawResponse);
9083
- const response = CreateTableRecordsApiResponseSchema.parse(rawResponse);
9084
- for (const changeset of response.data) {
9085
- throwOnRecordErrors(changeset.new);
9086
- }
9087
- return {
9088
- data: response.data.map((changeset) => ({
9089
- ...transformRecordItem(changeset.new),
9090
- data: translator.translateOutput(changeset.new.data)
9091
- }))
9092
- };
9093
- }
9094
- })
9095
- );
9096
- var DeleteTableRecordsDescription = "Delete one or more records from a table";
9097
- var DeleteTableRecordsOptionsSchema = z.object({
9098
- table: TablePropertySchema,
9099
- records: RecordsPropertySchema
9100
- }).describe(DeleteTableRecordsDescription).meta({ aliases: { tableId: "table", recordIds: "records" } });
9101
- var DeleteTableRecordsOptionsSchemaDeprecated = z.object({
9102
- tableId: z.string().regex(/^[A-Z0-9]{26}$/, "Table ID must be a valid ULID").describe("The unique identifier of the table"),
9103
- recordIds: z.array(z.string().regex(/^[A-Z0-9]{26}$/, "Record ID must be a valid ULID")).min(1).max(100).describe("Array of record IDs to delete (max 100)")
9104
- });
9105
- var DeleteTableRecordsOptionsInputSchema = z.union([
9106
- DeleteTableRecordsOptionsSchema,
9107
- DeleteTableRecordsOptionsSchemaDeprecated
9108
- ]).describe(DeleteTableRecordsDescription);
9109
-
9110
- // src/plugins/tables/deleteTableRecords/index.ts
9111
- var deleteTableRecordsPlugin = definePlugin(
9112
- (sdk) => createPluginMethod(sdk, {
9113
- ...tablesDefaults,
9114
- name: "deleteTableRecords",
9115
- type: "delete",
9116
- itemType: "Record",
9117
- inputSchema: DeleteTableRecordsOptionsInputSchema,
9118
- resolvers: { table: tableIdResolver, records: tableRecordIdsResolver },
9119
- confirm: "delete",
9120
- handler: async ({ sdk: sdk2, options }) => {
9121
- const tableId = "table" in options ? options.table : options.tableId;
9122
- const recordIds = "records" in options ? options.records : options.recordIds;
9123
- await sdk2.context.api.delete(
9124
- `/tables/api/v1/tables/${tableId}/records`,
9125
- { record_ids: recordIds },
9798
+ itemType: "Field",
9799
+ returnType: "FieldItem[]",
9800
+ inputSchema: CreateTableFieldsOptionsInputSchema,
9801
+ outputSchema: FieldItemSchema,
9802
+ formatter: tableFieldItemFormatter,
9803
+ resolvers: { table: tableIdResolver, fields: tableFieldsResolver },
9804
+ handler: async ({ sdk: sdk2, options }) => {
9805
+ const tableId = "table" in options ? options.table : options.tableId;
9806
+ const rawResponse = await sdk2.context.api.post(
9807
+ `/tables/api/v1/tables/${tableId}/fields`,
9808
+ { new_fields: options.fields },
9126
9809
  {
9127
9810
  authRequired: true,
9128
9811
  resource: { type: "table", id: tableId }
9129
9812
  }
9130
9813
  );
9131
- return { success: true };
9814
+ const response = CreateTableFieldsApiResponseSchema.parse(rawResponse);
9815
+ return {
9816
+ data: response.data.map(
9817
+ (changeset) => transformFieldItem(changeset.new)
9818
+ )
9819
+ };
9132
9820
  }
9133
9821
  })
9134
9822
  );
9135
- var RecordChangesetSchema2 = z.object({
9136
- change_id: z.string(),
9137
- old: RecordApiItemSchema.nullable(),
9138
- new: RecordApiItemSchema,
9139
- changed_field_ids: z.array(z.number()).nullable(),
9140
- record_id: z.string()
9141
- });
9142
- var UpdateTableRecordsApiResponseSchema = z.object({
9143
- data: z.array(RecordChangesetSchema2)
9144
- });
9145
- var UpdateRecordSchema = z.object({
9146
- id: z.string().describe("The record ID to update"),
9147
- data: z.record(z.string(), z.unknown()).describe("The field values to update, keyed by field key")
9148
- });
9149
- var UpdateTableRecordsDescription = "Update one or more records in a table";
9150
- var UpdateTableRecordsBase = z.object({
9151
- records: z.array(UpdateRecordSchema).min(1).max(100).describe("Array of records to update (max 100)"),
9152
- keyMode: KeyModeSchema
9823
+ var DeleteTableFieldsDescription = "Delete one or more fields from a table";
9824
+ var DeleteTableFieldsOptionsSchema = z.object({
9825
+ table: TablePropertySchema,
9826
+ fields: FieldsPropertySchema.min(1)
9827
+ }).describe(DeleteTableFieldsDescription).meta({ aliases: { tableId: "table", fieldKeys: "fields" } });
9828
+ var DeleteTableFieldsOptionsSchemaDeprecated = z.object({
9829
+ tableId: z.string().regex(/^[A-Z0-9]{26}$/, "Table ID must be a valid ULID").describe("The unique identifier of the table"),
9830
+ fieldKeys: z.array(z.union([z.string(), z.number()])).min(1).describe(
9831
+ 'Fields to delete. Accepts field names (e.g., "Email") or IDs (e.g., "f6", "6", or 6).'
9832
+ )
9153
9833
  });
9154
- var UpdateTableRecordsOptionsSchema = z.object({
9155
- table: TablePropertySchema
9156
- }).merge(UpdateTableRecordsBase).describe(UpdateTableRecordsDescription).meta({ aliases: { tableId: "table" } });
9157
- var UpdateTableRecordsOptionsSchemaDeprecated = z.object({
9158
- tableId: z.string().regex(/^[A-Z0-9]{26}$/, "Table ID must be a valid ULID").describe("The unique identifier of the table")
9159
- }).merge(UpdateTableRecordsBase);
9160
- var UpdateTableRecordsOptionsInputSchema = z.union([
9161
- UpdateTableRecordsOptionsSchema,
9162
- UpdateTableRecordsOptionsSchemaDeprecated
9163
- ]).describe(UpdateTableRecordsDescription);
9834
+ var DeleteTableFieldsOptionsInputSchema = z.union([
9835
+ DeleteTableFieldsOptionsSchema,
9836
+ DeleteTableFieldsOptionsSchemaDeprecated
9837
+ ]).describe(DeleteTableFieldsDescription);
9164
9838
 
9165
- // src/plugins/tables/updateTableRecords/index.ts
9166
- var updateTableRecordsPlugin = definePlugin(
9839
+ // src/plugins/tables/deleteTableFields/index.ts
9840
+ var deleteTableFieldsPlugin = definePlugin(
9167
9841
  (sdk) => createPluginMethod(sdk, {
9168
9842
  ...tablesDefaults,
9169
- name: "updateTableRecords",
9170
- type: "update",
9171
- itemType: "Record",
9172
- returnType: "RecordItem[]",
9173
- inputSchema: UpdateTableRecordsOptionsInputSchema,
9174
- outputSchema: RecordItemSchema,
9175
- resolvers: {
9176
- table: tableIdResolver,
9177
- records: tableUpdateRecordsResolver
9178
- },
9179
- formatter: tableRecordFormatter,
9843
+ name: "deleteTableFields",
9844
+ type: "delete",
9845
+ itemType: "Field",
9846
+ inputSchema: DeleteTableFieldsOptionsInputSchema,
9847
+ resolvers: { table: tableIdResolver, fields: tableFieldIdsResolver },
9848
+ confirm: "delete",
9180
9849
  handler: async ({ sdk: sdk2, options }) => {
9181
9850
  const { api } = sdk2.context;
9182
9851
  const tableId = "table" in options ? options.table : options.tableId;
9183
- const translator = await createFieldKeyTranslator({
9852
+ const fieldKeys = "fields" in options ? options.fields : options.fieldKeys;
9853
+ const numericFieldIds = await resolveFieldKeys({
9184
9854
  api,
9185
9855
  tableId,
9186
- keyMode: options.keyMode
9856
+ fieldKeys
9187
9857
  });
9188
- const rawResponse = await api.patch(
9189
- `/tables/api/v1/tables/${tableId}/records`,
9858
+ await api.delete(
9859
+ `/tables/api/v1/tables/${tableId}/fields`,
9860
+ { field_ids: numericFieldIds },
9190
9861
  {
9191
- updated_records: options.records.map((record) => ({
9192
- id: record.id,
9193
- data: translator.translateInput(record.data)
9194
- }))
9195
- },
9196
- { authRequired: true, resource: { type: "table", id: tableId } }
9862
+ authRequired: true,
9863
+ resource: { type: "table", id: tableId }
9864
+ }
9197
9865
  );
9198
- throwOnResponseErrors(rawResponse);
9199
- const response = UpdateTableRecordsApiResponseSchema.parse(rawResponse);
9200
- for (const changeset of response.data) {
9201
- throwOnRecordErrors(changeset.new);
9202
- }
9203
- return {
9204
- data: response.data.map((changeset) => ({
9205
- ...transformRecordItem(changeset.new),
9206
- data: translator.translateOutput(changeset.new.data)
9207
- }))
9208
- };
9866
+ return { success: true };
9209
9867
  }
9210
9868
  })
9211
9869
  );
9212
-
9213
- // src/core-stack.ts
9214
- var zapierCorePlugin = createCorePlugin({
9215
- adaptError: zapierAdaptError
9870
+ var RecordApiItemSchema = z.object({
9871
+ id: z.string().regex(/^[A-Z0-9]{26}$/, "Record ID must be a valid ULID"),
9872
+ data: z.record(z.string(), z.unknown()),
9873
+ created_at: z.string(),
9874
+ edited_at: z.string(),
9875
+ schema_revision_id: z.number(),
9876
+ errors: z.record(z.string(), z.unknown()).nullable().optional(),
9877
+ orig_data: z.record(z.string(), z.unknown()).nullable().optional(),
9878
+ is_source_record: z.boolean().nullable().optional(),
9879
+ deleted_at: z.string().nullable().optional()
9216
9880
  });
9217
- function createZapierCoreStack() {
9218
- return createPluginStack().use(zapierCorePlugin);
9219
- }
9220
- var GetConnectionStartUrlSchema = z.object({
9221
- app: AppPropertySchema
9222
- }).describe(
9223
- "Mint a short-lived URL that begins an SDK-initiated connection flow. The URL is signed by zapier.com and bound to the current user/account \u2014 opening it in a different browser session will fail the binding check. Returns the URL as data so the caller decides what to do with it.\n\nUse this directly (rather than the higher-level `create-connection`) when you want either of: (a) hand off the URL and *not* block waiting for completion \u2014 call this alone, skip `wait-for-new-connection` entirely, or (b) do something custom between minting the URL and waiting for the connection \u2014 call this, then email or DM the URL, render it as a QR code for mobile sign-in, etc., then call `wait-for-new-connection`. For the common case where you'd just print and poll back-to-back, `create-connection` is one call.\n\nPair with `wait-for-new-connection` to detect completion: pass the `startedAt` returned here straight through (it's the server's mint time, so polling isn't affected by client clock skew). Example (JS):\n\n```ts\nconst { data: { url, app, startedAt } } = await zapier.getConnectionStartUrl({ app: 'slack' });\n// hand `url` off \u2014 print it, DM it, email it, render a button, whatever\nconst { data: conn } = await zapier.waitForNewConnection({ app, startedAt });\n```"
9224
- );
9225
- var GetConnectionStartUrlItemSchema = z.object({
9226
- url: z.string().describe(
9227
- "URL the user should open in their browser to complete the auth flow. Single-use, time-limited."
9228
- ),
9229
- expiresAt: z.number().describe(
9230
- "Unix timestamp (seconds) after which the URL's signature is rejected by zapier.com."
9231
- ),
9232
- startedAt: z.number().describe(
9233
- "Unix timestamp (seconds) when the server minted the URL. Use it as the `startedAt` for `wait-for-new-connection` so polling is anchored to server time rather than a possibly-skewed client clock."
9234
- ),
9235
- app: z.string().describe(
9236
- "Versionless app key the URL was minted for (e.g., 'SlackCLIAPI'). Useful for downstream filtering."
9237
- )
9238
- }).describe(
9239
- "The signed start-URL plus metadata needed to poll for completion."
9240
- );
9881
+ var RecordItemSchema = z.object({
9882
+ id: z.string(),
9883
+ data: z.record(z.string(), z.unknown()),
9884
+ created_at: z.string(),
9885
+ edited_at: z.string(),
9886
+ deleted_at: z.string().nullable().optional()
9887
+ });
9888
+ var GetTableRecordApiResponseSchema = z.object({
9889
+ data: RecordApiItemSchema
9890
+ });
9891
+ var GetTableRecordDescription = "Get a single record from a table by ID";
9892
+ var GetTableRecordOptionsBaseSchema = z.object({
9893
+ keyMode: KeyModeSchema
9894
+ });
9895
+ var GetTableRecordOptionsSchema = z.object({
9896
+ table: TablePropertySchema,
9897
+ record: RecordPropertySchema
9898
+ }).merge(GetTableRecordOptionsBaseSchema).describe(GetTableRecordDescription).meta({ aliases: { tableId: "table", recordId: "record" } });
9899
+ var GetTableRecordOptionsSchemaDeprecated = z.object({
9900
+ tableId: z.string().regex(/^[A-Z0-9]{26}$/, "Table ID must be a valid ULID").describe("The unique identifier of the table"),
9901
+ recordId: z.string().regex(/^[A-Z0-9]{26}$/, "Record ID must be a valid ULID").describe("The unique identifier of the record")
9902
+ }).merge(GetTableRecordOptionsBaseSchema);
9903
+ var GetTableRecordOptionsInputSchema = z.union([GetTableRecordOptionsSchema, GetTableRecordOptionsSchemaDeprecated]).describe(GetTableRecordDescription);
9241
9904
 
9242
- // src/plugins/getConnectionStartUrl/index.ts
9243
- var START_PATH = "/zapier/api/authentications/v1/sdk/connections/start";
9244
- var getConnectionStartUrlPlugin = definePlugin(
9245
- (sdk) => createPluginMethod(sdk, {
9246
- name: "getConnectionStartUrl",
9247
- categories: ["connection"],
9248
- type: "create",
9249
- itemType: "ConnectionStartUrl",
9250
- inputSchema: GetConnectionStartUrlSchema,
9251
- outputSchema: GetConnectionStartUrlItemSchema,
9252
- resolvers: { app: appKeyResolver },
9253
- handler: async ({
9254
- sdk: inner,
9255
- options
9256
- }) => {
9257
- const versionedKey = await inner.context.getVersionedImplementationId(
9258
- options.app
9259
- );
9260
- const selectedApi = versionedKey ? versionedKey.split("@")[0] : options.app;
9261
- setMethodMetadata({ selectedApi });
9262
- const response = await inner.context.api.post(
9263
- START_PATH,
9264
- { selected_api: selectedApi },
9265
- { authRequired: true }
9266
- );
9267
- return {
9268
- data: GetConnectionStartUrlItemSchema.parse({
9269
- url: response.url,
9270
- expiresAt: response.expires_at,
9271
- startedAt: response.started_at,
9272
- app: selectedApi
9273
- })
9274
- };
9275
- }
9905
+ // src/formatters/tableRecord.ts
9906
+ var tableRecordFormatter = {
9907
+ fetch: async (sdk, params, item, context) => {
9908
+ if (context) return context;
9909
+ const hasFieldIds = Object.keys(item.data).some(isFieldId);
9910
+ if (!hasFieldIds) return {};
9911
+ const table = params.table ?? params.tableId;
9912
+ if (!table) return {};
9913
+ const { data: fields } = await sdk.listTableFields({ table });
9914
+ return Object.fromEntries(fields.map((f) => [f.id, f.name]));
9915
+ },
9916
+ format: (item, fieldLabels) => ({
9917
+ title: `Record ${item.id}`,
9918
+ id: item.id,
9919
+ details: Object.entries(item.data).map(([k, v]) => ({
9920
+ label: fieldLabels?.[k] ?? k,
9921
+ text: formatFieldValue(v),
9922
+ style: "normal"
9923
+ }))
9276
9924
  })
9277
- );
9278
- var WaitForNewConnectionSchema = z.object({
9279
- app: AppPropertySchema,
9280
- startedAt: z.number().int().nonnegative().describe(
9281
- "Unix timestamp (seconds). Only connections whose `date` is at or after this value count as 'new'. Prefer the `startedAt` returned by `get-connection-start-url` \u2014 it's server-stamped, so the comparison isn't thrown off by client clock skew. If you mint the timestamp yourself, capture it *before* showing the start URL so a fast OAuth completion isn't missed."
9282
- ),
9283
- timeoutMs: z.number().int().positive().optional().describe(
9284
- "How long to wait before giving up. Default 5 minutes (300_000)."
9285
- ),
9286
- pollIntervalMs: z.number().int().positive().optional().describe(
9287
- "Delay before the first poll request, in ms. Default 3 seconds (3_000). Subsequent polling cadence is managed by the SDK's polling primitive (backoff with sane defaults)."
9288
- )
9289
- }).describe(
9290
- "Wait for a new connection to appear for the given app. Polls `/api/v0/connections` with server-side `ordering=-date` until the most recent matching row's `date` is at or after the started-at timestamp, then returns it. Pair with `get-connection-start-url` \u2014 that mints the URL the user opens, this waits for the resulting connection to land. Errors with a timeout after the configured timeout (default 5 min). Example (JS):\n\n```ts\nconst { data: { url, app, startedAt } } = await zapier.getConnectionStartUrl({ app: 'slack' });\n// show `url` to the user via the channel they're reading from\nconst { data: conn } = await zapier.waitForNewConnection({ app, startedAt });\n```"
9291
- );
9292
- var WaitForNewConnectionItemSchema = z.object({
9293
- id: z.string().describe(
9294
- "The new connection's ID. Public UUID when available, falling back to the numeric ID."
9295
- ),
9296
- app: z.string().describe(
9297
- "Versionless app key the connection was created for (e.g., 'SlackCLIAPI')."
9298
- ),
9299
- title: z.string().nullable().optional().describe(
9300
- "Human-readable connection title set by the auth flow, when available."
9301
- )
9302
- }).describe("The new connection that was detected.");
9925
+ };
9303
9926
 
9304
- // src/plugins/waitForNewConnection/index.ts
9305
- var CONNECTIONS_PATH = "/api/v0/connections";
9306
- var waitForNewConnectionPlugin = definePlugin(
9307
- (sdk) => createPluginMethod(sdk, {
9308
- name: "waitForNewConnection",
9309
- categories: ["connection"],
9927
+ // src/plugins/tables/getTableRecord/index.ts
9928
+ var getTableRecordPlugin = definePlugin(
9929
+ (sdk) => createPluginMethod(sdk, {
9930
+ ...tablesDefaults,
9931
+ name: "getTableRecord",
9310
9932
  type: "item",
9311
- itemType: "Connection",
9312
- inputSchema: WaitForNewConnectionSchema,
9313
- outputSchema: WaitForNewConnectionItemSchema,
9314
- resolvers: { app: appKeyResolver },
9315
- handler: async ({
9316
- sdk: inner,
9317
- options
9318
- }) => {
9319
- const versionedKey = await inner.context.getVersionedImplementationId(
9320
- options.app
9933
+ itemType: "Record",
9934
+ inputSchema: GetTableRecordOptionsInputSchema,
9935
+ outputSchema: RecordItemSchema,
9936
+ resolvers: { table: tableIdResolver, record: tableRecordIdResolver },
9937
+ formatter: tableRecordFormatter,
9938
+ handler: async ({ sdk: sdk2, options }) => {
9939
+ const { api } = sdk2.context;
9940
+ const tableId = "table" in options ? options.table : options.tableId;
9941
+ const recordId = "record" in options ? options.record : options.recordId;
9942
+ const rawResponse = await api.get(
9943
+ `/tables/api/v1/tables/${tableId}/records/${recordId}`,
9944
+ {
9945
+ authRequired: true,
9946
+ resource: { type: "record", id: recordId }
9947
+ }
9321
9948
  );
9322
- const appKey = versionedKey ? versionedKey.split("@")[0] : options.app;
9323
- setMethodMetadata({ selectedApi: appKey });
9324
- try {
9325
- const top = await inner.context.api.poll(
9326
- CONNECTIONS_PATH,
9327
- {
9328
- searchParams: {
9329
- app_key: appKey,
9330
- // Scope to the current user's own connections. The connection
9331
- // we're waiting on is by definition owned by the caller; without
9332
- // this the one-row head-check could match a teammate's freshly
9333
- // created connection for the same app.
9334
- owner: "me",
9335
- is_expired: "false",
9336
- ordering: "-date",
9337
- page_size: "1"
9338
- },
9339
- authRequired: true,
9340
- timeoutMs: options.timeoutMs ?? 3e5,
9341
- initialDelay: options.pollIntervalMs ?? 3e3,
9342
- isPending: (body) => {
9343
- const rows = body.data ?? [];
9344
- const head = rows[0];
9345
- if (!head?.date) return true;
9346
- const created = Math.floor(new Date(head.date).getTime() / 1e3);
9347
- return !Number.isFinite(created) || created < options.startedAt;
9348
- },
9349
- resultExtractor: (body) => (
9350
- // `isPending` guaranteed a fresh row at index 0 before this fires.
9351
- body.data[0]
9352
- )
9353
- }
9354
- );
9355
- return {
9356
- data: WaitForNewConnectionItemSchema.parse({
9357
- id: String(top.public_id ?? top.id),
9358
- app: appKey,
9359
- title: top.title ?? null
9360
- })
9361
- };
9362
- } catch (err) {
9363
- if (err instanceof ZapierTimeoutError) {
9364
- throw new ZapierTimeoutError(
9365
- `Timed out waiting for a new "${appKey}" connection. If the user completed the auth flow, retrieve the connection via sdk.getConnection({ id }) with the ID shown on the completion page.`
9366
- );
9949
+ const response = GetTableRecordApiResponseSchema.parse(rawResponse);
9950
+ const translator = await createFieldKeyTranslator({
9951
+ api,
9952
+ tableId,
9953
+ keyMode: options.keyMode
9954
+ });
9955
+ return {
9956
+ data: {
9957
+ ...transformRecordItem(response.data),
9958
+ data: translator.translateOutput(response.data.data)
9367
9959
  }
9368
- throw err;
9369
- }
9960
+ };
9370
9961
  }
9371
9962
  })
9372
9963
  );
9964
+ var ListTableRecordsApiResponseSchema = z.object({
9965
+ data: z.array(RecordApiItemSchema),
9966
+ meta: z.object({
9967
+ pagination: z.object({
9968
+ start_cursor: z.string().nullable().optional(),
9969
+ end_cursor: z.string().nullable().optional(),
9970
+ has_more: z.boolean().optional(),
9971
+ has_less: z.boolean().optional()
9972
+ }).optional()
9973
+ }).optional()
9974
+ });
9975
+ var FilterOperatorSchema = z.enum([
9976
+ "exact",
9977
+ "different",
9978
+ "contains",
9979
+ "icontains",
9980
+ "gte",
9981
+ "gt",
9982
+ "lt",
9983
+ "lte",
9984
+ "range",
9985
+ "in",
9986
+ "isnull",
9987
+ "startswith",
9988
+ "search",
9989
+ "is_within"
9990
+ ]);
9991
+ var FilterConditionSchema = z.object({
9992
+ fieldKey: z.string().describe("The field key to filter on (e.g. f1, f2)"),
9993
+ operator: FilterOperatorSchema.describe("The comparison operator"),
9994
+ value: z.unknown().optional().describe("The value to compare against")
9995
+ });
9996
+ var SortDirectionSchema = z.enum(["asc", "desc"]);
9997
+ var SortConditionSchema = z.object({
9998
+ fieldKey: z.string().describe("The field key to sort by"),
9999
+ direction: SortDirectionSchema.optional().default("asc").describe("Sort direction")
10000
+ });
10001
+ var ListTableRecordsDescription = "List records in a table with optional filtering and sorting";
10002
+ var ListTableRecordsBase = z.object({
10003
+ filters: z.array(FilterConditionSchema).optional().describe("Filter conditions for the query"),
10004
+ sort: SortConditionSchema.optional().describe("Sort records by a field"),
10005
+ pageSize: z.number().min(1).max(1e3).optional().describe("Number of records per page (max 1000)"),
10006
+ maxItems: z.number().min(1).optional().describe("Maximum total items to return across all pages"),
10007
+ cursor: z.string().optional().describe("Cursor to start from"),
10008
+ keyMode: KeyModeSchema,
10009
+ trash: TrashSchema
10010
+ });
10011
+ var ListTableRecordsOptionsSchema = z.object({
10012
+ table: TablePropertySchema
10013
+ }).merge(ListTableRecordsBase).describe(ListTableRecordsDescription).meta({ aliases: { tableId: "table" } });
10014
+ var ListTableRecordsOptionsSchemaDeprecated = z.object({
10015
+ tableId: z.string().regex(/^[A-Z0-9]{26}$/, "Table ID must be a valid ULID").describe("The unique identifier of the table")
10016
+ }).merge(ListTableRecordsBase);
10017
+ var ListTableRecordsOptionsInputSchema = z.union([
10018
+ ListTableRecordsOptionsSchema,
10019
+ ListTableRecordsOptionsSchemaDeprecated
10020
+ ]).describe(ListTableRecordsDescription);
9373
10021
 
9374
- // src/utils/should-open-browser.ts
9375
- function shouldOpenBrowser() {
9376
- if (isCiEnv()) return false;
9377
- const env = globalThis.process?.env;
9378
- if (env?.SSH_TTY || env?.SSH_CONNECTION) return false;
9379
- if (globalThis.process?.platform === "linux" && !env?.DISPLAY && !env?.WAYLAND_DISPLAY) {
9380
- return false;
9381
- }
9382
- return true;
9383
- }
9384
- function isCiEnv() {
9385
- const env = globalThis.process?.env;
9386
- return !!(env?.CI || env?.CONTINUOUS_INTEGRATION || env?.GITHUB_ACTIONS || env?.JENKINS_URL || env?.GITLAB_CI || env?.CIRCLECI || env?.TRAVIS || env?.BUILDKITE || env?.DRONE || env?.BITBUCKET_PIPELINES_UUID);
9387
- }
9388
- var CreateConnectionSchema = z.object({
9389
- app: AppPropertySchema,
9390
- browser: z.enum(["auto", "always", "never"]).default("auto").describe(
9391
- "When to auto-open the URL in a browser. `auto` (default) opens in local sessions and skips opening in CI / SSH / headless-Linux. `always` forces the open attempt. `never` skips it. The URL is always printed to stderr regardless \u2014 a failed or skipped open degrades gracefully to copy-paste."
9392
- ),
9393
- timeoutMs: z.number().int().positive().optional().describe(
9394
- "How long to wait for the user to complete the connection flow before giving up. Default 5 minutes (300_000)."
9395
- ),
9396
- pollIntervalMs: z.number().int().positive().optional().describe(
9397
- "Delay before the first poll request, in ms. Default 3 seconds (3_000). Subsequent polling cadence is managed by the SDK's polling primitive (backoff with sane defaults)."
9398
- )
9399
- }).describe(
9400
- "Create a new app connection, end-to-end. Mints the start URL via `get-connection-start-url`, prints it to stderr, opportunistically opens it in a browser when it looks safe to do so (skipping CI / SSH / headless-Linux by default \u2014 pass `--browser always` to force, `--browser never` to suppress), then polls via `wait-for-new-connection` until the user completes OAuth and the new connection appears. Returns the connection.\n\nThis is the right command for most callers. Reach for the lower-level building blocks when you want either of: (a) hand off the URL and *not* block on completion \u2014 call `get-connection-start-url` alone, no `wait-for-new-connection` needed, or (b) do something custom between minting the URL and waiting \u2014 call `get-connection-start-url`, do your work (email or DM the URL, render a QR code, etc.), then `wait-for-new-connection`."
9401
- );
9402
- var CreateConnectionItemSchema = z.object({
9403
- id: z.string().describe(
9404
- "The new connection's ID. Public UUID when available, falling back to the numeric ID."
9405
- ),
9406
- app: z.string().describe(
9407
- "Versionless app key the connection was created for (e.g., 'SlackCLIAPI')."
9408
- ),
9409
- title: z.string().nullable().optional().describe(
9410
- "Human-readable connection title set by the auth flow, when available."
9411
- )
9412
- }).describe("The newly created connection.");
10022
+ // src/plugins/tables/listTableRecords/index.ts
10023
+ var listTableRecordsPlugin = definePlugin(
10024
+ (sdk) => createPaginatedPluginMethod(sdk, {
10025
+ ...tablesDefaults,
10026
+ name: "listTableRecords",
10027
+ type: "list",
10028
+ itemType: "Record",
10029
+ inputSchema: ListTableRecordsOptionsInputSchema,
10030
+ outputSchema: RecordItemSchema,
10031
+ defaultPageSize: DEFAULT_PAGE_SIZE,
10032
+ resolvers: {
10033
+ table: tableIdResolver,
10034
+ filters: tableFiltersResolver,
10035
+ sort: tableSortResolver
10036
+ },
10037
+ formatter: tableRecordFormatter,
10038
+ handler: async ({ sdk: sdk2, options }) => {
10039
+ const { api } = sdk2.context;
10040
+ const tableId = "table" in options ? options.table : options.tableId;
10041
+ const translator = await createFieldKeyTranslator({
10042
+ api,
10043
+ tableId,
10044
+ keyMode: options.keyMode
10045
+ });
10046
+ const body = {};
10047
+ if (options.pageSize !== void 0) {
10048
+ body.limit = options.pageSize;
10049
+ }
10050
+ if (options.filters) {
10051
+ body.filters = options.filters.map((f) => ({
10052
+ key: translator.translateFieldKey(f.fieldKey),
10053
+ operator: f.operator,
10054
+ value: f.value
10055
+ }));
10056
+ }
10057
+ if (options.sort) {
10058
+ body.orders = [
10059
+ {
10060
+ key: translator.translateFieldKey(options.sort.fieldKey),
10061
+ direction: options.sort.direction
10062
+ }
10063
+ ];
10064
+ }
10065
+ if (options.cursor) {
10066
+ body.cursor_query = {
10067
+ query_type: "window",
10068
+ start_cursor: options.cursor
10069
+ };
10070
+ }
10071
+ const searchParams = {
10072
+ allow_nested_queries: "true"
10073
+ };
10074
+ if (options.trash) {
10075
+ searchParams.trash = options.trash;
10076
+ }
10077
+ const rawResponse = await api.post(
10078
+ `/tables/api/v1/tables/${tableId}/records/query`,
10079
+ body,
10080
+ {
10081
+ searchParams,
10082
+ authRequired: true,
10083
+ resource: { type: "table", id: tableId }
10084
+ }
10085
+ );
10086
+ throwOnResponseErrors(rawResponse);
10087
+ const response = ListTableRecordsApiResponseSchema.parse(rawResponse);
10088
+ const pagination = response.meta?.pagination;
10089
+ const nextCursor = pagination?.has_more && pagination.end_cursor ? pagination.end_cursor : void 0;
10090
+ return {
10091
+ data: response.data.map((item) => ({
10092
+ ...transformRecordItem(item),
10093
+ data: translator.translateOutput(item.data)
10094
+ })),
10095
+ nextCursor
10096
+ };
10097
+ }
10098
+ })
10099
+ );
10100
+ var RecordChangesetSchema = z.object({
10101
+ change_id: z.string(),
10102
+ old: RecordApiItemSchema.nullable(),
10103
+ new: RecordApiItemSchema,
10104
+ changed_field_ids: z.array(z.number()).nullable(),
10105
+ record_id: z.string()
10106
+ });
10107
+ var CreateTableRecordsApiResponseSchema = z.object({
10108
+ data: z.array(RecordChangesetSchema)
10109
+ });
10110
+ var NewRecordSchema = z.object({
10111
+ data: z.record(z.string(), z.unknown()).describe("The field values for the record, keyed by field ID")
10112
+ });
10113
+ var CreateTableRecordsDescription = "Create one or more records in a table";
10114
+ var CreateTableRecordsBase = z.object({
10115
+ records: z.array(NewRecordSchema).min(1).max(100).describe("Array of records to create (max 100)"),
10116
+ keyMode: KeyModeSchema
10117
+ });
10118
+ var CreateTableRecordsOptionsSchema = z.object({
10119
+ table: TablePropertySchema
10120
+ }).merge(CreateTableRecordsBase).describe(CreateTableRecordsDescription).meta({ aliases: { tableId: "table" } });
10121
+ var CreateTableRecordsOptionsSchemaDeprecated = z.object({
10122
+ tableId: z.string().regex(/^[A-Z0-9]{26}$/, "Table ID must be a valid ULID").describe("The unique identifier of the table")
10123
+ }).merge(CreateTableRecordsBase);
10124
+ var CreateTableRecordsOptionsInputSchema = z.union([
10125
+ CreateTableRecordsOptionsSchema,
10126
+ CreateTableRecordsOptionsSchemaDeprecated
10127
+ ]).describe(CreateTableRecordsDescription);
9413
10128
 
9414
- // src/plugins/createConnection/index.ts
9415
- var createConnectionPlugin = definePlugin(
10129
+ // src/plugins/tables/createTableRecords/index.ts
10130
+ var createTableRecordsPlugin = definePlugin(
9416
10131
  (sdk) => createPluginMethod(sdk, {
9417
- name: "createConnection",
9418
- categories: ["connection"],
10132
+ ...tablesDefaults,
10133
+ name: "createTableRecords",
9419
10134
  type: "create",
9420
- itemType: "Connection",
9421
- inputSchema: CreateConnectionSchema,
9422
- outputSchema: CreateConnectionItemSchema,
9423
- resolvers: { app: appKeyResolver },
9424
- formatter: {
9425
- format: (item) => ({
9426
- title: `Connection created: ${item.title || item.id}`,
9427
- id: item.id,
9428
- details: [
9429
- { text: `App: ${item.app}`, style: "normal" },
9430
- { text: `ID: ${item.id}`, style: "accent" }
9431
- ]
9432
- })
9433
- },
9434
- handler: async ({
9435
- sdk: inner,
9436
- options
9437
- }) => {
9438
- const { data: start } = await inner.getConnectionStartUrl({
9439
- app: options.app
10135
+ itemType: "Record",
10136
+ returnType: "RecordItem[]",
10137
+ inputSchema: CreateTableRecordsOptionsInputSchema,
10138
+ outputSchema: RecordItemSchema,
10139
+ resolvers: { table: tableIdResolver, records: tableRecordsResolver },
10140
+ formatter: tableRecordFormatter,
10141
+ handler: async ({ sdk: sdk2, options }) => {
10142
+ const { api } = sdk2.context;
10143
+ const tableId = "table" in options ? options.table : options.tableId;
10144
+ const translator = await createFieldKeyTranslator({
10145
+ api,
10146
+ tableId,
10147
+ keyMode: options.keyMode
9440
10148
  });
9441
- setMethodMetadata({ selectedApi: start.app });
9442
- console.error(
9443
- `
9444
- Open this URL to complete the connection:
9445
- ${start.url}
9446
- `
10149
+ const rawResponse = await api.post(
10150
+ `/tables/api/v1/tables/${tableId}/records`,
10151
+ {
10152
+ new_records: options.records.map((record) => ({
10153
+ data: translator.translateInput(record.data)
10154
+ }))
10155
+ },
10156
+ { authRequired: true, resource: { type: "table", id: tableId } }
9447
10157
  );
9448
- const shouldOpen = options.browser === "always" || options.browser === "auto" && shouldOpenBrowser();
9449
- if (shouldOpen) {
9450
- try {
9451
- await open_url_default(start.url);
9452
- } catch {
9453
- }
10158
+ throwOnResponseErrors(rawResponse);
10159
+ const response = CreateTableRecordsApiResponseSchema.parse(rawResponse);
10160
+ for (const changeset of response.data) {
10161
+ throwOnRecordErrors(changeset.new);
9454
10162
  }
9455
- const { data: fresh } = await inner.waitForNewConnection({
9456
- app: start.app,
9457
- // Server-stamped mint time: measured on the same clock as a
9458
- // connection's `date`, so the freshness check is immune to
9459
- // client/server clock skew.
9460
- startedAt: start.startedAt,
9461
- timeoutMs: options.timeoutMs,
9462
- pollIntervalMs: options.pollIntervalMs
9463
- });
9464
10163
  return {
9465
- data: CreateConnectionItemSchema.parse({
9466
- id: fresh.id,
9467
- app: start.app,
9468
- title: fresh.title ?? null
9469
- })
10164
+ data: response.data.map((changeset) => ({
10165
+ ...transformRecordItem(changeset.new),
10166
+ data: translator.translateOutput(changeset.new.data)
10167
+ }))
9470
10168
  };
9471
10169
  }
9472
10170
  })
9473
10171
  );
10172
+ var DeleteTableRecordsDescription = "Delete one or more records from a table";
10173
+ var DeleteTableRecordsOptionsSchema = z.object({
10174
+ table: TablePropertySchema,
10175
+ records: RecordsPropertySchema
10176
+ }).describe(DeleteTableRecordsDescription).meta({ aliases: { tableId: "table", recordIds: "records" } });
10177
+ var DeleteTableRecordsOptionsSchemaDeprecated = z.object({
10178
+ tableId: z.string().regex(/^[A-Z0-9]{26}$/, "Table ID must be a valid ULID").describe("The unique identifier of the table"),
10179
+ recordIds: z.array(z.string().regex(/^[A-Z0-9]{26}$/, "Record ID must be a valid ULID")).min(1).max(100).describe("Array of record IDs to delete (max 100)")
10180
+ });
10181
+ var DeleteTableRecordsOptionsInputSchema = z.union([
10182
+ DeleteTableRecordsOptionsSchema,
10183
+ DeleteTableRecordsOptionsSchemaDeprecated
10184
+ ]).describe(DeleteTableRecordsDescription);
9474
10185
 
9475
- // src/plugins/deprecated/authentications.ts
9476
- var listAuthenticationsPlugin = definePlugin(
9477
- (sdk) => ({
9478
- listAuthentications: sdk.listConnections,
9479
- context: {
9480
- meta: {
9481
- listAuthentications: {
9482
- packages: ["cli", "mcp"],
9483
- categories: ["connection"],
9484
- deprecation: { message: "Use listConnections instead." },
9485
- type: "list",
9486
- itemType: "Connection",
9487
- inputSchema: ListConnectionsQuerySchema,
9488
- outputSchema: ConnectionItemSchema,
9489
- formatter: connectionItemFormatter
9490
- }
9491
- }
9492
- }
9493
- })
9494
- );
9495
- var getAuthenticationPlugin = definePlugin(
9496
- (sdk) => ({
9497
- getAuthentication: sdk.getConnection,
9498
- context: {
9499
- meta: {
9500
- getAuthentication: {
9501
- packages: ["cli", "mcp"],
9502
- categories: ["connection"],
9503
- deprecation: { message: "Use getConnection instead." },
9504
- type: "item",
9505
- itemType: "Connection",
9506
- inputSchema: GetConnectionParamSchema,
9507
- outputSchema: ConnectionItemSchema,
9508
- formatter: connectionItemFormatter
10186
+ // src/plugins/tables/deleteTableRecords/index.ts
10187
+ var deleteTableRecordsPlugin = definePlugin(
10188
+ (sdk) => createPluginMethod(sdk, {
10189
+ ...tablesDefaults,
10190
+ name: "deleteTableRecords",
10191
+ type: "delete",
10192
+ itemType: "Record",
10193
+ inputSchema: DeleteTableRecordsOptionsInputSchema,
10194
+ resolvers: { table: tableIdResolver, records: tableRecordIdsResolver },
10195
+ confirm: "delete",
10196
+ handler: async ({ sdk: sdk2, options }) => {
10197
+ const tableId = "table" in options ? options.table : options.tableId;
10198
+ const recordIds = "records" in options ? options.records : options.recordIds;
10199
+ await sdk2.context.api.delete(
10200
+ `/tables/api/v1/tables/${tableId}/records`,
10201
+ { record_ids: recordIds },
10202
+ {
10203
+ authRequired: true,
10204
+ resource: { type: "table", id: tableId }
9509
10205
  }
9510
- }
10206
+ );
10207
+ return { success: true };
9511
10208
  }
9512
10209
  })
9513
10210
  );
9514
- var findFirstAuthenticationPlugin = definePlugin(
9515
- (sdk) => ({
9516
- findFirstAuthentication: sdk.findFirstConnection,
9517
- context: {
9518
- meta: {
9519
- findFirstAuthentication: {
9520
- packages: ["cli", "mcp"],
9521
- categories: ["connection"],
9522
- deprecation: { message: "Use findFirstConnection instead." },
9523
- type: "item",
9524
- itemType: "Connection",
9525
- inputSchema: FindFirstConnectionSchema,
9526
- outputSchema: ConnectionItemSchema,
9527
- formatter: connectionItemFormatter
9528
- }
10211
+ var RecordChangesetSchema2 = z.object({
10212
+ change_id: z.string(),
10213
+ old: RecordApiItemSchema.nullable(),
10214
+ new: RecordApiItemSchema,
10215
+ changed_field_ids: z.array(z.number()).nullable(),
10216
+ record_id: z.string()
10217
+ });
10218
+ var UpdateTableRecordsApiResponseSchema = z.object({
10219
+ data: z.array(RecordChangesetSchema2)
10220
+ });
10221
+ var UpdateRecordSchema = z.object({
10222
+ id: z.string().describe("The record ID to update"),
10223
+ data: z.record(z.string(), z.unknown()).describe("The field values to update, keyed by field key")
10224
+ });
10225
+ var UpdateTableRecordsDescription = "Update one or more records in a table";
10226
+ var UpdateTableRecordsBase = z.object({
10227
+ records: z.array(UpdateRecordSchema).min(1).max(100).describe("Array of records to update (max 100)"),
10228
+ keyMode: KeyModeSchema
10229
+ });
10230
+ var UpdateTableRecordsOptionsSchema = z.object({
10231
+ table: TablePropertySchema
10232
+ }).merge(UpdateTableRecordsBase).describe(UpdateTableRecordsDescription).meta({ aliases: { tableId: "table" } });
10233
+ var UpdateTableRecordsOptionsSchemaDeprecated = z.object({
10234
+ tableId: z.string().regex(/^[A-Z0-9]{26}$/, "Table ID must be a valid ULID").describe("The unique identifier of the table")
10235
+ }).merge(UpdateTableRecordsBase);
10236
+ var UpdateTableRecordsOptionsInputSchema = z.union([
10237
+ UpdateTableRecordsOptionsSchema,
10238
+ UpdateTableRecordsOptionsSchemaDeprecated
10239
+ ]).describe(UpdateTableRecordsDescription);
10240
+
10241
+ // src/plugins/tables/updateTableRecords/index.ts
10242
+ var updateTableRecordsPlugin = definePlugin(
10243
+ (sdk) => createPluginMethod(sdk, {
10244
+ ...tablesDefaults,
10245
+ name: "updateTableRecords",
10246
+ type: "update",
10247
+ itemType: "Record",
10248
+ returnType: "RecordItem[]",
10249
+ inputSchema: UpdateTableRecordsOptionsInputSchema,
10250
+ outputSchema: RecordItemSchema,
10251
+ resolvers: {
10252
+ table: tableIdResolver,
10253
+ records: tableUpdateRecordsResolver
10254
+ },
10255
+ formatter: tableRecordFormatter,
10256
+ handler: async ({ sdk: sdk2, options }) => {
10257
+ const { api } = sdk2.context;
10258
+ const tableId = "table" in options ? options.table : options.tableId;
10259
+ const translator = await createFieldKeyTranslator({
10260
+ api,
10261
+ tableId,
10262
+ keyMode: options.keyMode
10263
+ });
10264
+ const rawResponse = await api.patch(
10265
+ `/tables/api/v1/tables/${tableId}/records`,
10266
+ {
10267
+ updated_records: options.records.map((record) => ({
10268
+ id: record.id,
10269
+ data: translator.translateInput(record.data)
10270
+ }))
10271
+ },
10272
+ { authRequired: true, resource: { type: "table", id: tableId } }
10273
+ );
10274
+ throwOnResponseErrors(rawResponse);
10275
+ const response = UpdateTableRecordsApiResponseSchema.parse(rawResponse);
10276
+ for (const changeset of response.data) {
10277
+ throwOnRecordErrors(changeset.new);
9529
10278
  }
10279
+ return {
10280
+ data: response.data.map((changeset) => ({
10281
+ ...transformRecordItem(changeset.new),
10282
+ data: translator.translateOutput(changeset.new.data)
10283
+ }))
10284
+ };
9530
10285
  }
9531
10286
  })
9532
10287
  );
9533
- var findUniqueAuthenticationPlugin = definePlugin(
9534
- (sdk) => ({
9535
- findUniqueAuthentication: sdk.findUniqueConnection,
9536
- context: {
9537
- meta: {
9538
- findUniqueAuthentication: {
9539
- packages: ["cli", "mcp"],
9540
- categories: ["connection"],
9541
- deprecation: { message: "Use findUniqueConnection instead." },
9542
- type: "item",
9543
- itemType: "Connection",
9544
- inputSchema: FindUniqueConnectionSchema,
9545
- outputSchema: ConnectionItemSchema,
9546
- formatter: connectionItemFormatter
9547
- }
10288
+
10289
+ // src/plugins/capabilities/index.ts
10290
+ function toDescription(key) {
10291
+ const words = key.replace(/^can/, "").replace(/([A-Z])/g, " $1").trim().toLowerCase();
10292
+ return `To ${words}`;
10293
+ }
10294
+ function toEnvVar(key) {
10295
+ return "ZAPIER_" + key.replace(/([A-Z])/g, "_$1").toUpperCase();
10296
+ }
10297
+ function toCliFlag(key) {
10298
+ return "--" + key.replace(/([A-Z])/g, "-$1").toLowerCase();
10299
+ }
10300
+ function buildCapabilityMessage(key) {
10301
+ return [
10302
+ `${toDescription(key)}, use ${toCliFlag(key)} in the CLI,`,
10303
+ `set ${key}: true in SDK options or .zapierrc,`,
10304
+ `or set ${toEnvVar(key)}=true.`
10305
+ ].join(" ");
10306
+ }
10307
+ var GATED_FLAGS = [
10308
+ "canIncludeSharedConnections",
10309
+ "canIncludeSharedTables",
10310
+ "canDeleteTables"
10311
+ ];
10312
+ function isEnabledByEnv(key) {
10313
+ const value = globalThis.process?.env?.[toEnvVar(key)];
10314
+ if (value === void 0) return void 0;
10315
+ if (value === "true" || value === "1") return true;
10316
+ if (value === "false" || value === "0") return false;
10317
+ return void 0;
10318
+ }
10319
+ var capabilitiesPlugin = definePlugin(
10320
+ (sdk) => {
10321
+ const options = sdk.context.options ?? {};
10322
+ let cached;
10323
+ async function resolveFlags() {
10324
+ if (cached) return cached;
10325
+ const manifest = await sdk.context.getResolvedManifest();
10326
+ cached = {};
10327
+ for (const flag of GATED_FLAGS) {
10328
+ cached[flag] = Boolean(
10329
+ options[flag] ?? isEnabledByEnv(flag) ?? manifest?.[flag]
10330
+ );
9548
10331
  }
10332
+ return cached;
9549
10333
  }
9550
- })
9551
- );
9552
-
9553
- // src/plugins/deprecated/inputFields.ts
9554
- var listInputFieldsDeprecatedPlugin = definePlugin(
9555
- (sdk) => ({
9556
- listInputFields: sdk.listActionInputFields,
9557
- context: {
9558
- meta: {
9559
- listInputFields: {
9560
- categories: ["action"],
9561
- deprecation: { message: "Use listActionInputFields instead." },
9562
- type: "list",
9563
- itemType: "RootField",
9564
- inputSchema: ListActionInputFieldsInputSchema,
9565
- outputSchema: RootFieldItemSchema,
9566
- formatter: rootFieldItemFormatter,
9567
- defaultPageSize: DEFAULT_PAGE_SIZE
10334
+ return {
10335
+ context: {
10336
+ checkCapability: async (key) => {
10337
+ const flags = await resolveFlags();
10338
+ if (flags[key]) return;
10339
+ throw new ZapierConfigurationError(
10340
+ buildCapabilityMessage(key) + " (If you are an AI agent, you MUST NOT retry. Ask the user if they want to enable this.)",
10341
+ { configType: key }
10342
+ );
10343
+ },
10344
+ hasCapability: async (key) => {
10345
+ const flags = await resolveFlags();
10346
+ return flags[key];
9568
10347
  }
9569
10348
  }
9570
- }
9571
- })
10349
+ };
10350
+ }
9572
10351
  );
9573
- var listInputFieldChoicesDeprecatedPlugin = definePlugin(
9574
- (sdk) => ({
9575
- listInputFieldChoices: sdk.listActionInputFieldChoices,
9576
- context: {
9577
- meta: {
9578
- listInputFieldChoices: {
9579
- categories: ["action"],
9580
- deprecation: {
9581
- message: "Use listActionInputFieldChoices instead."
9582
- },
9583
- type: "list",
9584
- itemType: "InputFieldChoiceItem",
9585
- inputSchema: ListActionInputFieldChoicesInputSchema,
9586
- outputSchema: InputFieldChoiceItemSchema,
9587
- formatter: inputFieldChoiceItemFormatter,
9588
- defaultPageSize: DEFAULT_PAGE_SIZE
9589
- }
10352
+
10353
+ // src/plugins/connections/index.ts
10354
+ var connectionsPlugin = definePlugin(
10355
+ (sdk) => {
10356
+ let cachedMap;
10357
+ async function loadConnectionsMap() {
10358
+ if (cachedMap === void 0) {
10359
+ cachedMap = await sdk.context.getManifestConnections() ?? null;
9590
10360
  }
10361
+ return cachedMap;
9591
10362
  }
9592
- })
9593
- );
9594
- var getInputFieldsSchemaDeprecatedPlugin = definePlugin(
9595
- (sdk) => ({
9596
- getInputFieldsSchema: sdk.getActionInputFieldsSchema,
9597
- context: {
9598
- meta: {
9599
- getInputFieldsSchema: {
9600
- categories: ["action"],
9601
- deprecation: { message: "Use getActionInputFieldsSchema instead." },
9602
- type: "function",
9603
- inputSchema: GetActionInputFieldsSchemaInputSchema
10363
+ return {
10364
+ context: {
10365
+ resolveConnection: async (name) => {
10366
+ const map = await loadConnectionsMap();
10367
+ return map?.[name];
10368
+ },
10369
+ getConnectionsMap: async () => {
10370
+ return loadConnectionsMap();
9604
10371
  }
9605
10372
  }
9606
- }
9607
- })
10373
+ };
10374
+ }
9608
10375
  );
9609
10376
 
9610
10377
  // src/plugins/eventEmission/transport.ts
@@ -10298,12 +11065,6 @@ var eventEmissionPlugin = definePlugin(
10298
11065
  function createOptionsPlugin(options) {
10299
11066
  return () => ({ context: { options } });
10300
11067
  }
10301
- function createSdk() {
10302
- logDeprecation2(
10303
- "createSdk() is deprecated. Build SDKs with createPluginStack().use(...).toSdk() instead. The chain pattern shares plugin closures (and their state) across derived SDKs in ways that are rarely what callers expect; stacks produce fresh closures per .toSdk() call."
10304
- );
10305
- return withDeprecatedAddPlugin(createZapierCoreStack().toSdk());
10306
- }
10307
11068
  function createZapierSdkWithoutRegistry(options = {}) {
10308
11069
  logDeprecation2(
10309
11070
  "createZapierSdkWithoutRegistry is deprecated; use createZapierSdk instead. getRegistry is now available on every sdk."
@@ -10311,10 +11072,112 @@ function createZapierSdkWithoutRegistry(options = {}) {
10311
11072
  return createZapierSdk(options);
10312
11073
  }
10313
11074
  function createZapierSdkStack(options = {}) {
10314
- return createZapierCoreStack().use(createOptionsPlugin(options)).use(eventEmissionPlugin).use(apiPlugin).use(manifestPlugin).use(capabilitiesPlugin).use(connectionsPlugin).use(listAppsPlugin).use(getAppPlugin).use(listConnectionsPlugin).use(getConnectionPlugin).use(findFirstConnectionPlugin).use(findUniqueConnectionPlugin).use(getConnectionStartUrlPlugin).use(waitForNewConnectionPlugin).use(createConnectionPlugin).use(listActionsPlugin).use(getActionPlugin).use(listActionInputFieldsPlugin).use(getActionInputFieldsSchemaPlugin).use(listActionInputFieldChoicesPlugin).use(listInputFieldsDeprecatedPlugin).use(getInputFieldsSchemaDeprecatedPlugin).use(listInputFieldChoicesDeprecatedPlugin).use(runActionPlugin).use(listAuthenticationsPlugin).use(getAuthenticationPlugin).use(findFirstAuthenticationPlugin).use(findUniqueAuthenticationPlugin).use(listClientCredentialsPlugin).use(createClientCredentialsPlugin).use(deleteClientCredentialsPlugin).use(fetchPlugin).use(requestPlugin).use(listTablesPlugin).use(getTablePlugin).use(deleteTablePlugin).use(createTablePlugin).use(listTableFieldsPlugin).use(createTableFieldsPlugin).use(deleteTableFieldsPlugin).use(listTableRecordsPlugin).use(getTableRecordPlugin).use(createTableRecordsPlugin).use(deleteTableRecordsPlugin).use(updateTableRecordsPlugin).use(appsPlugin).use(getProfilePlugin);
11075
+ return createZapierCoreStack().use(createOptionsPlugin(options)).use(eventEmissionPlugin).use(apiPlugin).use(manifestPlugin).use(capabilitiesPlugin).use(connectionsPlugin).use(listAppsPlugin).use(getAppPlugin).use(listConnectionsPlugin).use(getConnectionPlugin).use(findFirstConnectionPlugin).use(findUniqueConnectionPlugin).use(getConnectionStartUrlPlugin).use(waitForNewConnectionPlugin).use(createConnectionPlugin).use(listActionsPlugin).use(getActionPlugin).use(listActionInputFieldsPlugin).use(getActionInputFieldsSchemaPlugin).use(listActionInputFieldChoicesPlugin).use(listInputFieldsDeprecatedPlugin).use(getInputFieldsSchemaDeprecatedPlugin).use(listInputFieldChoicesDeprecatedPlugin).use(runActionPlugin).use(listAuthenticationsPlugin).use(getAuthenticationPlugin).use(findFirstAuthenticationPlugin).use(findUniqueAuthenticationPlugin).use(listClientCredentialsPlugin).use(createClientCredentialsPlugin).use(deleteClientCredentialsPlugin).use(fetchPlugin).use(requestPlugin).use(listTablesPlugin).use(getTablePlugin).use(deleteTablePlugin).use(createTablePlugin).use(listTableFieldsPlugin).use(createTableFieldsPlugin).use(deleteTableFieldsPlugin).use(listTableRecordsPlugin).use(getTableRecordPlugin).use(createTableRecordsPlugin).use(deleteTableRecordsPlugin).use(updateTableRecordsPlugin).use(appsPlugin);
10315
11076
  }
11077
+ var zapierSdkPlugin = definePlugin({
11078
+ namespace: "zapier",
11079
+ name: "sdk",
11080
+ exports: [getProfilePlugin]
11081
+ });
10316
11082
  function createZapierSdk(options = {}) {
10317
- return withDeprecatedAddPlugin(createZapierSdkStack(options).toSdk());
11083
+ return createSdk(
11084
+ defineLegacyMerge({
11085
+ namespace: "zapier",
11086
+ name: "sdk-stack-merge",
11087
+ legacy: createZapierSdkStack(options).toPlugin(),
11088
+ plugin: zapierSdkPlugin
11089
+ })
11090
+ );
11091
+ }
11092
+
11093
+ // src/utils/batch-utils.ts
11094
+ var DEFAULT_CONCURRENCY = 10;
11095
+ var BATCH_START_DELAY_MS = 25;
11096
+ var DEFAULT_BATCH_TIMEOUT_MS = 18e4;
11097
+ async function batch(tasks, options = {}) {
11098
+ const {
11099
+ concurrency = DEFAULT_CONCURRENCY,
11100
+ retry = true,
11101
+ batchDelay = BATCH_START_DELAY_MS,
11102
+ timeoutMs = DEFAULT_BATCH_TIMEOUT_MS,
11103
+ taskTimeoutMs
11104
+ } = options;
11105
+ if (concurrency <= 0) {
11106
+ throw new Error("Concurrency must be greater than 0");
11107
+ }
11108
+ if (timeoutMs <= 0) {
11109
+ throw new Error("Timeout must be greater than 0");
11110
+ }
11111
+ if (taskTimeoutMs !== void 0 && taskTimeoutMs <= 0) {
11112
+ throw new Error("Task timeout must be greater than 0");
11113
+ }
11114
+ if (tasks.length === 0) {
11115
+ return [];
11116
+ }
11117
+ const startTime = Date.now();
11118
+ const results = new Array(tasks.length);
11119
+ const taskQueue = tasks.map((task, index) => ({
11120
+ index,
11121
+ task,
11122
+ errorCount: 0
11123
+ }));
11124
+ async function executeTask(taskState) {
11125
+ const { index, task, errorCount } = taskState;
11126
+ try {
11127
+ let result;
11128
+ if (taskTimeoutMs !== void 0) {
11129
+ const timeoutPromise = sleep(taskTimeoutMs).then(() => {
11130
+ throw new ZapierTimeoutError(
11131
+ `Task timed out after ${taskTimeoutMs}ms`
11132
+ );
11133
+ });
11134
+ result = await Promise.race([task(), timeoutPromise]);
11135
+ } else {
11136
+ result = await task();
11137
+ }
11138
+ results[index] = { status: "fulfilled", value: result };
11139
+ } catch (error) {
11140
+ const newErrorCount = errorCount + 1;
11141
+ const isTimeout = error instanceof ZapierTimeoutError;
11142
+ if (retry && !isTimeout && newErrorCount < MAX_CONSECUTIVE_ERRORS) {
11143
+ const waitTime = calculateErrorBackoffMs(1e3, newErrorCount);
11144
+ await sleep(waitTime);
11145
+ taskQueue.push({
11146
+ index,
11147
+ task,
11148
+ errorCount: newErrorCount
11149
+ });
11150
+ } else {
11151
+ results[index] = { status: "rejected", reason: error };
11152
+ }
11153
+ }
11154
+ }
11155
+ async function worker() {
11156
+ while (taskQueue.length > 0) {
11157
+ const elapsedTime = Date.now() - startTime;
11158
+ if (elapsedTime >= timeoutMs) {
11159
+ throw new ZapierTimeoutError(
11160
+ `Batch operation timed out after ${Math.floor(elapsedTime / 1e3)}s. ${taskQueue.length} task(s) not completed.`
11161
+ );
11162
+ }
11163
+ const taskState = taskQueue.shift();
11164
+ if (!taskState) break;
11165
+ await executeTask(taskState);
11166
+ if (taskQueue.length > 0 && batchDelay > 0) {
11167
+ await sleep(batchDelay);
11168
+ }
11169
+ }
11170
+ }
11171
+ const workerCount = Math.min(concurrency, tasks.length);
11172
+ const workers = [];
11173
+ for (let i = 0; i < workerCount; i++) {
11174
+ workers.push(worker());
11175
+ if (i < workerCount - 1 && batchDelay > 0) {
11176
+ await sleep(batchDelay / 10);
11177
+ }
11178
+ }
11179
+ await Promise.all(workers);
11180
+ return results;
10318
11181
  }
10319
11182
  var BaseSdkOptionsSchema = z.object({
10320
11183
  credentials: CredentialsSchema.optional().describe(
@@ -10386,4 +11249,4 @@ var registryPlugin = definePlugin((_sdk) => {
10386
11249
  return {};
10387
11250
  });
10388
11251
 
10389
- export { ActionKeyPropertySchema, ActionPropertySchema, ActionTimeoutMsPropertySchema, ActionTypePropertySchema, AppKeyPropertySchema, AppPropertySchema, AppsPropertySchema, AuthMechanism, AuthenticationIdPropertySchema, BaseSdkOptionsSchema, CONTEXT_CACHE_MAX_SIZE, CONTEXT_CACHE_TTL_MS, CORE_ERROR_SYMBOL, ClientCredentialsObjectSchema, ConnectionEntrySchema, ConnectionIdPropertySchema, ConnectionPropertySchema, ConnectionsMapSchema, ConnectionsPropertySchema, CoreErrorCode, CredentialsFunctionSchema, CredentialsObjectSchema, CredentialsSchema, DEFAULT_ACTION_TIMEOUT_MS, DEFAULT_APPROVAL_TIMEOUT_MS, DEFAULT_CONFIG_PATH, DEFAULT_MAX_APPROVAL_RETRIES, DEFAULT_PAGE_SIZE, DebugPropertySchema, FieldsPropertySchema, InputFieldPropertySchema, InputsPropertySchema, LeaseLimitPropertySchema, LeasePropertySchema, LeaseSecondsPropertySchema, LimitPropertySchema, MAX_CONCURRENCY_LIMIT, MAX_PAGE_LIMIT, OffsetPropertySchema, OutputPropertySchema, ParamsPropertySchema, PkceCredentialsObjectSchema, RecordPropertySchema, RecordsPropertySchema, RelayFetchSchema, RelayRequestSchema, ResolvedCredentialsSchema, TablePropertySchema, TablesPropertySchema, TriggerInboxNamePropertySchema, TriggerInboxPropertySchema, ZAPIER_BASE_URL, ZAPIER_MAX_CONCURRENT_REQUESTS, ZAPIER_MAX_NETWORK_RETRIES, ZAPIER_MAX_NETWORK_RETRY_DELAY_MS, ZapierAbortDrainSignal, ZapierActionError, ZapierApiError, ZapierAppNotFoundError, ZapierApprovalError, ZapierAuthenticationError, ZapierBundleError, ZapierConfigurationError, ZapierConflictError, ZapierError, ZapierNotFoundError, ZapierRateLimitError, ZapierRelayError, ZapierReleaseTriggerMessageSignal, ZapierResourceNotFoundError, ZapierSignal, ZapierTimeoutError, ZapierUnknownError, ZapierValidationError, actionKeyResolver, actionTypeResolver, addPlugin, apiPlugin, appKeyResolver, appsPlugin, connectionIdGenericResolver as authenticationIdGenericResolver, connectionIdResolver as authenticationIdResolver, batch, buildApplicationLifecycleEvent, buildCapabilityMessage, buildErrorEvent, buildErrorEventWithContext, buildMethodCalledEvent, cleanupEventListeners, clearTokenCache, clientCredentialsNameResolver, clientIdResolver, composePlugins, connectionIdGenericResolver, connectionIdResolver, connectionsPlugin, createBaseEvent, createClientCredentialsPlugin, createCorePlugin, createFunction, createMemoryCache, createOptionsPlugin, createPaginatedPluginMethod, createPluginMethod, createPluginStack, createSdk, createTableFieldsPlugin, createTablePlugin, createTableRecordsPlugin, createZapierApi, createZapierCoreStack, createZapierSdk, createZapierSdkStack, createZapierSdkWithoutRegistry, definePlugin, deleteClientCredentialsPlugin, deleteTableFieldsPlugin, deleteTablePlugin, deleteTableRecordsPlugin, durableRunIdResolver, eventEmissionPlugin, fetchPlugin, findFirstConnectionPlugin, findManifestEntry, findUniqueConnectionPlugin, formatErrorMessage, generateEventId, getActionInputFieldsSchemaPlugin, getActionPlugin, getAgent, getAppPlugin, getBaseUrlFromCredentials, getCallerContext, getCiPlatform, getClientIdFromCredentials, getConnectionPlugin, getCoreErrorCause, getCoreErrorCode, getCpuTime, getCurrentTimestamp, getMemoryUsage, getOrCreateApiClient, getOsInfo, getPlatformVersions, getPreferredManifestEntryKey, getProfilePlugin, getReleaseId, getTablePlugin, getTableRecordPlugin, getTokenFromCliLogin, getTtyContext, getZapierApprovalMode, getZapierDefaultApprovalMode, getZapierOpenAutoModeApprovalsInBrowser, getZapierSdkService, injectCliLogin, inputFieldKeyResolver, inputsAllOptionalResolver, inputsResolver, invalidateCachedToken, invalidateCredentialsToken, isCi, isCliLoginAvailable, isClientCredentials, isCoreError, isCredentialsFunction, isCredentialsObject, isPermanentHttpError, isPkceCredentials, isPositional, listActionInputFieldChoicesPlugin, listActionInputFieldsPlugin, listActionsPlugin, listAppsPlugin, listClientCredentialsPlugin, listConnectionsPlugin, listTableFieldsPlugin, listTableRecordsPlugin, listTablesPlugin, logDeprecation2 as logDeprecation, manifestPlugin, parseConcurrencyEnvVar, readManifestFromFile, registryPlugin, requestPlugin, resetDeprecationWarnings2 as resetDeprecationWarnings, resolveAuth, resolveAuthToken, resolveCredentials, resolveCredentialsFromEnv, runActionPlugin, runInMethodScope, runWithCallerContext, runWithTelemetryContext, tableFieldIdsResolver, tableFieldsResolver, tableFiltersResolver, tableIdResolver, tableNameResolver, tableRecordIdResolver, tableRecordIdsResolver, tableRecordsResolver, tableSortResolver, tableUpdateRecordsResolver, toSnakeCase, toTitleCase, triggerInboxResolver, triggerMessagesResolver, updateTableRecordsPlugin, workflowIdResolver, workflowRunIdResolver, workflowVersionIdResolver, zapierAdaptError };
11252
+ export { ActionKeyPropertySchema, ActionPropertySchema, ActionTimeoutMsPropertySchema, ActionTypePropertySchema, AppKeyPropertySchema, AppPropertySchema, AppsPropertySchema, AuthMechanism, AuthenticationIdPropertySchema, BaseSdkOptionsSchema, CONTEXT_CACHE_MAX_SIZE, CONTEXT_CACHE_TTL_MS, CORE_ERROR_SYMBOL, ClientCredentialsObjectSchema, ConnectionEntrySchema, ConnectionIdPropertySchema, ConnectionPropertySchema, ConnectionsMapSchema, ConnectionsPropertySchema, CoreErrorCode, CredentialsFunctionSchema, CredentialsObjectSchema, CredentialsSchema, DEFAULT_ACTION_TIMEOUT_MS, DEFAULT_APPROVAL_TIMEOUT_MS, DEFAULT_CONFIG_PATH, DEFAULT_MAX_APPROVAL_RETRIES, DEFAULT_PAGE_SIZE, DebugPropertySchema, FieldsPropertySchema, InputFieldPropertySchema, InputsPropertySchema, LeaseLimitPropertySchema, LeasePropertySchema, LeaseSecondsPropertySchema, LimitPropertySchema, MAX_CONCURRENCY_LIMIT, MAX_PAGE_LIMIT, OffsetPropertySchema, OutputPropertySchema, ParamsPropertySchema, PkceCredentialsObjectSchema, RecordPropertySchema, RecordsPropertySchema, RelayFetchSchema, RelayRequestSchema, ResolvedCredentialsSchema, TablePropertySchema, TablesPropertySchema, TriggerInboxNamePropertySchema, TriggerInboxPropertySchema, ZAPIER_BASE_URL, ZAPIER_MAX_CONCURRENT_REQUESTS, ZAPIER_MAX_NETWORK_RETRIES, ZAPIER_MAX_NETWORK_RETRY_DELAY_MS, ZapierAbortDrainSignal, ZapierActionError, ZapierApiError, ZapierAppNotFoundError, ZapierApprovalError, ZapierAuthenticationError, ZapierBundleError, ZapierConfigurationError, ZapierConflictError, ZapierError, ZapierNotFoundError, ZapierRateLimitError, ZapierRelayError, ZapierReleaseTriggerMessageSignal, ZapierResourceNotFoundError, ZapierSignal, ZapierTimeoutError, ZapierUnknownError, ZapierValidationError, actionKeyResolver, actionTypeResolver, addPlugin, apiPlugin, appKeyResolver, appsPlugin, connectionIdGenericResolver as authenticationIdGenericResolver, connectionIdResolver as authenticationIdResolver, batch, buildApplicationLifecycleEvent, buildCapabilityMessage, buildErrorEvent, buildErrorEventWithContext, buildMethodCalledEvent, cleanupEventListeners, clearTokenCache, clientCredentialsNameResolver, clientIdResolver, composePlugins, connectionIdGenericResolver, connectionIdResolver, connectionsPlugin, createBaseEvent, createClientCredentialsPlugin, createCorePlugin, createFunction, createMemoryCache, createOptionsPlugin, createPaginatedPluginMethod, createPluginMethod, createPluginStack, createSdk, createTableFieldsPlugin, createTablePlugin, createTableRecordsPlugin, createZapierApi, createZapierCoreStack, createZapierSdk, createZapierSdkStack, createZapierSdkWithoutRegistry, dangerousContextPlugin, declareMethod, declareProperty, defineLegacyMerge, defineMethod, definePlugin, defineProperty, deleteClientCredentialsPlugin, deleteTableFieldsPlugin, deleteTablePlugin, deleteTableRecordsPlugin, durableRunIdResolver, eventEmissionPlugin, fetchPlugin, findFirstConnectionPlugin, findManifestEntry, findUniqueConnectionPlugin, formatErrorMessage, fromFunctionPlugin, generateEventId, getActionInputFieldsSchemaPlugin, getActionPlugin, getAgent, getAppPlugin, getBaseUrlFromCredentials, getCallerContext, getCiPlatform, getClientIdFromCredentials, getConnectionPlugin, getContext, getCoreErrorCause, getCoreErrorCode, getCpuTime, getCurrentTimestamp, getMemoryUsage, getOrCreateApiClient, getOsInfo, getPlatformVersions, getPreferredManifestEntryKey, getProfilePlugin, getReleaseId, getTablePlugin, getTableRecordPlugin, getTokenFromCliLogin, getTtyContext, getZapierApprovalMode, getZapierDefaultApprovalMode, getZapierOpenAutoModeApprovalsInBrowser, getZapierSdkService, injectCliLogin, inputFieldKeyResolver, inputsAllOptionalResolver, inputsResolver, invalidateCachedToken, invalidateCredentialsToken, isCi, isCliLoginAvailable, isClientCredentials, isCoreError, isCredentialsFunction, isCredentialsObject, isPermanentHttpError, isPkceCredentials, isPositional, listActionInputFieldChoicesPlugin, listActionInputFieldsPlugin, listActionsPlugin, listAppsPlugin, listClientCredentialsPlugin, listConnectionsPlugin, listTableFieldsPlugin, listTableRecordsPlugin, listTablesPlugin, logDeprecation2 as logDeprecation, manifestPlugin, parseConcurrencyEnvVar, readManifestFromFile, registryPlugin, requestPlugin, resetDeprecationWarnings2 as resetDeprecationWarnings, resolveAuth, resolveAuthToken, resolveCredentials, resolveCredentialsFromEnv, runActionPlugin, runInMethodScope, runWithCallerContext, runWithTelemetryContext, tableFieldIdsResolver, tableFieldsResolver, tableFiltersResolver, tableIdResolver, tableNameResolver, tableRecordIdResolver, tableRecordIdsResolver, tableRecordsResolver, tableSortResolver, tableUpdateRecordsResolver, toSnakeCase, toTitleCase, triggerInboxResolver, triggerMessagesResolver, updateTableRecordsPlugin, workflowIdResolver, workflowRunIdResolver, workflowVersionIdResolver, zapierAdaptError, zapierSdkPlugin };