npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@crud-api/core

v0.7.0

Published

CRUD API reference implementation: data model, engine, provider contract, field lists, projection, sorting, pagination, patch engines, negotiation

Readme

@crud-api/core

Core of the CRUD API reference implementation: the data model, the createCrudServer engine, the provider contract, field lists, projection, sorting, pagination, patch engines, negotiation, Warnings and the strict policy, and the conformance declaration. It knows no data source and does no I/O; providers (such as @crud-api/memory) and protocol adapters plug into it.

ESM only, requires Node 24 or later (also runs on Bun and Deno). Apache-2.0.

Usage

import { createCrudServer } from "@crud-api/core";
import { createMemoryProvider } from "@crud-api/memory";

const server = createCrudServer({ provider: createMemoryProvider({ implicitCollections: true }) });

const created = await server.execute({ operation: "create", collection: "orders", resources: [{ total: 10 }, { total: 25 }] });
const page = await server.execute({
  operation: "list",
  collection: "orders",
  query: { format: "text/vnd.unquery.sql", text: "total > 15" },
  params: { sort: "-total", limit: 20 },
});
if (page.ok) console.log(page.resources, page.meta.matchedCount);
else console.log(page.error.code, page.error.message);

execute never throws for an operation that fails: it returns { ok: false, error, meta }, where error is a CrudError (Base error codes, toProblemDetails for RFC 9457) and meta still carries the negotiated specification versions, representation, Correlation ID, Warnings and, for writes, the Modified Count. createCrudServer throws when the configuration is invalid (an extension enabled twice or missing a required extension, a reused Base code, an extension that needs system storage without one, an extension whose attach refuses the configuration).

The engine

An OperationRequest is protocol-neutral: operation (one of the ten Base operations, or an operation of the list verb an enabled extension adds, such as listByView), collection, the Subject (id, resources, resource, patch, newId, query, and view and viewParams for listByView), params (fields, sort, page, offset, cursor, limit, expectMatch, denyUpsert, custom) and meta (accept, returnPreference, strict, require, correlationId, principal, input, and for asynchronous operations async, asyncContext, waitUntil and onSettled), plus the adapter's warnings. Values are host values of the ECSON model; the core converts nothing and never serializes.

Each operation goes through the steps of the design, and the first failure stops it:

  1. specification versions (META_CRUD_RANGE_MATCH);
  2. Output representation (META_RES_PREFERENCE, META_RES_FALLBACK), then, with an execution hook, the execution mode (ASYNC_SERVER_MATRIX, below), then the Search Query format;
  3. the authorize hook (ACCESS_DENIED);
  4. the Collection (COLLECTION_SLUG, COLLECTION_NOT_FOUND, COLLECTION_CREATE_IMPLICIT);
  5. the operation;
  6. Parameters: field lists (indexes only in the Sorting Parameter, SORTING_ARRAY_PATH), sorting (SORTING_NULLS), pagination with the smaller maximum of server and provider, unknown Parameters reported as PARAM_IGNORED;
  7. the Subject: Resource IDs, Field names, reserved Fields (_meta without Metadata is dropped with FIELD_IGNORED), Client IDs (RES_NO_IDS), patch well-formedness;
  8. the Search Query, parsed with UnQuery and checked against the provider's operators;
  9. extension hooks (beforeWrite, afterRead);
  10. the write policy (WRITE_ATOMIC_STRICT, WRITE_STRICT_LATE_WARNINGS);
  11. prepare of every primitive, with the depth check of each Resource to write (a Resource the Server could not answer back inside a list, deeper than 999 levels with the ECSON default DEPTH_LIMIT of 1000, is INVALID_INPUT with ecsonCode: "DEPTH_LIMIT"; D108), then the strict policy on every Warning collected so far.

Only then does anything get written. When the operation runs asynchronously (below), steps 1 to 8 still run before the answer, so their failures stay synchronous (S87), and steps 9 to 11 run later in the extension's runner. Reads and writes are composed from provider primitives (find, findByIds, insert, replace, remove): writes by query read the exact matched set once and write each Resource by ID, never re-running the filter. Writes on several Resources run in provider.transaction() when the provider has one (all or nothing); without it they are partial in lenient mode (each failure becomes WRITE_FAILED) and fail with UNSUPPORTED before writing under the strict preference, unless it allows WRITE_FAILED.

