Collection of utility functions for Fluid Framework including async operations, data structures, performance monitoring, and cross-platform compatibility.
npx @tessl/cli install tessl/npm-fluidframework--common-utils@3.1.0The Fluid Framework Common Utils package provides a comprehensive collection of utility functions and classes specifically designed for the Fluid Framework ecosystem. This package includes essential utilities for cross-platform development, async operations, data structures, performance monitoring, and event handling that enable consistent behavior across all Fluid Framework components.
npm install @fluidframework/common-utilsimport {
assert,
delay,
Deferred,
TypedEventEmitter,
Timer,
Heap,
PromiseCache
} from "@fluidframework/common-utils";For CommonJS:
const {
assert,
delay,
Deferred,
TypedEventEmitter,
Timer,
Heap,
PromiseCache
} = require("@fluidframework/common-utils");import {
assert,
delay,
Deferred,
TypedEventEmitter,
Timer,
Heap
} from "@fluidframework/common-utils";
// Basic assertion
assert(someCondition, "Condition must be true");
// Async delay
await delay(1000); // Wait 1 second
// Deferred promise
const deferred = new Deferred<string>();
setTimeout(() => deferred.resolve("Hello"), 100);
const result = await deferred.promise;
// Typed event emitter
class MyEmitter extends TypedEventEmitter<{
data: (value: string) => void;
error: (error: Error) => void;
}> {}
const emitter = new MyEmitter();
emitter.on("data", (value) => console.log(value));
emitter.emit("data", "Hello World");
// Timer with long timeout support
const timer = new Timer(5000, () => console.log("Timer fired"));
timer.start();
// Heap data structure
const heap = new Heap<number>();
heap.add(5);
heap.add(2);
heap.add(8);
console.log(heap.get()); // Gets minimum: 2The Fluid Framework Common Utils package is organized around several key architectural patterns:
Essential assertion utilities and type safety helpers for runtime validation and exhaustiveness checking.
function assert(condition: any, message?: string | number): asserts condition;
function unreachableCase(x: never): never;Cross-platform buffer manipulation utilities with separate optimized implementations for Node.js and Browser environments.
interface IsoBuffer extends Uint8Array {
toString(encoding?: "utf8" | "base64"): string;
static from(data: string | ArrayBufferLike, encoding?: "utf8" | "base64"): IsoBuffer;
}
// Node.js only - not available in browser builds
class Buffer extends Uint8Array {
static from(data: string | ArrayBufferLike, encoding?: BufferEncoding): Buffer;
static alloc(size: number, fill?: string | Buffer | Uint8Array | number): Buffer;
toString(encoding?: BufferEncoding): string;
}
function Uint8ArrayToString(arr: Uint8Array, encoding: "utf8" | "base64"): string;
function stringToBuffer(str: string, encoding?: "utf8" | "base64"): ArrayBuffer;
function bufferToString(buffer: ArrayBufferLike, encoding?: "utf8" | "base64"): string;
function Uint8ArrayToArrayBuffer(array: Uint8Array): ArrayBuffer;
function isArrayBuffer(value: any): value is ArrayBuffer; // Browser only - not available in Node.js buildsBase64 encoding utilities and file hashing functions with platform-specific optimizations.
function fromBase64ToUtf8(str: string): string;
function fromUtf8ToBase64(str: string): string;
function toUtf8(str: string, encoding?: string): string;
function hashFile(file: ArrayBufferLike, algorithm?: "SHA-1" | "SHA-256"): Promise<string>;
function gitHashFile(file: ArrayBufferLike): Promise<string>;Comprehensive async utilities including promises, delays, timers, and promise caching with expiration support.
function delay(timeMs: number): Promise<void>;
class Deferred<T> {
readonly promise: Promise<T>;
readonly isCompleted: boolean;
resolve(value: T): void;
reject(reason?: any): void;
}
class LazyPromise<T> implements Promise<T> {
constructor(executor: () => Promise<T>);
}
class PromiseCache<TKey, TResult> {
constructor(options?: PromiseCacheOptions);
has(key: TKey): boolean;
get(key: TKey): Promise<TResult> | undefined;
remove(key: TKey): boolean;
add(key: TKey, asyncWorkFn: () => Promise<TResult>): boolean;
addOrGet(key: TKey, asyncWorkFn: () => Promise<TResult>): Promise<TResult>;
addValue(key: TKey, value: TResult): boolean;
addValueOrGet(key: TKey, value: TResult): Promise<TResult>;
}
function setLongTimeout(
timeoutFn: () => void,
timeoutMs: number,
setTimeoutIdFn?: (timeoutId: ReturnType<typeof setTimeout>) => void
): ReturnType<typeof setTimeout>;
interface ITimer {
readonly hasTimer: boolean;
start(): void;
clear(): void;
}
interface IPromiseTimerResult {
timerResult: "timeout" | "cancel";
}
interface IPromiseTimer extends ITimer {
start(): Promise<IPromiseTimerResult>;
}
class Timer implements ITimer {
constructor(defaultTimeout: number, defaultHandler: () => void, getCurrentTick?: () => number);
readonly hasTimer: boolean;
start(ms?: number, handler?: () => void): void;
clear(): void;
restart(ms?: number, handler?: () => void): void;
}
class PromiseTimer implements IPromiseTimer {
constructor(defaultTimeout: number, defaultHandler: () => void);
readonly hasTimer: boolean;
start(ms?: number, handler?: () => void): Promise<IPromiseTimerResult>;
clear(): void;
}Efficient data structures including priority heaps and range tracking utilities.
interface IComparer<T> {
min: T;
compare(a: T, b: T): number;
}
class Heap<T> {
constructor(comp: IComparer<T>);
get(): T;
peek(): IHeapNode<T>;
add(value: T): IHeapNode<T>;
update(node: IHeapNode<T>): void;
remove(node: IHeapNode<T>): void;
count(): number;
}
class RangeTracker {
add(primaryStart: number, primaryEnd: number, secondaryStart: number): void;
get(primaryPosition: number, primaryEnd?: number): IRange | undefined;
}Type-safe event emitters and event forwarding utilities for building reactive systems.
class TypedEventEmitter<TEvents> implements IEventProvider<TEvents> {
on<K extends keyof TEvents>(event: K, listener: TEvents[K]): this;
off<K extends keyof TEvents>(event: K, listener: TEvents[K]): this;
emit<K extends keyof TEvents>(event: K, ...args: Parameters<TEvents[K]>): boolean;
}
class EventForwarder<TEvents> extends TypedEventEmitter<TEvents> implements IDisposable {
constructor(from: IEventProvider<TEvents>, to?: IEventProvider<TEvents>);
readonly disposed: boolean;
dispose(): void;
}Performance measurement and tracing utilities for monitoring application performance.
interface IsomorphicPerformance {
now(): number;
mark(name: string): void;
measure(name: string, startMark?: string, endMark?: string): void;
clearMarks(name?: string): void;
}
class Trace {
static start(): Trace;
trace(): ITraceEvent;
}
interface ITraceEvent {
totalTimeElapsed: number;
duration: number;
tick: number;
}Collection of utility functions for common programming tasks including lazy initialization, disposal patterns, rate limiting, and safe JSON parsing.
class Lazy<T> {
constructor(valueGenerator: () => T);
get evaluated(): boolean;
get value(): T;
}
function doIfNotDisposed<TDisposable extends IDisposable>(
disposable: TDisposable
): <TArgs extends any[], TReturn>(
fn: (this: TDisposable, ...args: TArgs) => TReturn
) => (...args: TArgs) => TReturn;
class RateLimiter {
constructor(maxCount: number, windowSizeInMs: number);
filter<T>(items: T[]): T[];
}
function safelyParseJSON(json: string): any;This package provides platform-optimized implementations:
crypto.subtle for hashing and requestIdleCallback for task schedulingMany APIs in this package are marked as deprecated and have been moved to more specialized packages:
@fluidframework/core-utils@fluidframework-internal/client-utils@fluidframework/telemetry-utilsConsult the API documentation for migration guidance for specific functions.