@zapier/zapier-sdk 0.98.0 → 0.99.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.
@@ -33,6 +33,30 @@ function canonicalInputSchema(schema) {
33
33
  }
34
34
  return schema;
35
35
  }
36
+ function unwrapSchema(schema) {
37
+ let inner = schema;
38
+ let required = true;
39
+ for (; ; ) {
40
+ if (inner instanceof z.ZodOptional || inner instanceof z.ZodDefault) {
41
+ required = false;
42
+ inner = inner.unwrap();
43
+ } else if (inner instanceof z.ZodNullable) {
44
+ inner = inner.unwrap();
45
+ } else {
46
+ break;
47
+ }
48
+ }
49
+ return { inner, required };
50
+ }
51
+ function objectShapeOf(schema) {
52
+ const canonical = canonicalInputSchema(schema);
53
+ if (!canonical) return void 0;
54
+ const { inner } = unwrapSchema(canonical);
55
+ if (inner instanceof z.ZodObject) {
56
+ return inner.shape;
57
+ }
58
+ return void 0;
59
+ }
36
60
  function withPositional(schema) {
37
61
  Object.assign(schema._zod.def, {
38
62
  positionalMeta: { positional: true }
@@ -549,6 +573,117 @@ function createValidator(schema, { adaptError } = {}) {
549
573
  };
550
574
  }
551
575
  var validateOptions = (schema, options, { adaptError } = {}) => parseOrThrow(schema, options, { adaptError });
576
+ var CallFrameworkOptionsSchema = z.object({
577
+ /** Page to fetch. Opaque to kitcore: the head's API defines the format. */
578
+ cursor: z.string().optional(),
579
+ /** Items per page. */
580
+ pageSize: z.number().int().min(1).optional(),
581
+ /** Stop after this many items, across pages. */
582
+ maxItems: z.number().int().min(0).optional(),
583
+ /** Bypass output validation for this one call. */
584
+ skipOutputDataValidation: z.boolean().optional()
585
+ });
586
+ var ITEM_FRAMEWORK_OPTIONS = {
587
+ claims: ["skipOutputDataValidation"],
588
+ injects: []
589
+ };
590
+ var LIST_FRAMEWORK_OPTIONS = {
591
+ claims: ["cursor", "pageSize", "maxItems", "skipOutputDataValidation"],
592
+ injects: ["cursor", "pageSize"]
593
+ };
594
+ var PAGE_FRAMEWORK_OPTIONS = {
595
+ claims: ["cursor", "pageSize", "maxItems"],
596
+ injects: ["cursor", "pageSize", "maxItems"]
597
+ };
598
+ var NO_FRAMEWORK_OPTIONS = {
599
+ claims: [],
600
+ injects: []
601
+ };
602
+ function isRecord(value) {
603
+ return typeof value === "object" && value !== null && !Array.isArray(value);
604
+ }
605
+ function strictlyRefused(error, claims) {
606
+ const refused = /* @__PURE__ */ new Set();
607
+ for (const issue of error.issues) {
608
+ if (issue.code !== "unrecognized_keys" || issue.path.length > 0) continue;
609
+ for (const key of issue.keys) {
610
+ if (claims.includes(key)) refused.add(key);
611
+ }
612
+ }
613
+ return [...refused];
614
+ }
615
+ function withoutKeys(options, keys) {
616
+ const next = {};
617
+ for (const [key, value] of Object.entries(options)) {
618
+ if (!keys.includes(key)) next[key] = value;
619
+ }
620
+ return next;
621
+ }
622
+ function parseCallOptions(options, {
623
+ schema,
624
+ policy = NO_FRAMEWORK_OPTIONS,
625
+ adaptError
626
+ } = {}) {
627
+ const claims = policy.claims;
628
+ const call = isRecord(options) ? options : void 0;
629
+ let framework = {};
630
+ if (call && claims.length > 0) {
631
+ const present = {};
632
+ for (const key of claims) {
633
+ if (key in call) present[key] = call[key];
634
+ }
635
+ framework = parseOrThrow2(CallFrameworkOptionsSchema, present, adaptError);
636
+ }
637
+ if (!schema) return { framework, domain: options, supplied: /* @__PURE__ */ new Set() };
638
+ const first = schema.safeParse(options);
639
+ if (first.success) {
640
+ return { framework, domain: first.data, supplied: /* @__PURE__ */ new Set() };
641
+ }
642
+ const refused = call ? strictlyRefused(first.error, claims) : [];
643
+ if (refused.length === 0) throw toCoreError(first.error, options, adaptError);
644
+ const retry = schema.safeParse(withoutKeys(call, refused));
645
+ if (!retry.success) {
646
+ throw toCoreError(retry.error, options, adaptError);
647
+ }
648
+ return { framework, domain: retry.data, supplied: new Set(refused) };
649
+ }
650
+ function mergeCallOptions({
651
+ framework,
652
+ domain
653
+ }) {
654
+ const claimed = Object.entries(framework);
655
+ if (!isRecord(domain) || claimed.length === 0) return domain;
656
+ return { ...domain, ...Object.fromEntries(claimed) };
657
+ }
658
+ function withheldFromRun(policy) {
659
+ return new Set(policy.claims.filter((key) => !policy.injects.includes(key)));
660
+ }
661
+ function stripFrameworkOnlyOptions(options, withheld) {
662
+ if (withheld.size === 0 || !isRecord(options)) return options;
663
+ const entries = Object.entries(options);
664
+ if (!entries.some(([key]) => withheld.has(key))) return options;
665
+ return Object.fromEntries(entries.filter(([key]) => !withheld.has(key)));
666
+ }
667
+ function parseOrThrow2(schema, input, adaptError) {
668
+ const result = schema.safeParse(input);
669
+ if (result.success) return result.data;
670
+ throw toCoreError(result.error, input, adaptError);
671
+ }
672
+ function toCoreError(error, input, adaptError) {
673
+ const messages = error.issues.map((issue) => {
674
+ const path = issue.path.length > 0 ? issue.path.join(".") : "input";
675
+ return `${path}: ${issue.message}`;
676
+ });
677
+ return createCoreError(
678
+ {
679
+ code: CoreErrorCode.Validation,
680
+ message: `Validation failed:
681
+ ${messages.join("\n ")}`,
682
+ details: { zodErrors: error.issues, input }
683
+ },
684
+ adaptError
685
+ );
686
+ }
552
687
  function createAsyncContext() {
553
688
  let store = null;
554
689
  try {
@@ -730,7 +865,15 @@ function normalizeError(error, adaptError) {
730
865
  );
731
866
  }
732
867
  function createFunction(coreFn, options) {
733
- const { sdk, schema, name, annotator, getDeprecation, getStability } = options;
868
+ const {
869
+ sdk,
870
+ schema,
871
+ name,
872
+ annotator,
873
+ frameworkOptions,
874
+ getDeprecation,
875
+ getStability
876
+ } = options;
734
877
  const functionName = name || coreFn.name;
735
878
  const namedFunctions = {
736
879
  [functionName]: async function(callOptions) {
@@ -766,25 +909,15 @@ function createFunction(coreFn, options) {
766
909
  };
767
910
  hooks?.onMethodStart?.({ ...hookBase });
768
911
  try {
769
- let result;
770
- if (schema) {
771
- const validatedOptions = validateOptions(
772
- schema,
773
- normalizedOptions,
774
- {
775
- adaptError
776
- }
777
- );
778
- result = await coreFn(
779
- {
780
- ...normalizedOptions,
781
- ...validatedOptions
782
- },
783
- context
784
- );
785
- } else {
786
- result = await coreFn(normalizedOptions, context);
787
- }
912
+ const parsed = parseCallOptions(normalizedOptions, {
913
+ schema,
914
+ policy: frameworkOptions,
915
+ adaptError
916
+ });
917
+ const result = await coreFn(
918
+ mergeCallOptions(parsed),
919
+ context
920
+ );
788
921
  hooks?.onMethodEnd?.({
789
922
  ...hookBase,
790
923
  durationMs: Date.now() - startTime
@@ -905,7 +1038,7 @@ function createPageFunction(coreFn, {
905
1038
  `${functionName}: paginated result must be exactly { data: TItem[], nextCursor? } (produced by the handler or its \`adaptPage\`); got keys [${page && typeof page === "object" ? Object.keys(page).join(", ") : typeof page}]. If the handler returns a raw shape, set \`adaptPage\` to translate it; if \`adaptPage\` already runs, it must return only \`data\`/\`nextCursor\`.`
906
1039
  );
907
1040
  }
908
- return finalizePage ? finalizePage(page) : page;
1041
+ return finalizePage ? finalizePage(page, options) : page;
909
1042
  } catch (error) {
910
1043
  throw normalizeError(
911
1044
  error,
@@ -925,6 +1058,7 @@ function createPaginatedFunction(coreFn, options) {
925
1058
  adaptPage,
926
1059
  annotator,
927
1060
  finalizePage,
1061
+ frameworkOptions,
928
1062
  getDeprecation,
929
1063
  getStability
930
1064
  } = options;
@@ -968,10 +1102,13 @@ function createPaginatedFunction(coreFn, options) {
968
1102
  };
969
1103
  hooks?.onMethodStart?.({ ...hookBase });
970
1104
  try {
971
- const validatedOptions = {
972
- ...normalizedOptions,
973
- ...schema ? createValidator(schema, { adaptError })(normalizedOptions) : normalizedOptions
974
- };
1105
+ const validatedOptions = mergeCallOptions(
1106
+ parseCallOptions(normalizedOptions, {
1107
+ schema,
1108
+ policy: frameworkOptions,
1109
+ adaptError
1110
+ })
1111
+ );
975
1112
  const pageSize = validatedOptions.pageSize ?? defaultPageSize;
976
1113
  const optimizedOptions = {
977
1114
  ...validatedOptions,
@@ -1095,6 +1232,10 @@ function createPaginatedPluginMethod(sdk, config) {
1095
1232
  sdk,
1096
1233
  schema: inputSchema,
1097
1234
  name,
1235
+ // The page loop reads the page controls out of the call object, so a
1236
+ // handler's schema does not have to declare them. It reads nothing else:
1237
+ // no legacy handler honors the caller's output skip.
1238
+ frameworkOptions: PAGE_FRAMEWORK_OPTIONS,
1098
1239
  defaultPageSize,
1099
1240
  adaptPage
1100
1241
  });
@@ -1336,6 +1477,7 @@ function buildPluginStack(head, callerLabel) {
1336
1477
  };
1337
1478
  return stack;
1338
1479
  }
1480
+ var CONTEXT = Symbol.for("kitcore.context");
1339
1481
  function parseId(id) {
1340
1482
  const at = id.lastIndexOf("/");
1341
1483
  return at === -1 ? { name: id, namespace: void 0 } : { name: id.slice(at + 1), namespace: id.slice(0, at) };
@@ -1440,7 +1582,12 @@ function collectDynamicMembers(members) {
1440
1582
  };
1441
1583
  });
1442
1584
  }
1443
- function defineMethod(config) {
1585
+ function defineMethod(configOrRef, refConfig) {
1586
+ const config = refConfig === void 0 ? configOrRef : {
1587
+ ...refConfig,
1588
+ name: configOrRef.name,
1589
+ namespace: configOrRef.namespace
1590
+ };
1444
1591
  const deps = normalizeImports(config.imports);
1445
1592
  return {
1446
1593
  pluginType: "method",
@@ -1463,8 +1610,27 @@ function defineMethod(config) {
1463
1610
  run: config.run
1464
1611
  };
1465
1612
  }
1466
- function defineMethodOverride(config) {
1467
- const { target, namespace, ...rest } = config;
1613
+ var OVERRIDABLE = [
1614
+ "description",
1615
+ "categories",
1616
+ "itemType",
1617
+ "returnType",
1618
+ "packages",
1619
+ "experimental",
1620
+ "deprecation",
1621
+ "supportsJsonOutput"
1622
+ ];
1623
+ function assertOverridable(target, fields) {
1624
+ const offered = Object.keys(fields).filter(
1625
+ (key) => !OVERRIDABLE.includes(key)
1626
+ );
1627
+ if (offered.length === 0) return;
1628
+ throw new Error(
1629
+ `defineOverride("${target}"): cannot override ${offered.join(", ")}. An override changes how a surface presents a method, never what it does. The method's declared type is fixed at \`defineMethod\` and nothing re-checks it afterwards, so patching behavior here would let a call fail against a contract its own return type says it satisfies. Overridable: ${OVERRIDABLE.join(", ")}.`
1630
+ );
1631
+ }
1632
+ function buildOverride(target, namespace, fields) {
1633
+ assertOverridable(target, fields);
1468
1634
  return {
1469
1635
  pluginType: "method-override",
1470
1636
  name: `override:${target}`,
@@ -1472,12 +1638,34 @@ function defineMethodOverride(config) {
1472
1638
  target,
1473
1639
  imports: [],
1474
1640
  importBindings: [],
1475
- meta: collectLeafMeta(rest)
1641
+ meta: collectLeafMeta(fields)
1476
1642
  };
1477
1643
  }
1644
+ function defineOverride(ref, config = {}) {
1645
+ const { namespace, ...fields } = config;
1646
+ return buildOverride(ref.id, namespace, fields);
1647
+ }
1648
+ function defineMethodOverride(config) {
1649
+ logDeprecation(
1650
+ "defineMethodOverride({ target }) is deprecated. Use defineOverride(method, { ... }), which takes the method or its declareMethod stand-in."
1651
+ );
1652
+ const { target, namespace, ...fields } = config;
1653
+ return buildOverride(target, namespace, fields);
1654
+ }
1655
+ function assertRequirementPaths(requirements) {
1656
+ if (!requirements) return;
1657
+ for (const requirement of requirements) {
1658
+ if (typeof requirement !== "string" && requirement.length === 0) {
1659
+ throw new Error(
1660
+ "defineResolver: a requireParameters path must name at least one segment. An empty path names no parameter, and the engine would read it as already satisfied."
1661
+ );
1662
+ }
1663
+ }
1664
+ }
1478
1665
  function defineResolver(config) {
1479
1666
  const deps = normalizeImports(config.imports);
1480
1667
  const base = { imports: deps.plugins, importBindings: deps.bindings };
1668
+ assertRequirementPaths(config.requireParameters);
1481
1669
  const gates = {
1482
1670
  requireParameters: config.requireParameters
1483
1671
  };
@@ -1558,21 +1746,26 @@ function declareMethod(config) {
1558
1746
  }
1559
1747
  };
1560
1748
  }
1561
- function defineProperty(config) {
1562
- const deps = normalizeImports(config.imports);
1749
+ function defineProperty(config, refConfig) {
1750
+ const cfg = refConfig === void 0 ? config : {
1751
+ ...refConfig,
1752
+ name: config.name,
1753
+ namespace: config.namespace
1754
+ };
1755
+ const deps = normalizeImports(cfg.imports);
1563
1756
  return {
1564
1757
  pluginType: "property",
1565
- name: config.name,
1566
- namespace: config.namespace,
1567
- id: makeId(config.name, config.namespace),
1758
+ name: cfg.name,
1759
+ namespace: cfg.namespace,
1760
+ id: makeId(cfg.name, cfg.namespace),
1568
1761
  imports: deps.plugins,
1569
1762
  importBindings: deps.bindings,
1570
- setup: config.setup,
1571
- dispose: config.dispose,
1572
- value: config.value,
1573
- get: config.get,
1574
- meta: collectLeafMeta(config),
1575
- dynamicMembers: collectDynamicMembers(config.dynamicMembers)
1763
+ setup: cfg.setup,
1764
+ dispose: cfg.dispose,
1765
+ value: cfg.value,
1766
+ get: cfg.get,
1767
+ meta: collectLeafMeta(cfg),
1768
+ dynamicMembers: collectDynamicMembers(cfg.dynamicMembers)
1576
1769
  };
1577
1770
  }
1578
1771
  function declareProperty(config) {
@@ -1867,6 +2060,34 @@ function collectSurfaceProjection(context, formatterSdk) {
1867
2060
  }
1868
2061
  return { meta, formatters, resolvers, positional, skipInputValidation };
1869
2062
  }
2063
+ var REGISTRY_CACHE = Symbol.for("kitcore.registryCache");
2064
+ function freezeContainers(registry) {
2065
+ Object.freeze(registry.functions);
2066
+ for (const category of registry.categories) {
2067
+ Object.freeze(category.functions);
2068
+ Object.freeze(category);
2069
+ }
2070
+ Object.freeze(registry.categories);
2071
+ return Object.freeze(registry);
2072
+ }
2073
+ function getCachedRegistry(context, packageFilter) {
2074
+ const key = packageFilter ?? "";
2075
+ const caching = context;
2076
+ let byFilter = caching[REGISTRY_CACHE];
2077
+ if (!byFilter) {
2078
+ byFilter = /* @__PURE__ */ new Map();
2079
+ caching[REGISTRY_CACHE] = byFilter;
2080
+ }
2081
+ let registry = byFilter.get(key);
2082
+ if (!registry) {
2083
+ registry = freezeContainers(buildSurfaceRegistry(context, packageFilter));
2084
+ byFilter.set(key, registry);
2085
+ }
2086
+ return registry;
2087
+ }
2088
+ function invalidateRegistryCache(context) {
2089
+ delete context[REGISTRY_CACHE];
2090
+ }
1870
2091
  function buildSurfaceRegistry(context, packageFilter) {
1871
2092
  const surface = {};
1872
2093
  for (const [binding, id] of Object.entries(context.surface)) {
@@ -1874,9 +2095,11 @@ function buildSurfaceRegistry(context, packageFilter) {
1874
2095
  if (!entry || entry.pluginType === "aggregate") continue;
1875
2096
  surface[binding] = entry.pluginType === "property" && entry.getValue ? entry.getValue() : entry.value;
1876
2097
  }
2098
+ const projection = collectSurfaceProjection(context, surface);
2099
+ Object.assign(projection.meta, context.meta);
1877
2100
  return buildRegistry({
1878
2101
  sdk: surface,
1879
- ...collectSurfaceProjection(context, surface),
2102
+ ...projection,
1880
2103
  packageFilter
1881
2104
  });
1882
2105
  }
@@ -1895,9 +2118,9 @@ var getRegistryPlugin = defineMethod({
1895
2118
  namespace: "kitcore",
1896
2119
  imports: [dangerousContextPlugin],
1897
2120
  inputSchema: z.object({ package: z.string().optional() }).optional(),
1898
- run: ({ imports, input }) => buildSurfaceRegistry(imports.context, input?.package)
2121
+ run: ({ imports, input }) => getCachedRegistry(imports.context, input?.package)
1899
2122
  });
1900
- function isRecord(value) {
2123
+ function isRecord2(value) {
1901
2124
  return typeof value === "object" && value !== null && !Array.isArray(value);
1902
2125
  }
1903
2126
  function diffDroppedPaths(raw, parsed, prefix = "") {
@@ -1920,7 +2143,7 @@ function walkDroppedPaths(raw, parsed, prefix, out) {
1920
2143
  }
1921
2144
  return;
1922
2145
  }
1923
- if (isRecord(raw) && isRecord(parsed)) {
2146
+ if (isRecord2(raw) && isRecord2(parsed)) {
1924
2147
  for (const key of Object.keys(raw)) {
1925
2148
  const path = prefix ? `${prefix}.${key}` : key;
1926
2149
  if (!(key in parsed)) {
@@ -1932,7 +2155,22 @@ function walkDroppedPaths(raw, parsed, prefix, out) {
1932
2155
  return;
1933
2156
  }
1934
2157
  }
1935
- function parseOutput(schema, value, policy, locator) {
2158
+ var SKIP_OUTPUT_DATA_VALIDATION = "skipOutputDataValidation";
2159
+ function readSkipOutputDataValidation(options) {
2160
+ return isRecord2(options) && options[SKIP_OUTPUT_DATA_VALIDATION] === true;
2161
+ }
2162
+ function resolveValidatingSchema(policy) {
2163
+ if (policy.skipOutputValidation || policy.skippedByCaller) return void 0;
2164
+ return policy.outputSchema;
2165
+ }
2166
+ function shouldReport(policy) {
2167
+ return policy.skippedByCaller === true && policy.outputSchema !== void 0 && !policy.skipOutputValidation;
2168
+ }
2169
+ function parseOutput(schema, value, policy, {
2170
+ locator,
2171
+ hint,
2172
+ callerCanSkip = true
2173
+ } = {}) {
1936
2174
  const result = schema.safeParse(value);
1937
2175
  if (result.success) return result.data;
1938
2176
  const issues = result.error.issues.map((issue) => {
@@ -1947,57 +2185,134 @@ function parseOutput(schema, value, policy, locator) {
1947
2185
  message: `Output validation failed${subject}${at}:
1948
2186
  ${issues.join("\n ")}
1949
2187
 
1950
- The response does not match the method's \`outputSchema\`. Correct the schema, or set \`skipOutputValidation: true\` on the method to pass the response through unvalidated.`,
2188
+ ` + (hint ? `${hint}
2189
+
2190
+ ` : "") + `The response does not match the method's \`outputSchema\`. Correct the schema, or set \`skipOutputValidation: true\` on the method to pass the response through unvalidated.` + (callerCanSkip ? ` A caller who cannot change the method can pass \`skipOutputDataValidation: true\` with the input to bypass this one call.` : ``),
1951
2191
  details: { zodErrors: result.error.issues, output: value }
1952
2192
  },
1953
2193
  policy.adaptError
1954
2194
  );
1955
2195
  }
1956
2196
  function applyItemOutputPolicy(result, policy) {
1957
- const schema = policy.outputSchema;
1958
- if (!schema || policy.skipOutputValidation) return result;
1959
- if (!isRecord(result) || !("data" in result)) return result;
2197
+ const schema = resolveValidatingSchema(policy);
2198
+ const report = shouldReport(policy);
2199
+ if (!schema && !report) return result;
2200
+ if (!isRecord2(result) || !("data" in result)) return result;
2201
+ if (!schema) {
2202
+ return {
2203
+ ...result,
2204
+ meta: withOutputValidation(result.meta, { skipped: true })
2205
+ };
2206
+ }
1960
2207
  const data = parseOutput(schema, result.data, policy);
2208
+ const validation = buildValidatedReport({
2209
+ policy,
2210
+ before: result.data,
2211
+ after: data
2212
+ });
1961
2213
  const next = { ...result, data };
1962
- if (policy.includeOutputValidationDroppedPaths) {
1963
- const droppedPaths = diffDroppedPaths(result.data, data);
1964
- if (droppedPaths.length > 0) {
1965
- next.meta = withOutputValidation(result.meta, droppedPaths);
1966
- }
1967
- }
2214
+ if (validation) next.meta = withOutputValidation(result.meta, validation);
1968
2215
  return next;
1969
2216
  }
1970
- function withOutputValidation(existing, droppedPaths) {
1971
- const base = isRecord(existing) ? existing : {};
1972
- return { ...base, outputValidation: { droppedPaths } };
2217
+ function applyRawOutputPolicy(result, policy) {
2218
+ const schema = resolveValidatingSchema(policy);
2219
+ if (!schema) return result;
2220
+ const looksLikeEnvelope = isRecord2(result) && "data" in result;
2221
+ parseOutput(schema, result, policy, {
2222
+ hint: looksLikeEnvelope ? 'This returned a `{ data }` envelope, and with no `output` mode the schema is matched against the WHOLE return. Did you mean `output: "item"` (or `"list"`)?' : void 0,
2223
+ // Raw reserves nothing in the caller's call object, so there is no per-call
2224
+ // skip to point at. Offering one would be advice that does nothing.
2225
+ callerCanSkip: false
2226
+ });
2227
+ return result;
2228
+ }
2229
+ function withOutputValidation(existing, outputDataValidation) {
2230
+ const base = isRecord2(existing) ? existing : {};
2231
+ const deprecated = outputDataValidation.skipped === false && outputDataValidation.droppedPaths ? {
2232
+ outputValidation: { droppedPaths: outputDataValidation.droppedPaths }
2233
+ } : {};
2234
+ return { ...base, outputDataValidation, ...deprecated };
2235
+ }
2236
+ function buildValidatedReport({
2237
+ policy,
2238
+ before,
2239
+ after
2240
+ }) {
2241
+ const droppedPaths = policy.includeOutputValidationDroppedPaths ? diffDroppedPaths(before, after) : [];
2242
+ if (droppedPaths.length === 0) return void 0;
2243
+ return {
2244
+ skipped: false,
2245
+ droppedPaths,
2246
+ instruction: `Some fields were removed from \`data\` by output validation. To receive the raw, unvalidated result instead, set \`${SKIP_OUTPUT_DATA_VALIDATION}\`.`
2247
+ };
1973
2248
  }
1974
2249
  function applyListOutputPolicy(page, policy) {
1975
- const schema = policy.outputSchema;
1976
- if (!schema || policy.skipOutputValidation) return page;
2250
+ const schema = resolveValidatingSchema(policy);
2251
+ const report = shouldReport(policy);
2252
+ if (!schema && !report) return page;
2253
+ if (!schema) {
2254
+ return {
2255
+ ...page,
2256
+ meta: withOutputValidation(page.meta, { skipped: true })
2257
+ };
2258
+ }
1977
2259
  const data = page.data.map(
1978
- (item, index) => parseOutput(schema, item, policy, `data[${index}]`)
2260
+ (item, index) => parseOutput(schema, item, policy, { locator: `data[${index}]` })
1979
2261
  );
2262
+ const validation = buildValidatedReport({
2263
+ policy,
2264
+ before: page.data,
2265
+ after: data
2266
+ });
1980
2267
  const next = { ...page, data };
1981
- if (policy.includeOutputValidationDroppedPaths) {
1982
- const droppedPaths = diffDroppedPaths(page.data, data);
1983
- if (droppedPaths.length > 0) {
1984
- next.meta = { ...page.meta, outputValidation: { droppedPaths } };
1985
- }
1986
- }
2268
+ if (validation)
2269
+ next.meta = withOutputValidation(
2270
+ page.meta,
2271
+ validation
2272
+ );
1987
2273
  return next;
1988
2274
  }
1989
2275
  var FRAMEWORK_CONFIGURATION_IDS = /* @__PURE__ */ new Set([
1990
2276
  CORE_OPTIONS_ID
1991
2277
  ]);
2278
+ function isPromiseLike(value) {
2279
+ return value !== null && typeof value === "object" && typeof value.then === "function";
2280
+ }
1992
2281
  function normalizeOutput(output) {
1993
2282
  if (output === void 0) return { type: "raw" };
1994
2283
  if (typeof output === "string") return { type: output };
1995
2284
  return output;
1996
2285
  }
1997
- var CONTEXT = Symbol.for("kitcore.context");
1998
2286
  function getContext(sdk) {
1999
2287
  return sdk[CONTEXT];
2000
2288
  }
2289
+ function assertDynamicMemberRoot(entry) {
2290
+ if (!entry.dynamicMembers?.length) return;
2291
+ const value = entry.getValue ? entry.getValue() : entry.value;
2292
+ if (typeof value === "object" && value !== null) return;
2293
+ throw new Error(
2294
+ `Property "${entry.name}" declares dynamicMembers, so its value must be an object when the SDK is built; got ${value === null ? "null" : typeof value}. Build the root in \`setup\` and return it from \`get\`, so members like "${entry.dynamicMembers[0].name}" are reportable from the first registry read.`
2295
+ );
2296
+ }
2297
+ function getRegistry(sdk, packageFilter) {
2298
+ if (typeof sdk !== "object" && typeof sdk !== "function" || sdk === null)
2299
+ throw createNoRegistryError();
2300
+ const context = getContext(sdk);
2301
+ if (context?.surface) return getCachedRegistry(context, packageFilter);
2302
+ const surfaced = sdk.getRegistry;
2303
+ if (typeof surfaced === "function") {
2304
+ return surfaced.call(
2305
+ sdk,
2306
+ void 0
2307
+ );
2308
+ }
2309
+ throw createNoRegistryError();
2310
+ }
2311
+ function createNoRegistryError() {
2312
+ return new Error(
2313
+ "getRegistry: sdk has no kitcore context and no surfaced getRegistry()."
2314
+ );
2315
+ }
2001
2316
  function isResolverRef(value) {
2002
2317
  return "ref" in value;
2003
2318
  }
@@ -2217,8 +2532,9 @@ function bindValue({
2217
2532
  frameworkOrigin = false
2218
2533
  }) {
2219
2534
  if (entry.pluginType === "property" && entry.getValue) {
2535
+ const getValue = entry.getValue;
2220
2536
  Object.defineProperty(target, key, {
2221
- get: entry.getValue,
2537
+ get: ctx ? () => getValue(ctx) : getValue,
2222
2538
  enumerable: true,
2223
2539
  configurable: true
2224
2540
  });
@@ -2502,22 +2818,16 @@ function runLegacyPass(descriptors, context) {
2502
2818
  Object.assign(context, contextRest);
2503
2819
  context.hooks = buildHooks(context.hooks, hooks);
2504
2820
  const exports = mirrorLegacyRootKeys(context, rootKeys, meta);
2821
+ for (const name of Object.keys(rootKeys)) context.surface[name] = name;
2505
2822
  if (!("getRegistry" in exports)) {
2506
- let getRegistry2 = function(options) {
2507
- const sdk = this ?? exports;
2508
- const projection = collectSurfaceProjection(context, sdk);
2509
- Object.assign(projection.meta, context.meta);
2510
- return buildRegistry({
2511
- sdk,
2512
- ...projection,
2513
- packageFilter: options?.package
2514
- });
2823
+ let getRegistry3 = function(options) {
2824
+ return getCachedRegistry(context, options?.package);
2515
2825
  };
2516
- exports.getRegistry = getRegistry2;
2826
+ exports.getRegistry = getRegistry3;
2517
2827
  plugins.getRegistry = {
2518
2828
  pluginType: "method",
2519
2829
  name: "getRegistry",
2520
- value: getRegistry2,
2830
+ value: getRegistry3,
2521
2831
  chain: []
2522
2832
  };
2523
2833
  }
@@ -2581,50 +2891,73 @@ function buildMethodEntries(descriptors, context, states) {
2581
2891
  const sdk = { context };
2582
2892
  const methodAnnotator = descriptor.annotator;
2583
2893
  const boundAnnotator = methodAnnotator ? (input) => methodAnnotator({ input }) : void 0;
2584
- const outputPolicy = () => {
2894
+ const outputPolicy = (callOptions) => {
2585
2895
  const core = resolveCoreOptions(context);
2586
2896
  return {
2587
2897
  outputSchema: descriptor.meta?.outputSchema,
2588
2898
  skipOutputValidation: descriptor.skipOutputValidation,
2899
+ skippedByCaller: readSkipOutputDataValidation(callOptions),
2589
2900
  includeOutputValidationDroppedPaths: core?.includeOutputValidationDroppedPaths,
2590
2901
  methodName: descriptor.name,
2591
2902
  adaptError: core?.adaptError
2592
2903
  };
2593
2904
  };
2905
+ const frameworkOptions = out.type === "list" ? LIST_FRAMEWORK_OPTIONS : ITEM_FRAMEWORK_OPTIONS;
2906
+ const withheld = withheldFromRun(frameworkOptions);
2594
2907
  if (out.type === "list") {
2595
2908
  entry.value = createPaginatedFunction(
2596
- fold(callRun),
2909
+ fold(
2910
+ (input, ctx) => callRun(stripFrameworkOnlyOptions(input, withheld), ctx)
2911
+ ),
2597
2912
  {
2598
2913
  sdk,
2599
2914
  schema: descriptor.inputSchema,
2600
2915
  name: descriptor.name,
2916
+ frameworkOptions,
2601
2917
  defaultPageSize: out.defaultPageSize,
2602
2918
  adaptPage: out.adaptPage,
2603
2919
  annotator: boundAnnotator,
2604
2920
  // Validate + strip each item against the item `outputSchema`
2605
2921
  // (item mode's sibling); dropped paths surface as `[].x` in the page's
2606
2922
  // `meta`, unioned across items.
2607
- finalizePage: (page) => applyListOutputPolicy(page, outputPolicy()),
2923
+ finalizePage: (page, callOptions) => applyListOutputPolicy(page, outputPolicy(callOptions)),
2608
2924
  getDeprecation: () => entry.meta?.deprecation,
2609
2925
  getStability: () => entry.meta ? normalizeStability(entry.meta) : void 0
2610
2926
  }
2611
2927
  );
2612
2928
  } else if (out.type === "item") {
2613
- const itemCore = async (input, ctx) => applyItemOutputPolicy(await callRun(input, ctx), outputPolicy());
2929
+ const itemCore = async (input, ctx) => applyItemOutputPolicy(
2930
+ await callRun(stripFrameworkOnlyOptions(input, withheld), ctx),
2931
+ outputPolicy(input)
2932
+ );
2614
2933
  entry.value = createFunction(
2615
2934
  fold(itemCore),
2616
2935
  {
2617
2936
  sdk,
2618
2937
  schema: descriptor.inputSchema,
2619
2938
  name: descriptor.name,
2939
+ frameworkOptions,
2620
2940
  annotator: boundAnnotator,
2621
2941
  getDeprecation: () => entry.meta?.deprecation,
2622
2942
  getStability: () => entry.meta ? normalizeStability(entry.meta) : void 0
2623
2943
  }
2624
2944
  );
2625
2945
  } else {
2946
+ const rawValidates = descriptor.meta?.outputSchema !== void 0 && !descriptor.skipOutputValidation;
2947
+ const validateRaw = (out2) => {
2948
+ const policy = outputPolicy(void 0);
2949
+ if (isPromiseLike(out2)) {
2950
+ return Promise.resolve(out2).then(
2951
+ (value) => applyRawOutputPolicy(value, policy)
2952
+ );
2953
+ }
2954
+ return applyRawOutputPolicy(out2, policy);
2955
+ };
2626
2956
  entry.value = createRawFunction(
2627
- (input, ctx) => fold(callRun)(input, ctx),
2957
+ (input, ctx) => {
2958
+ const out2 = fold(callRun)(input, ctx);
2959
+ return rawValidates ? validateRaw(out2) : out2;
2960
+ },
2628
2961
  {
2629
2962
  sdk,
2630
2963
  name: descriptor.name,
@@ -2756,9 +3089,14 @@ function buildEagerArtifacts(descriptors, context, states) {
2756
3089
  plugins[id] = {
2757
3090
  pluginType: "property",
2758
3091
  name: descriptor.name,
2759
- getValue: () => get({
2760
- imports: buildImports({ plugins, importBindings }),
2761
- state: states.get(id)
3092
+ getValue: (callContext) => get({
3093
+ imports: buildImports({
3094
+ plugins,
3095
+ importBindings,
3096
+ ctx: callContext
3097
+ }),
3098
+ state: states.get(id),
3099
+ callContext
2762
3100
  }),
2763
3101
  meta: descriptor.meta,
2764
3102
  dynamicMembers: descriptor.dynamicMembers
@@ -2772,6 +3110,7 @@ function buildEagerArtifacts(descriptors, context, states) {
2772
3110
  dynamicMembers: descriptor.dynamicMembers
2773
3111
  };
2774
3112
  }
3113
+ assertDynamicMemberRoot(plugins[id]);
2775
3114
  }
2776
3115
  recordDisposer();
2777
3116
  building.delete(id);
@@ -2995,34 +3334,29 @@ function addModelPlugin(sdk, plugin, options = {}) {
2995
3334
  }
2996
3335
  }
2997
3336
  function addPlugin(sdk, plugin, options) {
2998
- if (typeof plugin === "function") {
2999
- const record = sdk;
3000
- const contribution = applyPluginToSdk(
3001
- record,
3002
- plugin,
3003
- options ?? {}
3004
- );
3005
- const context = record[CONTEXT];
3006
- if (context) {
3007
- mirrorLegacyRootKeys(context, contribution.rootKeys, contribution.meta);
3008
- for (const name of Object.keys(contribution.rootKeys)) {
3009
- context.surface[name] = name;
3337
+ const record = sdk;
3338
+ const context = getContext(record);
3339
+ try {
3340
+ if (typeof plugin === "function") {
3341
+ const contribution = applyPluginToSdk(
3342
+ record,
3343
+ plugin,
3344
+ options ?? {}
3345
+ );
3346
+ if (context) {
3347
+ mirrorLegacyRootKeys(context, contribution.rootKeys, contribution.meta);
3348
+ for (const name of Object.keys(contribution.rootKeys)) {
3349
+ context.surface[name] = name;
3350
+ }
3010
3351
  }
3352
+ } else if (plugin.pluginType === "method-override") {
3353
+ applyMethodOverride(context, plugin);
3354
+ } else {
3355
+ addModelPlugin(record, plugin, options ?? {});
3011
3356
  }
3012
- return;
3013
- }
3014
- if (plugin.pluginType === "method-override") {
3015
- applyMethodOverride(
3016
- getContext(sdk),
3017
- plugin
3018
- );
3019
- return;
3357
+ } finally {
3358
+ if (context) invalidateRegistryCache(context);
3020
3359
  }
3021
- addModelPlugin(
3022
- sdk,
3023
- plugin,
3024
- options ?? {}
3025
- );
3026
3360
  }
3027
3361
  var CORE_SIGNAL_SYMBOL = Symbol.for("kitcore.signal");
3028
3362
  var CoreSignal = class extends Error {
@@ -3052,24 +3386,6 @@ var CoreCancelledSignal = class extends CoreSignal {
3052
3386
  function isCoreCancelledSignal(value) {
3053
3387
  return isCoreSignal(value) && value.code === "CANCELLED";
3054
3388
  }
3055
- function unwrap(schema) {
3056
- let inner = schema;
3057
- let required = true;
3058
- for (; ; ) {
3059
- if (inner instanceof z.ZodOptional) {
3060
- required = false;
3061
- inner = inner._zod.def.innerType;
3062
- } else if (inner instanceof z.ZodDefault) {
3063
- required = false;
3064
- inner = inner._zod.def.innerType;
3065
- } else if (inner instanceof z.ZodNullable) {
3066
- inner = inner._zod.def.innerType;
3067
- } else {
3068
- break;
3069
- }
3070
- }
3071
- return { inner, required };
3072
- }
3073
3389
  function valueTypeOf(inner) {
3074
3390
  if (inner instanceof z.ZodString) return "string";
3075
3391
  if (inner instanceof z.ZodNumber) return "number";
@@ -3087,19 +3403,15 @@ function staticChoicesOf(inner) {
3087
3403
  }
3088
3404
  return void 0;
3089
3405
  }
3090
- function objectShape(schema) {
3091
- const canonical = canonicalInputSchema(schema);
3092
- const { inner } = canonical ? unwrap(canonical) : { inner: void 0 };
3093
- if (inner instanceof z.ZodObject) {
3094
- return inner.shape;
3095
- }
3096
- return void 0;
3097
- }
3098
3406
  function topoOrder2(specs) {
3099
3407
  const byName = new Map(specs.map((s) => [s.name, s]));
3100
3408
  const placed = /* @__PURE__ */ new Set();
3101
3409
  const ordered = [];
3102
- const isReady = (spec) => spec.requires.every((r) => !byName.has(r) || placed.has(r));
3410
+ const topLevelNameOf = (r) => typeof r === "string" ? r : r.length === 1 && typeof r[0] === "string" ? r[0] : void 0;
3411
+ const isReady = (spec) => spec.requires.every((r) => {
3412
+ const name = topLevelNameOf(r);
3413
+ return name === void 0 || !byName.has(name) || placed.has(name);
3414
+ });
3103
3415
  for (; ; ) {
3104
3416
  const next = specs.find((s) => !placed.has(s.name) && isReady(s));
3105
3417
  if (!next) break;
@@ -3110,7 +3422,7 @@ function topoOrder2(specs) {
3110
3422
  return ordered;
3111
3423
  }
3112
3424
  function planParameters(entry) {
3113
- const shape = objectShape(entry.inputSchema);
3425
+ const shape = objectShapeOf(entry.inputSchema);
3114
3426
  const resolvers = entry.resolvers ?? {};
3115
3427
  const names = shape ? [
3116
3428
  ...Object.keys(shape),
@@ -3120,7 +3432,7 @@ function planParameters(entry) {
3120
3432
  ] : Object.keys(resolvers);
3121
3433
  const specs = names.map((name) => {
3122
3434
  const field = shape?.[name];
3123
- const { inner, required } = field ? unwrap(field) : { inner: void 0, required: false };
3435
+ const { inner, required } = field ? unwrapSchema(field) : { inner: void 0, required: false };
3124
3436
  const resolver = resolvers[name];
3125
3437
  return {
3126
3438
  name,
@@ -3763,9 +4075,13 @@ async function findNext(ctx, state, path = []) {
3763
4075
  const hasAskableRequired = children.some((c) => c.required && asksUser(c));
3764
4076
  for (const leaf of ordered) {
3765
4077
  const childPath = [...path, leaf.name];
3766
- if (!leaf.requires.every(
3767
- (r) => container[r] !== void 0 || getAtPath(state.resolved, [r]) !== void 0 || isSettled(state, [...path, r]) || isSettled(state, [r])
3768
- )) {
4078
+ if (!leaf.requires.every((r) => {
4079
+ if (typeof r !== "string") {
4080
+ if (getAtPath(state.resolved, [...r]) !== void 0) return true;
4081
+ return r.some((_, index) => isSettled(state, r.slice(0, index + 1)));
4082
+ }
4083
+ return container[r] !== void 0 || getAtPath(state.resolved, [r]) !== void 0 || isSettled(state, [...path, r]) || isSettled(state, [r]);
4084
+ })) {
3769
4085
  continue;
3770
4086
  }
3771
4087
  const inArrayItem = path.some((segment) => typeof segment === "number");
@@ -4205,7 +4521,7 @@ function projectMethod(entry) {
4205
4521
  }
4206
4522
  function createController(sdk) {
4207
4523
  function entryFor(method) {
4208
- const entry = sdk.getRegistry().functions.find((f) => f.name === method);
4524
+ const entry = getRegistry(sdk).functions.find((f) => f.name === method);
4209
4525
  if (!entry) throw new Error(`unknown method "${method}"`);
4210
4526
  return entry;
4211
4527
  }
@@ -4244,7 +4560,7 @@ function createController(sdk) {
4244
4560
  throw new Error(`invalid input for "${method}": ${detail}`);
4245
4561
  };
4246
4562
  const listMethods = () => ({
4247
- data: sdk.getRegistry().functions.map(projectSummary)
4563
+ data: getRegistry(sdk).functions.map(projectSummary)
4248
4564
  });
4249
4565
  const getMethod = ({ method }) => ({
4250
4566
  data: projectMethod(entryFor(method))
@@ -5664,6 +5980,11 @@ function createSemaphore(maxPermits) {
5664
5980
  }
5665
5981
  };
5666
5982
  }
5983
+
5984
+ // src/api/correlation.ts
5985
+ var CORRELATION_CALL_ID = Symbol(
5986
+ "zapier.correlationCallId"
5987
+ );
5667
5988
  var ClientCredentialsObjectSchema = z.object({
5668
5989
  type: z.enum(["client_credentials"]).optional().meta({ internal: true }),
5669
5990
  clientId: z.string().describe("OAuth client ID for authentication.").meta({ valueHint: "id" }),
@@ -6563,13 +6884,13 @@ function sniffDeprecationNotice({
6563
6884
  payload: { ...payload },
6564
6885
  timestamp: Date.now()
6565
6886
  });
6566
- if (isPromiseLike(maybePromise)) {
6887
+ if (isPromiseLike2(maybePromise)) {
6567
6888
  void Promise.resolve(maybePromise).catch(() => {
6568
6889
  });
6569
6890
  }
6570
6891
  }
6571
6892
  }
6572
- function isPromiseLike(value) {
6893
+ function isPromiseLike2(value) {
6573
6894
  return (typeof value === "object" || typeof value === "function") && value !== null && "then" in value && typeof value.then === "function";
6574
6895
  }
6575
6896
  function parseDeprecationDate(value) {
@@ -6580,7 +6901,7 @@ function parseDeprecationDate(value) {
6580
6901
  }
6581
6902
 
6582
6903
  // src/sdk-version.ts
6583
- var SDK_VERSION = (typeof process !== "undefined" && process.env ? "0.98.0" : void 0) || "unknown";
6904
+ var SDK_VERSION = (typeof process !== "undefined" && process.env ? "0.99.0" : void 0) || "unknown";
6584
6905
 
6585
6906
  // src/utils/open-url.ts
6586
6907
  var nodePrefix = "node:";
@@ -6842,14 +7163,15 @@ var ZapierApiClient = class {
6842
7163
  * directly and drifting.
6843
7164
  */
6844
7165
  this.rawFetchUrl = async (url, init, pathConfig2) => {
6845
- if (init?.body && (isPlainObject(init.body) || Array.isArray(init.body))) {
6846
- init.body = JSON.stringify(init.body);
7166
+ const { [CORRELATION_CALL_ID]: callId, ...fetchInit } = init ?? {};
7167
+ if (fetchInit.body && (isPlainObject(fetchInit.body) || Array.isArray(fetchInit.body))) {
7168
+ fetchInit.body = JSON.stringify(fetchInit.body);
6847
7169
  }
6848
7170
  const builtHeaders = await this.buildHeaders(
6849
- init,
7171
+ fetchInit,
6850
7172
  pathConfig2
6851
7173
  );
6852
- const inputHeaders = new Headers(init?.headers ?? {});
7174
+ const inputHeaders = new Headers(fetchInit.headers ?? {});
6853
7175
  const mergedHeaders = new Headers();
6854
7176
  builtHeaders.forEach((value, key) => {
6855
7177
  mergedHeaders.set(key, value);
@@ -6857,11 +7179,11 @@ var ZapierApiClient = class {
6857
7179
  inputHeaders.forEach((value, key) => {
6858
7180
  mergedHeaders.set(key, value);
6859
7181
  });
6860
- this.applyTelemetryHeaders(mergedHeaders);
7182
+ this.applyTelemetryHeaders({ headers: mergedHeaders, callId });
6861
7183
  let retries = 0;
6862
7184
  while (true) {
6863
7185
  const response = await this.options.fetch(url, {
6864
- ...init,
7186
+ ...fetchInit,
6865
7187
  headers: mergedHeaders
6866
7188
  });
6867
7189
  if (response.status !== 429) {
@@ -6982,12 +7304,13 @@ var ZapierApiClient = class {
6982
7304
  );
6983
7305
  const askStatementIds = askStatementIdsHeader ? JSON.parse(askStatementIdsHeader) : void 0;
6984
7306
  try {
6985
- await this.runOneApprovalRound(
6986
- approvalContext,
6987
- approvalMode,
6988
- init?.signal ?? void 0,
6989
- askStatementIds
6990
- );
7307
+ await this.runOneApprovalRound({
7308
+ buildContext: approvalContext,
7309
+ mode: approvalMode,
7310
+ signal: init?.signal ?? void 0,
7311
+ askStatementIds,
7312
+ callId: init?.[CORRELATION_CALL_ID]
7313
+ });
6991
7314
  } catch (error) {
6992
7315
  return { response, approvalRoundError: error };
6993
7316
  }
@@ -7129,7 +7452,8 @@ var ZapierApiClient = class {
7129
7452
  method: "GET",
7130
7453
  searchParams: options.searchParams,
7131
7454
  authRequired: options.authRequired,
7132
- signal: options.signal
7455
+ signal: options.signal,
7456
+ [CORRELATION_CALL_ID]: options[CORRELATION_CALL_ID]
7133
7457
  }),
7134
7458
  initialDelay: options.initialDelayMilliseconds ?? options.initialDelay,
7135
7459
  timeoutMs: options.timeoutMilliseconds ?? options.timeoutMs,
@@ -7424,7 +7748,10 @@ var ZapierApiClient = class {
7424
7748
  // gateway now expects) and the legacy `x-zapier-*` names. The legacy names are
7425
7749
  // kept for backward compatibility with consumers that haven't migrated yet;
7426
7750
  // they can be removed once nothing reads them.
7427
- applyTelemetryHeaders(headers) {
7751
+ applyTelemetryHeaders({
7752
+ headers,
7753
+ callId
7754
+ }) {
7428
7755
  headers.set("zapier-sdk-version", SDK_VERSION);
7429
7756
  headers.set("x-zapier-sdk-version", SDK_VERSION);
7430
7757
  const sdkService = getZapierSdkService();
@@ -7447,6 +7774,11 @@ var ZapierApiClient = class {
7447
7774
  headers.set("zapier-sdk-package-operation", packageOperation);
7448
7775
  }
7449
7776
  }
7777
+ if (callId) {
7778
+ headers.set("zapier-correlation-id", callId);
7779
+ } else {
7780
+ headers.delete("zapier-correlation-id");
7781
+ }
7450
7782
  }
7451
7783
  // Helper to perform HTTP requests with JSON handling
7452
7784
  async fetchJson(method, path, data, options = {}) {
@@ -7589,7 +7921,13 @@ var ZapierApiClient = class {
7589
7921
  * Caller is responsible for passing a non-"disabled" mode; this method
7590
7922
  * unconditionally creates an approval.
7591
7923
  */
7592
- async runOneApprovalRound(buildContext, mode, signal, askStatementIds) {
7924
+ async runOneApprovalRound({
7925
+ buildContext,
7926
+ mode,
7927
+ signal,
7928
+ askStatementIds,
7929
+ callId
7930
+ }) {
7593
7931
  const context = buildContext();
7594
7932
  let approvalResponse;
7595
7933
  try {
@@ -7603,7 +7941,8 @@ var ZapierApiClient = class {
7603
7941
  context,
7604
7942
  ...askStatementIds?.length ? { ask_statement_ids: askStatementIds } : {}
7605
7943
  }),
7606
- signal
7944
+ signal,
7945
+ [CORRELATION_CALL_ID]: callId
7607
7946
  });
7608
7947
  } catch (err) {
7609
7948
  if (isAbortError(err)) throw err;
@@ -7739,7 +8078,10 @@ var ZapierApiClient = class {
7739
8078
  approvalId: approval.id,
7740
8079
  streamUrl,
7741
8080
  signal: streamAbortController.signal,
7742
- stream: (url, streamInit) => this.streamTrustedJsonUrl(url, streamInit),
8081
+ stream: (url, streamInit) => this.streamTrustedJsonUrl(url, {
8082
+ ...streamInit,
8083
+ [CORRELATION_CALL_ID]: callId
8084
+ }),
7743
8085
  emitEvent: (type, payload) => this.emitEvent(type, payload)
7744
8086
  });
7745
8087
  }
@@ -7748,7 +8090,8 @@ var ZapierApiClient = class {
7748
8090
  () => this.rawFetchUrl(approval.poll_url, {
7749
8091
  method: "GET",
7750
8092
  headers: { Accept: "application/json" },
7751
- signal
8093
+ signal,
8094
+ [CORRELATION_CALL_ID]: callId
7752
8095
  })
7753
8096
  );
7754
8097
  const pollApprovalUntilComplete = async (isPending, deadlineMs = approvalDeadline) => {
@@ -7940,6 +8283,23 @@ var API_ID = "zapier/api";
7940
8283
  var apiPluginRef = declareProperty({
7941
8284
  id: API_ID
7942
8285
  });
8286
+ function withCorrelationId({
8287
+ client,
8288
+ callId
8289
+ }) {
8290
+ const stamp = (options) => ({ ...options, [CORRELATION_CALL_ID]: callId });
8291
+ return {
8292
+ get: (path, options) => client.get(path, stamp(options)),
8293
+ post: (path, data, options) => client.post(path, data, stamp(options)),
8294
+ put: (path, data, options) => client.put(path, data, stamp(options)),
8295
+ patch: (path, data, options) => client.patch(path, data, stamp(options)),
8296
+ delete: (path, data, options) => client.delete(path, data, stamp(options)),
8297
+ poll: (path, options) => client.poll(path, stamp(options)),
8298
+ fetch: (path, init) => client.fetch(path, stamp(init)),
8299
+ fetchStream: (path, init) => client.fetchStream(path, stamp(init)),
8300
+ fetchJsonStream: (path, init) => client.fetchJsonStream(path, stamp(init))
8301
+ };
8302
+ }
7943
8303
  var apiPlugin = defineProperty({
7944
8304
  namespace: "zapier",
7945
8305
  name: "api",
@@ -7980,7 +8340,7 @@ var apiPlugin = defineProperty({
7980
8340
  callerPackage
7981
8341
  });
7982
8342
  },
7983
- get: ({ state }) => state
8343
+ get: ({ state, callContext }) => callContext?.callId ? withCorrelationId({ client: state, callId: callContext.callId }) : state
7984
8344
  });
7985
8345
  var RESOLVE_CREDENTIALS_ID = "zapier/resolveCredentials";
7986
8346
  var resolveCredentialsPluginRef = declareProperty({ id: RESOLVE_CREDENTIALS_ID });
@@ -8541,8 +8901,11 @@ var manifestPlugin = defineProperty({
8541
8901
  namespace: "zapier",
8542
8902
  name: "manifest",
8543
8903
  imports: [sdkOptionsPluginRef, apiPluginRef],
8904
+ // Deliberately does not read `imports.api`: at build time that resolves to the
8905
+ // bare shared client, and capturing it here would strip the correlation id off
8906
+ // every slug-resolution request. `get` supplies the reading call's client
8907
+ // instead.
8544
8908
  setup: ({ imports }) => {
8545
- const api = imports.api;
8546
8909
  const { manifestPath = DEFAULT_CONFIG_PATH, manifest } = imports.sdkOptions ?? {};
8547
8910
  let resolvedManifest;
8548
8911
  async function resolveManifest() {
@@ -8560,7 +8923,10 @@ var manifestPlugin = defineProperty({
8560
8923
  }
8561
8924
  return resolvedManifest;
8562
8925
  };
8563
- const getVersionedImplementationId = async (appKey) => {
8926
+ const getVersionedImplementationId = async ({
8927
+ appKey,
8928
+ api
8929
+ }) => {
8564
8930
  const resolvedApps = await resolveAppKeys({
8565
8931
  appKeys: [appKey],
8566
8932
  api,
@@ -8570,14 +8936,14 @@ var manifestPlugin = defineProperty({
8570
8936
  if (!resolvedApp) return null;
8571
8937
  return `${resolvedApp.implementationName}@${resolvedApp.version || "latest"}`;
8572
8938
  };
8573
- const updateManifestEntry = async (options) => {
8574
- const {
8575
- appKey,
8576
- entry,
8577
- configPath = DEFAULT_CONFIG_PATH,
8578
- skipWrite = false,
8579
- manifest: inputManifest
8580
- } = options;
8939
+ const updateManifestEntry = async ({
8940
+ api,
8941
+ appKey,
8942
+ entry,
8943
+ configPath = DEFAULT_CONFIG_PATH,
8944
+ skipWrite = false,
8945
+ manifest: inputManifest
8946
+ }) => {
8581
8947
  const manifest2 = inputManifest || await readManifestFromFile(configPath) || { apps: {} };
8582
8948
  let existingEntry = findManifestEntry({
8583
8949
  appKey,
@@ -8628,7 +8994,7 @@ var manifestPlugin = defineProperty({
8628
8994
  };
8629
8995
  return {
8630
8996
  getVersionedImplementationId,
8631
- resolveAppKeys: async ({ appKeys }) => resolveAppKeys({
8997
+ resolveAppKeys: async ({ appKeys, api }) => resolveAppKeys({
8632
8998
  appKeys,
8633
8999
  api,
8634
9000
  manifest: await getResolvedManifest() ?? { apps: {} }
@@ -8641,7 +9007,19 @@ var manifestPlugin = defineProperty({
8641
9007
  updateManifestEntry
8642
9008
  };
8643
9009
  },
8644
- get: ({ state }) => state
9010
+ // Bind the reading call's API client onto the slug-resolving entry points so
9011
+ // their requests carry that call's correlation id. The manifest-only reads pass
9012
+ // straight through.
9013
+ get: ({ imports, state }) => {
9014
+ const api = imports.api;
9015
+ return {
9016
+ getVersionedImplementationId: (appKey) => state.getVersionedImplementationId({ appKey, api }),
9017
+ resolveAppKeys: ({ appKeys }) => state.resolveAppKeys({ appKeys, api }),
9018
+ getResolvedManifest: state.getResolvedManifest,
9019
+ getManifestConnections: state.getManifestConnections,
9020
+ updateManifestEntry: (options) => state.updateManifestEntry({ ...options, api })
9021
+ };
9022
+ }
8645
9023
  });
8646
9024
 
8647
9025
  // src/plugins/connections/index.ts
@@ -15742,6 +16120,7 @@ function buildErrorEventWithContext(data, context = {}) {
15742
16120
  function buildMethodCalledEvent(data, context = {}) {
15743
16121
  return {
15744
16122
  ...createBaseEvent(context),
16123
+ correlation_id: data.correlation_id ?? context.correlation_id ?? null,
15745
16124
  method_name: data.method_name ?? null,
15746
16125
  method_module: data.method_module ?? null,
15747
16126
  execution_duration_ms: data.execution_duration_ms,
@@ -15799,6 +16178,7 @@ function makeMethodEndHook(emitMethodCalled) {
15799
16178
  args,
15800
16179
  isPaginated,
15801
16180
  depth,
16181
+ callId,
15802
16182
  callOrigin,
15803
16183
  annotations,
15804
16184
  durationMs,
@@ -15808,6 +16188,9 @@ function makeMethodEndHook(emitMethodCalled) {
15808
16188
  const metadata = readMethodMetadata(annotations);
15809
16189
  emitMethodCalled({
15810
16190
  method_name: methodName,
16191
+ // The per-call correlation id (also the `zapier-correlation-id` header on
16192
+ // this call's requests). Not the `call_context` surface label.
16193
+ correlation_id: callId ?? null,
15811
16194
  execution_duration_ms: durationMs,
15812
16195
  success_flag: !error,
15813
16196
  error_message: error?.message ?? null,
@@ -16494,4 +16877,4 @@ var registryPlugin = (_sdk) => {
16494
16877
  return {};
16495
16878
  };
16496
16879
 
16497
- export { ACTION_RUNS_PATH, API_ID, ActionKeyPropertySchema, ActionPropertySchema, ActionTimeoutMillisecondsPropertySchema, ActionTimeoutSecondsPropertySchema, ActionTypePropertySchema, AppKeyPropertySchema, AppPropertySchema, AppsPropertySchema, AuthMechanism, AuthenticationIdPropertySchema, BaseSdkOptionsSchema, CONNECTIONS_ID, CONTEXT, CONTEXT_CACHE_MAX_SIZE, CONTEXT_CACHE_TTL_MILLISECONDS, CORE_ERROR_SYMBOL, CORE_OPTIONS_ID, CORE_SIGNAL_SYMBOL, ClientCredentialsObjectSchema, ConnectionEntrySchema, ConnectionIdPropertySchema, ConnectionPropertySchema, ConnectionsMapSchema, ConnectionsPropertySchema, CoreCancelledSignal, CoreDisposeError, CoreErrorCode, CoreSignal, CredentialsFunctionSchema, CredentialsObjectSchema, CredentialsSchema, DEFAULT_ACTION_TIMEOUT_MILLISECONDS, DEFAULT_APPROVAL_TIMEOUT_MILLISECONDS, DEFAULT_CONFIG_PATH, DEFAULT_MAX_APPROVAL_RETRIES, DEFAULT_PAGE_SIZE, DEPRECATION_NOTICE_EVENT, DebugPropertySchema, DrainTriggerInboxSchema, EVENT_EMISSION_ID, FieldsPropertySchema, InputFieldPropertySchema, InputsPropertySchema, LeaseLimitPropertySchema, LeasePropertySchema, LeaseSecondsPropertySchema, LimitPropertySchema, MANIFEST_ID, MAX_CONCURRENCY_LIMIT, MAX_PAGE_LIMIT, OffsetPropertySchema, OutputPropertySchema, ParamsPropertySchema, PkceCredentialsObjectSchema, RESOLVE_CREDENTIALS_ID, RecordPropertySchema, RecordsPropertySchema, RelayFetchSchema, RelayRequestSchema, ResolvedCredentialsSchema, SDK_OPTIONS_ID, TablePropertySchema, TablesPropertySchema, TriggerInboxKeyPropertySchema, TriggerInboxNamePropertySchema, TriggerInboxPropertySchema, WatchTriggerInboxSchema, ZAPIER_BASE_URL, ZAPIER_MAX_CONCURRENT_REQUESTS, ZAPIER_MAX_NETWORK_RETRIES, ZAPIER_MAX_NETWORK_RETRY_DELAY_MILLISECONDS, ZapierAbortDrainSignal, ZapierActionError, ZapierApiError, ZapierAppNotFoundError, ZapierApprovalError, ZapierAuthenticationError, ZapierBundleError, ZapierConfigurationError, ZapierConflictError, ZapierError, ZapierNotFoundError, ZapierRateLimitError, ZapierRelayError, ZapierReleaseTriggerMessageSignal, ZapierResourceNotFoundError, ZapierSignal, ZapierTimeoutError, ZapierUnknownError, ZapierValidationError, actionKeyResolver, actionTypeResolver, addPlugin, apiPlugin, apiPluginRef, appKeyResolver, appsPlugin, batch, buildApplicationLifecycleEvent, buildCapabilityMessage, buildErrorEvent, buildErrorEventWithContext, buildMethodCalledEvent, cleanupEventListeners, clearTokenCache, clientCredentialsNameResolver, clientIdResolver, composePlugins, connectionIdGenericResolver, connectionIdResolver, connectionsPlugin, connectionsPluginRef, createActionRunPlugin, createBaseEvent, createClientCredentialsPlugin, createController, createCorePlugin, createFunction, createMemoryCache, createPaginatedFunction, createPaginatedPluginMethod, createPluginMethod, createPluginStack, createSdk, createTableFieldsPlugin, createTablePlugin, createTableRecordsPlugin, createZapierApi, createZapierSdk, createZapierSdkWithoutRegistry, declareMethod, declareOptionalProperty, declarePlugin, declareProperty, defineFormatter, defineLegacyMerge, defineMethod, defineMethodOverride, definePlugin, defineProperty, defineResolver, deleteClientCredentialsPlugin, deleteTableFieldsPlugin, deleteTablePlugin, deleteTableRecordsPlugin, disposeSdk, durableRunIdResolver, eventEmissionHookPlugin, eventEmissionPlugin, eventEmissionPluginRef, extractErrorDetail, fetchPlugin2 as fetchPlugin, findFirstConnectionPlugin, findManifestEntry, findUniqueConnectionPlugin, formatErrorMessage, fromFunctionPlugin, generateEventId, getActionInputFieldsSchemaPlugin, getActionPlugin, getActionRunPlugin, getAgent, getAppPlugin, getBaseUrlFromCredentials, getCallerContext, getCiPlatform, getClientIdFromCredentials, getConnectionPlugin, getContext, getCoreErrorCause, getCoreErrorCode, getCpuTime, getCurrentTimestamp, getMemoryUsage, getNegatable, getOrCreateApiClient, getOsInfo, getPlatformVersions, getPreferredManifestEntryKey, getProfilePlugin, getRegistryPlugin, getReleaseId, getTablePlugin, getTableRecordPlugin, getTokenFromCliLogin, getTtyContext, getZapierApprovalMode, getZapierDefaultApprovalMode, getZapierOpenAutoModeApprovalsInBrowser, getZapierSdkService, injectCliLogin, inputFieldKeyResolver, inputsAllOptionalResolver, inputsResolver, invalidateCachedToken, invalidateCredentialsToken, isCi, isCliLoginAvailable, isClientCredentials, isCoreCancelledSignal, isCoreError, isCoreSignal, isCredentialsFunction, isCredentialsObject, isPermanentHttpError, isPkceCredentials, isPositional, isZapierAbortDrainSignal, isZapierActionError, isZapierAppNotFoundError, isZapierApprovalError, isZapierAuthenticationError, isZapierBundleError, isZapierConflictError, isZapierError, isZapierNotFoundError, isZapierRateLimitError, isZapierReleaseTriggerMessageSignal, isZapierResourceNotFoundError, isZapierSignal, isZapierTimeoutError, isZapierValidationError, listActionInputFieldChoicesPlugin, listActionInputFieldsPlugin, listActionsPlugin, listAppsPlugin, listClientCredentialsPlugin, listConnectionsPlugin, listTableFieldsPlugin, listTableRecordsPlugin, listTablesPlugin, logDeprecation2 as logDeprecation, manifestPlugin, manifestPluginRef, omitExports, openEnum, operationAnnotatorPlugin, parseConcurrencyEnvVar, readManifestFromFile, registryPlugin, requestPlugin, resetDeprecationWarnings2 as resetDeprecationWarnings, resolveAuth, resolveAuthToken, resolveCredentials, resolveCredentialsFromEnv, resolveCredentialsPlugin, resolveCredentialsPluginRef, resolvePlugin, runActionPlugin, runInMethodScope, runWithCallerContext, runWithTelemetryContext, sdkOptionsPluginRef, selectExports, tableFieldIdsResolver, tableFieldsResolver, tableFiltersResolver, tableIdResolver, tableNameResolver, tableRecordIdResolver, tableRecordIdsResolver, tableRecordsResolver, tableSortResolver, tableUpdateRecordsResolver, toSnakeCase, toTitleCase, triggerInboxResolver, triggerMessagesResolver, updateTableRecordsPlugin, workflowDraftIdResolver, workflowIdResolver, workflowRunIdResolver, workflowVersionIdResolver, zapierAdaptError, zapierCoreOptions, zapierSdkPlugin };
16880
+ export { ACTION_RUNS_PATH, API_ID, ActionKeyPropertySchema, ActionPropertySchema, ActionTimeoutMillisecondsPropertySchema, ActionTimeoutSecondsPropertySchema, ActionTypePropertySchema, AppKeyPropertySchema, AppPropertySchema, AppsPropertySchema, AuthMechanism, AuthenticationIdPropertySchema, BaseSdkOptionsSchema, CONNECTIONS_ID, CONTEXT, CONTEXT_CACHE_MAX_SIZE, CONTEXT_CACHE_TTL_MILLISECONDS, CORE_ERROR_SYMBOL, CORE_OPTIONS_ID, CORE_SIGNAL_SYMBOL, ClientCredentialsObjectSchema, ConnectionEntrySchema, ConnectionIdPropertySchema, ConnectionPropertySchema, ConnectionsMapSchema, ConnectionsPropertySchema, CoreCancelledSignal, CoreDisposeError, CoreErrorCode, CoreSignal, CredentialsFunctionSchema, CredentialsObjectSchema, CredentialsSchema, DEFAULT_ACTION_TIMEOUT_MILLISECONDS, DEFAULT_APPROVAL_TIMEOUT_MILLISECONDS, DEFAULT_CONFIG_PATH, DEFAULT_MAX_APPROVAL_RETRIES, DEFAULT_PAGE_SIZE, DEPRECATION_NOTICE_EVENT, DebugPropertySchema, DrainTriggerInboxSchema, EVENT_EMISSION_ID, FieldsPropertySchema, InputFieldPropertySchema, InputsPropertySchema, LeaseLimitPropertySchema, LeasePropertySchema, LeaseSecondsPropertySchema, LimitPropertySchema, MANIFEST_ID, MAX_CONCURRENCY_LIMIT, MAX_PAGE_LIMIT, OffsetPropertySchema, OutputPropertySchema, ParamsPropertySchema, PkceCredentialsObjectSchema, RESOLVE_CREDENTIALS_ID, RecordPropertySchema, RecordsPropertySchema, RelayFetchSchema, RelayRequestSchema, ResolvedCredentialsSchema, SDK_OPTIONS_ID, TablePropertySchema, TablesPropertySchema, TriggerInboxKeyPropertySchema, TriggerInboxNamePropertySchema, TriggerInboxPropertySchema, WatchTriggerInboxSchema, ZAPIER_BASE_URL, ZAPIER_MAX_CONCURRENT_REQUESTS, ZAPIER_MAX_NETWORK_RETRIES, ZAPIER_MAX_NETWORK_RETRY_DELAY_MILLISECONDS, ZapierAbortDrainSignal, ZapierActionError, ZapierApiError, ZapierAppNotFoundError, ZapierApprovalError, ZapierAuthenticationError, ZapierBundleError, ZapierConfigurationError, ZapierConflictError, ZapierError, ZapierNotFoundError, ZapierRateLimitError, ZapierRelayError, ZapierReleaseTriggerMessageSignal, ZapierResourceNotFoundError, ZapierSignal, ZapierTimeoutError, ZapierUnknownError, ZapierValidationError, actionKeyResolver, actionTypeResolver, addPlugin, apiPlugin, apiPluginRef, appKeyResolver, appsPlugin, batch, buildApplicationLifecycleEvent, buildCapabilityMessage, buildErrorEvent, buildErrorEventWithContext, buildMethodCalledEvent, cleanupEventListeners, clearTokenCache, clientCredentialsNameResolver, clientIdResolver, composePlugins, connectionIdGenericResolver, connectionIdResolver, connectionsPlugin, connectionsPluginRef, createActionRunPlugin, createBaseEvent, createClientCredentialsPlugin, createController, createCorePlugin, createFunction, createMemoryCache, createPaginatedFunction, createPaginatedPluginMethod, createPluginMethod, createPluginStack, createSdk, createTableFieldsPlugin, createTablePlugin, createTableRecordsPlugin, createZapierApi, createZapierSdk, createZapierSdkWithoutRegistry, declareMethod, declareOptionalProperty, declarePlugin, declareProperty, defineFormatter, defineLegacyMerge, defineMethod, defineMethodOverride, defineOverride, definePlugin, defineProperty, defineResolver, deleteClientCredentialsPlugin, deleteTableFieldsPlugin, deleteTablePlugin, deleteTableRecordsPlugin, disposeSdk, durableRunIdResolver, eventEmissionHookPlugin, eventEmissionPlugin, eventEmissionPluginRef, extractErrorDetail, fetchPlugin2 as fetchPlugin, findFirstConnectionPlugin, findManifestEntry, findUniqueConnectionPlugin, formatErrorMessage, fromFunctionPlugin, generateEventId, getActionInputFieldsSchemaPlugin, getActionPlugin, getActionRunPlugin, getAgent, getAppPlugin, getBaseUrlFromCredentials, getCallerContext, getCiPlatform, getClientIdFromCredentials, getConnectionPlugin, getContext, getCoreErrorCause, getCoreErrorCode, getCpuTime, getCurrentTimestamp, getMemoryUsage, getNegatable, getOrCreateApiClient, getOsInfo, getPlatformVersions, getPreferredManifestEntryKey, getProfilePlugin, getRegistryPlugin, getReleaseId, getTablePlugin, getTableRecordPlugin, getTokenFromCliLogin, getTtyContext, getZapierApprovalMode, getZapierDefaultApprovalMode, getZapierOpenAutoModeApprovalsInBrowser, getZapierSdkService, injectCliLogin, inputFieldKeyResolver, inputsAllOptionalResolver, inputsResolver, invalidateCachedToken, invalidateCredentialsToken, isCi, isCliLoginAvailable, isClientCredentials, isCoreCancelledSignal, isCoreError, isCoreSignal, isCredentialsFunction, isCredentialsObject, isPermanentHttpError, isPkceCredentials, isPositional, isZapierAbortDrainSignal, isZapierActionError, isZapierAppNotFoundError, isZapierApprovalError, isZapierAuthenticationError, isZapierBundleError, isZapierConflictError, isZapierError, isZapierNotFoundError, isZapierRateLimitError, isZapierReleaseTriggerMessageSignal, isZapierResourceNotFoundError, isZapierSignal, isZapierTimeoutError, isZapierValidationError, listActionInputFieldChoicesPlugin, listActionInputFieldsPlugin, listActionsPlugin, listAppsPlugin, listClientCredentialsPlugin, listConnectionsPlugin, listTableFieldsPlugin, listTableRecordsPlugin, listTablesPlugin, logDeprecation2 as logDeprecation, manifestPlugin, manifestPluginRef, omitExports, openEnum, operationAnnotatorPlugin, parseConcurrencyEnvVar, readManifestFromFile, registryPlugin, requestPlugin, resetDeprecationWarnings2 as resetDeprecationWarnings, resolveAuth, resolveAuthToken, resolveCredentials, resolveCredentialsFromEnv, resolveCredentialsPlugin, resolveCredentialsPluginRef, resolvePlugin, runActionPlugin, runInMethodScope, runWithCallerContext, runWithTelemetryContext, sdkOptionsPluginRef, selectExports, tableFieldIdsResolver, tableFieldsResolver, tableFiltersResolver, tableIdResolver, tableNameResolver, tableRecordIdResolver, tableRecordIdsResolver, tableRecordsResolver, tableSortResolver, tableUpdateRecordsResolver, toSnakeCase, toTitleCase, triggerInboxResolver, triggerMessagesResolver, updateTableRecordsPlugin, workflowDraftIdResolver, workflowIdResolver, workflowRunIdResolver, workflowVersionIdResolver, zapierAdaptError, zapierCoreOptions, zapierSdkPlugin };