UNPKG

flareutils

Version:

Small utilities and little goodies that make developing with Cloudflare easier and faster.

570 lines (557 loc) 26.3 kB
/** * Supported seed types for Isaac. */ type IsaacSeed = string | number | number[]; /** * Cryptographically-secure random number generator. Based on the [ISAAC algorithm](http://burtleburtle.net/bob/rand/isaac.html) by [Bob Jenkins](http://burtleburtle.net/bob/), and the JS implementation by [Yves-Marie K. Rinquin](https://github.com/rubycon). Backed by [crypto.getRandomValues](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues), and the [DRAND](https://drand.love) network. */ declare class Isaac { private readonly runs; private m; private acc; private brs; private cnt; private r; private gnt; /** * This promise represents whether the seeding process has been completed. It is recommended that you create the Isaac object as early as possible, do other tasks as needed, and then *await* the promise afterward to ensure that the seeding process has completed. If it is *false*, then the seeding process has completed, and no *await* is necessary. */ seeding: Promise<void> | false; /** * Creates a new Isaac CSPRNG. Note that you must await `seeding` before using the generator. * @param {IsaacSeed} seed Seed to be fed into the generator. * @param {number} runs Number of times to re-run the generator. * @constructor */ constructor(seed: IsaacSeed, runs?: number); /** * Batch-generates 256 random numbers, and stores them in the number buffer. * @private */ private prng; /** * Shuffles the given array with the seed array, to ensure even mix. * @param {number[]} arr Array filled with mixed numbers * @param {number[]} s The seed, as an array of numbers * @returns {number[]} The mixed array * @private */ private superShuffle; /** * Resets the internal state of the generator. * @private */ private reset; /** * Seeds the generator. Note that you must await `seeding` before using the generator, if not manually seeded and awaited. * @param {IsaacSeed} seed Seed to be fed into the generator * @returns {Promise<void>} Promise that resolves when the generator has been seeded * @async * @example ```ts * await isaac.seed(seed); * ``` */ seed(seed: IsaacSeed): Promise<void>; /** * Returns a pre-generated random number from the number buffer. * @returns {number} A random number between 0 and 1 * @example ```ts * const num = isaac.rand(); * ``` */ rand(): number; } declare type RandNum = () => number; declare type RandLetter = () => string; /** * Generator that generates random phonetic strings. Cryptographic security is dependent on the random number generator that is passed in. */ declare class Phonetic { /** * Random number generator used by Phonetic. Must generate numbers from 0 to 1. */ private readonly generator; /** * Returns a random vowel. */ private readonly vowel; /** * Returns a random consonant. */ private readonly consonant; /** * Creates a new Phonetic generator. * @param {RandNum} rand Random Number Generator. While it is recommended to use a cryptographically secure random number generator(a la. [Isaac](/classes/Isaac)), this is not required. * @constructor */ constructor(rand: RandNum); /** * Generates a random phonetic string. * @param {number} length Length of the string to generate. * @returns {string} Random phonetic string. * @example * const phonetic = phonetic.rand(10); */ rand(len?: number): string; } type BetterKVGetReturns<V = unknown> = string | V | ArrayBuffer | ReadableStream; type BetterKVPutValues = string | ArrayBuffer | ArrayBufferView | ReadableStream; type BetterKVCacheStatus = "HIT" | "MISS" | "REVALIDATED"; interface BetterKVWithMetadata$1<V, M> { value: V; metadata: M | null; cacheStatus: BetterKVCacheStatus; } interface BetterKVPutOptions$1<Metadata = unknown> { expiration?: number; expirationTtl?: number; metadata?: Metadata; } type BetterKVListReturns<Metadata = unknown> = KVNamespaceListResult<Metadata> & { cacheStatus: BetterKVCacheStatus; }; interface BetterKVConfig { /** * The name utilized to create a dedicated cache for this BetterKV instance. If you have multiple instances of BetterKV running in parallel, make sure each has their own unique cacheSpace. */ cacheSpace: string | undefined; /** * The rate at which the probability of BetterKV refetching a cached value increases. Default is 1.28 times per second. * @warning Only modify this value if you know what you're doing. */ probabilityGrowth: number; /** * Time to Live for the fronting Cache. Default is 55 seconds. * @warning Only modify this value if you know what you're doing. */ cacheTtl: number; /** * Time to Live for the back-end KV Cache. Default is 1 year. * @note This value should be greater than the cacheTtl. * @warning Only modify this value if you know what you're doing. */ kvCacheTtl: number; } type BetterKVValueOptions$1 = string | ArrayBuffer | ArrayBufferView | ReadableStream; declare interface BetterKVTypedGetOptions<L extends string> { type: L; cacheTtl?: number; } declare interface BetterKVGetOptions { type?: BetterKVTypeOptions; cacheTtl?: number; } declare interface BetterKVWithMetadata<V, M> { value: V | null; metadata: M | null; cacheStatus: BetterKVCacheStatus; } declare interface BetterKVPutOptions<K = unknown> { expiration?: number; expirationTtl?: number; metadata?: K | null; cacheTtl?: number; } declare interface BetterKVListOptions extends KVNamespaceListOptions { cacheTtl?: number; } declare type BetterKVTypeOptions = "text" | "json" | "arrayBuffer" | "stream"; declare type BetterKVValueOptions = string | ArrayBuffer | ArrayBufferView | ReadableStream; /** * A Storage namespace that uses the Cloudflare Workers [KV API](https://developers.cloudflare.com/workers/runtime-apis/kv) to store data, with a [Cache API](https://developers.cloudflare.com/workers/runtime-apis/cache) backing that allows you to reduce your KV billable reads. * * For the most part, *BetterKV* should match to the Workers *KVNamespace* standard, other than how it is instantiated, and all methods(except delete) support cacheTtl. For the *KVNamespace* API, see the [types](https://github.com/cloudflare/workers-types) supplied by Cloudflare. * * @note This version of BetterKV is provided for backwards compatibility with KV v1. For projects using KV v2, use the regular `BetterKV` import. */ declare class BetterKVOld { /** * Base URL used by BetterKV in Cache Operations. */ private readonly url; /** * Root KV instance utilized by BetterKV. */ private readonly kv; /** * Utilized to ensure that any operations performed on the cache do not block the main thread. */ private waitUntil; /** * The name utilized to create a dedicated cache for this BetterKV instance. If you have multiple instances of BetterKV running in parallel, make sure each has their own unique cacheSpace. */ private readonly cacheSpace; /** * Cache instance utilized by BetterKV. */ private cache; /** * Creates a new BetterKV instance. * @param {KVNamespace} kv The KV Namespace to use as the primary data store. * @param {ExecutionContext["waitUntil"]} waitUntil The waitUntil function used to asyncronously update the cache. Must be passed in before executing any other methods on every new request. * @param {string} cacheSpace The name utilized to create a dedicated cache for this BetterKV instance. If you have multiple instances of BetterKV running in parallel, make sure each has their own unique cacheSpace. * @example ```ts * const NAMESPACE = new BetterKV(env.KV, "BetterKVNamespace"); * ``` */ constructor(kv: KVNamespace, waitUntil: ExecutionContext["waitUntil"], cacheSpace?: string); /** * Retrieves the cache instance utilized by BetterKV. Ensures that the cache is only opened once, and can be shared across multiple runs of BetterKV. If no cacheSpace is provided, the default cache is used. * @private */ getCache(): Promise<Cache>; /** * Used to update the waitUntil function to the ExecutionContext of the currently executing request. Should be passed in before executing any other methods on every new request. * @param {ExecutionContext["waitUntil"]} waitUntil The waitUntil function used to asyncronously update the cache. */ setWaitUntil(waitUntil: ExecutionContext["waitUntil"]): void; get(key: string, options: BetterKVGetOptions): Promise<string | null>; get(key: string, options: BetterKVTypedGetOptions<"text">): Promise<string | null>; get(key: string, options: BetterKVTypedGetOptions<"arrayBuffer">): Promise<ArrayBuffer | null>; get(key: string, options: BetterKVTypedGetOptions<"stream">): Promise<ReadableStream | null>; get<V = unknown>(key: string, options: BetterKVTypedGetOptions<"json">): Promise<V | null>; getWithMetadata<M = unknown>(key: string, options: BetterKVGetOptions): Promise<BetterKVWithMetadata<string, M> | null>; getWithMetadata<M = unknown>(key: string, options: BetterKVTypedGetOptions<"text">): Promise<BetterKVWithMetadata<string, M> | null>; getWithMetadata<M = unknown>(key: string, options: BetterKVTypedGetOptions<"arrayBuffer">): Promise<BetterKVWithMetadata<ArrayBuffer, M> | null>; getWithMetadata<M = unknown>(key: string, options: BetterKVTypedGetOptions<"stream">): Promise<BetterKVWithMetadata<ReadableStream, M> | null>; getWithMetadata<V = unknown, M = unknown>(key: string, options: BetterKVTypedGetOptions<"json">): Promise<BetterKVWithMetadata<V, M> | null>; /** * Adds a new value to the BetterKV Namespace. Supports CacheTtl. * @param {string} key The key to add. * @param {BetterKVValueOptions} val The value to add. Type is inferred from the value. * @param {BetterKVAddOptions} options Options for the addition. * @example ```ts * await NAMESPACE.put(key, value); * ``` */ put<M = unknown>(key: string, val: BetterKVValueOptions, options?: BetterKVPutOptions<M>): Promise<void>; /** * Removes a value from the BetterKV Namespace. * @param {string} key The key to remove. * @example ```ts * await NAMESPACE.delete(key); * ``` */ delete(key: string): Promise<void>; /** * Lists keys in the BetterKV Namespace according to the options given. Supports CacheTtl. * @template M The type of the metadata. * @param {BetterKVListOptions} [options] Options for the listing. * @returns {Promise<BetterKVListReturns<M>>} The keys in the namespace, and their associated metadata(if any). * @example ```ts * const {keys, list_complete, cursor} = await NAMESPACE.list(); * ``` */ list<M = unknown>(opts?: BetterKVListOptions): Promise<BetterKVListReturns<M>>; } /** * A Storage namespace that uses the Cloudflare Workers [KV API](https://developers.cloudflare.com/workers/runtime-apis/kv) to store data, with a [Cache API](https://developers.cloudflare.com/workers/runtime-apis/cache) backing that allows you to reduce your KV billable reads. * * For the most part, *BetterKV* should match to the Workers *KVNamespace* standard, other than how it is instantiated, and all methods(except delete) will be cached according to the configured `cacheTtl`. For the *KVNamespace* API, see the [types](https://github.com/cloudflare/workers-types) supplied by Cloudflare. * * @note This version of BetterKV supports KV v2. If you require support for KV v1, please import `BetterKVOld`. */ declare class BetterKV { /** * Base URL used by BetterKV in Cache Operations. * @private */ private readonly URL; /** * Root KV instance utilized by BetterKV. * @private */ private readonly KV; /** * Utilized to ensure that any operations performed on the cache do not block the main thread. * @private */ private waitUntil; /** * The name utilized to create a dedicated cache for this BetterKV instance. If you have multiple instances of BetterKV running in parallel, make sure each has their own unique cacheSpace. * @private */ private readonly config; /** * Cache instance utilized by BetterKV. * @private */ private cache; /** * Creates a new BetterKV instance. * @param {KVNamespace} KV The KV Namespace to use as the primary data store. * @param {ExecutionContext["waitUntil"]} waitUntil The waitUntil function used to asyncronously update the cache. Must be passed in before executing any other methods on every new request. * @param {BetterKVConfig} config Configuration for the BetterKV instance. * @example ```ts * const NAMESPACE = new BetterKV(env.KV, ctx.waitUntil); * ``` */ constructor(KV: KVNamespace, waitUntil: ExecutionContext["waitUntil"], config?: Partial<BetterKVConfig>); /** * Retrieves the cache instance utilized by BetterKV. Ensures that the cache is only opened once, and can be shared across multiple runs of BetterKV. If no cacheSpace is provided, the default cache is used. * @private */ private getCache; /** * Used to update the waitUntil function to the ExecutionContext of the currently executing request. Should be passed in before executing any other methods on every new request. * @param {ExecutionContext["waitUntil"]} waitUntil The waitUntil function used to asyncronously update the cache. */ setWaitUntil(waitUntil: ExecutionContext["waitUntil"]): void; /** * Function to handle all GET-ops hitting origin KV. Should not be called manually. * @param {string} key The key to retrieve. * @private */ private getFromOrigin; /** * Retrieves a value from the BetterKV Namespace. * @template JSONValue The type of the value. Only used if using the "json" type. * @param {string} key The key to retrieve. * @param {BetterKVTypeOptions} type Type of value to retrieve. * @returns {Promise<BetterKVGetReturns | null>} The value of the key, or null if the key does not exist. * @example ```ts * const value = await NAMESPACE.get(key); * ``` */ get(key: string, type?: "text"): Promise<string | null>; get(key: string, type: "arrayBuffer"): Promise<ArrayBuffer | null>; get(key: string, type: "stream"): Promise<ReadableStream | null>; get<JSONValue = unknown>(key: string, type: "json"): Promise<JSONValue | null>; /** * Retrieves a value from the BetterKV Namespace, and its associated metadata, if provided. * @template JSONValue The type of the value. Only used if using the "json" type. * @template Metadata The type of the metadata. * @param {string} key The key to retrieve. * @param {BetterKVTypeOptions} type Type of value to retrieve. * @returns {Promise<BetterKVWithMetadata<BetterKVGetReturns, M> | null>} The value of the key, and its associated metadata(if any), or null if the key does not exist. */ getWithMetadata<Metadata = unknown>(key: string, type?: "text"): Promise<BetterKVWithMetadata$1<string, Metadata> | null>; getWithMetadata<Metadata = unknown>(key: string, type: "arrayBuffer"): Promise<BetterKVWithMetadata$1<ArrayBuffer, Metadata> | null>; getWithMetadata<Metadata = unknown>(key: string, type: "stream"): Promise<BetterKVWithMetadata$1<ReadableStream, Metadata> | null>; getWithMetadata<JSONValue = unknown, Metadata = unknown>(key: string, type: "json"): Promise<BetterKVWithMetadata$1<JSONValue, Metadata> | null>; /** * Adds a new value to the BetterKV Namespace. Supports CacheTtl. * @param {string} key The key to add. * @param {BetterKVValueOptions} val The value to add. Type is inferred from the value. * @param {BetterKVAddOptions} options Options for the addition. * @example ```ts * await NAMESPACE.put(key, value); * ``` */ put<Metadata = unknown>(key: string, val: BetterKVPutValues, options?: BetterKVPutOptions$1<Metadata>): Promise<void>; /** * Removes a value from the BetterKV Namespace. * @param {string} key The key to remove. * @example ```ts * await NAMESPACE.delete(key); * ``` */ delete(key: string): Promise<void>; /** * Lists keys in the BetterKV Namespace according to the options given. Supports CacheTtl. * @template M The type of the metadata. * @param {KVNamespaceListOptions} [opts] Options for the listing. * @returns {Promise<BetterKVListReturns<M>>} The keys in the namespace, and their associated metadata(if any). * @example ```ts * const {keys, list_complete, cursor} = await NAMESPACE.list(); * ``` */ list<M = unknown>(opts?: KVNamespaceListOptions): Promise<BetterKVListReturns<M>>; } type ReplaceFunction<Environment = unknown, Optionals = unknown> = (e: Element, optionals?: TransformationOptionals<Environment, Optionals>) => Promise<string> | string; type SelectorType = "tagName" | "className" | "id" | "attribute" | "universal"; interface AddOptions<Environment, Optionals> { replacerFunction?: ReplaceFunction<Environment, Optionals>; selectorType?: SelectorType; attributeValue?: string; removeSelector?: boolean; } interface Replacer<Environment, Optionals> { type: SelectorType; attributeValue?: string; delete?: boolean; replacerFunction?: ReplaceFunction<Environment, Optionals>; isHTML?: boolean; removeSelector?: boolean; } interface TransformationOptionals<Environment = unknown, Optionals = unknown> { env?: Environment; req?: Request; other?: Optionals; } /** * Simple Workers-native templating engine. Utilizes the [*HTMLRewriter*](http://developers.cloudflare.com/workers/runtime-apis/html-rewriter) API, allowing templating operations to be streamed to the user, rather than being a blocking process. While it is not required, it is recommended that any resulting HTML be cached before being returned. * @template Environment The Environment object, provided by the Workers Runtime. * @template Optional Optional parameters, provided to your replacer function. */ declare class Temra<Environment = unknown, Optionals = unknown> { /** * Default Prefix used for tag names. */ private readonly tagPrefix; /** * Whether comments should be removed. */ private readonly deleteComments; /** * Replacers applied to your HTML. */ private replacers; /** * Initializes a new Temra instance. * @param {string} prefix Default Prefix used for tag names. For example, if the prefix is "Temra", then the tag name "TemraName" will be read as "Name". * @param {boolean} deleteComments Whether comments should be removed. */ constructor(prefix?: string, deleteComments?: boolean); /** * Add a replacer to the Temra instance. * @param {string} selector Selector used to find elements. * @param {AddOptions} options Options used to configure the replacer. * @returns {Temra} Returns the Temra instance, for chaining. * @example ```ts * temra.add("username", () => "Jay Doe", {removeSelector: true}); * ``` */ add(selector: string, options: AddOptions<Environment, Optionals>): this; /** * Applies the currently added replacer functions to the provided HTML. * @param {Response} body HTML response that will be transformed. * @param {TransformationOptionals<E, O>} [optionals] Optional parameters to pass to the replacer function. * @returns Response * @example ```ts * return temra.transform(await fetch(req), {req, env}); * ``` */ transform(body: Response, optionals?: TransformationOptionals<Environment, Optionals>): Response; } declare interface MailChannelsEmailAddress { email: string; name?: string; } declare interface MailChannelsBodyObjects { type: string; value: string; } declare interface MailChannelsHeaders { [key: string]: string; } declare interface MailChannelsPersonalizations { to: MailChannelsEmailAddress[]; from: MailChannelsEmailAddress; reply_to: MailChannelsEmailAddress; cc?: MailChannelsEmailAddress[]; bcc?: MailChannelsEmailAddress[]; subject?: string; dkim_domain?: string; dkim_private_key?: string; dkim_selector?: string; headers?: MailChannelsHeaders; } declare interface MailChannelsOptions { personalizations?: MailChannelsPersonalizations; from: MailChannelsEmailAddress; reply_to?: MailChannelsEmailAddress; subject?: string; content?: MailChannelsBodyObjects[]; headers?: MailChannelsHeaders; } /** * Helper to quickly send emails with the MailChannels API. * @note This helper function performs no verification of your inputs, and should only be used for utilizing types with MailChannels. * @param {MailChannelsOptions} opts Options that the MailChannels API may accept when sending an email. * @returns {Promise<Response>} Response from the MailChannels API. * @example ```ts * await sendMail({from: {email: "user@example.com"}, content: [{type: "text/plain", value: "Hello, world!"}]}); * ``` */ declare function sendMail(opts: MailChannelsOptions): Promise<Response>; /** * Stores Durable Object Stubs in Memory, allowing faster recall. Utilizes KV and Unique DO IDs to reduce time to stub return, due to not necessitating global DO availability checks. */ declare class Stubby { /** * Durable Object Namespace, to which the stubs pertain. */ private readonly ns; /** * KV Namespace used to globally cache DO Stub IDs. */ private readonly kv; /** * Used to ensure Cache Operations are executed while not blocking script execution. */ private readonly waitUntil; /** * Prefix used in KV operations, allows for multiple projects to share one KV namespace. Should be unique. */ private readonly prefix; /** * In memory DO Stub Cache. */ private readonly stubMap; /** * Constructs a Stubby Instance. * @param {DurableObjectNamespace} ns Durable Object Namespace utilized for stubs. * @param {KVNamespace} kv KV Namespace used to store raw DO IDs. * @param {ExecutionContext["waitUntil"]} waitUntil Used to unblock thread, ensuring KV writes are completed without pausing execution of the rest of the script. * @param {string} prefix Used to prefix KV writes, allowing multiple systems to share one KV namespaces without collisions. */ constructor(ns: DurableObjectNamespace, kv: KVNamespace, waitUntil: ExecutionContext["waitUntil"], prefix?: string); /** * Returns a stub from memory or KV, or generates a new stub if not available. Caches returned stubs to ensure quickest recall. * @param {string} key Used to identify stub for retrieval or creation. * @param {string} [locationHint] Used to hint at the location of the stub, allowing for faster stub creation. Available hints are available on the [DO Docs](https://developers.cloudflare.com/workers/runtime-apis/durable-objects/#providing-a-location-hint). * @returns {Promise<DurableObjectStub>} */ get(key: string, locationHint?: DurableObjectLocationHint): Promise<DurableObjectStub>; /** * Removes a singular stub from local and KV storage. Note that this operation is irreversable, and stubs will not be recoverable unless stored elsewhere. * @param {string} key Used to identify stub to remove. * @returns {Promise<void>} */ remove(key: string): Promise<void>; /** * Clears all stubs belonging to this Stubby instance. * @returns {Promise<void>} */ clearAll(): Promise<void>; } /** * A queue that runs a maximum of 6 promises at a time, to stay within Workers' concurrent I/O limit. */ declare class PromiseQueue { private queue; constructor(); /** * Add a promise to the queue. Always await this function. * @param promise The promise to add to the queue. */ add(promise: Promise<unknown>): Promise<void>; /** * Flush the queue. Always await this function. * @note Run this function when all tasks have been added to the queue. */ flush(): Promise<void>; } declare const inputFormats: string[]; type StreamOrBuffer = ReadableStream | ArrayBuffer; interface ResizerConfig<T extends "stream" | "buffer" = "stream"> { contentType: (typeof inputFormats)[number]; transformOpts: Omit<RequestInitCfPropertiesImage, "origin-auth">; storage: { bucket: R2Bucket; url: string; prefix?: string; }; returnType: T; } /** * Resizes an image using Image Resizing. * @note Requires manual setup. See https://flareutils.pages.dev/resizer/ * @param image ReadableStream or ArrayBuffer * @param config ResizerConfig * @returns Resized image as ReadableStream or ArrayBuffer */ declare function resizeImage(image: StreamOrBuffer, config: ResizerConfig<"buffer">): Promise<ArrayBuffer>; declare function resizeImage(image: StreamOrBuffer, config: ResizerConfig<"stream">): Promise<ReadableStream>; export { type AddOptions, BetterKV, type BetterKVCacheStatus, type BetterKVConfig, type BetterKVGetReturns, type BetterKVListReturns, BetterKVOld, type BetterKVPutOptions$1 as BetterKVPutOptions, type BetterKVPutValues, type BetterKVValueOptions$1 as BetterKVValueOptions, type BetterKVWithMetadata$1 as BetterKVWithMetadata, Isaac, type MailChannelsBodyObjects, type MailChannelsEmailAddress, type MailChannelsHeaders, type MailChannelsOptions, type MailChannelsPersonalizations, Phonetic, PromiseQueue, type RandLetter, type RandNum, type ReplaceFunction, type Replacer, type ResizerConfig, type SelectorType, Stubby, Temra, type TransformationOptionals, resizeImage, sendMail };