@simpleapps-com/augur-core
The framework-free foundation under augur-hooks and augur-server. It runs anywhere JavaScript runs (browser, Node, Workers, React Native) and covers every SDK method through a Proxy, so no method needs a hand-written wrapper.
pnpm add @simpleapps-com/augur-core @simpleapps-com/augur-api@simpleapps-com/augur-api is a peer dependency; @simpleapps-com/augur-utils comes with it. Every export, with its description: API Reference.
Entry points
| Import | Purpose |
|---|---|
@simpleapps-com/augur-core |
Proxy factories, cache tiers, key builders, classification, defineSite, types |
@simpleapps-com/augur-core/testing |
createMockClient for tests |
Proxy factories
Each factory walks the SDK by property access (q.items.invMast.stock) and, when the leaf is called, builds its result from the method path and arguments. createDeepProxy is the mechanism the others share.
| Export | Has an SDK? | Leaf returns | Use |
|---|---|---|---|
createOptionsProxy(api, config?) |
Yes | Query options (queryKey, queryFn, staleTime, gcTime), or mutation options for writes |
Client or SSR prefetch with an SDK instance |
createQueryActionProxy(action, config?) |
No | The same options; queryFn calls action(methodPath, ...args) |
Sites whose JWT stays on the server |
createKeysOnlyProxy(config?) |
No | The same keys and tiers; queryFn throws until you override it |
Fallback inside augur-hooks' provider |
createActionsProxy(api, config?) |
Yes | An async call to the SDK, with optional transforms and wrapCall |
Server actions, scripts, agents |
createDeepProxy(handler) |
n/a | Whatever handler(path, args) returns |
Building a new kind of proxy |
createFetchQueryAction(basePath = "/api/augur", options?) builds a query action that POSTs { methodPath, args } to an API route, for platforms where server actions can't read request cookies (Cloudflare Workers through OpenNext). Pass it to createQueryActionProxy, or to augur-hooks' registerQueryAction. options.cacheTtl (FetchQueryOptions) goes with every call: the server's cache number for it, in seconds, 0 for none, at most 3600 (the route answers 400 otherwise); it is not part of any query key.
import { createActionsProxy, createOptionsProxy } from "@simpleapps-com/augur-core";
import { AugurAPI } from "@simpleapps-com/augur-api";
const api = new AugurAPI({ siteId: "example-site", bearerToken });
const q = createOptionsProxy(api);
q.items.invMast.stock.get(42);
// → { queryKey: ["items", "invMast", "stock", "get", 42], queryFn, staleTime: 60000, gcTime }
const actions = createActionsProxy(api);
await actions.items.invMast.stock.get(42); // the SDK's responseWhat a query resolves to
Every options proxy's queryFn and mutationFn resolve to the SDK response's data (unwrapBaseResponse), never the { data, status, message } envelope, so one query key always holds one shape. Don't read .data off a query result. createActionsProxy returns the SDK's response as it is; augur-server's queryAction unwraps it.
A read by path id (get called with its id first) answers a missing record as null (atlas#99): createOptionsProxy runs it through absentOnNotFound, which returns null when absentOnFailure(leaf, leadsWithId, status) holds (a get, its first argument a number or string, the error's statusCode 404) and throws every other failure on. Its type is T | null in DeepQueryOptions and MethodData. createActionsProxy and a list keep throwing.
To page a list you need the envelope's total, which data doesn't carry: call augur-server's queryActionRaw, or in fetch mode createFetchQueryActionRaw(basePath), under a query key of your own, never a proxy's.
On the server, gcTime is Infinity (resolveGcTime): query-core then sets no GC timer, and a per-request QueryClient is freed when the request ends. In the browser it is the tier's gcTime.
Method classification
A leaf is a read when its name is get, list, lookup, search or suggest (isReadMethod). Anything else (create, update, delete, enable, …) is a write (isWriteMethod). A get called with a path id first is a read by path id (readsById). Reads get query options and a cache tier; writes get { mutationKey, mutationFn }.
Cache tiers
getCacheTier(methodPath, overrides?) picks a tier from the method path. A path matches a namespace when it equals it or continues it after a dot, so payments matches payments.unified.transactionSetup.list but not paymentsProcessor.get.
| Tier | staleTime | gcTime | edgeCache |
redisTtl |
Paths |
|---|---|---|---|---|---|
none |
0 | 0 | none | none | commerce, payments (NO_CACHE_PATHS) |
user |
1 min | 5 min | none | none | items.itemWishlist, items.itemFavorites (USER_PATHS) |
p21 |
1 min | 5 min | none | 1 min | The P21 namespaces below (P21_PATHS) |
onRequest |
0 | 0 | none | 0 | legacy.legacy.coupons (ON_REQUEST_PATHS) |
static |
1 h | 24 h | 8 h | 8 h | The 17 reference-data namespaces below (STATIC_PATHS) |
semiStatic |
1 min | 4 h | 1 h | 1 h | Everything else |
static and semiStatic take their browser times (staleTime, gcTime) from augur-utils' tierStaleTime / tierBrowserGcTime, the same tiers as CACHE_CONFIG (augur-utils), so a query built by hand gets the same times as the proxy's. gcTime is the browser's value; on the server it is always Infinity.
user and p21 hold one user's data.
- User (wishlists, favorites: what the user changes): the server never caches it, in Redis or at the edge (
isServerNoCachePath), since it can't clear a copy when the data changes. The browser keeps a short cache that the user's own writes clear (clearedBy, and augur-hooks'userWriteClearing). - P21 (
customers.customer,joomla.users,orders.oeHdr,vmi: their customer record, orders, invoices, quotes, ship-tos, profile and VMI stock, which change in P21, not by the user): one minute in Redis and one minute fresh in the browser, so every layer is at most a minute behind P21; no edge copy (isEdgeFreePath), since no one can clear one.
Cached on request (legacy.legacy.coupons: a deactivated or re-dated coupon must stop validating at once): not cached anywhere by default, not in the browser, Redis or at the edge. A query that sends its own cacheTtl (augur-server queryActionWith({ cacheTtl })) is cached in Redis for that long; 0 is none.
Static namespaces: agrSite.settings, agrSite.metaFiles, agrSite.geoCodesPostalCodes, items.categories, items.itemCategory, items.brands, items.attributeGroups, items.attributes, p21Core.company, p21Core.location, p21Core.paymentTypes, p21Core.codeP21, p21Core.cashDrawer, joomla.menu, joomla.tags, joomla.userGroups, legacy.legacy.state.
overrides (the proxies' config.cache) changes the static and semiStatic values; none, user, p21 and onRequest can't be overridden. The defaults are exported as DEFAULT_CACHE_TIERS.
On no-cache, user, P21 and on-request paths the proxies also remove edgeCache from every top-level argument before the SDK sees it (stripEdgeCacheForNoCachePaths), so those responses never get a CDN cache directive.
clearedBy(writePath, readPath) says whether a write clears a cached read: only when both are under the same user namespace. A wishlist write clears the wishlists and their lines; a favorites write leaves the wishlists alone; a catalogue write clears nothing.
Keys
| Export | Result |
|---|---|
buildQueryKey(path, args) |
[...path, ...args], unchanged |
stableArgs(args) |
Each object argument with its keys sorted and undefined values dropped |
buildCacheKey(prefix, methodPath, args) |
`${prefix}actAt:${methodPath}:${fnv1a(stableStringify(args))}`: an action's shaped value |
buildRawCacheKey(prefix, methodPath, args) |
`${prefix}rawAt:${methodPath}:${fnv1a(stableStringify(args))}`: a raw SDK result |
stableStringify(value) |
JSON.stringify with sorted object keys |
fnv1a(text) |
32-bit FNV-1a as 8 hex characters |
The proxies build query keys from stableArgs(args), so { itemId, customerId } and { customerId, itemId } give the same key, on the server and in the browser alike:
q.pricing.priceEngine.list({ itemId: "SKU-1", customerId: 42 }).queryKey;
// → ["pricing", "priceEngine", "list", { customerId: 42, itemId: "SKU-1" }]
buildCacheKey("example:", "pricing.priceEngine.list", [{ itemId: "SKU-1", customerId: 42 }]);
// → "example:actAt:pricing.priceEngine.list:<8 hex>"A cache key holds one shape. An action's shaped value (response.data, a list it builds) and a raw SDK result (the { data, status, message } envelope queryAction caches) have their own key spaces, actAt: and rawAt:, so the same call cached both ways is two entries and a reader never gets the other's shape. Each entry carries the time it was written, so a query's own cache number (augur-server cacheTtl) is an age limit. Keys from before that (act:, raw:) and before the split (sdk:) are read by neither and expire with their TTL.
If SSR data doesn't hydrate, the server and the browser built different keys: build both through a proxy, which gives the same key for the same method path and arguments.
Site config
defineSite(config) returns its argument; it exists for type-checking and autocomplete of AugurSiteConfig (name, mode, defaults, formatting, analytics, items, search, plus any keys of your own).
import { defineSite } from "@simpleapps-com/augur-core";
export const siteConfig = defineSite({
name: "example-site",
mode: "b2b",
defaults: { customerId: 4096 },
});defaults.customerId is a P21 customer: a whole number at least 1, or its digits. A non-numeric
value is no customer and is ignored (atlas#95).
Types
DeepQueryOptions<T> and DeepActions<T> map the SDK's type tree to options and actions, so createOptionsProxy<AugurAPI>(api) gives typed parameters and results at every leaf. Also exported: AugurAuthContext, CacheConfig, CacheTierConfig, ResolvedCacheTier, EdgeCacheValue, InfiniteScrollPage, QueryActionFn and the AugurSite* config types; the full list is in the API Reference.
Related
- augur-hooks:
useAugurOptionsand the provider built on these proxies - augur-server:
queryAction,createServerQueryProxyand server-side caching