CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-notion-types

TypeScript types for core Notion data structures.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

api.mddocs/

API Types

Type definitions for Notion API requests, responses, search operations, and aggregate data structures including RecordMaps and ExtendedRecordMaps.

Capabilities

Record Maps

Core data structures for Notion API responses that aggregate related data with permission information.

/**
 * Generic wrapper for Notion data with role permissions
 */
interface NotionMap<T> {
  [key: string]: {
    /** User's role/permission for this item */
    role: Role;
    /** The actual data item */
    value: T;
  };
}

/**
 * Specific map types for different data categories
 */
type BlockMap = NotionMap<Block>;
type UserMap = NotionMap<User>;
type CollectionMap = NotionMap<Collection>;
type CollectionViewMap = NotionMap<CollectionView>;

/**
 * Map of property values
 */
interface PropertyMap {
  [key: string]: Decoration[];
}

/**
 * Core data structure for Notion API responses
 */
interface RecordMap {
  /** Block data (required) */
  block: BlockMap;
  /** Collection data (optional) */
  collection?: CollectionMap;
  /** Collection view data (optional) */
  collection_view?: CollectionViewMap;
  /** User data (optional) */
  notion_user?: UserMap;
}

/**
 * Enhanced record map with convenience data
 */
interface ExtendedRecordMap extends RecordMap {
  /** Collection data (required) */
  collection: CollectionMap;
  /** Collection view data (required) */
  collection_view: CollectionViewMap;
  /** User data (required) */
  notion_user: UserMap;
  /** Collection query results */
  collection_query: {
    [collectionId: string]: {
      [collectionViewId: string]: CollectionQueryResult;
    };
  };
  /** Signed URLs for file access */
  signed_urls: {
    [blockId: string]: string;
  };
  /** Optional preview images */
  preview_images?: PreviewImageMap;
}

API Request Types

/**
 * Generic interface for API result sets
 */
interface RecordValues<T> {
  /** Array of result items */
  results: T[];
}

/**
 * Parameters for search operations
 */
interface SearchParams {
  /** ID of ancestor block to search within */
  ancestorId: string;
  /** Search query string */
  query: string;
  /** Optional search filters */
  filters?: {
    isDeletedOnly: boolean;
    excludeTemplates: boolean;
    isNavigableOnly: boolean;
    requireEditPermissions: boolean;
  };
  /** Optional result limit */
  limit?: number;
  /** Optional session ID */
  searchSessionId?: string;
}

API Response Types

/**
 * Search operation results
 */
interface SearchResults {
  /** Map of retrieved records */
  recordMap: RecordMap;
  /** Array of search result items */
  results: SearchResult[];
  /** Total number of results */
  total: number;
}

/**
 * Individual search result item
 */
interface SearchResult {
  /** Result item ID */
  id: string;
  /** Whether item can be navigated to */
  isNavigable: boolean;
  /** Search relevance score */
  score: number;
  /** Highlighted text snippets */
  highlight: {
    pathText: string;
    text: string;
  };
}

/**
 * API error response structure
 */
interface APIError {
  /** Unique error identifier */
  errorId: string;
  /** Error name/type */
  name: string;
  /** Human-readable error message */
  message: string;
}

Collection Query Results

/**
 * Page data chunk from API
 */
interface PageChunk {
  /** Page record data */
  recordMap: RecordMap;
  /** Pagination cursor */
  cursor: {
    stack: any[];
  };
}

/**
 * Collection data with query results
 */
interface CollectionInstance {
  /** Collection record data */
  recordMap: RecordMap;
  /** Query execution results */
  result: CollectionQueryResult;
}

/**
 * Results from collection query
 */
interface CollectionQueryResult {
  /** View type that generated results */
  type: CollectionViewType;
  /** Total number of results */
  total: number;
  /** Array of result block IDs */
  blockIds: string[];
  /** Aggregation computation results */
  aggregationResults: Array<AggregationResult>;
  /** Board view grouping results (optional) */
  groupResults?: Array<{
    value: AggregationResult;
    blockIds: string[];
    total: number;
    aggregationResult: AggregationResult;
  }>;
  /** Collection grouping results (optional) */
  collection_group_results?: {
    type: string;
    blockIds: string[];
    hasMore: boolean;
  };
  /** Reducer view results (optional) */
  reducerResults?: {
    collection_group_results: {
      type: string;
      blockIds: string[];
      hasMore: boolean;
    };
  };
  /** Associated collection IDs (optional) */
  collectionIds?: string[];
  /** Embedded record map (optional) */
  recordMap?: ExtendedRecordMap;
}

