@slates/provider 1.0.0-rc.32 → 1.0.0-rc.34

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.d.ts CHANGED
@@ -459,6 +459,13 @@ declare class SlateSpecification<ConfigType extends {}, AuthType extends {}> {
459
459
  }
460
460
  declare let spec: <ConfigType extends {}, AuthType extends {}>(params: SlateSpecificationCreateParameters<ConfigType, AuthType>) => SlateSpecification<ConfigType, AuthType>;
461
461
 
462
+ interface SlateRuntimeInfo {
463
+ metorial?: {
464
+ apiUrl: string;
465
+ region?: string | null;
466
+ environment?: string | null;
467
+ };
468
+ }
462
469
  type SlateAddAttachmentContent = Buffer | Uint8Array | ArrayBuffer | ReadableStream<Uint8Array> | NodeJS.ReadableStream | Response;
463
470
  type SlateAddAttachmentInput = {
464
471
  type: 'url';
@@ -479,7 +486,8 @@ declare class SlatePublicContext<InputType extends {}> {
479
486
  #private;
480
487
  private readonly spec;
481
488
  private readonly logger;
482
- constructor(input: InputType, spec: SlateSpecification<any, any>, logger: SlateLogger, liveInvocation?: SlateLiveInvocationInfo | null);
489
+ constructor(input: InputType, spec: SlateSpecification<any, any>, logger: SlateLogger, liveInvocation?: SlateLiveInvocationInfo | null, runtimeInfo?: SlateRuntimeInfo | null);
490
+ get runtimeInfo(): Readonly<SlateRuntimeInfo> | null;
483
491
  get specification(): SlateSpecification<any, any>;
484
492
  get input(): Readonly<InputType>;
485
493
  get event(): Readonly<InputType>;
@@ -517,7 +525,7 @@ declare class SlatePublicContext<InputType extends {}> {
517
525
  }
518
526
  declare class SlateContext<ConfigType extends {}, AuthType extends {}, InputType extends {}> extends SlatePublicContext<InputType> {
519
527
  #private;
520
- constructor(config: ConfigType, input: InputType, auth: AuthType, spec: SlateSpecification<ConfigType, AuthType>, logger: SlateLogger, liveInvocation?: SlateLiveInvocationInfo | null);
528
+ constructor(config: ConfigType, input: InputType, auth: AuthType, spec: SlateSpecification<ConfigType, AuthType>, logger: SlateLogger, liveInvocation?: SlateLiveInvocationInfo | null, runtimeInfo?: SlateRuntimeInfo | null);
521
529
  get config(): Readonly<ConfigType>;
522
530
  get auth(): Readonly<AuthType>;
523
531
  _getAuthConfigForRedaction(): Record<string, unknown> | undefined;
@@ -525,9 +533,11 @@ declare class SlateContext<ConfigType extends {}, AuthType extends {}, InputType
525
533
 
526
534
  declare let runWithContext: <InputType extends {}, RV>(context: SlatePublicContext<InputType>, fn: () => Promise<RV>) => Promise<RV>;
527
535
  declare let getCurrentContext: <ConfigType extends {}, AuthType extends {}, InputType extends {}>() => SlateContext<ConfigType, AuthType, InputType>;
536
+ declare let getRuntimeInfo: () => Readonly<SlateRuntimeInfo> | null;
528
537
 
529
538
  declare let SlateDefaultPollingIntervalSeconds: number;
530
539
  type SlateTriggerRoutingMatcher = Record<string, any>;
540
+ type SlateTriggerGroupSelection = Record<string, any>;
531
541
  type SlateWebhookTargetOwnership = 'single_user' | 'multi_user';
532
542
  interface SlateWebhookTarget {
533
543
  webhookTargetIdentifier: string;
@@ -540,6 +550,7 @@ interface SlateWebhookTarget {
540
550
  type SlateTriggerGroupRoutingMatchersHandler<ConfigType extends {}, AuthType extends {}> = (context: SlateContext<ConfigType, AuthType, {}>) => Promise<SlateTriggerRoutingMatcher[]>;
541
551
  type SlateTriggerGroupPollHandler<ConfigType extends {}, AuthType extends {}> = (context: SlateContext<ConfigType, AuthType, {
542
552
  state: any | null;
553
+ selection?: SlateTriggerGroupSelection;
543
554
  }>) => Promise<{
544
555
  events: {
545
556
  payload: any;
@@ -584,6 +595,7 @@ type SlateTriggerGroupGatewayReceiveHandler<ConfigType extends {}, AuthType exte
584
595
  }>;
585
596
  type SlateWebhookTargetListHandler<ConfigType extends {}, AuthType extends {}> = (context: SlateContext<ConfigType, AuthType, {
586
597
  pageToken: any | null;
598
+ selection?: SlateTriggerGroupSelection;
587
599
  }>) => Promise<{
588
600
  targets: SlateWebhookTarget[];
589
601
  nextPageToken: any | null;
@@ -593,9 +605,40 @@ type SlateWebhookRegisterHandler<ConfigType extends {}, AuthType extends {}> = (
593
605
  webhookTargetIdentifier: string;
594
606
  webhookTargetPayload: any;
595
607
  webhookUrl: string;
596
- }>) => Promise<{
608
+ operationId?: string;
609
+ selection?: SlateTriggerGroupSelection;
610
+ deliveryConfig?: unknown;
611
+ }>) => Promise<SlateWebhookRegistrationResult>;
612
+ interface SlateWebhookRegistrationResult {
613
+ webhookRegistrationIdentifier: string;
614
+ webhookRegistrationPayload: any;
615
+ expiresAt?: string | null;
616
+ renewAfter?: string | null;
617
+ /** Identities of this registration on a delivery channel shared with other registrations. */
618
+ routingKeys?: string[];
619
+ }
620
+ type SlateWebhookRenewHandler<ConfigType extends {}, AuthType extends {}> = (context: SlateContext<ConfigType, AuthType, {
597
621
  webhookRegistrationIdentifier: string;
598
622
  webhookRegistrationPayload: any;
623
+ webhookUrl: string;
624
+ webhookTargetIdentifier: string;
625
+ webhookTargetPayload: any;
626
+ operationId: string;
627
+ selection?: SlateTriggerGroupSelection;
628
+ deliveryConfig?: unknown;
629
+ }>) => Promise<SlateWebhookRegistrationResult>;
630
+ type SlateWebhookExpandHandler<ConfigType extends {}, AuthType extends {}> = (context: SlateContext<ConfigType, AuthType, {
631
+ payload: unknown | null;
632
+ state: any | null;
633
+ selection?: SlateTriggerGroupSelection;
634
+ deliveryId: string;
635
+ webhookRegistrationPayload: any;
636
+ }>) => Promise<{
637
+ events: {
638
+ payload: any;
639
+ idempotencyKey?: string;
640
+ }[];
641
+ updatedState?: any;
599
642
  }>;
600
643
  type SlateWebhookUnregisterHandler<ConfigType extends {}, AuthType extends {}> = (context: SlateContext<ConfigType, AuthType, {
601
644
  webhookRegistrationIdentifier: string;
@@ -629,6 +672,23 @@ type SlateWebhookProcessHandler = (context: SlateContext<{}, {}, {
629
672
  interface SlateWebhookSkipped {
630
673
  reason: string;
631
674
  }
675
+ /**
676
+ * Routing keys name the registrations a request addresses; an empty list acknowledges it
677
+ * without handing it to any. A rejection answers the sender with its status.
678
+ */
679
+ type SlateWebhookDeliveryAuthentication = {
680
+ routingKeys: string[];
681
+ rejected?: undefined;
682
+ } | {
683
+ rejected: {
684
+ status: number;
685
+ };
686
+ routingKeys?: undefined;
687
+ };
688
+ type SlateWebhookDeliveryAuthenticateHandler = (context: SlateContext<{}, {}, {
689
+ request: Request;
690
+ deliveryConfig: unknown;
691
+ }>) => Promise<SlateWebhookDeliveryAuthentication>;
632
692
  interface SlateTriggerGroupPollingParameters<ConfigType extends {}, AuthType extends {}> {
633
693
  intervalSeconds: number;
634
694
  pollEvents: SlateTriggerGroupPollHandler<ConfigType, AuthType>;
@@ -640,6 +700,7 @@ interface SlateTriggerGroupGatewayParameters<ConfigType extends {}, AuthType ext
640
700
  interface SlateTriggerGroupWebhookAutoRegistrationParameters<ConfigType extends {}, AuthType extends {}> {
641
701
  webhookTargetList: SlateWebhookTargetListHandler<ConfigType, AuthType>;
642
702
  webhookRegister: SlateWebhookRegisterHandler<ConfigType, AuthType>;
703
+ webhookRenew?: SlateWebhookRenewHandler<ConfigType, AuthType>;
643
704
  webhookUnregister: SlateWebhookUnregisterHandler<ConfigType, AuthType>;
644
705
  }
645
706
  interface SlateTriggerGroupWebhookManualRegistrationParameters<UserConfigSchema extends z$1.ZodType<any> = z$1.ZodType<any>, FullConfigSchema extends z$1.ZodType<any> = z$1.ZodType<any>> {
@@ -648,10 +709,18 @@ interface SlateTriggerGroupWebhookManualRegistrationParameters<UserConfigSchema
648
709
  setup: SlateWebhookManualSetupHandler<FullConfigSchema>;
649
710
  finish?: SlateWebhookManualFinishHandler<UserConfigSchema, FullConfigSchema>;
650
711
  }
712
+ /** A delivery setup a person completes once for an automatically registered group. */
713
+ type SlateTriggerGroupWebhookDeliveryConfigParameters<UserConfigSchema extends z$1.ZodType<any> = z$1.ZodType<any>, FullConfigSchema extends z$1.ZodType<any> = z$1.ZodType<any>> = SlateTriggerGroupWebhookManualRegistrationParameters<UserConfigSchema, FullConfigSchema> & {
714
+ finish: SlateWebhookManualFinishHandler<UserConfigSchema, FullConfigSchema>;
715
+ authenticate: SlateWebhookDeliveryAuthenticateHandler;
716
+ };
651
717
  interface SlateTriggerGroupWebhookParameters<ConfigType extends {}, AuthType extends {}> {
652
718
  autoRegistration?: SlateTriggerGroupWebhookAutoRegistrationParameters<ConfigType, AuthType>;
653
719
  manualRegistration?: SlateTriggerGroupWebhookManualRegistrationParameters<any, any>;
720
+ deliveryConfig?: SlateTriggerGroupWebhookDeliveryConfigParameters<any, any>;
654
721
  process: SlateWebhookProcessHandler;
722
+ expandWebhook?: SlateWebhookExpandHandler<ConfigType, AuthType>;
723
+ reconcileIntervalSeconds?: number;
655
724
  }
656
725
  interface SlateTriggerGroupCreateParameters<InputType extends {} = Record<string, unknown>> {
657
726
  key: string;
@@ -659,6 +728,7 @@ interface SlateTriggerGroupCreateParameters<InputType extends {} = Record<string
659
728
  description?: string;
660
729
  metadata?: Record<string, any>;
661
730
  eventSchema?: z$1.ZodType<InputType>;
731
+ selectionSchema?: z$1.ZodType<SlateTriggerGroupSelection>;
662
732
  }
663
733
  interface SlateTriggerGroupParameters<ConfigType extends {}, AuthType extends {}, InputType extends {} = Record<string, unknown>> extends SlateTriggerGroupCreateParameters<InputType> {
664
734
  source: 'polling' | 'webhook' | 'gateway';
@@ -679,6 +749,7 @@ declare class SlateTriggerGroup<ConfigType extends {}, AuthType extends {}, Inpu
679
749
  get metadata(): Record<string, any> | undefined;
680
750
  get eventSchema(): z$1.ZodType<InputType, unknown, z$1.core.$ZodTypeInternals<InputType, unknown>>;
681
751
  get source(): "polling" | "webhook" | "gateway";
752
+ get selectionSchema(): z$1.ZodType<SlateTriggerGroupSelection, unknown, z$1.core.$ZodTypeInternals<SlateTriggerGroupSelection, unknown>> | undefined;
682
753
  get polling(): SlateTriggerGroupPollingParameters<ConfigType, AuthType> | undefined;
683
754
  get webhook(): SlateTriggerGroupWebhookParameters<ConfigType, AuthType> | undefined;
684
755
  get gateway(): SlateTriggerGroupGatewayParameters<ConfigType, AuthType> | undefined;
@@ -697,7 +768,10 @@ declare class SlateTriggerGroupBuilder<ConfigType extends {}, AuthType extends {
697
768
  webhook<UserConfigSchema extends z$1.ZodType<any> = z$1.ZodType<any>, FullConfigSchema extends z$1.ZodType<any> = z$1.ZodType<any>>(props: {
698
769
  autoRegistration?: SlateTriggerGroupWebhookAutoRegistrationParameters<ConfigType, AuthType>;
699
770
  manualRegistration?: SlateTriggerGroupWebhookManualRegistrationParameters<UserConfigSchema, FullConfigSchema>;
771
+ deliveryConfig?: SlateTriggerGroupWebhookDeliveryConfigParameters<UserConfigSchema, FullConfigSchema>;
700
772
  process: SlateWebhookProcessHandler;
773
+ expandWebhook?: SlateWebhookExpandHandler<ConfigType, AuthType>;
774
+ reconcileIntervalSeconds?: number;
701
775
  }): SlateTriggerGroupBuilder<ConfigType, AuthType, InputType>;
702
776
  /** Receive events over a platform-managed persistent connection (e.g. a WebSocket gateway). */
703
777
  gateway(props: SlateTriggerGroupGatewayParameters<ConfigType, AuthType>): SlateTriggerGroupBuilder<ConfigType, AuthType, InputType>;
@@ -1000,6 +1074,8 @@ declare let isApiErrorRecord: (value: unknown) => value is Record<string, unknow
1000
1074
  declare let collectApiErrorDetails: (value: unknown, details: string[], options?: ApiErrorDetailOptions) => void;
1001
1075
  declare let getApiErrorResponse: (error: unknown) => ApiErrorResponse | undefined;
1002
1076
  declare let getApiErrorStatus: (error: unknown) => ApiErrorStatus | undefined;
1077
+ /** Upstream HTTP status of an HTTP client error or a ServiceError with `upstreamStatus`. */
1078
+ declare let getUpstreamErrorStatus: (error: unknown) => number | undefined;
1003
1079
  declare let getApiErrorResponseWithBody: (error: unknown) => ApiErrorResponse | undefined;
1004
1080
  declare let API_ERROR_MAX_DETAILS: number;
1005
1081
  declare let API_ERROR_MAX_MESSAGE_LENGTH: number;
@@ -1109,6 +1185,11 @@ declare class SlateDeclarationError extends SlateError {
1109
1185
  static is(error: unknown): error is SlateDeclarationError;
1110
1186
  }
1111
1187
 
1188
+ /** Parses a saved or received value, throwing a user-facing `ServiceError` on mismatch. */
1189
+ declare let parseWithServiceError: <T extends z$1.ZodType>(schema: T, value: unknown, message: string, options?: {
1190
+ reason?: string;
1191
+ }) => z$1.output<T>;
1192
+
1112
1193
  declare let mapServiceErrorCode: (code: string, status?: number) => string;
1113
1194
  declare let isServiceErrorData: (value: unknown) => value is SlateServiceErrorData;
1114
1195
  declare let getServiceErrorData: (error: unknown) => SlateServiceErrorData | null;
@@ -1143,14 +1224,38 @@ interface VerifyHmacSignatureOptions extends CreateHmacSignatureOptions {
1143
1224
  signature: string;
1144
1225
  }
1145
1226
  declare let createHmacSignature: ({ secret, payload, algorithm, digest, prefix }: CreateHmacSignatureOptions) => string;
1227
+ /** Constant-time secret comparison; an empty expected secret matches nothing. */
1228
+ declare let timingSafeStringEqual: (expected: string, received: string | null | undefined) => boolean;
1146
1229
  declare let verifyHmacSignature: (options: VerifyHmacSignatureOptions) => boolean;
1147
1230
 
1231
+ /** An event a poller already reported, saved so an overlapping read can skip it. */
1232
+ declare let seenEntrySchema: z$1.ZodObject<{
1233
+ key: z$1.ZodString;
1234
+ at: z$1.ZodNumber;
1235
+ }, z$1.core.$strip>;
1236
+ type SeenEntry = z$1.infer<typeof seenEntrySchema>;
1237
+ /** A short stable key for an idempotency key, so remembered events cost little state. */
1238
+ declare let seenEntryKey: (idempotencyKey: string) => string;
1239
+ /** Keeps entries at or after `cutoff` (or `retain`), newest first, at most `maxEntries`. */
1240
+ declare let pruneSeenEntries: (entries: Iterable<SeenEntry & {
1241
+ retain?: boolean;
1242
+ }>, options: {
1243
+ cutoff: number;
1244
+ maxEntries: number;
1245
+ onOverflow?: (dropped: number) => void;
1246
+ }) => SeenEntry[];
1247
+
1148
1248
  declare let getResponseHeaderValue: (headers: unknown, name: string) => string | undefined;
1149
1249
  declare let getBase64ByteLength: (contentBase64: string) => number;
1150
1250
 
1151
1251
  declare let pickDefined: <T extends object>(value: T) => Partial<T> & Record<string, unknown>;
1152
1252
  declare let setIfDefined: (target: Record<string, unknown>, key: string, value: unknown) => Record<string, unknown>;
1153
1253
 
1254
+ /** Records a page token in `seen`; `false` means it repeated and following it would loop. */
1255
+ declare let rememberPageToken: (seen: Set<string>, token: string) => boolean;
1256
+ /** Throws `repeated()` when a listing returns a page token it already returned. */
1257
+ declare let assertNewPageToken: (seen: Set<string>, token: string | null | undefined, repeated: () => unknown) => void;
1258
+
1154
1259
  declare class Slate<ConfigType extends {}, AuthType extends {}> {
1155
1260
  private readonly _spec;
1156
1261
  private readonly _actions;
@@ -1206,4 +1311,4 @@ declare let skipWebhook: (reason: string, response?: Response | SlateWebhookHttp
1206
1311
  response: Response | SlateWebhookHttpResponseInit;
1207
1312
  };
1208
1313
 
1209
- export { API_ERROR_MAX_DETAILS, API_ERROR_MAX_MESSAGE_LENGTH, API_ERROR_TRUNCATED_PLACEHOLDER, AUTH_CONFIG_SECRET_PLACEHOLDER_PREFIX, type ApiErrorBuildHelpers, type ApiErrorDetailOptions, type ApiErrorResponse, type ApiErrorStatus, type ApiErrorTextOptions, type ApiServiceError, type AuthConfigSecretFilter, AuthConfigSecretRedactor, type BoundedApiErrorDetailOptions, type BuildApiServiceErrorOptions, type CreateHmacSignatureOptions, type DecodeApiErrorBodyOptions, GET_FILE_URL_TOOL_ID, type GetFileUrlHandler, type GetFileUrlToolInput, type GetFileUrlToolOutput, type NormalizeOAuthTokenResponseOptions, type OAuthExpiresAtOptions, type OAuthRefreshTokenFallbackMode, type OAuthTokenResponse, Slate, SlateAction, SlateActionBuilder, type SlateActionCreateParameters, type SlateActionDocsReference, type SlateActionParameters, type SlateActionParametersAny, type SlateActionParametersTool, type SlateActionParametersTrigger, type SlateActionScopeClause, type SlateActionScopeClauseInput, type SlateActionScopeValue, type SlateActionScopes, type SlateActionScopesInput, type SlateActionType, SlateAdapter, type SlateAdapterCapability, SlateAdapterSpec, type SlateAdapterSpecParameters, type SlateAddAttachmentContent, type SlateAddAttachmentInput, type SlateAttachment, type SlateAttachmentInlineContent, type SlateAttachmentUploadReferenceContent, type SlateAttachmentUrlContent, SlateAuth, type SlateAuthDocsReference, type SlateAuthType, type SlateAuthWithCustomData, type SlateAuthWithNone, type SlateAuthWithOauth, type SlateAuthWithServiceAccount, type SlateAuthWithToken, type SlateAuthenticatedAxiosDefaults, type SlateAxiosDefaults, type SlateAxiosErrorAdapter, type SlateAxiosErrorOptions, SlateConfig, type SlateConfigDocsReference, SlateContext, SlateDeclarationError, SlateDefaultPollingIntervalSeconds, type SlateDirectUploadInput, type SlateDocsReference, SlateError, type SlateErrorInput, type SlateErrorIssue, type SlateErrorKind, type SlateErrorProviderInfo, type SlateErrorResponse, type SlateErrorUpstreamInfo, type SlateGatewayEvent, type SlateLiveInvocationInfo, type SlateLogEntry, type SlateLogFields, type SlateLogListener, type SlateLogMessageInput, type SlateLogType, SlateLogger, type SlateProviderDocsReference, SlatePublicContext, SlatePublicTool, type SlatePublicToolInvocationHandler, type SlatePublicToolParameters, type SlateServiceErrorData, SlateSpecification, type SlateSpecificationCreateParameters, type SlateSpecificationParameters, SlateTool, SlateToolCategory, type SlateToolCategoryParameters, type SlateToolInvocationHandler, type SlateToolParameters, SlateTrigger, SlateTriggerGroup, SlateTriggerGroupBuilder, type SlateTriggerGroupCreateParameters, type SlateTriggerGroupGatewayConnectHandler, type SlateTriggerGroupGatewayParameters, type SlateTriggerGroupGatewayReceiveHandler, type SlateTriggerGroupParameters, type SlateTriggerGroupPollHandler, type SlateTriggerGroupPollingParameters, type SlateTriggerGroupRoutingMatchersHandler, type SlateTriggerGroupWebhookAutoRegistrationParameters, type SlateTriggerGroupWebhookManualRegistrationParameters, type SlateTriggerGroupWebhookParameters, type SlateTriggerMappingHandler, type SlateTriggerMatchesHandler, type SlateTriggerParameters, type SlateTriggerRoutingMatcher, type SlateTypedDocsReference, type SlateWebhookHttpResponseInit, type SlateWebhookManualFinishHandler, type SlateWebhookManualSetupHandler, type SlateWebhookProcessHandler, type SlateWebhookRegisterHandler, type SlateWebhookSkipped, type SlateWebhookTarget, type SlateWebhookTargetListHandler, type SlateWebhookTargetOwnership, type SlateWebhookUnregisterHandler, type VerifyHmacSignatureOptions, adapterSpec, allOf, anyOf, auth, axios, buildApiServiceError, collectApiErrorDetails, config, createApiServiceError, createAuthenticatedAxios, createAxios, createBase64Attachment, createHmacSignature, createSlateError, createTextAttachment, createUrlAttachment, decodeApiErrorBody, extractApiErrorMessage, getApiErrorResponse, getApiErrorResponseWithBody, getApiErrorStatus, getBase64ByteLength, getCurrentContext, getFileUrlTool, getFileUrlToolInputSchema, getFileUrlToolOutputSchema, getGraphWebhookValidationResponse, getMetaWebhookVerificationResponse, getOAuthExpiresAtFromExpiresIn, getResponseHeaderValue, getServiceErrorData, graphWebhookHttp, inferSlateErrorFromAxios, isApiErrorRecord, isAxiosErrorLike, isServiceErrorData, isUrlEmbeddedCredential, looksLikeHtmlErrorBody, mapServiceErrorCode, mapServiceErrorToSlateErrorInput, mergeScopes, metaWebhookHttp, normalizeOAuthTokenResponse, pickDefined, publicTool, pushBoundedApiErrorDetail, readApiErrorText, redactUrlAttachmentSecrets, requestAxios, requestAxiosData, runWithContext, scopeClause, setIfDefined, skipWebhook, spec, statusLabelForApiError, tool, toolCategory, trigger, triggerGroup, truncateApiErrorMessage, uploadAttachmentDirect, validateScopes, verifyHmacSignature };
1314
+ export { API_ERROR_MAX_DETAILS, API_ERROR_MAX_MESSAGE_LENGTH, API_ERROR_TRUNCATED_PLACEHOLDER, AUTH_CONFIG_SECRET_PLACEHOLDER_PREFIX, type ApiErrorBuildHelpers, type ApiErrorDetailOptions, type ApiErrorResponse, type ApiErrorStatus, type ApiErrorTextOptions, type ApiServiceError, type AuthConfigSecretFilter, AuthConfigSecretRedactor, type BoundedApiErrorDetailOptions, type BuildApiServiceErrorOptions, type CreateHmacSignatureOptions, type DecodeApiErrorBodyOptions, GET_FILE_URL_TOOL_ID, type GetFileUrlHandler, type GetFileUrlToolInput, type GetFileUrlToolOutput, type NormalizeOAuthTokenResponseOptions, type OAuthExpiresAtOptions, type OAuthRefreshTokenFallbackMode, type OAuthTokenResponse, type SeenEntry, Slate, SlateAction, SlateActionBuilder, type SlateActionCreateParameters, type SlateActionDocsReference, type SlateActionParameters, type SlateActionParametersAny, type SlateActionParametersTool, type SlateActionParametersTrigger, type SlateActionScopeClause, type SlateActionScopeClauseInput, type SlateActionScopeValue, type SlateActionScopes, type SlateActionScopesInput, type SlateActionType, SlateAdapter, type SlateAdapterCapability, SlateAdapterSpec, type SlateAdapterSpecParameters, type SlateAddAttachmentContent, type SlateAddAttachmentInput, type SlateAttachment, type SlateAttachmentInlineContent, type SlateAttachmentUploadReferenceContent, type SlateAttachmentUrlContent, SlateAuth, type SlateAuthDocsReference, type SlateAuthType, type SlateAuthWithCustomData, type SlateAuthWithNone, type SlateAuthWithOauth, type SlateAuthWithServiceAccount, type SlateAuthWithToken, type SlateAuthenticatedAxiosDefaults, type SlateAxiosDefaults, type SlateAxiosErrorAdapter, type SlateAxiosErrorOptions, SlateConfig, type SlateConfigDocsReference, SlateContext, SlateDeclarationError, SlateDefaultPollingIntervalSeconds, type SlateDirectUploadInput, type SlateDocsReference, SlateError, type SlateErrorInput, type SlateErrorIssue, type SlateErrorKind, type SlateErrorProviderInfo, type SlateErrorResponse, type SlateErrorUpstreamInfo, type SlateGatewayEvent, type SlateLiveInvocationInfo, type SlateLogEntry, type SlateLogFields, type SlateLogListener, type SlateLogMessageInput, type SlateLogType, SlateLogger, type SlateProviderDocsReference, SlatePublicContext, SlatePublicTool, type SlatePublicToolInvocationHandler, type SlatePublicToolParameters, type SlateRuntimeInfo, type SlateServiceErrorData, SlateSpecification, type SlateSpecificationCreateParameters, type SlateSpecificationParameters, SlateTool, SlateToolCategory, type SlateToolCategoryParameters, type SlateToolInvocationHandler, type SlateToolParameters, SlateTrigger, SlateTriggerGroup, SlateTriggerGroupBuilder, type SlateTriggerGroupCreateParameters, type SlateTriggerGroupGatewayConnectHandler, type SlateTriggerGroupGatewayParameters, type SlateTriggerGroupGatewayReceiveHandler, type SlateTriggerGroupParameters, type SlateTriggerGroupPollHandler, type SlateTriggerGroupPollingParameters, type SlateTriggerGroupRoutingMatchersHandler, type SlateTriggerGroupSelection, type SlateTriggerGroupWebhookAutoRegistrationParameters, type SlateTriggerGroupWebhookDeliveryConfigParameters, type SlateTriggerGroupWebhookManualRegistrationParameters, type SlateTriggerGroupWebhookParameters, type SlateTriggerMappingHandler, type SlateTriggerMatchesHandler, type SlateTriggerParameters, type SlateTriggerRoutingMatcher, type SlateTypedDocsReference, type SlateWebhookDeliveryAuthenticateHandler, type SlateWebhookDeliveryAuthentication, type SlateWebhookExpandHandler, type SlateWebhookHttpResponseInit, type SlateWebhookManualFinishHandler, type SlateWebhookManualSetupHandler, type SlateWebhookProcessHandler, type SlateWebhookRegisterHandler, type SlateWebhookRegistrationResult, type SlateWebhookRenewHandler, type SlateWebhookSkipped, type SlateWebhookTarget, type SlateWebhookTargetListHandler, type SlateWebhookTargetOwnership, type SlateWebhookUnregisterHandler, type VerifyHmacSignatureOptions, adapterSpec, allOf, anyOf, assertNewPageToken, auth, axios, buildApiServiceError, collectApiErrorDetails, config, createApiServiceError, createAuthenticatedAxios, createAxios, createBase64Attachment, createHmacSignature, createSlateError, createTextAttachment, createUrlAttachment, decodeApiErrorBody, extractApiErrorMessage, getApiErrorResponse, getApiErrorResponseWithBody, getApiErrorStatus, getBase64ByteLength, getCurrentContext, getFileUrlTool, getFileUrlToolInputSchema, getFileUrlToolOutputSchema, getGraphWebhookValidationResponse, getMetaWebhookVerificationResponse, getOAuthExpiresAtFromExpiresIn, getResponseHeaderValue, getRuntimeInfo, getServiceErrorData, getUpstreamErrorStatus, graphWebhookHttp, inferSlateErrorFromAxios, isApiErrorRecord, isAxiosErrorLike, isServiceErrorData, isUrlEmbeddedCredential, looksLikeHtmlErrorBody, mapServiceErrorCode, mapServiceErrorToSlateErrorInput, mergeScopes, metaWebhookHttp, normalizeOAuthTokenResponse, parseWithServiceError, pickDefined, pruneSeenEntries, publicTool, pushBoundedApiErrorDetail, readApiErrorText, redactUrlAttachmentSecrets, rememberPageToken, requestAxios, requestAxiosData, runWithContext, scopeClause, seenEntryKey, seenEntrySchema, setIfDefined, skipWebhook, spec, statusLabelForApiError, timingSafeStringEqual, tool, toolCategory, trigger, triggerGroup, truncateApiErrorMessage, uploadAttachmentDirect, validateScopes, verifyHmacSignature };
@@ -899,6 +899,7 @@ var getCurrentContext = () => {
899
899
  }
900
900
  return context;
901
901
  };
902
+ var getRuntimeInfo = () => asyncLocalStorage.getStore()?.runtimeInfo ?? null;
902
903
 
903
904
  // src/error/defaults.ts
904
905
  var DEFAULT_CODE = "internal.unexpected";
@@ -1265,6 +1266,11 @@ var getApiErrorResponse = (error) => {
1265
1266
  };
1266
1267
  };
1267
1268
  var getApiErrorStatus = (error) => getApiErrorResponse(error)?.status;
1269
+ var getUpstreamErrorStatus = (error) => {
1270
+ let value = error instanceof ServiceError ? error.data.upstreamStatus : getApiErrorStatus(error);
1271
+ let status = Number(value);
1272
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : void 0;
1273
+ };
1268
1274
  var getApiErrorResponseWithBody = (error) => {
1269
1275
  let response = getApiErrorResponse(error);
1270
1276
  if (response?.data !== void 0) return response;
@@ -1772,6 +1778,13 @@ var SlateDeclarationError = class _SlateDeclarationError extends SlateError {
1772
1778
  }
1773
1779
  };
1774
1780
 
1781
+ // src/error/parse.ts
1782
+ var parseWithServiceError = (schema, value, message, options = {}) => {
1783
+ let result = schema.safeParse(value);
1784
+ if (!result.success) throw createApiServiceError(message, options);
1785
+ return result.data;
1786
+ };
1787
+
1775
1788
  // src/action/scopes.ts
1776
1789
  var scopeClause = (...scopes) => {
1777
1790
  assertScopeValues(scopes);
@@ -2149,6 +2162,9 @@ var SlateTriggerGroup = class _SlateTriggerGroup {
2149
2162
  get source() {
2150
2163
  return this._params.source;
2151
2164
  }
2165
+ get selectionSchema() {
2166
+ return this._params.selectionSchema;
2167
+ }
2152
2168
  get polling() {
2153
2169
  return this._params.polling;
2154
2170
  }
@@ -2196,11 +2212,41 @@ var SlateTriggerGroupBuilder = class {
2196
2212
  "Webhook trigger groups require exactly one of autoRegistration or manualRegistration"
2197
2213
  );
2198
2214
  }
2215
+ if (props.deliveryConfig !== void 0) {
2216
+ if (!props.autoRegistration) {
2217
+ throw new SlateDeclarationError(
2218
+ "A webhook delivery config requires automatic webhook registration"
2219
+ );
2220
+ }
2221
+ if (!props.deliveryConfig.finish) {
2222
+ throw new SlateDeclarationError("A webhook delivery config requires a finish handler");
2223
+ }
2224
+ if (!props.deliveryConfig.authenticate) {
2225
+ throw new SlateDeclarationError(
2226
+ "A webhook delivery config requires an authenticate handler"
2227
+ );
2228
+ }
2229
+ }
2230
+ if (props.reconcileIntervalSeconds !== void 0) {
2231
+ if (!Number.isSafeInteger(props.reconcileIntervalSeconds) || props.reconcileIntervalSeconds < 900) {
2232
+ throw new SlateDeclarationError(
2233
+ "Webhook reconciliation interval must be an integer of at least 900 seconds"
2234
+ );
2235
+ }
2236
+ if (!props.expandWebhook) {
2237
+ throw new SlateDeclarationError(
2238
+ "Webhook reconciliation requires an expandWebhook handler"
2239
+ );
2240
+ }
2241
+ }
2199
2242
  this.#source = "webhook";
2200
2243
  this.#webhook = {
2201
2244
  autoRegistration: props.autoRegistration,
2202
2245
  manualRegistration: props.manualRegistration,
2203
- process: props.process
2246
+ deliveryConfig: props.deliveryConfig,
2247
+ process: props.process,
2248
+ expandWebhook: props.expandWebhook,
2249
+ reconcileIntervalSeconds: props.reconcileIntervalSeconds
2204
2250
  };
2205
2251
  return this;
2206
2252
  }
@@ -2769,6 +2815,10 @@ var resolveDefaultExport = (value) => {
2769
2815
  var PQueue = resolveDefaultExport(PQueueImport);
2770
2816
 
2771
2817
  // src/context/context.ts
2818
+ var freezeRuntimeInfo = (runtimeInfo) => Object.freeze({
2819
+ ...runtimeInfo,
2820
+ ...runtimeInfo.metorial ? { metorial: Object.freeze({ ...runtimeInfo.metorial }) } : {}
2821
+ });
2772
2822
  var isBufferLike = (value) => value instanceof Uint8Array || value instanceof ArrayBuffer;
2773
2823
  var toUint8Array = (value) => value instanceof ArrayBuffer ? new Uint8Array(value) : value;
2774
2824
  var isReadableStream = (value) => typeof ReadableStream !== "undefined" && value instanceof ReadableStream;
@@ -2785,17 +2835,19 @@ var readStreamToBuffer = async (stream) => {
2785
2835
  return Buffer.concat(chunks);
2786
2836
  };
2787
2837
  var SlatePublicContext = class {
2788
- constructor(input, spec2, logger, liveInvocation = null) {
2838
+ constructor(input, spec2, logger, liveInvocation = null, runtimeInfo = null) {
2789
2839
  this.spec = spec2;
2790
2840
  this.logger = logger;
2791
2841
  this.#input = input;
2792
2842
  this.#liveInvocation = liveInvocation;
2843
+ this.#runtimeInfo = runtimeInfo && freezeRuntimeInfo(runtimeInfo);
2793
2844
  }
2794
2845
  spec;
2795
2846
  logger;
2796
2847
  #input;
2797
2848
  #httpTraces = [];
2798
2849
  #liveInvocation;
2850
+ #runtimeInfo;
2799
2851
  #attachmentsDisabled = false;
2800
2852
  #attachments = [];
2801
2853
  #pendingUploads = [];
@@ -2806,6 +2858,9 @@ var SlatePublicContext = class {
2806
2858
  }
2807
2859
  return this.#uploadQueue;
2808
2860
  }
2861
+ get runtimeInfo() {
2862
+ return this.#runtimeInfo;
2863
+ }
2809
2864
  get specification() {
2810
2865
  return this.spec;
2811
2866
  }
@@ -2946,8 +3001,8 @@ var SlatePublicContext = class {
2946
3001
  var SlateContext = class extends SlatePublicContext {
2947
3002
  #config;
2948
3003
  #auth;
2949
- constructor(config2, input, auth2, spec2, logger, liveInvocation = null) {
2950
- super(input, spec2, logger, liveInvocation);
3004
+ constructor(config2, input, auth2, spec2, logger, liveInvocation = null, runtimeInfo = null) {
3005
+ super(input, spec2, logger, liveInvocation, runtimeInfo);
2951
3006
  this.#config = config2;
2952
3007
  this.#auth = auth2;
2953
3008
  }
@@ -2971,13 +3026,29 @@ var createHmacSignature = ({
2971
3026
  digest,
2972
3027
  prefix = ""
2973
3028
  }) => `${prefix}${createHmac(algorithm, secret).update(payload).digest(digest)}`;
2974
- var verifyHmacSignature = (options) => {
2975
- let expected = createHmacSignature(options);
3029
+ var timingSafeStringEqual = (expected, received) => {
2976
3030
  let expectedBytes = Buffer.from(expected);
2977
- let signatureBytes = Buffer.from(options.signature);
2978
- let lengthsMatch = signatureBytes.length === expectedBytes.length;
2979
- let comparableSignature = lengthsMatch ? signatureBytes : Buffer.alloc(expectedBytes.length);
2980
- return timingSafeEqual(comparableSignature, expectedBytes) && lengthsMatch;
3031
+ let receivedBytes = Buffer.from(received ?? "");
3032
+ let lengthsMatch = receivedBytes.length === expectedBytes.length;
3033
+ let comparable = lengthsMatch ? receivedBytes : Buffer.alloc(expectedBytes.length);
3034
+ return timingSafeEqual(comparable, expectedBytes) && lengthsMatch && expectedBytes.length > 0;
3035
+ };
3036
+ var verifyHmacSignature = (options) => timingSafeStringEqual(createHmacSignature(options), options.signature);
3037
+
3038
+ // src/dedup/index.ts
3039
+ import { createHash } from "crypto";
3040
+ import { z as z3 } from "zod";
3041
+ var seenEntrySchema = z3.object({ key: z3.string().min(1), at: z3.number().finite() });
3042
+ var seenEntryKey = (idempotencyKey) => createHash("sha256").update(idempotencyKey).digest("base64url").slice(0, 16);
3043
+ var pruneSeenEntries = (entries, options) => {
3044
+ let kept = [];
3045
+ for (let { key, at, retain } of entries) {
3046
+ if (retain || at >= options.cutoff) kept.push({ key, at });
3047
+ }
3048
+ kept.sort((a, b) => b.at - a.at || (a.key < b.key ? -1 : 1));
3049
+ if (kept.length <= options.maxEntries) return kept;
3050
+ options.onOverflow?.(kept.length - options.maxEntries);
3051
+ return kept.slice(0, options.maxEntries);
2981
3052
  };
2982
3053
 
2983
3054
  // src/file/index.ts
@@ -3107,6 +3178,16 @@ var setIfDefined = (target, key, value) => {
3107
3178
  return target;
3108
3179
  };
3109
3180
 
3181
+ // src/pagination/index.ts
3182
+ var rememberPageToken = (seen, token) => {
3183
+ if (seen.has(token)) return false;
3184
+ seen.add(token);
3185
+ return true;
3186
+ };
3187
+ var assertNewPageToken = (seen, token, repeated) => {
3188
+ if (token && !rememberPageToken(seen, token)) throw repeated();
3189
+ };
3190
+
3110
3191
  // src/specification/slate.ts
3111
3192
  var Slate = class _Slate {
3112
3193
  constructor(_spec, _actions, _adapters, _triggerGroups, _toolCategories, _toolCategoryKeysByActionKey) {
@@ -3158,12 +3239,12 @@ var Slate = class _Slate {
3158
3239
  }
3159
3240
  seenTriggerGroupKeys.add(group.key);
3160
3241
  }
3161
- let manualWebhookTriggerGroups = triggerGroups.filter(
3162
- (group) => group.source === "webhook" && group.webhook?.manualRegistration
3242
+ let configuredWebhookTriggerGroups = triggerGroups.filter(
3243
+ (group) => group.source === "webhook" && (group.webhook?.manualRegistration || group.webhook?.deliveryConfig)
3163
3244
  );
3164
- if (manualWebhookTriggerGroups.length > 1) {
3245
+ if (configuredWebhookTriggerGroups.length > 1) {
3165
3246
  throw new SlateDeclarationError(
3166
- `Only one trigger group may use manual webhook registration, but found: ${manualWebhookTriggerGroups.map((group) => group.key).join(", ")}`
3247
+ `Only one trigger group may use manual webhook registration or a delivery config, but found: ${configuredWebhookTriggerGroups.map((group) => group.key).join(", ")}`
3167
3248
  );
3168
3249
  }
3169
3250
  let toolCategories = params.toolCategories ?? [];
@@ -3265,7 +3346,7 @@ var resolveToolCategoryMembership = (toolCategories, actions) => {
3265
3346
  };
3266
3347
 
3267
3348
  // src/specification/specification.ts
3268
- import z3 from "zod";
3349
+ import z4 from "zod";
3269
3350
  var SlateSpecification = class _SlateSpecification {
3270
3351
  constructor(_config, _auth, _params) {
3271
3352
  this._config = _config;
@@ -3282,7 +3363,7 @@ var SlateSpecification = class _SlateSpecification {
3282
3363
  return this._config.configSchema;
3283
3364
  }
3284
3365
  get authSchema() {
3285
- return "outputSchema" in this._auth ? this._auth.outputSchema : z3.object({});
3366
+ return "outputSchema" in this._auth ? this._auth.outputSchema : z4.object({});
3286
3367
  }
3287
3368
  get config() {
3288
3369
  return this._config;
@@ -3397,6 +3478,7 @@ export {
3397
3478
  adapterSpec,
3398
3479
  allOf,
3399
3480
  anyOf,
3481
+ assertNewPageToken,
3400
3482
  auth,
3401
3483
  axios,
3402
3484
  buildApiServiceError,
@@ -3424,7 +3506,9 @@ export {
3424
3506
  getMetaWebhookVerificationResponse,
3425
3507
  getOAuthExpiresAtFromExpiresIn,
3426
3508
  getResponseHeaderValue,
3509
+ getRuntimeInfo,
3427
3510
  getServiceErrorData,
3511
+ getUpstreamErrorStatus,
3428
3512
  graphWebhookHttp,
3429
3513
  inferSlateErrorFromAxios,
3430
3514
  isApiErrorRecord,
@@ -3437,19 +3521,25 @@ export {
3437
3521
  mergeScopes,
3438
3522
  metaWebhookHttp,
3439
3523
  normalizeOAuthTokenResponse,
3524
+ parseWithServiceError,
3440
3525
  pickDefined,
3526
+ pruneSeenEntries,
3441
3527
  publicTool,
3442
3528
  pushBoundedApiErrorDetail,
3443
3529
  readApiErrorText,
3444
3530
  redactUrlAttachmentSecrets,
3531
+ rememberPageToken,
3445
3532
  requestAxios,
3446
3533
  requestAxiosData,
3447
3534
  runWithContext,
3448
3535
  scopeClause,
3536
+ seenEntryKey,
3537
+ seenEntrySchema,
3449
3538
  setIfDefined,
3450
3539
  skipWebhook,
3451
3540
  spec,
3452
3541
  statusLabelForApiError,
3542
+ timingSafeStringEqual,
3453
3543
  tool,
3454
3544
  toolCategory,
3455
3545
  trigger,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@slates/provider",
3
- "version": "1.0.0-rc.32",
3
+ "version": "1.0.0-rc.34",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -0,0 +1,90 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { z } from 'zod';
3
+ import { SlateAuth } from '../auth';
4
+ import { SlateConfig } from '../config';
5
+ import { SlateSpecification } from '../specification/specification';
6
+ import { triggerGroup } from './triggerGroup';
7
+
8
+ let spec = SlateSpecification.create({
9
+ key: 'demo',
10
+ name: 'Demo',
11
+ config: SlateConfig.create(z.object({})),
12
+ auth: SlateAuth.create<{}>().output(z.object({}))
13
+ });
14
+
15
+ let autoRegistration = {
16
+ webhookTargetList: async () => ({ targets: [], nextPageToken: null }),
17
+ webhookRegister: async () => ({
18
+ webhookRegistrationIdentifier: 'reg',
19
+ webhookRegistrationPayload: {}
20
+ }),
21
+ webhookUnregister: async () => {}
22
+ };
23
+ let setup = async () => ({ webhookSetupDocument: '', partialWebhookRegistrationPayload: {} });
24
+ let manualRegistration = {
25
+ userConfigSchema: z.object({}),
26
+ fullConfigSchema: z.object({}),
27
+ setup
28
+ };
29
+ let deliveryConfig = {
30
+ ...manualRegistration,
31
+ finish: async () => ({ webhookRegistrationPayload: {} }),
32
+ authenticate: async () => ({ routingKeys: [] })
33
+ };
34
+
35
+ type WebhookProps = Parameters<ReturnType<typeof triggerGroup>['webhook']>[0];
36
+
37
+ let build = (props: Omit<WebhookProps, 'process'>) =>
38
+ triggerGroup(spec, { key: 'group', name: 'Group' })
39
+ .webhook({ ...props, process: async () => ({ events: [] }) })
40
+ .routingMatchers(async () => [])
41
+ .build();
42
+
43
+ describe('webhook trigger group declaration', () => {
44
+ it('builds plain automatic and manual groups as before', () => {
45
+ expect(build({ autoRegistration }).webhook).toMatchObject({
46
+ autoRegistration,
47
+ manualRegistration: undefined,
48
+ deliveryConfig: undefined
49
+ });
50
+ expect(build({ manualRegistration }).webhook).toMatchObject({
51
+ autoRegistration: undefined,
52
+ manualRegistration,
53
+ deliveryConfig: undefined
54
+ });
55
+ });
56
+
57
+ it('requires exactly one of automatic or manual registration', () => {
58
+ let message =
59
+ 'Webhook trigger groups require exactly one of autoRegistration or manualRegistration';
60
+ expect(() => build({})).toThrow(message);
61
+ expect(() => build({ deliveryConfig })).toThrow(message);
62
+ expect(() => build({ autoRegistration, manualRegistration })).toThrow(message);
63
+ });
64
+
65
+ it('allows a delivery config only with automatic registration and its handlers', () => {
66
+ expect(build({ autoRegistration, deliveryConfig }).webhook?.deliveryConfig).toBe(
67
+ deliveryConfig
68
+ );
69
+ expect(() => build({ manualRegistration, deliveryConfig })).toThrow(
70
+ 'A webhook delivery config requires automatic webhook registration'
71
+ );
72
+ let { finish: _, ...withoutFinish } = deliveryConfig;
73
+ expect(() =>
74
+ build({
75
+ autoRegistration,
76
+ deliveryConfig: withoutFinish as unknown as typeof deliveryConfig
77
+ })
78
+ ).toThrow('A webhook delivery config requires a finish handler');
79
+ });
80
+
81
+ it('requires a delivery config to authenticate the requests it receives', () => {
82
+ let { authenticate: _, ...withoutAuthenticate } = deliveryConfig;
83
+ expect(() =>
84
+ build({
85
+ autoRegistration,
86
+ deliveryConfig: withoutAuthenticate as unknown as typeof deliveryConfig
87
+ })
88
+ ).toThrow('A webhook delivery config requires an authenticate handler');
89
+ });
90
+ });