Types
All exported TypeScript types and interfaces from @kelpclick/client with field tables.
KelpClientConfig
Configuration object passed to createKelpClient and createKelpSearch.
| Field | Type | Required | Default | Notes |
|---|---|---|---|---|
searchUrl | string | yes | - | Base URL for search + browse. |
analyticsUrl | string | yes | - | Base URL for analytics batches. Not inferred from searchUrl. |
apiKey | string | yes | - | Sent as X-Api-Key. Throws if missing. |
tenantCode | string | no | - | Tenant slug stamped on every analytics batch envelope. |
timeoutMs | number | no | 10000 | Per-request timeout in ms. |
fetch | typeof fetch | no | globalThis.fetch | Inject a custom fetch (SSR / testing). |
serializeFilters | (filters: KelpFilters) => Record<string, unknown> | no | { filters } | Override the filter wire shape. |
maxRetries | number | no | 0 | Retry attempts after the initial try. |
retryBaseMs | number | no | 250 | Base delay for exponential backoff (ms). |
retryMaxMs | number | no | 5000 | Cap on per-attempt delay (ms). |
debug | boolean | no | false | Emit debug log for every attempt. |
logger | { debug, info, warn, error } | no | console | Custom log sink. Only active when debug: true. |
onRequest | (info: { url, method, attempt }) => void | no | - | Called before each attempt. |
onResponse | (info: { url, method, status, attempt }) => void | no | - | Called after response received. |
onError | (err: unknown) => void | no | - | Called after all retries exhausted. |
KelpDocumentBase
Minimal shape that every indexed document carries. Extend it with your own document type.
interface KelpDocumentBase {
id: string;
objectId: string;
[field: string]: unknown;
}interface Product extends KelpDocumentBase {
title: string;
handle: string;
vendor: string;
}
const res = await kelp.search<Product>('products', { q: 'shirt' });
res.hits[0].document.title; // typed as stringKelpSearchResponse<TDoc>
Returned by both search and browse.
| Field | Type | Notes |
|---|---|---|
hits | KelpHit<TDoc>[] | Matched documents with highlights. |
facetCounts | KelpFacetCount[] | Facet field counts. |
found | number | Total number of matching documents. |
page | number | Current page number. |
processingTimeMs | number | Server-side processing time in ms. |
queryId | string | undefined | Server-assigned id for this response. Pass to click/conversion events for attribution. |
KelpHit<TDoc>
One item in KelpSearchResponse.hits.
| Field | Type | Notes |
|---|---|---|
document | TDoc | The indexed document. |
highlights | KelpHighlight[] | Array of matched field snippets. |
KelpHighlight
A highlight snippet for a matched field.
| Field | Type | Notes |
|---|---|---|
field | string | The document field name. |
snippet | string | Excerpt that may contain <mark> tags around matched terms. |
KelpFacetCount
Counts for one facet field.
| Field | Type | Notes |
|---|---|---|
field | string | Facet field name. |
counts | KelpFacetValue[] | Array of { value, count } pairs, sorted by count descending. |
KelpFacetValue
One value bucket within a KelpFacetCount.
| Field | Type | Notes |
|---|---|---|
value | string | The facet value. |
count | number | Number of documents matching this value. |
KelpFilter
One filter clause. Multiple clauses are ANDed together.
| Field | Type | Notes |
|---|---|---|
field | string | Document field to filter on. Must be a configured facet attribute. |
op | KelpFilterOp | Comparison operator. Defaults to = on the backend when omitted. |
values | string[] | =/!= accept one or more (IN-list); comparisons take one; range takes [min, max]. |
KelpFilterOp
type KelpFilterOp = '=' | '!=' | '>' | '>=' | '<' | '<=' | 'range';| Op | Meaning | Values |
|---|---|---|
= | Equals / IN-list (default) | One or more |
!= | Not equals | One or more |
> >= < <= | Numeric comparison | One (values[0]) |
range | Inclusive range | Two ([min, max]) |
KelpFilters
type KelpFilters = KelpFilter[];An array of KelpFilter clauses. The default wire format is { "filters": [ ... ] }. Override with serializeFilters on KelpClientConfig.
SortItem
One sort key. Pass an array to sort for multi-key sorting applied in order.
| Field | Type | Notes |
|---|---|---|
field | string | Document field to sort on. |
direction | SortDirection | 'asc' or 'desc'. Defaults to 'asc' on the backend when omitted. |
SortDirection
type SortDirection = 'asc' | 'desc';BrowseParams
Parameters accepted by browse (and inherited by SearchParams for search).
| Field | Type | Notes |
|---|---|---|
facets | string[] | Facet fields to count. Omit to return counts for all configured facet attributes. |
page | number | Page number. Default 1. |
perPage | number | Results per page. Default 20. |
filters | KelpFilters | Filter clauses. |
sort | SortItem[] | Multi-key sort, applied in order. |
fields | string[] | Restrict returned document fields, e.g. ['id', 'title', 'handle']. |
distinctBy | string | Optional. One hit per distinct value of that field (for example, styleId returns one hit per keyedTags.styleId). |
userId | string | Per-visitor stable id for personalization. Caller-supplied. |
sessionId | string | Current session id for behavioral signals. |
personalize | boolean | Explicit opt in/out of behavioral re-ranking for this request. |
extraParams | Record<string, unknown> | Escape hatch merged directly into the request body. |
SemanticWeight
Named semantic blend sent on search. Not a raw engine float.
type SemanticWeight =
| 'strict'
| 'heavy'
| 'default'
| 'balanced'
| 'light'
| 'keyword'
| 'off';See Semantic search for what each value does. Omit the field for keyword-only.
SearchParams
Extends BrowseParams with search-only fields q and semanticWeight. distinctBy is on BrowseParams (and therefore on search as well).
| Field | Type | Notes |
|---|---|---|
q | string | Required. The search query. Pass '*' for match-all. Must not exceed 512 characters or 50 words (backend-enforced). |
semanticWeight | SemanticWeight | Optional. Search only. Semantic blend when the collection has enableSemanticSearch and this field is sent. Omit or unset = keyword-only. Not on BrowseParams. |
RequestOptions
Options accepted by search, browse, suggest, and trackEvents as the last argument.
| Field | Type | Notes |
|---|---|---|
signal | AbortSignal | Cancel the request in flight. Throws DOMException(AbortError) - not wrapped in KelpApiError. |
KelpError
Base class for all SDK errors. Extends Error.
class KelpError extends Error {}KelpApiError
Thrown on non-2xx responses, network failures, and timeouts. Extends KelpError.
| Field | Type | Notes |
|---|---|---|
status | number | HTTP status code. 0 for network and timeout errors. |
body | unknown | Parsed response body, if any. |
code | KelpErrorCode | Discriminated error code for programmatic handling. |
requestId | string | undefined | From x-request-id or x-trace-id response header. Include in support requests. |
KelpErrorCode
type KelpErrorCode = 'auth' | 'rate_limit' | 'client' | 'server' | 'network' | 'timeout';See Error handling for the full code-to-scenario table.
KelpAnalyticsEvent
One analytics event. Mirrors the backend AnalyticsEventDto. Sent batched as { id, events: [...] }.
| Field | Type | Required | Notes |
|---|---|---|---|
kind | KelpEventKind | yes | Event type. Closed set of 12 kinds. |
occurredAt | string | yes | ISO 8601 timestamp on the event root only. Auto-filled by createAnalytics. |
sessionId | string | yes | Session id. Auto-filled by createAnalytics. |
collection | string | no | Collection scoping. Required for search/product/collection events; omitted for email events. |
q | string | no | Search query string. |
filterBy | string | no | Serialized filter expression, e.g. brand:=[globex] && price:>0. |
found | number | no | Result count (search events). |
page | number | no | Page number. |
objectId | string | no | Subject document id (product id, or collection handle for collection_viewed). |
queryId | string | no | Ties the event to the search response that produced it (queryId chaining). Separate from the UTM Attribution object. |
userId | string | no | Kelp visitor id or anon_-prefixed anonymous id. Auto-filled by createAnalytics. |
value | number | no | Order/basket total (mainly purchase). First-class persisted. |
currency | string | no | ISO 4217 currency code (mainly purchase). First-class persisted. |
orderId | string | no | Order id (mainly purchase). First-class persisted. |
items | Array<{ objectId, quantity?, price? }> | no | Purchased line items (mainly purchase). First-class persisted. |
email | Email | no | Nested Email DTO (optional on every kind). See Email below. |
attribution | Attribution | no | Nested Attribution DTO (optional on every kind). See Attribution below. |
metadata | object | no | Optional event-level JSON (KEL-52). Stored as jsonb. Separate from email.meta / attribution.meta. An empty object is stored as null. Only objects are valid. |
Purchase scalars and typed email / attribution are first-class persisted (KEL-57). See Events.
Email
Nested email DTO. Optional on every event kind. When present, email (address) is required. source is optional (source?: string) for the capture point, e.g. 'footer-form'. Separate from Attribution source, which is required when Attribution is present. Flat string helpers map to { email } only.
| Field | Type | Required | Notes |
|---|---|---|---|
email | string | yes (when present) | Contact address. |
source | string | no | Capture point, e.g. 'footer-form'. Optional on object form. |
listId | string | no | Target list id. |
campaignId | string | no | Campaign id. |
details | EmailDetails | no | Person fields. |
meta | Record<string, unknown> | no | Email-scoped overflow. Not event metadata. |
EmailDetails
| Field | Type | Required | Notes |
|---|---|---|---|
name | string | no | Full name. |
firstName | string | no | Given name. |
lastName | string | no | Family name. |
phone | string | no | Phone number. |
Attribution
Nested UTM / traffic Attribution DTO. Optional on every event kind. When present, source is required; medium is optional. occurredAt is not on this object (event-root only).
| Field | Type | Required | Notes |
|---|---|---|---|
source | string | yes (when present) | Traffic source, e.g. 'google'. |
medium | string | no | e.g. 'organic', 'cpc'. |
campaign | string | no | Campaign name. |
content | string | no | Creative / content. |
term | string | no | Paid keyword. |
campaignRef | string | no | External campaign reference. |
clickId | string | no | Click id value. |
clickIdParam | string | no | Param name that held the click id. |
referrer | string | no | Document referrer. |
landingPage | string | no | Landing path. |
meta | Record<string, unknown> | no | Attribution-scoped overflow. Not event metadata. |
Search-to-conversion queryId chaining is documented in Attribution and is separate from this object.
KelpEventKind
type KelpEventKind =
| 'session_started'
| 'search'
| 'product_viewed'
| 'product_clicked'
| 'product_wishlisted'
| 'product_added_to_cart'
| 'collection_viewed'
| 'purchase'
| 'email_subscribed'
| 'email_unsubscribed'
| 'email_opened' // reserved
| 'email_clicked'; // reservedClosed named set. email_opened and email_clicked are reserved and are not emitted by the client yet. The SDK does not accept custom kind strings.
CreateAnalyticsOptions
Options for createAnalytics.
| Field | Type | Required | Default | Notes |
|---|---|---|---|---|
client | KelpClient | yes | - | The Kelp client used to send events. |
identity | KelpIdentity | yes | - | Identity instance for auto-filling sessionId and userId. |
flushAt | number | no | 10 | Flush when this many events are buffered. |
flushIntervalMs | number | no | 5000 | Also flush on this interval. 0 disables the interval. |
maxBufferedEvents | number | no | 1000 | Drop oldest events past this cap if the ingester is down. |
serializeFilterBy | (filters: KelpFilters) => string | no | defaultSerializeFilterBy | Custom filter serializer for trackSearch. |
sanitizeEvent | (event: KelpAnalyticsEvent) => KelpAnalyticsEvent | no | - | Redact or transform each event before buffering. Must be synchronous. |
KelpIdentityOptions
Options for createIdentity.
| Field | Type | Default | Notes |
|---|---|---|---|
storage | KelpStorage | resolveStorage() | Custom storage backend. |
sessionTtlMs | number | 1800000 (30 min) | Inactivity window before a new session id is minted. |
keyPrefix | string | 'kelp' | Prefix for storage keys. Set per-tenant when multiple tenants share a browser origin. |
KelpStorage
Interface for pluggable identity storage.
interface KelpStorage {
get(key: string): string | null;
set(key: string, value: string): void;
remove(key: string): void;
}KelpIdentity
Returned by createIdentity.
| Method | Signature | Notes |
|---|---|---|
getAnonymousId | () => string | Stable per-browser id. Created and persisted on first read. |
getSessionId | () => string | Rolling session id. A new id is minted after sessionTtlMs of inactivity; every call refreshes the activity timestamp. |
getUserId | () => string | null | The identified user id, or null. |
identify | (traits: IdentifyTraits & { userId?: string }) => KelpUserToken | Records the known user locally. Returns { anonymousId, userId? }. |
reset | () => void | Clears the known user. Keeps the anonymous id. |
KelpClient
The type of the object returned by createKelpClient. Composed from the search capability and events transport.
type KelpClient = ReturnType<typeof createKelpClient>;
// { search, browse, suggest, trackEvents, identify }React types (@kelpclick/client/react)
| Type | Notes |
|---|---|
KelpProviderProps | Props for KelpProvider: client, optional identity, optional analytics, children. |
UseSearchOptions | Options for useSearch: collection, facets, sort, fields, perPage, debounceMs, initialQuery, trackSearch, and any BrowseParams fields. |
UseBrowseOptions | Options for useBrowse: same as UseSearchOptions minus query fields. |
UseKelpQueryOptions | Lower-level options for useKelpQuery. |
KelpQueryRunnerArgs | Arguments passed to the query runner function in useKelpQuery. |
QueryStatus | 'idle' | 'loading' | 'success' | 'error' - status field returned by useSearch and useBrowse. |
Related
- Functions - all exported functions
- Error handling -
KelpErrorandKelpApiErrorin practice - Client configuration -
KelpClientConfigin context