/**
 * Result of aggregation function
 */
interface AggregationResult {
  /** Property type being aggregated */
  type: PropertyType;
  /** Aggregated value */
  value: any;
}

Utility Types

/**
 * Map of page data
 */
interface PageMap {
  [pageId: string]: ExtendedRecordMap | null;
}

/**
 * Preview image metadata
 */
interface PreviewImage {
  /** Original image width */
  originalWidth: number;
  /** Original image height */
  originalHeight: number;
  /** Base64 data URI of preview */
  dataURIBase64: string;
}

/**
 * Map of preview images
 */
interface PreviewImageMap {
  [url: string]: PreviewImage | null;
}

Usage Examples:

import { 
  RecordMap,
  ExtendedRecordMap,
  SearchParams,
  SearchResults,
  CollectionQueryResult,
  PageChunk,
  NotionMap 
} from "notion-types";

// Create search parameters
const searchParams: SearchParams = {
  ancestorId: "page-123",
  query: "project management",
  filters: {
    isDeletedOnly: false,
    excludeTemplates: true,
    isNavigableOnly: true,
    requireEditPermissions: false
  },
  limit: 20
};

// Process search results
function processSearchResults(results: SearchResults) {
  console.log(`Found ${results.total} results`);
  
  results.results.forEach(result => {
    console.log(`${result.id}: ${result.highlight.text} (score: ${result.score})`);
  });
  
  // Access the record map
  const blocks = Object.keys(results.recordMap.block);
  console.log(`Retrieved ${blocks.length} blocks`);
}

// Work with RecordMap
function processRecordMap(recordMap: RecordMap) {
  // Process blocks
  Object.entries(recordMap.block).forEach(([blockId, blockData]) => {
    console.log(`Block ${blockId} (role: ${blockData.role})`);
    console.log(`Type: ${blockData.value.type}`);
  });
  
  // Process collections if present
  if (recordMap.collection) {
    Object.entries(recordMap.collection).forEach(([collectionId, collectionData]) => {
      console.log(`Collection ${collectionId}: ${collectionData.value.name}`);
    });
  }
  
  // Process users if present
  if (recordMap.notion_user) {
    Object.entries(recordMap.notion_user).forEach(([userId, userData]) => {
      console.log(`User ${userId}: ${userData.value.given_name} ${userData.value.family_name}`);
    });
  }
}

// Create an extended record map
const extendedRecordMap: ExtendedRecordMap = {
  block: {},
  collection: {},
  collection_view: {},
  notion_user: {},
  collection_query: {
    "collection-123": {
      "view-456": {
        type: "table",
        total: 10,
        blockIds: ["block-1", "block-2", "block-3"],
        aggregationResults: []
      }
    }
  },
  signed_urls: {
    "image-block-789": "https://signed-url.example.com/image.png"
  }
};

// Process collection query results
function processCollectionQuery(result: CollectionQueryResult) {
  console.log(`Query returned ${result.total} items of type ${result.type}`);
  
  result.blockIds.forEach(blockId => {
    console.log(`Result block: ${blockId}`);
  });
  
  if (result.groupResults) {
    result.groupResults.forEach(group => {
      console.log(`Group has ${group.blockIds.length} items`);
    });
  }
}

// Handle API errors
function handleAPIError(error: APIError) {
  console.error(`API Error [${error.errorId}]: ${error.name}`);
  console.error(`Message: ${error.message}`);
}

// Type-safe access to NotionMap
function getBlockFromMap(blockMap: BlockMap, blockId: string): Block | null {
  const blockData = blockMap[blockId];
  return blockData ? blockData.value : null;
}

// Check user permissions
function hasEditPermission(blockMap: BlockMap, blockId: string): boolean {
  const blockData = blockMap[blockId];
  return blockData ? blockData.role === 'editor' : false;
}

Install with Tessl CLI

npx tessl i tessl/npm-notion-types

docs

api.md

blocks.md

collection-views.md

collections.md

formatting.md

formulas.md

index.md

users.md

tile.json