Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

9.3 KB
Raw Blame
import {
  AppConnectionType,
  AppConnectionValue,
  ExecutionType,
  RespondResponse,
  ResumePayload,
  TriggerPayload,
  TriggerStrategy,
  DelayPauseMetadata,
  PauseMetadata,
  WebhookPauseMetadata,
} from '@activepieces/core-piece-types';
import type { SeekPage } from '@activepieces/core-utils';
import type { FlowRunId, ProjectId } from '@activepieces/core-utils';
import type { Readable } from 'node:stream'

import {
  BasicAuthProperty,
  CustomAuthProperty,
  InputPropertyMap,
  OIDCProperty,
  OAuth2Property,
  SecretTextProperty,
  StaticPropsValue,
} from '../property';
import { PieceAuthProperty } from '../property/authentication';
import type { PopulatedFlowSummary } from '@activepieces/core-piece-types';

export type BaseContext<
  PieceAuth extends PieceAuthProperty | PieceAuthProperty[] | undefined,
  Props extends InputPropertyMap
> = {
  flows: FlowsContext;
  step: StepContext;
    auth: AppConnectionValueForAuthProperty<PieceAuth>;
  propsValue: StaticPropsValue<Props>;
  store: Store;
  project: {
    id: ProjectId;
    externalId: () => Promise<string | undefined>;
  };
  connections: ConnectionsManager;
};


type ExtractCustomAuthProps<T> = T extends CustomAuthProperty<infer Props> ? Props : never;

type ExtractOIDCProps<T> = T extends OIDCProperty<infer Props> ? Props : never;

type ExtractOAuth2Props<T> = T extends OAuth2Property<infer Props> ? Props : never;


export type AppConnectionValueForAuthProperty<T extends PieceAuthProperty | PieceAuthProperty[] | undefined> = 
  T extends PieceAuthProperty[] ? AppConnectionValueForSingleAuthProperty<T[number]> :
  T extends PieceAuthProperty ? AppConnectionValueForSingleAuthProperty<T> :
  T extends undefined ? undefined : never;

type AppConnectionValueForSingleAuthProperty<T extends PieceAuthProperty | undefined> =
  T extends SecretTextProperty<boolean> ? AppConnectionValue<AppConnectionType.SECRET_TEXT> :
  T extends BasicAuthProperty ? AppConnectionValue<AppConnectionType.BASIC_AUTH> :
  T extends CustomAuthProperty<any> ? AppConnectionValue<AppConnectionType.CUSTOM_AUTH, StaticPropsValue<ExtractCustomAuthProps<T>>> :
  T extends OIDCProperty<any> ? AppConnectionValue<AppConnectionType.OIDC, StaticPropsValue<ExtractOIDCProps<T>>> :
  T extends OAuth2Property<any> ? AppConnectionValue<AppConnectionType.OAUTH2, StaticPropsValue<ExtractOAuth2Props<T>>> :
  T extends undefined ? undefined : never;
type AppWebhookTriggerHookContext<
  PieceAuth extends PieceAuthProperty | PieceAuthProperty[] | undefined,
  TriggerProps extends InputPropertyMap
> = BaseContext<PieceAuth, TriggerProps> & {
  webhookUrl: string;
  payload: TriggerPayload;
  app: {
    createListeners({
      events,
      identifierValue,
    }: {
      events: string[];
      identifierValue: string;
    }): void;
  };
};

type PollingTriggerHookContext<
  PieceAuth extends PieceAuthProperty | PieceAuthProperty[] | undefined,
  TriggerProps extends InputPropertyMap
> = BaseContext<PieceAuth, TriggerProps> & {
  server: ServerContext;
  setSchedule(schedule: SetScheduleRequest): void;
  isRepublish?: boolean;
};

type WebhookTriggerHookContext<
  PieceAuth extends PieceAuthProperty | PieceAuthProperty[] | undefined,
  TriggerProps extends InputPropertyMap,
> = BaseContext<PieceAuth, TriggerProps> & {
  webhookUrl: string;
  payload: TriggerPayload;
  server: ServerContext;
};
export type TriggerHookContext<
  PieceAuth extends PieceAuthProperty | PieceAuthProperty[] | undefined,
  TriggerProps extends InputPropertyMap,
  S extends TriggerStrategy,
> = S extends TriggerStrategy.APP_WEBHOOK
  ? AppWebhookTriggerHookContext<PieceAuth, TriggerProps>
  : S extends TriggerStrategy.POLLING
  ? PollingTriggerHookContext<PieceAuth, TriggerProps>
  : S extends TriggerStrategy.WEBHOOK
  ? WebhookTriggerHookContext<PieceAuth, TriggerProps> & {
    server: ServerContext;
  }
  : never;

export type TestOrRunHookContext<
  PieceAuth extends PieceAuthProperty | PieceAuthProperty[] | undefined,
  TriggerProps extends InputPropertyMap,
  S extends TriggerStrategy
> = TriggerHookContext<PieceAuth, TriggerProps, S> & {
  files: FilesService;
};

export type StopHookParams = {
  response: RespondResponse;
};

export type RespondHookParams = {
  response: RespondResponse;
};

export type StopHook = (params?: StopHookParams) => void;

export type RespondHook = (params?: RespondHookParams) => void;

/** @deprecated Since 2026-04-12. Use {@link CreateWaitpointHook} and {@link WaitForWaitpointHook} instead. */
export type PauseHookParams = {
  pauseMetadata: PauseMetadata;
};