Options

  • provider: the data provider.
  • system: the system storage of extensions such as Schema, Views and Async; by default the data provider when it declares systemCollections, otherwise none.
  • extensions: extension objects (name, spec, versions, requires, before, needsSystemStorage, reservedFields, reservedCollections, errorCodes, warningCodes, parameters, operations and the hooks below).
  • specs: specifications and versions declared (default { base: ["0.2.0"] }, plus each extension's).
  • representations: Output representations (default ["ecson", "json"]).
  • limits: maxLimit, defaultLimit and UnQuery query limits.
  • clock, random: injected time and random source (defaults Date.now and crypto.getRandomValues), used for UUIDv7 Resource IDs and Correlation IDs.
  • generateId: replaces the UUIDv7 generator for new Resource IDs.
  • authorize: returns false to refuse an operation.
  • customParams: Custom Parameters the server recognizes.
  • onError: receives the original of every INTERNAL error, which never reaches the Client; a throwing onError is ignored.
  • codec: the ECSON codec (@ecson/core createCodec) with the types of the enabled extensions; used for sorting, composite keys and Search Queries, and passed to the provider as ctx.codec. Default: createCodec(), the core, References ($rel, Rel) and Error ($error) type sets of @ecson/core 0.2.0 (D111). Exposed as server.codec.

Extension hooks

Extensions (such as @crud-api/metadata, @crud-api/relationships, @crud-api/schema, @crud-api/views and @crud-api/async) plug into the steps above through generic hooks; the decisions that introduced them are D116, D129, D137, D138, D155 and D167.

  • parameters: extra Parameters ({ name, operations, check?, appliesTo? }), recognized by the listed operations (and, with appliesTo, only on the Collections it accepts), checked in step 6 and given to the extension's hooks in params.
  • beforeWrite(input, ctx): each Resource about to be written, with its previous state (null on create, clone, upsert and a write over a placeholder), the extension's Parameters, the clone source and the Client's patch; returns the Resource to write.
  • precondition(input, ctx): the current state of each Resource a write by ID or by query targets, before anything changes; throwing fails the operation.
  • afterRead(input, ctx): the Resources read by get and list, with the Parameters and the Client's Projection.
  • ownedValues(input, ctx): a predicate over Field paths whose values the extension reads itself, so FIELDS_NAMES and FIELDS_NO_PREFIXES skip them (Schema owns the schema Field of @schema and the values under estype).
  • reservedCollections and reservedProvider(collection): a provider that serves a reserved Collection (@schema); the whole operation runs with it, its capabilities and its transactions. A claimed name without one is UNSUPPORTED.
  • attach(env): called once when the Server is built, with the data provider, the system storage, the codec, the clock and the enabled extensions (env.extension(name) gives an enabled extension's instance); throwing stops the Server.
  • operations: operations of the list verb the extension adds ({ name, resolve(input, ctx) }, such as listByView). resolve turns the Subject into a plan (ListPlan: a filter or a rendered native query, sort keys and a Projection), and the core runs it as a list combined with the Client's Search Query (and-ed), sort keys (after the plan's) and Projection (intersected, intersectProjections); pagination and the Matched Count count the combined items. Such an operation runs only on data Collections (a reserved name is NOT_FOUND, target collection) and recognizes every Parameter of list. The Client's filter and sort keys may use only Fields the plan's Projection keeps: a hidden path is UNSUPPORTED, rule VIEW_COMBO_UNSUPPORTED, before reading (S85). Declaring a Base operation, a name other than listByView (the only extra member of OperationName), or one name in two extensions, throws when the Server is built.
  • before: extensions that must come after this one in extensions.
  • execution (D167): one enabled extension may declare how operations run asynchronously (two are a construction Error), { support(operation, collection), accept(input), get(id, meta), watch(id, listener) }. support answers "sync", "async" or "both", and the core applies the matrix of ASYNC_SERVER_MATRIX to meta.async ("prefer", "require" or absent; another value is INVALID_INPUT): require on a sync-only operation and nothing on an async-only one are NEGOTIATION, rule ASYNC_SERVER_MATRIX, data.supported. The hook is asked only about Base and extension list operations with a string Collection; without a hook meta.async is ignored. For an asynchronous run the core validates the request through step 8, then calls accept({ request, operation, collection, run }), where run(progress) executes steps 9 to 11 once and resolves with the result execute would have returned (never rejecting), and answers { ok: true, resources: null, accepted: OperationState, meta } with the Warnings found so far. Under the strict preference, those Warnings fail the final state with STRICT_WARNINGS, as the synchronous run fails; Warnings an adapter passes in fail at once. A failing accept is INTERNAL. ExtensionEnv.newUuid() gives the Server's UUIDv7 generator to the extension. @crud-api/async implements it.
  • CollectionInfo.isPlaceholder(resource): a Resource the Collection shows but does not store, which is not a conflict for create and clone.
  • HookCtx: warn, warnOnce, clock, principal, codec, stored (the stored form of a Resource), read(collection, ids) (Resources of a data Collection, authorized as a get of the Client), annotate(name, value) (sets meta.annotations[name] of a successful result, for the Protocols), local (a Map shared by the hooks of one operation) and input (the Representation the Subject was read in, from meta.input).

For Protocol adapters

  • query is text in a negotiated format ({ format, text }), the same text combined with conditions read elsewhere ({ format, text, and }, where and is an UnQuery model, such as the query string of an HTTP QUERY request), or a model the adapter already built ({ filter }). Limits and the provider's operators apply to the final model; a native format cannot be combined with and (UNSUPPORTED).
  • warnings carries the Warnings the adapter found while reading the request (an unknown control parameter, a condition on a single-Resource endpoint). They come first in meta.warnings, and under the strict preference the operation fails with STRICT_WARNINGS before any provider call.
  • Every Warning, whoever reports it (the adapter, an extension, the provider), keeps only the members whose names follow WARN_MEMBER_NAMES (lowercase ASCII letters, digits, _ and -, starting with a letter): docUrl or 1x are left out, doc_url stays, so every Protocol sends a member under the same name (D114). isWarningMemberName(name) tells which names a Client must ignore.
  • server.registerProtocol({ name, warningCodes, errorCodes }) registers the codes a Protocol specification defines (CONDITION_IGNORED for HTTP). It is idempotent, and throws (registering nothing) on a Base code or a code another extension or Protocol owns.
  • server.description lists the specifications, extensions, customParams, queryFormats (UnQuery JSON, UnQuery SQL, then the provider's) and representations.
  • meta.limit is the page size a list used (the requested limit, the maximum it was reduced to, the default limit, or null for a page without limit; D97), so an adapter can build the links of the next page (Link header fields).
  • meta.input says how the Subject was read: "ecson" (the default) or "json" for a plain JSON body (REPR_PLAIN_JSON); Schema validates what the Client sent in that form.
  • meta.annotations (absent when none) carries what extensions annotate on a successful result, for the Protocol to describe it: schema ({ collection, version }), compiled (the compiled schemas of a read on @schema with params.compiled), view ({ collection, name }, a listByView of a View with a schema) and compiledViews (the compiled params and schema of a read on <slug>/@views with params.compiledViews).
  • server.operations (Operations, null without an execution hook, D167): get(id, { principal?, correlationId? }) resolves { ok: true, state } or { ok: false, error } (never rejects) after the host's authorize({ operation: "get", collection: "@operations", id, meta }), a refusal being ACCESS_DENIED; an unknown, foreign or expired Operation ID is NOT_FOUND, target operation. watch(id, listener) listens to every stored change of a state (progress, completion) and returns the unsubscribe function. support(operation, collection) tells a Protocol what the Server supports for an operation before running it ("sync" for an unknown operation, or when the hook throws, whose error goes to onError, or answers another value). OperationState is { id, status: "pending" | "succeeded" | "failed", operation, collection, progress?, createdAt, updatedAt, completedAt?, expiresAt?, pollInterval?, result?, context? } (Unix ms), result being exactly the synchronous result and context the adapter's meta.asyncContext (JSON it needs to render the result again). meta.waitUntil is the host's (design 7.3), and meta.onSettled(state) runs after the final state is stored, inside the same task (HTTP callbacks). negotiateExecution(support, declared) is the matrix alone.
  • meta.ids lists the canonical IDs written by create, clone, patchById, replaceById and deleteById, in Subject order, also with returnPreference: "minimal" (for Location header fields).
  • exceedsDepth(tree, max), DEPTH_LIMIT and RESOURCE_MAX_DEPTH bound the bodies and arguments an adapter reads with the same iterative walk the engine uses, so hostile nesting cannot overflow the stack (D108).

Providers

A provider implements Provider (capabilities, collection, listCollections, createCollection, dropEmptyCollection, prepare, execute, transaction, schema, testing; testing.inspectNative optionally tells how a stored value is kept, for the conformance kit). prepare is pure and synchronous: it translates a primitive and reports the Warnings that depend only on the input, so that the core can fail before writing. Both prepare and execute receive the Server's ECSON codec as ctx.codec. A find that sorts reads values with getPath (or sorts natively by the same rules) and reports from execute the SORT_ARRAY_PATH Warnings of sortArrayPathWarnings over every matched Resource (SORTING_ARRAY_PATH). An implicit Collection is created inside the transaction when the transaction object has createCollection; otherwise it is created before the writes and removed again with dropEmptyCollection when the create writes nothing. A provider whose Data source enforces a schema of its own implements schema (ProviderSchemaHooks: ownSchema, acceptsDbType, inferDbType, convertValue, optional deriveSchema) and the applySchema primitive, whose prepare is a dry run and whose execute changes the Data source's schema or fails with SCHEMA_INCOMPATIBLE changing nothing (D138). A provider with a native query language may receive a rendered View query in find (view: { format, query }, RenderedQuery: text segments with the values to bind apart, or a JSON value), whose items the filter, sort keys, projection and page then apply to; nativeCombination: { filter, sort } declares whether it can apply the Client's filter and sort keys to those items (D155). While an operation runs asynchronously, ExecCtx.progress?.(done, total?) is set and the provider may report progress (non-negative integers, total >= done; other values are ignored, ASYNC_PROGRESS); it is absent in synchronous runs. Capabilities declare what the provider can do exactly (operators, pagination, sorting, counts, transactions, ID kinds, native types, implicit and system Collections, lateWarnings); the core rejects anything outside them.

Conformance

conformance declares the CRUD Base specification 0.2.0 with its ten operations and no extension.