JavaScript testing

Use calmlens/testing to test your JavaScript SDK integration offline, with mock clients, storage, API keys and webhook deliveries. Keep these imports in test files: the main, /server and /app entry points exclude testing utilities from production bundles.

Setup

import { MockCalmLensServerClient, createMockApiKey } from "calmlens/testing";

const client = new MockCalmLensServerClient({
  apiKey: createMockApiKey(),
  projectId: "proj_8fK2mQx7Lp4NvB3tRz9Y",
});

createMockApiKey() mints mock keys locally without contacting CalmLens. projectId is optional on the mock and defaults to project-1.

MockCalmLensServerClient is a CalmLensServerClient, so your code receives the real client. Every method runs the real client's code: options are checked, requests are built and responses and errors are read exactly as against CalmLens. Instead of the network, its requests go to an in-memory CalmLens API and CDN that answer them as CalmLens does, with the same HTTP statuses, response bodies, error bodies and headers. Nothing leaves the process. MockCalmLensAppClient does the same for the app client.

App client

MockCalmLensAppClient takes the app client's options plus mockOptions.server, the MockCalmLensServerClient whose project receives the uploads, and mockOptions.preset, the upload preset rules the in-memory API applies, with the same names as an uploadPresets.ensure definition (access, allowedContentTypes, maxSizeInBytes, visibility, folderId and so on). Read the uploads back through server:

import { MockCalmLensAppClient } from "calmlens/testing";

const app = new MockCalmLensAppClient({
  uploadPresetId: "preset_4Lk8Qw2Xm9Rt5Vb3Nc7P",
  mockOptions: {
    server: client,
    preset: { allowedContentTypes: ["image/*"], maxSizeInBytes: 5_000_000 },
  },
});

const upload = await app.assets.create({
  name: "avatar.png",
  content: { base64: pngBase64, type: "image/png" },
});
const stored = await app.server.assets.retrieve({ assetId: upload.id });

Without mockOptions.server, the app client creates its own server mock, available as app.server. The preset also takes revealDecision and processingOptions, whose features turn on face and person detection for its uploads, and the app client can check and continue only the uploads it made, with the API's error codes. To run the upload widget on it, pass createClient: (options) => new MockCalmLensAppClient({ ...options, mockOptions }).

Options

Configure moderation, deterministic IDs and clocks, and storage with mockOptions:

let nextId = 0;

const client = new MockCalmLensServerClient({
  apiKey: createMockApiKey(),
  projectId: "proj_8fK2mQx7Lp4NvB3tRz9Y",
  mockOptions: {
    // Generate deterministic, unique IDs for snapshot testing
    createId: (prefix) => `${prefix}_${String(++nextId).padStart(20, "0")}`,

    // Fix timestamps for reproducible assertions
    now: () => 1_700_000_000_000,

    // Decides each upload (see "Moderation decisions" below)
    moderate: ({ content }) => (content.text?.includes("spam") ? "blocked" : "allowed"),
  },
});

The mock accepts the same options as CalmLensServerClient (baseUrl, cdnBaseUrl, timeoutMs, maxRetries and so on) and rejects invalid ones the same way. Requests never leave the process, whatever fetch you pass. cdn.getAssetUrl and cdn.signAssetUrl use cdnBaseUrl, which defaults to mock://calmlens/v1.

Keys from createMockApiKey() have no grants. Pass grants to create a key that has them, such as createMockApiKey([{ actions: ["assets:download"], folderId: null, includeSubfolders: true }]), and change them later with client.setApiKeyGrants(grants).

Moderation decisions

mockOptions.moderate decides each asset the mock moderates. It receives:

  • asset: the stored asset, still processing.
  • content: the uploaded bytes, and text for a plain-text upload such as text.classify. Both are null when there is no content, such as for a website.
  • trigger: why the asset is moderated: upload, retry (after assets.retry) or complete (see below).
  • queued: true when CalmLens would queue the work rather than answer with the decision: queued uploads, retries and complete.

It returns a status, pending, failed, allowed, limited, age-restricted, blocked or purged, or a decision built with mockDecision, and may return a promise of either. A failed asset gets classification.failureReason processing-error. Without moderate, queued uploads and retries stay pending and everything else is allowed.

