import { Client } from "@notionhq/client"; import type { ClientOptions } from "@notionhq/client/build/src/Client.js"; export type CapabilityContext = { /** Notion API SDK client for this execution. */ notion: Client; }; const LOCAL_FIX_STEPS = "\n\nFor local execution:\n" + "1. Create a personal access token at https://app.notion.com/developers/tokens\n" + "2. Add NOTION_API_TOKEN= to your .env file\n\n" + "Deployed apps receive Notion API credentials automatically. Do not push NOTION_API_TOKEN."; function missingTokenMessage(): string { if (process.env.NOTION_WORKFLOW_STEP_DIRECTORY) { return ( "Notion API access is not configured for this deployed workflow. " + "In Notion, open Developer Tools → Workers, select this workflow, and grant access to the pages or databases it uses. " + "The runtime provides NOTION_API_TOKEN automatically after access is configured; do not set or push it yourself." ); } return ( "NOTION_API_TOKEN is not set. " + "context.notion requires an API token when an app capability runs locally." + LOCAL_FIX_STEPS ); } function createUnauthenticatedNotionProxy(): Client { return new Proxy({} as Client, { get(_target, prop) { if (prop === "then" || typeof prop === "symbol") { return undefined; } throw new Error(missingTokenMessage()); }, }); } export function createCapabilityContext(): CapabilityContext { const options: ClientOptions = {}; if (process.env.NOTION_API_BASE_URL) { options.baseUrl = process.env.NOTION_API_BASE_URL; } if (!process.env.NOTION_API_TOKEN) { return { notion: createUnauthenticatedNotionProxy() }; } options.auth = process.env.NOTION_API_TOKEN; const notion = new Client(options); return { notion }; }