CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-jupyterlab--nbformat

Notebook format interfaces and utilities for working with Jupyter Notebook format specifications

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

mime-validation.mddocs/

MIME and Validation

MIME bundle interfaces and validation functions for handling multimedia content in notebook cells, ensuring data integrity and format compliance with nbformat specifications.

Capabilities

MIME Bundle Interface

Interface for representing multimedia content with MIME type keys.

/**
 * A mime-type keyed dictionary of data for multimedia content
 */
interface IMimeBundle extends PartialJSONObject {
  /** MIME type mapped to content data */
  [key: string]: MultilineString | PartialJSONObject;
}

Usage Example:

import { IMimeBundle, MultilineString } from "@jupyterlab/nbformat";

// Rich display data with multiple MIME types
const richOutput: IMimeBundle = {
  'text/plain': 'A simple plot',
  'text/html': '<div>Interactive plot here</div>',
  'image/png': 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==',
  'application/json': {
    'data': [1, 2, 3, 4, 5],
    'labels': ['A', 'B', 'C', 'D', 'E']
  }
};

// Text content as array of lines
const multilineContent: IMimeBundle = {
  'text/plain': [
    'Line 1 of output',
    'Line 2 of output', 
    'Line 3 of output'
  ]
};

Attachments Interface

Interface for media attachments in cells, such as inline images.

/**
 * Media attachments (e.g. inline images) keyed by attachment name
 */
interface IAttachments {
  /** Attachment name mapped to MIME bundle data */
  [key: string]: IMimeBundle | undefined;
}

Usage Example:

import { IAttachments, IMimeBundle } from "@jupyterlab/nbformat";

const attachments: IAttachments = {
  'logo.png': {
    'image/png': 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=='
  },
  'chart.svg': {
    'image/svg+xml': '<svg width="100" height="100"><circle cx="50" cy="50" r="40"/></svg>'
  }
};

MIME Validation Function

Function to validate MIME type and value pairs for data integrity.

/**
 * Validate a mime type/value pair for format compliance
 * 
 * @param type - The mimetype name (e.g., 'text/plain', 'application/json')
 * @param value - The value associated with the type
 * @returns Whether the type/value pair are valid according to nbformat rules
 */
function validateMimeValue(
  type: string,
  value: MultilineString | PartialJSONObject
): boolean;

Usage Examples:

import { validateMimeValue } from "@jupyterlab/nbformat";

// Valid cases
console.log(validateMimeValue('text/plain', 'Hello world')); // true
console.log(validateMimeValue('text/plain', ['Line 1', 'Line 2'])); // true
console.log(validateMimeValue('application/json', { key: 'value' })); // true
console.log(validateMimeValue('application/vnd.custom+json', { data: 123 })); // true

// Invalid cases
console.log(validateMimeValue('application/json', 'string data')); // false - JSON type with string
console.log(validateMimeValue('text/plain', { key: 'value' })); // false - text type with object
console.log(validateMimeValue('application/json', ['array', 'data'])); // false - JSON type with array

// Validation logic
function isValidMimeBundle(bundle: IMimeBundle): boolean {
  return Object.entries(bundle).every(([mimeType, value]) => 
    validateMimeValue(mimeType, value)
  );
}

// Practical usage in output processing
function sanitizeDisplayData(data: IMimeBundle): IMimeBundle {
  const sanitized: IMimeBundle = {};
  
  Object.entries(data).forEach(([mimeType, value]) => {
    if (validateMimeValue(mimeType, value)) {
      sanitized[mimeType] = value;
    } else {
      console.warn(`Invalid MIME data for type ${mimeType}, skipping`);
    }
  });
  
  return sanitized;
}

Validation Rules

The validateMimeValue function enforces the following rules:

  1. JSON MIME types (application/json, application/*+json):

    • Must have object values (not strings or arrays)
    • Value must be a valid JSON object structure
  2. Text MIME types (everything else):

    • Can have string values or string arrays
    • Cannot have object values
  3. Array validation:

    • Only allowed for non-JSON MIME types
    • All array elements must be strings

Advanced Validation Example:

import { validateMimeValue, IMimeBundle } from "@jupyterlab/nbformat";

class MimeValidator {
  /**
   * Validate an entire MIME bundle
   */
  static validateBundle(bundle: IMimeBundle): { valid: boolean; errors: string[] } {
    const errors: string[] = [];
    
    Object.entries(bundle).forEach(([mimeType, value]) => {
      if (!validateMimeValue(mimeType, value)) {
        errors.push(`Invalid value for MIME type '${mimeType}'`);
      }
    });
    
    return {
      valid: errors.length === 0,
      errors
    };
  }
  
  /**
   * Get the preferred MIME type from a bundle
   */
  static getPreferredMimeType(bundle: IMimeBundle): string | null {
    const preferenceOrder = [
      'application/json',
      'text/html', 
      'image/png',
      'image/jpeg',
      'text/plain'
    ];
    
    for (const mimeType of preferenceOrder) {
      if (mimeType in bundle && validateMimeValue(mimeType, bundle[mimeType])) {
        return mimeType;
      }
    }
    
    // Fallback to first valid MIME type
    const validTypes = Object.keys(bundle).filter(type => 
      validateMimeValue(type, bundle[type])
    );
    
    return validTypes.length > 0 ? validTypes[0] : null;
  }
}

Types

/**
 * A multiline string that can be a single string or array of strings
 */
type MultilineString = string | string[];

docs

cell-interfaces.md

index.md

mime-validation.md

notebook-metadata.md

output-interfaces.md

tile.json