mockDecision(status) builds a decision with findings: flag(category, score, qualifiers?) records a category's score from 0 to 1 and, optionally, its qualifiers' scores, notEvaluated(category) marks a category as not assessed, and pendingReview(reason, uncertainCategories?) leaves the decision waiting for human review (sampled, or uncertain with the categories that made it so), which sets classification.moderation.pendingReview. client.decide clears it, as the review queue does; assets.decide leaves it. A decided asset gets a complete report, as from CalmLens: raw.categories holds every category (unflagged ones evaluated with score 0), categories holds each evaluated category's policy score and action, and flaggedCategories lists the categories the decision acted on (categories scored 0.5 or more, unless the status is allowed). An unknown category or qualifier, or a score outside 0 to 1, throws sdk/invalid-argument.

Use withOcr(text, textRegions?) and withLinkDetection(qrCodes?, links?) on a mock decision to supply findings for an image. The mock reports each result when the corresponding feature is enabled. OCR text appears in content.extractedText when the upload keeps its content.

Use withPersonDetection(people) and withFaceDetection(faces) to supply the people and faces an image holds, in the API's shape ({ box, confidence }, and an optional ageRange for a face). The mock reports them when the upload turns person or face detection on, with a face's ageRange only when it also turns on ageEstimation. Without them, the mock reports no people or faces.

import { MockCalmLensServerClient, createMockApiKey, mockDecision } from "calmlens/testing";

const client = new MockCalmLensServerClient({
  apiKey: createMockApiKey(),
  projectId: "proj_8fK2mQx7Lp4NvB3tRz9Y",
  mockOptions: {
    moderate: ({ content }) =>
      content.text?.includes("kill")
        ? mockDecision("blocked").flag("violence", 0.92, { "violence-threat": 0.9 })
        : "allowed",
  },
});

const comment = await client.text.classify({ text: "I will kill you" });
const violence = comment.classification.moderation.raw?.categories.violence;
expect(violence).toMatchObject({ status: "evaluated", score: 0.92 });
expect(comment.classification.moderation.flaggedCategories).toEqual(["violence"]);

A moderate function decides queued uploads straight away too. Return pending for them (queued && trigger === "upload") to finish them later.

Finish processing

client.completeProcessing(assetId, decision?) finishes processing a pending asset as CalmLens would, with the decision you pass or else the one moderate returns for the complete trigger (allowed by default). It fails with 404 asset/not-found for an unknown asset and sdk/invalid-argument for an asset that isn't processing:

const upload = await client.assets.create({
  name: "photo.png",
  content: { base64: pngBase64, type: "image/png" },
}); // pending

await client.completeProcessing(upload.id, mockDecision("age-restricted").flag("sexual", 0.8));
const decided = await client.assets.waitForDecision({ assetId: upload.id });
expect(decided.classification.moderation.decision).toBe("age-restricted");

Storage

client.databaseStorage and client.imageStorage hold the mock's records and uploaded bytes. Use them in assertions to verify saved records without extra API calls:

// Inspect database records directly
const asset = await client.databaseStorage.getAsset(createdAsset.id);
const allAssets = await client.databaseStorage.listAssets(projectId);

const folder = await client.databaseStorage.getFolder(createdFolder.id);
const allFolders = await client.databaseStorage.listFolders(projectId);

// Inspect raw binary upload content and multipart parts
const storedContent = await client.imageStorage.getContent(createdAsset.id);
console.log(storedContent?.type); // "image/png"
console.log(storedContent?.parts.get(1)); // Uint8Array of bytes

To track method calls or simulate storage failures, pass your own implementations of MockDatabaseStorage or MockImageStorage. Extending the in-memory stores lets you override one method:

import {
  MockCalmLensServerClient,
  InMemoryMockDatabaseStorage,
  InMemoryMockImageStorage,
  createMockApiKey,
} from "calmlens/testing";

class FailingDatabaseStorage extends InMemoryMockDatabaseStorage {
  override async getAsset(): Promise<undefined> {
    throw new Error("Database unavailable");
  }
}

const databaseStorage = new FailingDatabaseStorage();
const imageStorage = new InMemoryMockImageStorage();

const client = new MockCalmLensServerClient({
  apiKey: createMockApiKey(),
  projectId: "proj_8fK2mQx7Lp4NvB3tRz9Y",
  mockOptions: { databaseStorage, imageStorage },
});