/** @deprecated Since 2026-04-12. Use {@link CreateWaitpointHook} and {@link WaitForWaitpointHook} instead. */
export type PauseHook = (params: {
  pauseMetadata: Omit<DelayPauseMetadata, 'requestIdToReply'> | Omit<WebhookPauseMetadata, 'requestId' | 'requestIdToReply'>
}) => void;

export type FlowsContext = {
  list(params?: ListFlowsContextParams): Promise<SeekPage<PopulatedFlowSummary>>
  current: {
    id: string;
    version: {
      id: string;
    };
  };
}

export type StepContext = {
  name: string;
}

export type ListFlowsContextParams = {
  externalIds?: string[]
}


export type PropertyContext = {
  server: ServerContext;
  project: {
    id: ProjectId;
    externalId: () => Promise<string | undefined>;
  };
  searchValue?: string;
  flows: FlowsContext;
  connections: ConnectionsManager;
};

export type ServerContext = {
  apiUrl: string;
  publicUrl: string;
  token: string;
};

export type AuthValidationServerContext = Omit<ServerContext, 'token'> & {
  mintOidcToken: (params: { audience: string }) => Promise<string>;
};

export class PieceServerContextError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'PieceServerContextError';
  }
}

export function isPieceServerContextError(error: unknown): error is PieceServerContextError {
  return error instanceof Error && error.name === 'PieceServerContextError';
}

export type CreateWaitpointParams = {
  type: 'DELAY' | 'WEBHOOK';
  version?: 'V0' | 'V1';
  resumeDateTime?: string;
  responseToSend?: RespondResponse;
  maxTestWaitMs?: number;
};

export type CreateWaitpointResult = {
  id: string;
  resumeUrl: string;
  publicResumeUrl?: string;
  buildResumeUrl: (params: { queryParams: Record<string, string>, sync?: boolean }) => string;
};

export type CreateWaitpointHook = (params: CreateWaitpointParams) => Promise<CreateWaitpointResult>;
export type WaitForWaitpointHook = (waitpointId: string) => void;

export type RunContext = {
  id: FlowRunId;
  canPause: boolean;
  stop: StopHook;
  /** @deprecated Use createWaitpoint + waitForWaitpoint instead */
  pause?: PauseHook;
  respond: RespondHook;
  createWaitpoint: CreateWaitpointHook;
  waitForWaitpoint: WaitForWaitpointHook;
}

export type OnStartContext<
  PieceAuth extends PieceAuthProperty | PieceAuthProperty[] | undefined,
  TriggerProps extends InputPropertyMap
> = Omit<BaseContext<PieceAuth, TriggerProps>, 'flows'> & {
  run: Pick<RunContext, 'id'>;
  payload: unknown;
}


export type OutputContext = {
  update: (params: {
    data: {
      [key: string]: unknown;
    };
  }) => Promise<void>;
}

type BaseActionContext<
  ET extends ExecutionType,
  PieceAuth extends PieceAuthProperty | PieceAuthProperty[] | undefined,
  ActionProps extends InputPropertyMap
> = BaseContext<PieceAuth, ActionProps> & {
  executionType: ET;
  tags: TagsManager;
  server: ServerContext;
  files: FilesService;
  output: OutputContext;
  run: RunContext;
  /** @deprecated Use waitpoint.buildResumeUrl() from createWaitpoint result instead */
  generateResumeUrl?: (params: {
    queryParams: Record<string, string>,
    sync?: boolean
  }) => string;
};

type BeginExecutionActionContext<
  PieceAuth extends PieceAuthProperty | PieceAuthProperty[] | undefined = undefined,
  ActionProps extends InputPropertyMap = InputPropertyMap
> = BaseActionContext<ExecutionType.BEGIN, PieceAuth, ActionProps>;

type ResumeExecutionActionContext<
  PieceAuth extends PieceAuthProperty | PieceAuthProperty[] | undefined = undefined,
  ActionProps extends InputPropertyMap = InputPropertyMap
> = BaseActionContext<ExecutionType.RESUME, PieceAuth, ActionProps> & {
  resumePayload: ResumePayload;
};

export type ActionContext<
  PieceAuth extends PieceAuthProperty | PieceAuthProperty[] | undefined = undefined,
  ActionProps extends InputPropertyMap = InputPropertyMap
> =
  | BeginExecutionActionContext<PieceAuth, ActionProps>
  | ResumeExecutionActionContext<PieceAuth, ActionProps>;




export interface FilesService {
  write({
    fileName,
    data,
  }: {
    fileName: string;
    data: Buffer | Readable;
  }): Promise<string>;
  upload({
    fileName,
    data,
  }: {
    fileName: string;
    data: Buffer | Readable;
  }): Promise<UploadedFile>;
}

export type UploadedFile = {
  id: string;
  url: string;
};

export interface ConnectionsManager {
  get(
    key: string
  ): Promise<AppConnectionValue | Record<string, unknown> | string | null>;
}

export interface TagsManager {
  add(params: { name: string }): Promise<void>;
}

export interface Store {
  put<T>(key: string, value: T, scope?: StoreScope): Promise<T>;
  get<T>(key: string, scope?: StoreScope): Promise<T | null>;
  delete(key: string, scope?: StoreScope): Promise<void>;
}

export enum StoreScope {
  // Collection were deprecated in favor of project
  PROJECT = 'COLLECTION',
  FLOW = 'FLOW',
}

export type SetScheduleRequest =
  | { cronExpression: string; timezone?: string }
  | { intervalMs: number };