Migrating from jmap-jam
json-meta-client is the successor to jmap-jam. This guide shows each part of jmap-jam 0.13 next to its json-meta-client 1.0 equivalent.
Installing
json-meta-client needs Node.js 22 or later, and TypeScript 5.4 or later.
npm remove jmap-jam
npm add json-meta-clientCreating a client
The client is a named export. auth replaces bearerToken, and capabilities lists the entities the client can call. List "mail", "submission", and "vacationResponse" to match jmap-jam.
import JamClient from "jmap-jam";
const jam = new JamClient({
sessionUrl: "https://jmap.example.com/.well-known/jmap",
bearerToken: "<token>",
});import { JsonMetaClient } from "json-meta-client";
new JsonMetaClient({
sessionUrl: "https://jmap.example.com/.well-known/jmap",
auth: "<token>",
capabilities: ["mail", "submission", "vacationResponse"],
});auth also takes Basic credentials or a callback. See auth and Capabilities.
Custom capabilities
defineCapability() replaces customCapabilities. Add withMethods() to type the methods. See Extending.
const jam = new JamClient({
sessionUrl: "https://jmap.example.com/.well-known/jmap",
bearerToken: "<token>",
customCapabilities: {
Note: "urn:example:notes",
},
});import { defineCapability } from "json-meta-client";
const notes = defineCapability({
urn: "urn:example:notes",
entities: ["Note"],
});
const notesClient = new JsonMetaClient({
sessionUrl: "https://jmap.example.com/.well-known/jmap",
auth: "<token>",
capabilities: ["mail", notes],
});Results and account IDs
A call resolves to its data, not a [data, meta] tuple. The client fills in accountId from the primary account of the method's capability. See Account IDs.
Plain requests
Call the method on client.api instead of request().
Several calls in one request
Calls made together are batched into one request, so requestMany() isn't needed. resultRef() replaces $ref(). See Batching.
const [{ emails }] = await jam.requestMany((t) => {
const emailIds = t.Email.query({
accountId,
filter: { inMailbox: "<inboxId>" },
limit: 10,
});
const emails = t.Email.get({
accountId,
ids: emailIds.$ref("/ids"),
properties: ["subject"],
});
return { emailIds, emails };
});To await several results, use Promise.all:
const [{ inboxes, identities }] = await jam.requestMany(
(t) => ({
inboxes: t.Mailbox.query({
accountId,
filter: { role: "inbox" },
}),
identities: t.Identity.get({ accountId }),
}),
);Method call IDs
The client generates method call IDs. Pass id to choose one.
Creation references
createdRef() replaces hand-written "#id" strings, and checks the ID against the keys of create. Make the calls that use it in the same batch. See Creation references.
await jam.requestMany((t) => ({
draft: t.Email.set({
accountId,
create: {
hello: {
mailboxIds: { [draftsId]: true },
subject: "Hello",
},
},
}),
send: t.EmailSubmission.set({
accountId,
create: {
send: { emailId: "#hello", identityId },
},
}),
}));Updates
As in JMAP, a plain object in update replaces the whole property. To change only some keys, wrap them in patch(). The client builds and escapes the JSON Pointer paths. See Patch updates.
await jam.api.Email.set({
accountId,
update: {
[emailId]: {
[`mailboxIds/${archiveId}`]: true,
[`mailboxIds/${inboxId}`]: null,
"keywords/$seen": true,
},
},
});Paths written by hand are now typed. A path built from a variable is typed as string, so build it with patchMap():
Request options
Options apply to the whole client, through hooks:
beforeFetchreplacesfetchInit.beforeJmapRequestcan addcreatedIds.- For
using, list the URN in a capability'sdependsOn.
await jam.api.Mailbox.get(
{ accountId },
{
fetchInit: { headers: { "X-Trace": "<traceId>" } },
createdIds: {},
},
);new JsonMetaClient({
sessionUrl: "https://jmap.example.com/.well-known/jmap",
auth: "<token>",
capabilities: ["mail"],
hooks: {
beforeFetch: [
({ httpRequest }) => {
httpRequest.headers.set("X-Trace", "<traceId>");
return httpRequest;
},
],
beforeJmapRequest: [
({ jmapRequest }) => ({ ...jmapRequest, createdIds: {} }),
],
},
});Response metadata
Read what meta held in the afterJmapResponse and afterFetch hooks.
const [, meta] = await jam.api.Mailbox.get({ accountId });
console.log(meta.sessionState, meta.createdIds);
console.log(meta.response.status);new JsonMetaClient({
sessionUrl: "https://jmap.example.com/.well-known/jmap",
auth: "<token>",
capabilities: ["mail"],
hooks: {
afterJmapResponse: [
({ jmapResponse }) => {
console.log(
jmapResponse.sessionState,
jmapResponse.createdIds,
);
return jmapResponse;
},
],
afterFetch: [
({ httpResponse }) => {
console.log(httpResponse.status);
return httpResponse;
},
],
},
});Errors
The client throws Error subclasses instead of plain problem details. Only the failed call rejects, and the rest of its batch resolves. See Errors.
try {
await jam.api.Email.query({ accountId, sort });
} catch (error) {
if (JamClient.isProblemDetails(error)) {
console.error(error.type);
}
}Session
The client loads the session on first use and caches it. refreshSession() replaces JamClient.loadSession(), and updates the cache.
const session = await jam.session;
const accountId = await jam.getPrimaryAccount();
const fresh = await JamClient.loadSession(
sessionUrl,
authHeader,
);Blobs
Blob transfers are on client.blob, and still require accountId. type and name replace mimeType and fileName. See Blobs.
const uploaded = await jam.uploadBlob(accountId, file);
const response = await jam.downloadBlob({
accountId,
blobId: uploaded.blobId,
mimeType: "text/plain",
fileName: "notes.txt",
});Events
onStateChange() replaces connectEventSource(). The handler gets one change per type and account. The client reads the stream with fetch, so auth applies to each connection, and it reconnects on its own. See Events.
const sse = await jam.connectEventSource({
types: ["Email"],
ping: 30,
closeafter: "no",
});
sse.addEventListener("state", (event) => {
const { changed } = JSON.parse(event.data);
// { [accountId]: { [type]: state } }
});The client subscribes to every type, so filter on change.entity. To unsubscribe, dispose of the subscription or pass a signal.
Types
json-meta-client/rfc-types replaces jmap-rfc-types. Some names differ, such as ReadableEmail for Email.
import type { Email, Mailbox } from "jmap-rfc-types";import type {
Mailbox,
ReadableEmail,
} from "json-meta-client/rfc-types";