What the mock simulates

The in-memory API reproduces CalmLens where tests usually depend on it. It doesn't classify content: decisions come from your moderate option.

  • Errors carry the API's code, HTTP status, details, a requestId and response headers, so error.isNotFound() and status checks work as they do against CalmLens. Options the real client refuses before sending, such as a missing asset name, fail the same way without a request.
  • assets.list applies sort and filter, including folderId==, like the API: the documented asset fields with ==, !=, >, >=, <, <=, =in= and =out=, joined by ; (and), which binds tighter than , (or), and grouped with parentheses, as in (name==a.png,name==b.png);type==image. * in an == or != value matches any run of characters, ignoring case. Any other field or operator, such as =like= or =gt=, fails with 400 filter/invalid, and a sort with an unknown or repeated field, or more than two fields, fails with 400 validation/invalid-request (issue validation/invalid-value at path sort). Its cursors resume after the last asset returned, so assets created or deleted between pages are neither repeated nor skipped. Iterating assets.list pages through the results.
  • folders.list, hashLists.list, hashLists.listEntries, policies.list and lenses.list return cursor pages like the API, which you can iterate: folders by name unless sort says otherwise, hash lists, entries and lenses newest first, policies oldest first.
  • The project starts on the organisation's own General policy, live on preset release 1. The mock's presets define every category with its default action, allow for personal information and profanity and block otherwise, and no rules; uploads are decided by moderate, never by a policy. Settings that leave out a category, or a category's action, allowances or restrictions, fail with 400 validation/invalid-request whose issue names the first missing path, such as settings.categorySettings.hate.
  • lenses.create with an identifier the project already uses fails with 409 lens/identifier-taken, and an unknown lens ID with 404 lens/not-found.
  • assets.search runs the API's keyword search: every word of the query must appear, in any case, in the asset's name, ID, external ID, description, tags, type, content format or extension, or moderation status. Results have the API's keyword scores and matchedFields, best match first, then newest first. There is no semantic search, so semanticStatus is disabled.
  • Assets created one after another get increasing createdAt values, so sorting by createdAt is predictable. Pass mockOptions.now to control the clock.
  • A second asset with the same externalId fails with 409 asset/duplicate-external-id.
  • New objects get IDs like the API's: the kind's prefix, an underscore and 20 random base62 characters, such as asset_e5Gm2Rk8XqT3wLp9VbN4. mockOptions.createId receives the prefix (asset, fldr, hl, hle, lens, evt or rev).
  • Unset asset fields are null, as the API returns them. Out-of-range pageSize values and search queries fail with 400 validation/invalid-request, whose issue is validation/too-small or validation/too-big.
  • Multipart parts must arrive in order (409 upload-part/invalid-number with details.expectedPartNumber), every part but the last is at least 5 MiB, images total at most 20 MiB, and parts add up to any declared totalSizeInBytes. The wait choice made at the start applies to the final part unless assets.uploadPart overrides it, and parts after it fail with 409 upload/not-open.
  • Content is removed with reason retention once processing finishes when retention is off; an automated purged outcome removes it with reason policy, and assets.removeContent and a reviewer's purge with reason requested.
  • Uploads, assets.decide, hashLists.addEntry and assets.requestReview honour an idempotencyKey, as CalmLens does: reusing it returns the first response, with its status; reusing it for a different request fails with 409 idempotency/key-reused, and a request that failed frees its key. Other requests ignore it.
  • The mock's API key has the ID MOCK_API_KEY_ID (exported from calmlens/testing), so the events its requests record have that actor.id, and its assets.decide reviews that decidedBy.id.
  • assets.retrieveByExternalId finds the asset with that externalId. assets.requestReview queues a review with the reason reported and its note, sets the asset's classification.moderation.pendingReview and records asset.review-requested. While a review is waiting, it returns that review with HTTP 200. It refuses an asset that isn't decided yet, or whose content is purged or removed, with 409 asset/not-reviewable and its details.reason, as CalmLens does. client.decide settles the review, so the asset can be reported again.
  • A decided image's content.perceptualHash is the SHA-256 of its bytes, standing in for its image hash, so hashLists.addEntry({ assetId }) works. An image with exactly the bytes of a hash list entry's image matches it: classification.moderation.raw.hashMatches lists the match with its list's action, and a block list blocks the image with source hash-list and records asset.hash-matched. Similar but different images never match in the mock.
  • By default, assets.waitForDecision takes no real time. It returns a completed or failed asset and returns sdk/timeout for one that stays queued or processing. Set mockOptions.useTimers: true to test polling or retry delays with fake timers.
  • Every upload adds asset.uploaded to the events feed, then asset.classified and the automated asset.<status> (whose actor is automated) once it is decided, or asset.failed. assets.retry, assets.removeContent and assets.delete add asset.retried, asset.content-removed and asset.deleted.
  • client.serveUrl(url, { content, type }) gives a URL content, bytes or a string, and a content type. A URL upload of it stores the content, passes it to moderate and takes its type from the content type, as an upload of those bytes would; text/html is a website.
  • Other URL uploads take their type from the file extension of the URL's path, ignoring case, the query and the fragment, since the mock fetches nothing: image for jpg, jpeg, png, gif, webp, avif, heic, heif, bmp, tif, tiff and svg; video for mp4, m4v, mov, webm, mkv and avi; audio for mp3, m4a, aac, wav, ogg, oga, opus and flac; multimedia-document for pdf, doc, docx, odt, ppt, pptx, odp and rtf; and plaintext-document for txt and md. Any other extension, such as html, or none gives a website.

