@fluidframework/common-utils Package

Packages > @fluidframework/common-utils

Classes

List of classes contained in this package or namespace
Class Description
BaseTelemetryNullLogger Null logger It can be used in places where logger instance is required, but events should be not send over.
BatchManager Manages a queue of work to be batch processed at next javascript turn of execution
Buffer Declare the subset of Buffer functionality we want to make available instead of exposing the entirely of Node's typings. This should match the public interface of the browser implementation, so any changes made in one should be made in both.
Deferred A deferred creates a promise and the ability to resolve or reject it
EventForwarder Base class used for forwarding events from a source EventEmitter. This can be useful when all arbitrary listeners need to be removed, but the primary source needs to stay intact.
Heap Ordered Heap data structure implementation
Lazy Helper class for lazy initialized values. Ensures the value is only generated once, and remain immutable
LazyPromise A lazy evaluated promise. The execute function is delayed until the promise is used, e.g. await, then, catch ... The execute function is only called once. All calls are then proxied to the promise returned by the execute method.
PromiseCache A specialized cache for async work, allowing you to safely cache the promised result of some async work without fear of running it multiple times or losing track of errors.
PromiseTimer This class is a wrapper over setTimeout and clearTimeout which makes it simpler to keep track of recurring timeouts with the same handlers and timeouts, while also providing a promise that resolves when it times out.
RangeTracker Helper class that keeps track of the relation between two ranges in a 1:N fashion. Primary is continuous and always maps to a single value in secondary above the base value. The range defines an increasing step function.Used by deli to keep track of the branch map
RateLimiter A rate limiter to make sure that a client can only request help for one task within a time window.
TelemetryNullLogger Null logger It can be used in places where logger instance is required, but events should be not send over.
Timer This class is a thin wrapper over setTimeout and clearTimeout which makes it simpler to keep track of recurring timeouts with the same or similar handlers and timeouts.
Trace Helper class for tracing performance of events Time measurements are in milliseconds as a floating point with a decimal
TypedEventEmitter Event Emitter helper class the supports emitting typed events

Functions

List of functions contained in this package or namespace
Function Description
assert(condition, message) A browser friendly version of the node assert library. Use this instead of the 'assert' package, which has a big impact on bundle sizes.
doIfNotDisposed(disposable, f)
gitHashFile(file) Create a github hash (Github hashes the string with blob and size) Must be called under secure context for browsers
hashFile(file) Hash a file. Consistent within a session, but should not be persisted and is not consistent with git. If called under an insecure context for a browser, an override function needs to be set using setInsecureContextHashFn
safelyParseJSON(json) Wrapper for JSON.parse to translate all exception to return undefined
setInsecureContextHashFn(hashFn) Set a hashing function to be called in place of hashFile's internal implementation when running under insecure contexts. Not needed when running under Node. The internal algorithm should match that the one used internally by hashFile.
stringToBuffer(input, encoding) Convert base64 or utf8 string to array buffer
Uint8ArrayToString(arr, encoding) Converts a Uint8Array to a string of the provided encoding Useful when the array might be an IsoBuffer
unreachableCase(_, message) This function can be used to assert at compile time that a given value has type never. One common usage is in the default case of a switch block, to ensure that all cases are explicitly handled.

Interfaces

List of interfaces contained in this package or namespace
Interface Description
IComparer Interface for a comparere
IHeapNode Interface to a node in Heap
IPromiseTimer Timer which offers a promise that fulfills when the timer completes.
IPromiseTimerResult
IRange A range in the RangeTracker
IRangeTrackerSnapshot A serialized version of the RangeTracker
ITimer
ITraceEvent Event in a performance trace including time elapsed.
PromiseCacheOptions Options for configuring the PromiseCache

Variables

List of variables contained in this package or namespace
Variable Description
bufferToString Convert binary blob to string format
fromBase64ToUtf8
fromUtf8ToBase64
IsoBuffer
NumberComparer A comparer for numbers
performance_2
toUtf8 Convenience function to convert unknown encoding to utf8 that avoids buffer copies/encode ops when no conversion is needed

Type Aliases

List of type aliases contained in this package or namespace
Type Alias Description
EventEmitterEventType
IsoBuffer
IsomorphicPerformance This type contains all browser performance properties as optional, and some of the intersecting properties of node and browser performance as required.
PromiseCacheExpiry Three supported expiry policies: - indefinite: entries don't expire and must be explicitly removed - absolute: entries expire after the given duration in MS, even if accessed multiple times in the mean time - sliding: entries expire after the given duration in MS of inactivity (i.e. get resets the clock)
TypedEventTransform

Functions

assert

A browser friendly version of the node assert library. Use this instead of the ‘assert’ package, which has a big impact on bundle sizes.

Signature:

export declare function assert(condition: boolean, message?: string): asserts condition;

Parameters

List of parameters
Parameter Type Description
condition boolean The condition that should be true, if the condition is false an error will be thrown.
message string The message to include in the error when the condition does not hold

Returns:

asserts condition

doIfNotDisposed

Signature:

export declare function doIfNotDisposed<T>(disposable: IDisposable, f: (...args: any[]) => T): (...args: any[]) => T;

Parameters

List of parameters
Parameter Type Description
disposable IDisposable
f (...args: any[]) => T

Returns:

(…args: any[]) => T

gitHashFile

Create a github hash (Github hashes the string with blob and size) Must be called under secure context for browsers

Signature:

export declare function gitHashFile(file: IsoBuffer): Promise<string>;

Parameters

List of parameters
Parameter Type Description
file IsoBuffer The contents of the file in a buffer

Returns:

Promise<string>

The sha1 hash of the content of the buffer with the blob prefix and size

hashFile

Hash a file. Consistent within a session, but should not be persisted and is not consistent with git. If called under an insecure context for a browser, an override function needs to be set using setInsecureContextHashFn

Signature:

export declare function hashFile(file: IsoBuffer): Promise<string>;

Parameters

List of parameters
Parameter Type Description
file IsoBuffer The contents of the file in a buffer

Returns:

Promise<string>

The hash of the content of the buffer

safelyParseJSON

Wrapper for JSON.parse to translate all exception to return undefined

Signature:

export declare function safelyParseJSON(json: string): any;

Parameters

List of parameters
Parameter Type Description
json string the JSON string to parse

Returns:

any

the result JSON.parse is successful, undefined if exception happens

setInsecureContextHashFn

Set a hashing function to be called in place of hashFile’s internal implementation when running under insecure contexts. Not needed when running under Node. The internal algorithm should match that the one used internally by hashFile.

Signature:

export declare function setInsecureContextHashFn(hashFn: (f: IsoBuffer) => Promise<string>): void;

Parameters

List of parameters
Parameter Type Description
hashFn (f: IsoBuffer) => Promise The function that should be used in place of hashFile

Returns:

void

stringToBuffer

Convert base64 or utf8 string to array buffer

Signature:

export declare function stringToBuffer(input: string, encoding: string): ArrayBufferLike;

Parameters

List of parameters
Parameter Type Description
input string
encoding string

Returns:

ArrayBufferLike

Uint8ArrayToString

Converts a Uint8Array to a string of the provided encoding Useful when the array might be an IsoBuffer

Signature:

export declare function Uint8ArrayToString(arr: Uint8Array, encoding?: string): string;

Parameters

List of parameters
Parameter Type Description
arr Uint8Array The array to convert
encoding string Optional target encoding; only "utf8" and "base64" are supported, with "utf8" being default

Returns:

string

The converted string

unreachableCase

This function can be used to assert at compile time that a given value has type never. One common usage is in the default case of a switch block, to ensure that all cases are explicitly handled.

Signature:

export declare function unreachableCase(_: never, message?: string): never;

Parameters

List of parameters
Parameter Type Description
_ never
message string

Returns:

never

Variables

bufferToString

Convert binary blob to string format

Signature:

bufferToString: (blob: ArrayBuffer | SharedArrayBuffer, encoding: string) => string

fromBase64ToUtf8

Signature:

fromBase64ToUtf8: (input: string) => string

fromUtf8ToBase64

Signature:

fromUtf8ToBase64: (input: string) => string

IsoBuffer

Signature:

IsoBuffer: typeof Buffer

NumberComparer

A comparer for numbers

Signature:

NumberComparer: IComparer<number>

performance_2

Signature:

performance: IsomorphicPerformance

toUtf8

Convenience function to convert unknown encoding to utf8 that avoids buffer copies/encode ops when no conversion is needed

Signature:

toUtf8: (input: string, encoding: string) => string

Type Aliases

EventEmitterEventType

Signature:

export declare type EventEmitterEventType = EventEmitter extends {
    on(event: infer E, listener: any): any;
} ? E : never;

IsoBuffer

Signature:

export declare type IsoBuffer = Buffer;

IsomorphicPerformance

This type contains all browser performance properties as optional, and some of the intersecting properties of node and browser performance as required.

Signature:

export declare type IsomorphicPerformance = Partial<Performance> & Pick<Performance, "clearMarks" | "mark" | "measure" | "now">;

PromiseCacheExpiry

Three supported expiry policies: - indefinite: entries don’t expire and must be explicitly removed - absolute: entries expire after the given duration in MS, even if accessed multiple times in the mean time - sliding: entries expire after the given duration in MS of inactivity (i.e. get resets the clock)

Signature:

export declare type PromiseCacheExpiry = {
    policy: "indefinite";
} | {
    policy: "absolute" | "sliding";
    durationMs: number;
};

TypedEventTransform

Signature:

export declare type TypedEventTransform<TThis, TEvent extends IEvent> = TransformedEvent<TThis, "newListener" | "removeListener", Parameters<(event: string, listener: (...args: any[]) => void) => void>> & IEventTransformer<TThis, TEvent> & TransformedEvent<TThis, EventEmitterEventType, any[]>;