CDN serving and access control

cdn.serve and cdn.getAssetInfo requests are answered by the in-memory CDN, which serves the stored bytes and each asset's info, names assets by ID or ext: external ID, and checks access control like CalmLens. client.fetchCdn(url, init?) fetches one of its URLs as a browser would, without the API key, such as a signed asset URL with a resource appended. Like the CDN, it returns Content-Type, Content-Length and X-Request-Id headers, an ETag for images, and Cache-Control as the CDN sets it (public files use public, max-age=86400, must-revalidate, unsigned private files use private, no-cache, signed files expire with the grant or after one day, and embed pages and requests with viewer claims use private, no-store), or a JSON error body:

  • A private asset fetched without a grant or the API key, as a browser would with client.fetchCdn, returns 404 with 404 asset/not-found whatever its state, like an unknown asset.
  • Assets whose content was removed return 404 with 404 asset/not-found to everyone, as an unknown asset does, on every resource but /info. For the API key, blocked, purged and failed assets return 403 with 403 asset/not-available.
  • For the API key, private assets then return 403 with 403 auth/permission-denied unless the key has assets:download for the asset's folder.
  • Signed asset URLs work until they expire, then return 403 with 403 signed-url/expired; /original under a URL not signed for it returns 403 with 403 signed-url/original-not-granted.
  • Age-restricted assets require viewerClaims.ageConfirmed: true, including requests using signed URLs or API keys; otherwise delivery returns 403 with 403 viewer/age-confirmation-required.
  • Unknown assets return 404 with 404 asset/not-found.
  • A classified image’s placeholder resource is a PNG. A public asset's placeholder is served to anyone whatever its decision, blocked included, so a page can show it in the asset's place; a private asset's requires a signed URL or download permission. Purged assets and assets with removed content have no placeholder.

Responses also carry Cache-Tag and the CDN's protection headers, and images an Expires header.

// Public assets can be served directly
const publicAsset = await client.assets.create({
  name: "public.png",
  content: { base64: pngBase64, type: "image/png" },
  visibility: "public",
});

const response = await client.cdn.serve({ assetId: publicAsset.id });
expect(response.status).toBe(200);

// A key without assets:download cannot read private assets directly
const privateAsset = await client.assets.create({
  name: "secret.png",
  content: { base64: pngBase64, type: "image/png" },
  visibility: "private",
});

const privateResponse = await client.cdn.serve({ assetId: privateAsset.id });
expect(privateResponse.status).toBe(403);

// A signed asset URL serves it to a browser without the key
const { url } = await client.cdn.signAssetUrl({ assetId: privateAsset.id });
const signedResponse = await client.fetchCdn(`${url}/rendered`);
expect(signedResponse.status).toBe(200);

Events and reviewer decisions

Besides the events the mock records itself, add events with client.enqueueEvent, which resolves to the stored event. An event about a stored asset carries the asset as it is, as from CalmLens. An asset.<status> event carries the moderation status it announces, as CalmLens sends it once the asset has that status. Read them with a cursor as you would from the API:

const { nextCursor: cursor } = await client.events.list(); // a cursor for "now"
await client.enqueueEvent({ type: "asset.allowed", assetId: asset.id });

const page = await client.events.list({ cursor });
expect(page.items.map((event) => event.type)).toEqual(["asset.allowed"]);

client.decide(assetId, decision) applies a reviewer's decision (allowed, limited, age-restricted, blocked or purged) to a stored asset: its moderation status changes, purged also removes the content, and an asset.<decision> event whose actor is a user joins the feed:

await client.decide(asset.id, "blocked");
const { items } = await client.events.list({ cursor });
expect(items.at(-1)).toMatchObject({ type: "asset.blocked", assetId: asset.id });

client.decide is a test hook for a reviewer's decision: it applies any decision, records the review without a note and adds the event; pending and failed are not decisions and throw sdk/invalid-argument. To finish processing as CalmLens's moderation would, use completeProcessing. assets.decide, the client method your code calls, is checked like the API: it fails with 409 asset/decision-not-allowed when an asset pending moderation is allowed, limited or age-restricted, 409 asset/decision-unchanged when the status would not change, 409 asset/content-purged when purged content is anything but blocked, and 409 asset/processing while an upload is still open or processing, such as a queued upload still pending. It records the note with the reviewer name An API key.

Recorded requests and failures

Every request the client sends is recorded in client.calls, oldest first, as { operation, method, url, path, query, headers, body, status }:

  • operation is the client method that sends the request, such as "assets.retrieve", "events.list" or "cdn.serve". A request that several methods send is recorded under the underlying one, such as a waitForDecision poll as "assets.retrieve". A text upload is recorded as "text.classify", and a file or URL upload as "assets.classify".
  • path is relative to the API or CDN base URL, so it leaves out /v1, with each segment decoded, such as /assets/<id>. query holds the query parameters as sent.
  • body is the parsed JSON body, the text of a text upload or the bytes of a file upload.
  • status is the HTTP status the in-memory API answered with, or undefined for a request that failed without a response.

client.callsTo(operation) returns the requests one method sent. A request that several methods send matches each of them: assets.waitForDecision polls with assets.retrieve, ensureLens sends ensureLenses, and the iterators send list requests. Methods that send nothing are not recorded, such as uploadTokens.sign, which signs locally, or an ensureLens answered from the client's lens cache:

await client.text.classify({ text: "hello", externalId: "comment-1" });

expect(client.callsTo("text.classify")).toEqual([
  expect.objectContaining({
    method: "POST",
    query: expect.objectContaining({ externalId: "comment-1", wait: "true" }),
    body: "hello",
    status: 200,
  }),
]);

client.clearCalls() forgets the requests recorded so far.

client.failNextRequest() makes the next request fail as if the network had failed, so the client throws the CalmLensError that CalmLensServerClient throws when a request cannot complete (code: "sdk/transport-error", with the network error as cause). It also takes:

ArgumentFailure
"timeout"sdk/timeout
An API error code, such as "usage/free-uploads-exhausted"That error and its HTTP status
A CalmLensErrorThrown as is
Another Errorsdk/transport-error, with it as the cause

{ operation } limits the failure to the next request that method sends, and { times } fails that many requests instead of one, so a retry takes the same failure again until it is used up. client.failRequests(failure, options) fails every matching request until client.clearFailures(), which also drops queued failures. For an API error, details sets the error's details and retryAfter answers with a Retry-After of that many seconds, so you can test code that reads error.details or error.retryAfter; they don't apply to transport errors or timeouts, and an operation the client doesn't have throws sdk/invalid-argument. Both classify methods upload, but a failure for one never fails the other: a text upload is text.classify's request, and a file or URL upload assets.classify's. Failures queue in order, and each request takes the oldest one that matches it; once used up, a retry takes the next queued failure or reaches the in-memory API:

client.failNextRequest("timeout", { operation: "text.classify" });

await expect(client.text.classify({ text: "hello" })).rejects.toMatchObject({
  code: "sdk/timeout",
});
await expect(client.text.classify({ text: "hello" })).resolves.toMatchObject({
  classification: { moderation: { decision: "allowed" } },
});
client.failNextRequest("upload/rate-limit-reached", { retryAfter: 30 });
await expect(client.assets.list()).rejects.toMatchObject({ status: 429, retryAfter: 30 });
client.failRequests("server/internal-error", { operation: "assets.retrieve" });
await expect(client.assets.retrieve({ assetId })).rejects.toMatchObject({ status: 500 });
client.clearFailures();

The mock's maxRetries defaults to 0, unlike the real client, so a failed request fails once; set it to test how your code handles retries. Retry backoff and deadlineMs run on the mock's clock, which only its waits move, so they take no real time.

Webhook handlers

toWebhookEventPayload turns an event into a delivery body, and createWebhookHeaders signs it the way CalmLens does, so your handler's parseWebhookEvent or verifyWebhookSignature call runs unchanged:

import { createWebhookHeaders, toWebhookEventPayload } from "calmlens/testing";

const event = await client.enqueueEvent({ type: "asset.allowed", assetId: asset.id });
const body = JSON.stringify(toWebhookEventPayload(event));
const headers = await createWebhookHeaders({ secret, body, deliveryId: "dlv_3Vm8Qk2Xt7Lp9Rb4Nw6C" });
const response = await handler(new Request("http://localhost/webhooks", { method: "POST", body, headers }));

createWebhookHeaders uses the current time unless you pass timestampSeconds. To build only the x-calmlens-signature value, call createWebhookSignatureHeader(secret, timestamp, body).

Upload tokens

signUploadToken(apiKey, options, { now, nonce }) from calmlens/testing signs an upload token like uploadTokens.sign at a fixed time (epoch milliseconds) and nonce, checking options the same way, so tests can compare exact tokens. The mock's own uploadTokens.sign signs at mockOptions.now with a random nonce.

Generate test inputs

Use these helpers to generate authenticated text, PNG and media inputs for a project. They come from calmlens/test-inputs and need your project's secret test input key (under Project settings → Processing → Test inputs in the portal). Presets use the same editable instance format as the test input builder. generateMediaTestCode(signal, testInputKey) builds audio and video test codes.

CalmLens recognises a text code only when it is the whole text you submit (surrounding whitespace aside), and a test image only when it is the whole upload. A code inside other text, or a test image drawn into a larger picture, is moderated as ordinary content.

import { generateTestTextCode, paintTestImage, TEST_INPUT_PRESETS, type TestInput } from "calmlens/test-inputs";

const testInputKey = process.env.CALMLENS_TEST_INPUT_KEY!;
const input: TestInput = structuredClone(TEST_INPUT_PRESETS.mixed);
input.instances = input.instances.map((instance) => ({ ...instance, action: "limit" }));
input.instances.push({ category: "harassment", qualifiers: ["harassment-abuse"], action: "block" });
const text = await generateTestTextCode(input, testInputKey);
const { width, height, rgba } = await paintTestImage(input, testInputKey);
// Encode these RGBA pixels as a lossless PNG using the returned dimensions.

detectTestTrigger(text, testInputKey) and detectTestImage({ width, height, rgba }, testInputKey) read a code or image back, the way CalmLens recognises one. They return the scenario, or undefined for anything CalmLens would moderate as ordinary content.

Set action on every instance to choose its outcome independently of the project policy. Actions are limit, age-restrict and block; the strongest wins, and an instance can never allow its content. The image and text code carry identical outcomes. Omit every instance action when testing the normal policy resolver instead. Do not mix the two forms.

For delivery testing without category evidence, set explicit regional actions:

const regionalInput: TestInput = {
  instances: [],
  regionalActions: [
    { region: "DE", action: "block" },
    { region: "GB", action: "age-restrict" },
    { region: "FR", action: "limit" },
  ],
};
const regionalText = await generateTestTextCode(regionalInput, testInputKey);
const regionalImage = await paintTestImage(regionalInput, testInputKey);

Every project serves these jurisdictions; an EU outcome applies unless the project turned the EU standard off. These restrictions apply to the matching viewer region and cannot soften a stricter base decision or jurisdiction rule. See regional outcome testing for CDN requests and expected results. The regionalDelivery preset supplies this same example.

Last updated

Cookies on CalmLens

We use essential cookies for sign-in and security. With your permission, functional cookies remember your preferences and Google Analytics measures website use and signups. Optional ad measurement cookies link Google ad clicks to signups. Personalised advertising stays off. Manage cookies