@craftainer/crud-sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events-Cqj9Rbon.mjs","names":[],"sources":["../src/cache/policy.ts","../node_modules/.pnpm/eventsource-parser@4.1.2/node_modules/eventsource-parser/dist/errors.js","../node_modules/.pnpm/eventsource-parser@4.1.2/node_modules/eventsource-parser/dist/parse.js","../src/events.ts"],"sourcesContent":["/** Per-resource cache policy, defaulted from the manifest `cache` hints. */\n\n/**\n * How one resource is cached. Times are seconds. `maxAge` and\n * `staleWhileRevalidate` only take effect while the resource's SSE stream is\n * running; without it every read revalidates. `statsTtl` bounds the staleness\n * of `stats`/`predict` on its own, as the server caches those bodies for the\n * same time. `revalidateOnly` means no fresh window and no\n * stale-while-revalidate.\n */\nexport interface CachePolicy {\n readonly enabled: boolean;\n readonly maxAge: number;\n readonly statsTtl: number;\n readonly staleWhileRevalidate: number;\n readonly etag: boolean;\n readonly revalidateOnly: boolean;\n}\n\n/** The manifest resource members a policy reads (I1); everything else is ignored. */\nexport interface ManifestCacheHints {\n readonly cache?: {\n readonly max_age?: unknown;\n readonly stats_ttl?: unknown;\n readonly stale_while_revalidate?: unknown;\n readonly etag?: unknown;\n readonly revalidate_only?: unknown;\n } | null;\n}\n\nfunction seconds(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value)\n ? Math.max(value, 0)\n : 0;\n}\n\n/** Build a policy from a manifest resource object; `overrides` win over the hints. */\nexport function cachePolicyFromManifest(\n resource: ManifestCacheHints,\n overrides: Partial<CachePolicy> = {},\n): CachePolicy {\n const hints = resource.cache ?? {};\n return {\n enabled: overrides.enabled ?? true,\n maxAge: overrides.maxAge ?? seconds(hints.max_age),\n statsTtl: overrides.statsTtl ?? seconds(hints.stats_ttl),\n staleWhileRevalidate:\n overrides.staleWhileRevalidate ?? seconds(hints.stale_while_revalidate),\n etag: overrides.etag ?? hints.etag !== false,\n revalidateOnly: overrides.revalidateOnly ?? hints.revalidate_only === true,\n };\n}\n\n/**\n * The policy to use under TanStack Query: its `staleTime` decides freshness,\n * so the SDK cache only revalidates (ETag/304) unless told otherwise.\n */\nexport function tanstackCachePolicy(\n resource: ManifestCacheHints,\n overrides: Partial<CachePolicy> = {},\n): CachePolicy {\n return cachePolicyFromManifest(resource, {\n revalidateOnly: true,\n ...overrides,\n });\n}\n","/**\n * Error thrown when encountering an issue during parsing.\n *\n * @public\n */\nexport class ParseError extends Error {\n constructor(message, options) {\n super(message);\n this.name = 'ParseError';\n this.type = options.type;\n this.field = options.field;\n this.value = options.value;\n this.line = options.line;\n }\n}\n//# sourceMappingURL=errors.js.map","/**\n * EventSource/Server-Sent Events parser\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html\n */\nimport { ParseError } from './errors.js';\n// ASCII codes used in the hot parsing paths.\nconst LF = 10;\nconst CR = 13;\nconst SPACE = 32;\nconst MAX_FIELD_PREFIX_LENGTH = 6;\n/**\n * Creates a new EventSource parser.\n *\n * @param config - Parser configuration. Accepts callbacks (see {@link ParserCallbacks})\n * and options like `maxBufferSize` (see {@link ParserConfig}).\n *\n * @returns A new EventSource parser, with `feed` and `reset` methods.\n * @public\n */\nexport function createParser(config) {\n if (typeof config === 'function') {\n throw new TypeError('`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?');\n }\n const { maxBufferSize, onComment, onError, onEvent, onId, onRetry } = config;\n // Trailing bytes from prior `feed()` calls that did not yet form a complete line.\n // Stored as an array of fragments and only joined when a line terminator arrives.\n // Concatenating per-feed (`prefix + chunk`) is O(N²) when a single SSE line spans\n // many chunks (e.g. a large `data:` payload streamed in tiny slices, or an MCP-style\n // server that emits one giant content block). Buffering as fragments + joining once\n // makes the same workload linear.\n const pendingFragments = [];\n // Running total of `pendingFragments` lengths, kept in sync with the array so the\n // `maxBufferSize` check doesn't have to walk the fragment list on every feed.\n let pendingFragmentsLength = 0;\n // Empty or partial leading BOM; undefined once the BOM check is complete.\n let bomPrefix = '';\n let id;\n let data = '';\n let dataLines = 0;\n let eventType;\n // Set after a `maxBufferSize` overflow. Once tripped, `feed()` throws until\n // `reset()` is called — see the comment on `maxBufferSize` in `ParserConfig`.\n let terminated = false;\n let skippingLine = false;\n // Set when a line (parsed or discarded) was terminated by a trailing `\\r` at the very\n // end of a chunk. That `\\r` is ambiguous: it may be a bare-CR terminator or the first\n // half of a `\\r\\n` whose `\\n` lands in the next chunk. The line itself is complete\n // either way, but we must remember to swallow a single leading `\\n` from the next\n // chunk so the pair is treated as one terminator rather than a blank line (which\n // would dispatch an event prematurely).\n let skipNextLineFeed = false;\n /**\n * Feeds a chunk of the SSE stream to the parser. Any trailing bytes that do\n * not yet form a complete line are held back and prepended to the next chunk,\n * so callers can pass arbitrary slices of the stream without worrying about\n * line boundaries.\n *\n * Per the SSE spec, one leading UTF-8 BOM is stripped before parsing,\n * even when split across chunks. This handles both the raw 3-byte form (0xEF 0xBB\n * 0xBF) and a single decoded U+FEFF, so a leading BOM is ignored regardless of\n * how the caller decoded the bytes.\n *\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream\n */\n function feed(chunk) {\n if (terminated) {\n throw new Error('Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.');\n }\n if (bomPrefix !== undefined) {\n chunk = bomPrefix + chunk;\n // Wait only while the input could still be a raw BOM. Empty chunks must\n // not finish the check, and a mismatched prefix must remain ordinary input.\n if (chunk === '' || chunk === '\\xEF' || chunk === '\\xEF\\xBB') {\n bomPrefix = chunk;\n return;\n }\n bomPrefix = undefined;\n // Strip exactly one leading BOM, in decoded or raw byte-valued form.\n chunk = chunk.replace(/^(?:\\uFEFF|\\xEF\\xBB\\xBF)/, '');\n }\n // Rare resume states from a prior chunk boundary: a pending `\\r\\n` split or a\n // line being discarded. Single combined check keeps the hot path to one branch;\n // the actual handling lives out-of-line in `resumeAfterSkip`.\n if (skippingLine || skipNextLineFeed) {\n chunk = resumeAfterSkip(chunk);\n if (!chunk) {\n return;\n }\n }\n // Hot path: no buffered prefix from a prior partial line. Hand the chunk\n // straight to `processLines`, exactly like the original implementation.\n // Zero new work in the common case (every chunk ends with `\\n\\n`).\n if (!pendingFragments.length) {\n const trailing = processLines(chunk);\n if (trailing !== '') {\n storeTrailing(trailing);\n }\n checkForBufferOverflow();\n return;\n }\n // We have a buffered prefix. If this chunk also has no terminator, append\n // to the buffer without concatenating — that's the O(N²) trap we're\n // avoiding (large single `data:` payload split across many tiny chunks).\n if (chunk.indexOf('\\n') === -1 && chunk.indexOf('\\r') === -1) {\n if (pendingFragmentsLength < MAX_FIELD_PREFIX_LENGTH) {\n const head = pendingFragments.join('') +\n chunk.slice(0, MAX_FIELD_PREFIX_LENGTH - pendingFragmentsLength);\n if (!shouldBufferTrailing(head)) {\n pendingFragments.length = 0;\n pendingFragmentsLength = 0;\n skippingLine = true;\n return;\n }\n }\n pendingFragments.push(chunk);\n pendingFragmentsLength += chunk.length;\n checkForBufferOverflow();\n return;\n }\n // Terminator arrived. Join the accumulated fragments + this chunk once,\n // process, and buffer any new trailing partial line.\n pendingFragments.push(chunk);\n const input = pendingFragments.join('');\n pendingFragments.length = 0;\n pendingFragmentsLength = 0;\n storeTrailing(processLines(input));\n checkForBufferOverflow();\n }\n // Out-of-line handler for the rare post-boundary states. `skipNextLineFeed` means a\n // line (parsed or discarded) ended with a trailing `\\r` at the previous chunk boundary,\n // so a single leading `\\n` must be swallowed to consume a split `\\r\\n` as one terminator.\n // `skippingLine` means we are discarding an invalid line until its terminator arrives.\n // The two states are mutually exclusive. Returns the remaining chunk to parse ('' if\n // this chunk was fully consumed).\n function resumeAfterSkip(chunk) {\n if (chunk.length === 0) {\n return chunk;\n }\n if (skipNextLineFeed) {\n skipNextLineFeed = false;\n return chunk.charCodeAt(0) === LF ? chunk.slice(1) : chunk;\n }\n const crIndex = chunk.indexOf('\\r');\n const lfIndex = chunk.indexOf('\\n');\n const lineEnd = crIndex === -1 ? lfIndex : lfIndex === -1 ? crIndex : crIndex < lfIndex ? crIndex : lfIndex;\n if (lineEnd === -1) {\n return '';\n }\n // Trailing `\\r` at the very end of the chunk: defer the CRLF/CR decision to the\n // next chunk (see `skipNextLineFeed`) rather than greedily consuming just the `\\r`.\n if (lineEnd === chunk.length - 1 && chunk.charCodeAt(lineEnd) === CR) {\n skippingLine = false;\n skipNextLineFeed = true;\n return '';\n }\n skippingLine = false;\n return chunk.slice(lineEnd + (chunk.charCodeAt(lineEnd) === CR && chunk.charCodeAt(lineEnd + 1) === LF ? 2 : 1));\n }\n function storeTrailing(trailing) {\n if (!trailing)\n return;\n // A trailing that ends with `\\r` is not a partial line: the `\\r` terminates it,\n // and only the CRLF-vs-CR ambiguity remains (the matching `\\n` may start the next\n // chunk). Parse the completed line now — buffering it could grow unbounded through\n // the no-terminator append path, and discarding it would eat the terminator and\n // make skip mode swallow the next line.\n if (trailing.charCodeAt(trailing.length - 1) === CR) {\n parseLine(trailing, 0, trailing.length - 1);\n if (checkForBufferOverflow())\n return;\n skipNextLineFeed = true;\n return;\n }\n if (shouldBufferTrailing(trailing)) {\n pendingFragments.push(trailing);\n pendingFragmentsLength = trailing.length;\n return;\n }\n skippingLine = true;\n }\n function shouldBufferTrailing(trailing) {\n const firstCharCode = trailing.charCodeAt(0);\n return ((firstCharCode === 58 && !!onComment) ||\n (firstCharCode === 100 && isPotentialField(trailing, 'data')) ||\n (firstCharCode === 101 && isPotentialField(trailing, 'event')) ||\n (firstCharCode === 105 && isPotentialField(trailing, 'id')) ||\n (firstCharCode === 114 && isPotentialField(trailing, 'retry')));\n }\n // Returns true when parsing must stop for the current chunk (the parser was already\n // terminated or has just overflowed), and false when processing can continue.\n function checkForBufferOverflow() {\n if (terminated)\n return true;\n if (maxBufferSize === undefined)\n return false;\n if (pendingFragmentsLength + data.length <= maxBufferSize)\n return false;\n terminated = true;\n pendingFragments.length = 0;\n pendingFragmentsLength = 0;\n id = undefined;\n data = '';\n dataLines = 0;\n eventType = undefined;\n skippingLine = false;\n skipNextLineFeed = false;\n onError === null || onError === void 0 ? void 0 : onError(new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {\n type: 'max-buffer-size-exceeded',\n }));\n return true;\n }\n /**\n * Splits `chunk` into SSE lines and dispatches each to the appropriate handler.\n * Returns any trailing bytes that did not terminate with a line break, so the\n * caller can prepend them to the next chunk.\n *\n * The SSE spec permits three line terminators: `\\n`, `\\r`, and `\\r\\n`. Real-world\n * streams almost always use plain `\\n`, so we take a fast path when no `\\r` is\n * present in the chunk. The slow path is spec-correct but does more work per line.\n */\n function processLines(chunk) {\n let searchIndex = 0;\n // Fast path: LF-only chunk (the common case for typical SSE servers).\n // We can scan forward with a single `indexOf('\\n')` per line and inline\n // the hot-path branches for `data:` and `event:` without the CR bookkeeping\n // the slow path needs.\n if (chunk.indexOf('\\r') === -1) {\n let lfIndex = chunk.indexOf('\\n', searchIndex);\n while (lfIndex !== -1) {\n // Blank line: end-of-event marker. Dispatch the accumulated event (if any)\n // and reset the buffered fields. This is hoisted out of `parseLine` because\n // it's the single most common line shape after `data:` lines.\n if (searchIndex === lfIndex) {\n if (id !== undefined) {\n onId === null || onId === void 0 ? void 0 : onId(id);\n }\n if (dataLines > 0) {\n onEvent === null || onEvent === void 0 ? void 0 : onEvent({ id, event: eventType, data });\n }\n id = undefined;\n data = '';\n dataLines = 0;\n eventType = undefined;\n searchIndex = lfIndex + 1;\n lfIndex = chunk.indexOf('\\n', searchIndex);\n continue;\n }\n const firstCharCode = chunk.charCodeAt(searchIndex);\n if (isDataPrefix(chunk, searchIndex, firstCharCode)) {\n // `data:` line — append the value to the event's data buffer.\n // 'data:'.length === 5, 'data: '.length === 6\n const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5;\n const value = chunk.slice(valueStart, lfIndex);\n // Fast path within a fast path: if this is the first data line AND the\n // next char is another LF (i.e. `data:foo\\n\\n`), dispatch immediately\n // without ever writing to the `data` buffer. This is the shape of a\n // typical single-line SSE event (ChatGPT-style streams, etc.) and is\n // hot enough to be worth the duplication.\n if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {\n if (id !== undefined) {\n onId === null || onId === void 0 ? void 0 : onId(id);\n }\n onEvent === null || onEvent === void 0 ? void 0 : onEvent({ id, event: eventType, data: value });\n id = undefined;\n data = '';\n eventType = undefined;\n searchIndex = lfIndex + 2;\n lfIndex = chunk.indexOf('\\n', searchIndex);\n continue;\n }\n // Multi-line data: concatenate with newline separator per spec.\n data = dataLines === 0 ? value : `${data}\\n${value}`;\n dataLines++;\n }\n else if (isEventPrefix(chunk, searchIndex, firstCharCode)) {\n // `event:` line — set the event type for the next dispatch. Per spec,\n // an empty value resets `event type` to its default (undefined here).\n // 'event:'.length === 6, 'event: '.length === 7\n eventType =\n chunk.slice(chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6, lfIndex) || undefined;\n }\n else {\n // Everything else: `id:`, `retry:`, comment lines (`:` prefix), unknown\n // fields, or malformed lines. These are rarer and go through the full\n // per-line parser, which handles the SSE field grammar in detail.\n parseLine(chunk, searchIndex, lfIndex);\n }\n if (checkForBufferOverflow())\n return '';\n searchIndex = lfIndex + 1;\n lfIndex = chunk.indexOf('\\n', searchIndex);\n }\n return chunk.slice(searchIndex);\n }\n // Slow path: the chunk contains at least one `\\r`, so lines may be terminated\n // by `\\r`, `\\n`, or `\\r\\n`. We locate the next terminator by looking at both\n // the nearest `\\r` and `\\n` and picking whichever comes first.\n while (searchIndex < chunk.length) {\n const crIndex = chunk.indexOf('\\r', searchIndex);\n const lfIndex = chunk.indexOf('\\n', searchIndex);\n let lineEnd = -1;\n if (crIndex !== -1 && lfIndex !== -1) {\n lineEnd = crIndex < lfIndex ? crIndex : lfIndex;\n }\n else if (crIndex !== -1) {\n // A trailing `\\r` at the very end of the chunk is ambiguous: it could be\n // a bare-CR terminator, or the first half of a `\\r\\n` whose `\\n` arrives\n // in the next chunk. Defer until we see more input.\n if (crIndex === chunk.length - 1) {\n lineEnd = -1;\n }\n else {\n lineEnd = crIndex;\n }\n }\n else if (lfIndex !== -1) {\n lineEnd = lfIndex;\n }\n if (lineEnd === -1) {\n break;\n }\n parseLine(chunk, searchIndex, lineEnd);\n if (checkForBufferOverflow())\n return '';\n searchIndex = lineEnd + 1;\n // If we just consumed a `\\r` and the next char is `\\n`, skip it so the\n // pair is treated as a single terminator rather than an empty line.\n if (chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF) {\n searchIndex++;\n }\n }\n return chunk.slice(searchIndex);\n }\n function parseLine(chunk, start, end) {\n if (start === end) {\n dispatchEvent();\n return;\n }\n const firstCharCode = chunk.charCodeAt(start);\n if (isDataPrefix(chunk, start, firstCharCode)) {\n // 'data:'.length === 5, 'data: '.length === 6\n const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5;\n const value = chunk.slice(valueStart, end);\n data = dataLines === 0 ? value : `${data}\\n${value}`;\n dataLines++;\n return;\n }\n if (isEventPrefix(chunk, start, firstCharCode)) {\n // 'event:'.length === 6, 'event: '.length === 7\n eventType =\n chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || undefined;\n return;\n }\n // Fast path for \"id:\" — 'i' = 105, 'd' = 100, ':' = 58\n if (firstCharCode === 105 &&\n chunk.charCodeAt(start + 1) === 100 &&\n chunk.charCodeAt(start + 2) === 58) {\n // 'id:'.length === 3, 'id: '.length === 4\n const value = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);\n // If the field value does not contain U+0000 NULL, then set the `ID` buffer to\n // the field value. Otherwise, ignore the field.\n if (!value.includes('\\0'))\n id = value;\n return;\n }\n // Comment line — ':' = 58\n if (firstCharCode === 58) {\n if (onComment) {\n const line = chunk.slice(start, end);\n // skip ':' (+1), or ': ' (+2) when a space follows\n onComment(line.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));\n }\n return;\n }\n const line = chunk.slice(start, end);\n const fieldSeparatorIndex = line.indexOf(':');\n if (fieldSeparatorIndex === -1) {\n processField(line, '', line);\n return;\n }\n const field = line.slice(0, fieldSeparatorIndex);\n // skip ':' (+1), or ': ' (+2) when a space follows\n const offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1;\n const value = line.slice(fieldSeparatorIndex + offset);\n processField(field, value, line);\n }\n function processField(field, value, line) {\n // Field names must be compared literally, with no case folding performed.\n switch (field) {\n case 'event':\n // Set the `event type` buffer to field value\n eventType = value || undefined;\n break;\n case 'data':\n data = dataLines === 0 ? value : `${data}\\n${value}`;\n dataLines++;\n break;\n case 'id':\n // If the field value does not contain U+0000 NULL, then set the `ID` buffer to\n // the field value. Otherwise, ignore the field.\n if (!value.includes('\\0'))\n id = value;\n break;\n case 'retry':\n // If the field value consists of only ASCII digits, then interpret the field value as an\n // integer in base ten, and set the event stream's reconnection time to that integer.\n // Otherwise, ignore the field.\n if (/^\\d+$/.test(value)) {\n onRetry === null || onRetry === void 0 ? void 0 : onRetry(parseInt(value, 10));\n }\n else {\n onError === null || onError === void 0 ? void 0 : onError(new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n type: 'invalid-retry',\n value,\n line,\n }));\n }\n break;\n default:\n // Otherwise, the field is ignored.\n onError === null || onError === void 0 ? void 0 : onError(new ParseError(`Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}…` : field}\"`, { type: 'unknown-field', field, value, line }));\n break;\n }\n }\n function dispatchEvent() {\n if (id !== undefined) {\n onId === null || onId === void 0 ? void 0 : onId(id);\n }\n if (dataLines > 0) {\n onEvent === null || onEvent === void 0 ? void 0 : onEvent({\n id,\n event: eventType,\n data,\n });\n }\n id = undefined;\n data = '';\n dataLines = 0;\n eventType = undefined;\n }\n function reset(options = {}) {\n if (options.consume && pendingFragments.length > 0) {\n const incompleteLine = pendingFragments.join('');\n parseLine(incompleteLine, 0, incompleteLine.length);\n }\n bomPrefix = '';\n id = undefined;\n data = '';\n dataLines = 0;\n eventType = undefined;\n pendingFragments.length = 0;\n pendingFragmentsLength = 0;\n terminated = false;\n skippingLine = false;\n skipNextLineFeed = false;\n }\n return { feed, reset };\n}\n/**\n * Checks if `chunk` starts with the literal `data:` at index `i`.\n *\n * Equivalent to `chunk.startsWith('data:', i)`, but benchmarks show this\n * hand-unrolled char-code comparison is ~20% faster on common event types.\n * The caller passes `firstCharCode` (the code at `i`) so it can be reused\n * across prefix checks.\n *\n * ASCII: 'd' = 100, 'a' = 97, 't' = 116, 'a' = 97, ':' = 58\n */\nfunction isDataPrefix(chunk, i, firstCharCode) {\n return (firstCharCode === 100 &&\n chunk.charCodeAt(i + 1) === 97 &&\n chunk.charCodeAt(i + 2) === 116 &&\n chunk.charCodeAt(i + 3) === 97 &&\n chunk.charCodeAt(i + 4) === 58);\n}\n/**\n * Checks if `chunk` starts with the literal `event:` at index `i`.\n *\n * See {@link isDataPrefix} for why this is hand-unrolled rather than using\n * `String.prototype.startsWith`.\n *\n * ASCII: 'e' = 101, 'v' = 118, 'e' = 101, 'n' = 110, 't' = 116, ':' = 58\n */\nfunction isEventPrefix(chunk, i, firstCharCode) {\n return (firstCharCode === 101 &&\n chunk.charCodeAt(i + 1) === 118 &&\n chunk.charCodeAt(i + 2) === 101 &&\n chunk.charCodeAt(i + 3) === 110 &&\n chunk.charCodeAt(i + 4) === 116 &&\n chunk.charCodeAt(i + 5) === 58);\n}\nfunction isPotentialField(line, field) {\n let i = 1;\n while (i < line.length && i < field.length) {\n if (line.charCodeAt(i) !== field.charCodeAt(i)) {\n return false;\n }\n i++;\n }\n return line.length <= field.length || line.charCodeAt(field.length) === 58;\n}\n//# sourceMappingURL=parse.js.map","/**\n * SSE subscriber that turns `GET {base_path}/events` into callbacks.\n *\n * One connection per (fetch, url), reference-counted and fanned out to every\n * subscriber. The caller passes an already authenticated `fetch`: this is\n * fetch streaming, not `EventSource`, because `EventSource` cannot send an\n * Authorization header. Frames carry no `event:` name: the first has\n * `id: 0` and `{\"subscriber_id\": ...}`; later ones are record events. A\n * reconnect passes `?{resume_param}=<subscriber_id>` explicitly (never\n * `Last-Event-ID`, which the server would read as a subscriber id) when the\n * stream replays, and always tells subscribers to reset, so the gap is\n * covered even without replay. A stream silent for three keep-alive\n * intervals is dead and is reconnected with exponential backoff and jitter.\n * Events invalidate; they never apply snapshots.\n */\nimport { createParser } from \"eventsource-parser\";\nimport type { EventSourceMessage } from \"eventsource-parser\";\nimport type { CrudEvent, MaybePromise } from \"./interfaces.ts\";\n\n/** The manifest's `capabilities.events` object (I1), plain. */\nexport interface EventsConfig {\n /** The server's event label, not the manifest name. */\n readonly resource: string;\n readonly path?: string;\n readonly resume_param?: string;\n readonly replay?: \"persistent\" | \"none\";\n readonly keepalive_seconds?: number;\n}\n\n/**\n * What a subscriber wants to hear. A handler that throws must not kill the\n * stream, so errors are swallowed; handlers run one after another, in order.\n */\nexport interface EventHandlers {\n onEvent(event: CrudEvent): MaybePromise<void>;\n /** After every connect (the first included), and for an event with no usable record id: clear the resource. */\n onReset?(): MaybePromise<void>;\n /** `true` when the stream is connected, `false` on any loss, exit or unsubscribe. */\n onStatus?(connected: boolean): MaybePromise<void>;\n}\n\n/** A shared event stream: `subscribe` returns the (idempotent) unsubscribe. */\nexport interface EventHub {\n subscribe(handlers: EventHandlers): () => void;\n}\n\nexport interface EventHubOptions {\n /** Authenticated; shared hubs are keyed by this function and `url`. */\n readonly fetch: typeof fetch;\n /** Absolute URL of the events endpoint. */\n readonly url: string;\n readonly events: EventsConfig;\n /** Jitter source in `[0, 1)`; defaults to `Math.random`. */\n readonly random?: () => number;\n}\n\nexport interface SubscribeEventsOptions extends EventHubOptions, EventHandlers {\n /** Aborting unsubscribes. */\n readonly signal?: AbortSignal;\n}\n\nconst BACKOFF_START_MS = 1000;\nconst BACKOFF_MAX_MS = 30_000;\nconst DEFAULT_KEEPALIVE_S = 15;\nconst DEAD_AFTER_KEEPALIVES = 3;\nconst ACTIONS: ReadonlySet<unknown> = new Set([\n \"create\",\n \"update\",\n \"delete\",\n \"restore\",\n]);\n\nconst registry = new WeakMap<typeof fetch, Map<string, Hub>>();\n\nfunction sleep(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal.aborted) {\n resolve();\n return;\n }\n const done = (): void => {\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", done);\n resolve();\n };\n const timer = setTimeout(done, ms);\n signal.addEventListener(\"abort\", done, { once: true });\n });\n}\n\nclass Hub {\n private readonly handlers = new Set<EventHandlers>();\n private readonly options: EventHubOptions;\n private readonly onEmpty: () => void;\n private controller: AbortController | undefined;\n private connected = false;\n private subscriberId: string | undefined;\n private attempt = 0;\n\n constructor(options: EventHubOptions, onEmpty: () => void) {\n this.options = options;\n this.onEmpty = onEmpty;\n }\n\n subscribe(handlers: EventHandlers): () => void {\n // The same object may subscribe twice; give each subscription its own identity.\n const entry: EventHandlers = {\n onEvent: (event) => handlers.onEvent(event),\n onReset: () => handlers.onReset?.(),\n onStatus: (connected) => handlers.onStatus?.(connected),\n };\n this.handlers.add(entry);\n if (this.controller === undefined) {\n this.controller = new AbortController();\n void this.run(this.controller.signal);\n } else if (this.connected) {\n void this.guard(() => entry.onStatus?.(true));\n }\n return () => {\n if (!this.handlers.delete(entry)) {\n return;\n }\n void this.guard(() => entry.onStatus?.(false));\n if (this.handlers.size === 0) {\n // Abort the live stream instead of waiting for the next frame.\n this.controller?.abort();\n this.controller = undefined;\n this.onEmpty();\n }\n };\n }\n\n private async guard(\n call: () => MaybePromise<void> | undefined,\n ): Promise<void> {\n try {\n await call();\n } catch {\n // A failing subscriber must not take the stream down.\n }\n }\n\n private async fan(\n call: (handlers: EventHandlers) => MaybePromise<void> | undefined,\n ): Promise<void> {\n for (const handlers of Array.from(this.handlers)) {\n await this.guard(() => call(handlers));\n }\n }\n\n private async setConnected(connected: boolean): Promise<void> {\n if (this.connected === connected) {\n return;\n }\n this.connected = connected;\n await this.fan((handlers) => handlers.onStatus?.(connected));\n }\n\n private backoff(): number {\n const base = Math.min(BACKOFF_START_MS * 2 ** this.attempt, BACKOFF_MAX_MS);\n this.attempt += 1;\n const jitter = (this.options.random ?? Math.random)();\n return Math.min(base * (1 + 0.5 * jitter), BACKOFF_MAX_MS);\n }\n\n /** Connect, read and reconnect until aborted. */\n private async run(signal: AbortSignal): Promise<void> {\n try {\n while (!signal.aborted) {\n try {\n await this.readOnce(signal);\n } catch {\n // Lost, refused or dead: reconnect below.\n }\n await this.setConnected(false);\n await sleep(this.backoff(), signal);\n }\n } finally {\n // On any exit, tell the subscribers so the freshness gate closes.\n await this.setConnected(false);\n }\n }\n\n private resumeUrl(): string {\n const { url, events } = this.options;\n if (events.replay !== \"persistent\" || this.subscriberId === undefined) {\n return url;\n }\n const param = events.resume_param ?? \"subscriber_id\";\n const separator = url.includes(\"?\") ? \"&\" : \"?\";\n return `${url}${separator}${encodeURIComponent(param)}=${encodeURIComponent(this.subscriberId)}`;\n }\n\n private async readOnce(signal: AbortSignal): Promise<void> {\n const keepalive = this.options.events.keepalive_seconds;\n const deadMs =\n (keepalive ?? DEFAULT_KEEPALIVE_S) * DEAD_AFTER_KEEPALIVES * 1000;\n const conn = new AbortController();\n const abortConn = (): void => {\n conn.abort();\n };\n signal.addEventListener(\"abort\", abortConn, { once: true });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const arm = (): void => {\n clearTimeout(timer);\n timer = setTimeout(abortConn, deadMs);\n };\n try {\n arm();\n const response = await this.options.fetch(this.resumeUrl(), {\n headers: { accept: \"text/event-stream\" },\n signal: conn.signal,\n });\n if (!response.ok || response.body === null) {\n throw new Error(`event stream refused: HTTP ${response.status}`);\n }\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n const pending: EventSourceMessage[] = [];\n const parser = createParser({\n onEvent: (message) => {\n pending.push(message);\n },\n });\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n return;\n }\n arm(); // any byte, keep-alive comments included, proves the stream is alive\n parser.feed(decoder.decode(value, { stream: true }));\n for (const message of pending.splice(0)) {\n await this.handle(message);\n }\n }\n } finally {\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", abortConn);\n conn.abort(); // release the connection on every way out\n }\n }\n\n private async handle(message: EventSourceMessage): Promise<void> {\n let data: unknown;\n try {\n data = JSON.parse(message.data);\n } catch {\n return;\n }\n if (typeof data !== \"object\" || data === null || Array.isArray(data)) {\n return;\n }\n const record = data as Record<string, unknown>;\n if (\"subscriber_id\" in record) {\n this.subscriberId = String(record[\"subscriber_id\"]);\n this.attempt = 0;\n // Every connect, the first included: entries stored before this stream\n // (an earlier page session, a persisted store) may predate server changes.\n await this.fan((handlers) => handlers.onReset?.());\n await this.setConnected(true);\n return;\n }\n if (record[\"resource\"] !== this.options.events.resource) {\n return;\n }\n const action = record[\"action\"];\n const recordId = record[\"record_id\"];\n if (!ACTIONS.has(action) || !Number.isInteger(recordId)) {\n await this.fan((handlers) => handlers.onReset?.());\n return;\n }\n const snapshot = record[\"snapshot\"];\n const event: CrudEvent = {\n resource: String(record[\"resource\"]),\n recordId: recordId as number,\n action: action as CrudEvent[\"action\"],\n snapshot:\n typeof snapshot === \"object\" && snapshot !== null\n ? (snapshot as Record<string, unknown>)\n : {},\n timestamp: String(record[\"timestamp\"] ?? \"\"),\n };\n await this.fan((handlers) => handlers.onEvent(event));\n }\n}\n\n/**\n * The shared hub for `(fetch, url)`: the first subscriber opens the stream,\n * the last one aborts it. A later subscribe after that opens a fresh one.\n */\nexport function getEventHub(options: EventHubOptions): EventHub {\n return {\n subscribe(handlers) {\n let hubs = registry.get(options.fetch);\n if (hubs === undefined) {\n hubs = new Map();\n registry.set(options.fetch, hubs);\n }\n const byUrl = hubs;\n let hub = byUrl.get(options.url);\n if (hub === undefined) {\n hub = new Hub(options, () => {\n byUrl.delete(options.url);\n });\n byUrl.set(options.url, hub);\n }\n return hub.subscribe(handlers);\n },\n };\n}\n\n/**\n * Subscribe to one resource's event stream. Returns the unsubscribe; the\n * last unsubscribe aborts the stream. `signal` aborting unsubscribes too.\n */\nexport function subscribeEvents(options: SubscribeEventsOptions): () => void {\n const { signal } = options;\n if (signal?.aborted === true) {\n return () => undefined;\n }\n const unsubscribe = getEventHub(options).subscribe(options);\n signal?.addEventListener(\"abort\", unsubscribe, { once: true });\n return () => {\n signal?.removeEventListener(\"abort\", unsubscribe);\n unsubscribe();\n };\n}\n"],"ignoreList":[1,2],"mappings":";AA8BA,SAAS,QAAQ,OAAwB;CACvC,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IACrD,KAAK,IAAI,OAAO,CAAC,IACjB;AACN;;AAGA,SAAgB,wBACd,UACA,YAAkC,CAAC,GACtB;CACb,MAAM,QAAQ,SAAS,SAAS,CAAC;CACjC,OAAO;EACL,SAAS,UAAU,WAAW;EAC9B,QAAQ,UAAU,UAAU,QAAQ,MAAM,OAAO;EACjD,UAAU,UAAU,YAAY,QAAQ,MAAM,SAAS;EACvD,sBACE,UAAU,wBAAwB,QAAQ,MAAM,sBAAsB;EACxE,MAAM,UAAU,QAAQ,MAAM,SAAS;EACvC,gBAAgB,UAAU,kBAAkB,MAAM,oBAAoB;CACxE;AACF;;;;;AAMA,SAAgB,oBACd,UACA,YAAkC,CAAC,GACtB;CACb,OAAO,wBAAwB,UAAU;EACvC,gBAAgB;EAChB,GAAG;CACL,CAAC;AACH;;;;;;;;AC5DA,IAAa,aAAb,cAAgC,MAAM;CAClC,YAAY,SAAS,SAAS;EAC1B,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO,QAAQ;EACpB,KAAK,QAAQ,QAAQ;EACrB,KAAK,QAAQ,QAAQ;EACrB,KAAK,OAAO,QAAQ;CACxB;AACJ;;;;;;;ACRA,MAAM,KAAK;AACX,MAAM,KAAK;AACX,MAAM,QAAQ;AACd,MAAM,0BAA0B;;;;;;;;;;AAUhC,SAAgB,aAAa,QAAQ;CACjC,IAAI,OAAO,WAAW,YA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;EACrC,IAAI,SAAS,KAAA,GAAW;GACtB,uBAAO,IAAI,IAAI;GACf,SAAS,IAAI,QAAQ,OAAO,IAAI;EAClC;EACA,MAAM,QAAQ;EACd,IAAI,MAAM,MAAM,IAAI,QAAQ,GAAG;EAC/B,IAAI,QAAQ,KAAA,GAAW;GACrB,MAAM,IAAI,IAAI,eAAe;IAC3B,MAAM,OAAO,QAAQ,GAAG;GAC1B,CAAC;GACD,MAAM,IAAI,QAAQ,KAAK,GAAG;EAC5B;EACA,OAAO,IAAI,UAAU,QAAQ;CAC/B,EACF;AACF;;;;;AAMA,SAAgB,gBAAgB,SAA6C;CAC3E,MAAM,EAAE,WAAW;CACnB,IAAI,QAAQ,YAAY,MACtB,aAAa,KAAA;CAEf,MAAM,cAAc,YAAY,OAAO,CAAC,CAAC,UAAU,OAAO;CAC1D,QAAQ,iBAAiB,SAAS,aAAa,EAAE,MAAM,KAAK,CAAC;CAC7D,aAAa;EACX,QAAQ,oBAAoB,SAAS,WAAW;EAChD,YAAY;CACd;AACF"}
@@ -0,0 +1,88 @@
1
+ import { i as MaybePromise, r as CrudEvent } from "./interfaces-s73cVfIF.mjs";
2
+ //#region src/cache/policy.d.ts
3
+ /** Per-resource cache policy, defaulted from the manifest `cache` hints. */
4
+ /**
5
+ * How one resource is cached. Times are seconds. `maxAge` and
6
+ * `staleWhileRevalidate` only take effect while the resource's SSE stream is
7
+ * running; without it every read revalidates. `statsTtl` bounds the staleness
8
+ * of `stats`/`predict` on its own, as the server caches those bodies for the
9
+ * same time. `revalidateOnly` means no fresh window and no
10
+ * stale-while-revalidate.
11
+ */
12
+ interface CachePolicy {
13
+ readonly enabled: boolean;
14
+ readonly maxAge: number;
15
+ readonly statsTtl: number;
16
+ readonly staleWhileRevalidate: number;
17
+ readonly etag: boolean;
18
+ readonly revalidateOnly: boolean;
19
+ }
20
+ /** The manifest resource members a policy reads (I1); everything else is ignored. */
21
+ interface ManifestCacheHints {
22
+ readonly cache?: {
23
+ readonly max_age?: unknown;
24
+ readonly stats_ttl?: unknown;
25
+ readonly stale_while_revalidate?: unknown;
26
+ readonly etag?: unknown;
27
+ readonly revalidate_only?: unknown;
28
+ } | null;
29
+ }
30
+ /** Build a policy from a manifest resource object; `overrides` win over the hints. */
31
+ declare function cachePolicyFromManifest(resource: ManifestCacheHints, overrides?: Partial<CachePolicy>): CachePolicy;
32
+ /**
33
+ * The policy to use under TanStack Query: its `staleTime` decides freshness,
34
+ * so the SDK cache only revalidates (ETag/304) unless told otherwise.
35
+ */
36
+ declare function tanstackCachePolicy(resource: ManifestCacheHints, overrides?: Partial<CachePolicy>): CachePolicy;
37
+ //#endregion
38
+ //#region src/events.d.ts
39
+ /** The manifest's `capabilities.events` object (I1), plain. */
40
+ interface EventsConfig {
41
+ /** The server's event label, not the manifest name. */
42
+ readonly resource: string;
43
+ readonly path?: string;
44
+ readonly resume_param?: string;
45
+ readonly replay?: "persistent" | "none";
46
+ readonly keepalive_seconds?: number;
47
+ }
48
+ /**
49
+ * What a subscriber wants to hear. A handler that throws must not kill the
50
+ * stream, so errors are swallowed; handlers run one after another, in order.
51
+ */
52
+ interface EventHandlers {
53
+ onEvent(event: CrudEvent): MaybePromise<void>;
54
+ /** After every connect (the first included), and for an event with no usable record id: clear the resource. */
55
+ onReset?(): MaybePromise<void>;
56
+ /** `true` when the stream is connected, `false` on any loss, exit or unsubscribe. */
57
+ onStatus?(connected: boolean): MaybePromise<void>;
58
+ }
59
+ /** A shared event stream: `subscribe` returns the (idempotent) unsubscribe. */
60
+ interface EventHub {
61
+ subscribe(handlers: EventHandlers): () => void;
62
+ }
63
+ interface EventHubOptions {
64
+ /** Authenticated; shared hubs are keyed by this function and `url`. */
65
+ readonly fetch: typeof fetch;
66
+ /** Absolute URL of the events endpoint. */
67
+ readonly url: string;
68
+ readonly events: EventsConfig;
69
+ /** Jitter source in `[0, 1)`; defaults to `Math.random`. */
70
+ readonly random?: () => number;
71
+ }
72
+ interface SubscribeEventsOptions extends EventHubOptions, EventHandlers {
73
+ /** Aborting unsubscribes. */
74
+ readonly signal?: AbortSignal;
75
+ }
76
+ /**
77
+ * The shared hub for `(fetch, url)`: the first subscriber opens the stream,
78
+ * the last one aborts it. A later subscribe after that opens a fresh one.
79
+ */
80
+ declare function getEventHub(options: EventHubOptions): EventHub;
81
+ /**
82
+ * Subscribe to one resource's event stream. Returns the unsubscribe; the
83
+ * last unsubscribe aborts the stream. `signal` aborting unsubscribes too.
84
+ */
85
+ declare function subscribeEvents(options: SubscribeEventsOptions): () => void;
86
+ //#endregion
87
+ export { SubscribeEventsOptions as a, CachePolicy as c, tanstackCachePolicy as d, EventsConfig as i, ManifestCacheHints as l, EventHub as n, getEventHub as o, EventHubOptions as r, subscribeEvents as s, EventHandlers as t, cachePolicyFromManifest as u };
88
+ //# sourceMappingURL=events-DpSWzSN9.d.mts.map
@@ -0,0 +1,98 @@
1
+ import { a as Middleware, c as RequestContext, i as MaybePromise, l as TokenProvider, n as CacheStore, o as Next, r as CrudEvent, s as Op, t as CacheEntry, u as composeMiddleware } from "./interfaces-s73cVfIF.mjs";
2
+ import { A as Pagination, C as Capabilities, D as JsonObject, E as GetJson, F as manifestUrlFromCatalog, I as parseManifest, M as Schemas, N as findResource, O as Manifest, P as loadManifest, S as CacheHints, T as FieldSpec, _ as encodeParams, a as PredictOptions, b as AuthSpec, c as RestoreOptions, d as createClient, f as Filters, g as buildQuery, h as Sort, i as ListOptions, j as Resource, k as PROFILE, l as StatsOptions, m as QueryParams, n as ClientOptions, o as RequestOptions, p as QueryField, r as CrudClient, s as ResourceClient, t as BulkResult, u as WriteOptions, v as formatScalar, w as EventsSpec, x as CATALOG_PATH, y as quote } from "./client-BLd126Jt.mjs";
3
+ //#region src/auth.d.ts
4
+ /** The scope of an anonymous caller. */
5
+ export declare const ANON = "anon";
6
+ /**
7
+ * Cache scope of a caller: `"anon"`, or the first 32 hex characters of the
8
+ * SHA-256 of the whole bearer token. Nothing in the token is trusted or
9
+ * decoded (a forged `sub` must not select another caller's entries), and the
10
+ * raw token never leaves this function.
11
+ */
12
+ export declare function cacheScope(token: string | null | undefined): Promise<string>;
13
+ /** A provider that always returns `token` (a refresh changes nothing). */
14
+ export declare function staticToken(token: string | null): TokenProvider;
15
+ //#endregion
16
+ //#region src/errors.d.ts
17
+ /**
18
+ * Error hierarchy: client-side errors and RFC 9457 problem details (ADR-0004).
19
+ * Mirrors the Python SDK class for class.
20
+ */
21
+ /** Base class of every error this package throws on purpose. */
22
+ export declare class CrudError extends Error {
23
+ constructor(message: string, options?: ErrorOptions);
24
+ }
25
+ /** The call was refused before any request was sent. */
26
+ export declare class ClientError extends CrudError {}
27
+ /** The resource does not support the operation (manifest capability or path missing). */
28
+ export declare class CapabilityError extends ClientError {}
29
+ /** A filter, sort or paging argument is not valid for the resource. */
30
+ export declare class InvalidQueryError extends ClientError {}
31
+ /** The discovery document or the manifest is missing, unusable or of an unknown version. */
32
+ export declare class ManifestError extends ClientError {}
33
+ /** The manifest lists no such resource for this caller. */
34
+ export declare class UnknownResourceError extends ClientError {}
35
+ /** A successful response whose body is not the JSON the client expects; `cause` holds the parse error. */
36
+ export declare class ResponseError extends CrudError {}
37
+ /** The request never produced a response; `cause` holds the transport error. */
38
+ export declare class ConnectionFailed extends CrudError {}
39
+ /** One normalized validation error (`422`). */
40
+ interface ProblemDetail {
41
+ readonly loc: readonly (string | number)[];
42
+ readonly msg: string;
43
+ readonly type: string;
44
+ }
45
+ /** Members of a {@link ProblemError}. */
46
+ interface ProblemInit {
47
+ readonly status: number;
48
+ readonly title: string;
49
+ readonly detail?: string | undefined;
50
+ readonly type?: string | undefined;
51
+ readonly instance?: string | undefined;
52
+ readonly errors?: readonly ProblemDetail[] | undefined;
53
+ readonly headers?: Headers | undefined;
54
+ readonly response?: Response | undefined;
55
+ }
56
+ /** An error response, as RFC 9457 problem details. */
57
+ export declare class ProblemError extends CrudError {
58
+ readonly status: number;
59
+ readonly title: string;
60
+ readonly detail: string | undefined;
61
+ readonly type: string;
62
+ readonly instance: string | undefined;
63
+ readonly errors: readonly ProblemDetail[];
64
+ readonly headers: Headers;
65
+ readonly response: Response | undefined;
66
+ constructor(init: ProblemInit);
67
+ }
68
+ /** 400. */
69
+ export declare class BadRequest extends ProblemError {}
70
+ /** 401; `wwwAuthenticate` keeps the challenge. */
71
+ export declare class Unauthorized extends ProblemError {
72
+ get wwwAuthenticate(): string | undefined;
73
+ }
74
+ /** 403. */
75
+ export declare class Forbidden extends ProblemError {}
76
+ /** 404. */
77
+ export declare class NotFound extends ProblemError {}
78
+ /** 412: a stale `If-Match`. */
79
+ export declare class PreconditionFailed extends ProblemError {}
80
+ /** 422; `errors` holds normalized `{loc, msg, type}` entries. */
81
+ export declare class ValidationFailed extends ProblemError {}
82
+ /** 423. */
83
+ export declare class Locked extends ProblemError {}
84
+ /** 429; `retryAfter` is the `Retry-After` header in seconds, when it is a number. */
85
+ export declare class RateLimited extends ProblemError {
86
+ get retryAfter(): number | undefined;
87
+ }
88
+ /** 5xx. */
89
+ export declare class ServerError extends ProblemError {}
90
+ /**
91
+ * Builds the matching `ProblemError` subclass from an error response. A body
92
+ * that is not a JSON object yields a synthesized problem from the status
93
+ * phrase. Reads a clone, so `response.body` stays readable.
94
+ */
95
+ export declare function problemFromResponse(response: Response): Promise<ProblemError>;
96
+ //#endregion
97
+ export { type AuthSpec, type BulkResult, CATALOG_PATH, type CacheEntry, type CacheHints, type CacheStore, type Capabilities, type ClientOptions, CrudClient, type CrudEvent, type EventsSpec, type FieldSpec, type Filters, type GetJson, type JsonObject, type ListOptions, type Manifest, type MaybePromise, type Middleware, type Next, type Op, PROFILE, type Pagination, type PredictOptions, type ProblemDetail, type ProblemInit, type QueryField, type QueryParams, type RequestContext, type RequestOptions, type Resource, ResourceClient, type RestoreOptions, type Schemas, type Sort, type StatsOptions, type TokenProvider, type WriteOptions, buildQuery, composeMiddleware, createClient, encodeParams, findResource, formatScalar, loadManifest, manifestUrlFromCatalog, parseManifest, quote };
98
+ //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs ADDED
@@ -0,0 +1,3 @@
1
+ import { A as UnknownResourceError, C as NotFound, D as ResponseError, E as RateLimited, M as problemFromResponse, N as composeMiddleware, O as ServerError, S as ManifestError, T as ProblemError, _ as ConnectionFailed, a as encodeParams, b as InvalidQueryError, c as CATALOG_PATH, d as loadManifest, f as manifestUrlFromCatalog, g as ClientError, h as CapabilityError, i as buildQuery, j as ValidationFailed, k as Unauthorized, l as PROFILE, m as BadRequest, n as ResourceClient, o as formatScalar, p as parseManifest, r as createClient, s as quote, t as CrudClient, u as findResource, v as CrudError, w as PreconditionFailed, x as Locked, y as Forbidden } from "./client-D0drumeA.mjs";
2
+ import { n as cacheScope, r as staticToken, t as ANON } from "./auth-DwtNEKrw.mjs";
3
+ export { ANON, BadRequest, CATALOG_PATH, CapabilityError, ClientError, ConnectionFailed, CrudClient, CrudError, Forbidden, InvalidQueryError, Locked, ManifestError, NotFound, PROFILE, PreconditionFailed, ProblemError, RateLimited, ResourceClient, ResponseError, ServerError, Unauthorized, UnknownResourceError, ValidationFailed, buildQuery, cacheScope, composeMiddleware, createClient, encodeParams, findResource, formatScalar, loadManifest, manifestUrlFromCatalog, parseManifest, problemFromResponse, quote, staticToken };
@@ -0,0 +1,109 @@
1
+ //#region src/interfaces.d.ts
2
+ /**
3
+ * Contracts shared by the client core (TS1) and the cache layer (TS2).
4
+ * Fixed in TS0 (plan interface I3): change them only through the plan.
5
+ */
6
+ /** A value or a promise of it. */
7
+ type MaybePromise<T> = T | Promise<T>;
8
+ /** What a request does, as classified by the client. */
9
+ type Op = "manifest" | "list" | "record" | "filters" | "stats" | "predict" | "revisions" | "create" | "update" | "delete" | "bulk_update" | "bulk_delete" | "clone" | "draft" | "publish" | "restore" | "events";
10
+ /**
11
+ * One stored `200` response. Times are epoch milliseconds (`Date.now()`).
12
+ * Structured-clone safe, so IndexedDB can store it as is.
13
+ */
14
+ interface CacheEntry {
15
+ readonly status: number;
16
+ readonly headers: ReadonlyArray<readonly [string, string]>;
17
+ /** JSON text; the SDK only caches JSON. */
18
+ readonly body: string;
19
+ readonly storedAt: number;
20
+ /** `<= storedAt` means "always revalidate". */
21
+ readonly freshUntil: number;
22
+ /** End of the stale-while-revalidate window (`>= freshUntil`). */
23
+ readonly staleUntil: number;
24
+ readonly etag?: string;
25
+ }
26
+ /**
27
+ * Cache backend. Keys are opaque, slash-separated strings built by
28
+ * `./cache`'s `cacheKey`
29
+ * (`v1/{resource}/{kind}/{subject}/{apiVersion}/{scope}/{query}`, with `_`
30
+ * when there is no apiVersion).
31
+ * `ttlMs` is how long the backend may keep the entry (undefined = backend
32
+ * default); freshness lives in `CacheEntry`. `clear(prefix)` removes every
33
+ * key starting with `prefix`; `clear()` removes everything the store owns.
34
+ * Methods may be sync or async. They must not reject for a missing key
35
+ * (`get` resolves `undefined`), and a failing backend must not fail the
36
+ * request: the cache layer swallows store errors and treats them as a miss.
37
+ */
38
+ interface CacheStore {
39
+ get(key: string): MaybePromise<CacheEntry | undefined>;
40
+ set(key: string, entry: CacheEntry, ttlMs?: number): MaybePromise<void>;
41
+ delete(key: string): MaybePromise<void>;
42
+ clear(prefix?: string): MaybePromise<void>;
43
+ }
44
+ /**
45
+ * What the client knows about a request that a bare `Request` does not. The
46
+ * client builds it for every call; middleware read it, so they never parse
47
+ * URLs or read Authorization.
48
+ */
49
+ interface RequestContext {
50
+ /** The request about to be sent; replace it by passing a new context to `next`. */
51
+ readonly request: Request;
52
+ /** Manifest name; `undefined` for the manifest document itself. */
53
+ readonly resource: string | undefined;
54
+ readonly op: Op;
55
+ /** The record the request targets, when it targets one. */
56
+ readonly recordId: number | undefined;
57
+ /**
58
+ * "anon", or the first 32 hex characters of the SHA-256 of the
59
+ * Authorization credential actually sent.
60
+ */
61
+ readonly scope: string;
62
+ /**
63
+ * The resource's `api_version` from the manifest, or `null` when it has
64
+ * none. Part of the cache key, so versions never share entries (the cache
65
+ * layer renders `null` as `_`).
66
+ */
67
+ readonly apiVersion: string | null;
68
+ readonly signal: AbortSignal | undefined;
69
+ }
70
+ /** Calls the next middleware, or the network when none is left. */
71
+ type Next = (ctx: RequestContext) => Promise<Response>;
72
+ /**
73
+ * Onion middleware. In `chain = [a, b]`, `a` is outermost: the request runs
74
+ * a -> b -> fetch and the response returns fetch -> b -> a. A middleware may
75
+ * replace `ctx.request` (pass `{ ...ctx, request }` to `next`), return
76
+ * without calling `next` (short-circuit, e.g. a fresh cache hit), or replace
77
+ * the response (e.g. a `304` rebuilt from the cache). It must not consume
78
+ * `response.body` unless it returns a different `Response`; use
79
+ * `response.clone()` to read it.
80
+ */
81
+ type Middleware = (ctx: RequestContext, next: Next) => Promise<Response>;
82
+ /**
83
+ * Returns the bearer token, or `null`/`undefined` for an anonymous call.
84
+ * `refresh: true` is passed once after a `401`, to force a new token.
85
+ */
86
+ type TokenProvider = (opts: {
87
+ readonly refresh: boolean;
88
+ }) => MaybePromise<string | null | undefined>;
89
+ /** One record-mutation event from `GET {basePath}/events` (the server's event envelope). */
90
+ interface CrudEvent {
91
+ /** The server's event label (e.g. "hero"), not the manifest name. */
92
+ readonly resource: string;
93
+ readonly recordId: number;
94
+ readonly action: "create" | "update" | "delete" | "restore";
95
+ /** The read view of the record after the change. */
96
+ readonly snapshot: Readonly<Record<string, unknown>>;
97
+ /** ISO 8601, UTC. */
98
+ readonly timestamp: string;
99
+ }
100
+ /**
101
+ * Folds `chain` (outermost first) around `terminal`, usually the network
102
+ * `fetch`, into one `Next`. Each middleware's `next` is the rest of the
103
+ * chain; an empty chain is `terminal`. A throwing middleware yields a
104
+ * rejected promise.
105
+ */
106
+ declare function composeMiddleware(chain: readonly Middleware[], terminal: Next): Next;
107
+ //#endregion
108
+ export { Middleware as a, RequestContext as c, MaybePromise as i, TokenProvider as l, CacheStore as n, Next as o, CrudEvent as r, Op as s, CacheEntry as t, composeMiddleware as u };
109
+ //# sourceMappingURL=interfaces-s73cVfIF.d.mts.map
@@ -0,0 +1,182 @@
1
+ import { r as CrudEvent } from "../interfaces-s73cVfIF.mjs";
2
+ import { a as SubscribeEventsOptions, c as CachePolicy, d as tanstackCachePolicy, i as EventsConfig, l as ManifestCacheHints, n as EventHub, o as getEventHub, r as EventHubOptions, s as subscribeEvents, t as EventHandlers } from "../events-DpSWzSN9.mjs";
3
+ import { D as JsonObject, O as Manifest, r as CrudClient, s as ResourceClient } from "../client-BLd126Jt.mjs";
4
+ import { DataTag, QueryClient } from "@tanstack/query-core";
5
+ //#region src/tanstack/adapter.d.ts
6
+ type Init = {
7
+ signal?: AbortSignal;
8
+ };
9
+ /** What `tanstackApi` returns: every slice the factories use, bound to one resource. */
10
+ interface TanstackApi<Read, Create, Update> {
11
+ list(query: CrudQuery | undefined, init?: Init): Promise<Read[]>;
12
+ get(id: number, init?: Init): Promise<Read>;
13
+ stats(query: CrudQuery | undefined, init?: Init): Promise<JsonObject>;
14
+ predict(query: CrudQuery | undefined, init?: Init): Promise<JsonObject>;
15
+ revisions(id: number, init?: Init): Promise<JsonObject[]>;
16
+ /** The manifest the client already loaded (the client's loader takes no signal). */
17
+ manifest(init?: Init): Promise<Manifest>;
18
+ create(body: Create): Promise<Read>;
19
+ update(id: number, patch: Update, init?: {
20
+ ifMatch?: string;
21
+ }): Promise<Read>;
22
+ delete(id: number): Promise<void>;
23
+ }
24
+ /**
25
+ * A query is the client's `ListOptions`, `StatsOptions` or `PredictOptions`
26
+ * without `signal` (`{ filters, sort, skip, limit, ... }`); TanStack's signal
27
+ * is added per call.
28
+ */
29
+ export declare function tanstackApi<Read extends object, Create extends object, Update extends object>(client: CrudClient, resource: ResourceClient<Read, Create, Update>): TanstackApi<Read, Create, Update>;
30
+ //#endregion
31
+ //#region src/tanstack/index.d.ts
32
+ /** A query object as the client's query builder takes it. */
33
+ export type CrudQuery = Readonly<Record<string, unknown>>;
34
+ type Key = readonly unknown[];
35
+ /** The key factory type. */
36
+ export interface CrudKeys {
37
+ readonly all: readonly ["crud"];
38
+ /** Everything of one resource. */
39
+ resource(resource: string): readonly ["crud", string];
40
+ /** All lists of one resource, plain and infinite. */
41
+ lists(resource: string): readonly ["crud", string, "list"];
42
+ list(resource: string, query?: CrudQuery): Key;
43
+ infiniteList(resource: string, query: CrudQuery, limit: number): Key;
44
+ /** All record queries of one resource. */
45
+ records(resource: string): readonly ["crud", string, "record"];
46
+ record(resource: string, id: number): readonly ["crud", string, "record", number];
47
+ stats(resource: string, query?: CrudQuery): Key;
48
+ predict(resource: string, query?: CrudQuery): Key;
49
+ revisions(resource: string, id: number): readonly ["crud", string, "revisions", number];
50
+ /** The manifest, optionally of one caller scope. */
51
+ manifest(scope?: string): Key;
52
+ }
53
+ /** The key factory. Every key starts with `["crud", resource, ...]`, so prefixes invalidate by resource, kind or record. */
54
+ export declare const crudKeys: CrudKeys;
55
+ /** What a query function receives from TanStack Query (a subset). */
56
+ export interface QueryContext {
57
+ readonly signal: AbortSignal;
58
+ }
59
+ export interface QueryOptionsInit {
60
+ /** TanStack's `staleTime` in milliseconds. Default 0 (the SDK cache revalidates for free). */
61
+ readonly staleTime?: number;
62
+ }
63
+ /** Plain query options with a typed key; spread into `useQuery`/`fetchQuery`. */
64
+ export interface CrudQueryOptions<T> {
65
+ readonly queryKey: DataTag<Key, T, Error>;
66
+ readonly queryFn: (context: QueryContext) => Promise<T>;
67
+ readonly staleTime: number;
68
+ }
69
+ export interface CrudInfiniteQueryOptions<T> {
70
+ readonly queryKey: DataTag<Key, {
71
+ pages: T[][];
72
+ pageParams: number[];
73
+ }, Error>;
74
+ readonly queryFn: (context: QueryContext & {
75
+ pageParam: number;
76
+ }) => Promise<T[]>;
77
+ readonly initialPageParam: number;
78
+ /** `skip + limit` unless the page was short. */
79
+ readonly getNextPageParam: (lastPage: T[], allPages: T[][], lastPageParam: number) => number | undefined;
80
+ readonly staleTime: number;
81
+ }
82
+ /** The slices of a resource API the factories call (structural: TS1's resource client fits). */
83
+ export interface ListApi<T> {
84
+ list(query: CrudQuery | undefined, init?: {
85
+ signal?: AbortSignal;
86
+ }): Promise<T[]>;
87
+ }
88
+ export interface RecordApi<T> {
89
+ get(id: number, init?: {
90
+ signal?: AbortSignal;
91
+ }): Promise<T>;
92
+ }
93
+ export interface StatsApi<S> {
94
+ stats(query: CrudQuery | undefined, init?: {
95
+ signal?: AbortSignal;
96
+ }): Promise<S>;
97
+ }
98
+ export interface PredictApi<P> {
99
+ predict(query: CrudQuery | undefined, init?: {
100
+ signal?: AbortSignal;
101
+ }): Promise<P>;
102
+ }
103
+ export interface RevisionsApi<R> {
104
+ revisions(id: number, init?: {
105
+ signal?: AbortSignal;
106
+ }): Promise<R[]>;
107
+ }
108
+ export interface ManifestApi<M> {
109
+ manifest(init?: {
110
+ signal?: AbortSignal;
111
+ }): Promise<M>;
112
+ }
113
+ export interface CreateApi<T, C> {
114
+ create(body: C): Promise<T>;
115
+ }
116
+ export interface UpdateApi<T, P> {
117
+ update(id: number, patch: P, init?: {
118
+ ifMatch?: string;
119
+ }): Promise<T>;
120
+ }
121
+ export interface DeleteApi {
122
+ delete(id: number): Promise<unknown>;
123
+ }
124
+ export declare function listOptions<T>(resource: string, api: ListApi<T>, query?: CrudQuery, init?: QueryOptionsInit): CrudQueryOptions<T[]>;
125
+ export declare function recordOptions<T>(resource: string, api: RecordApi<T>, id: number, init?: QueryOptionsInit): CrudQueryOptions<T>;
126
+ export declare function statsOptions<S>(resource: string, api: StatsApi<S>, query?: CrudQuery, init?: QueryOptionsInit): CrudQueryOptions<S>;
127
+ export declare function predictOptions<P>(resource: string, api: PredictApi<P>, query?: CrudQuery, init?: QueryOptionsInit): CrudQueryOptions<P>;
128
+ export declare function revisionsOptions<R>(resource: string, api: RevisionsApi<R>, id: number, init?: QueryOptionsInit): CrudQueryOptions<R[]>;
129
+ export declare function manifestOptions<M>(api: ManifestApi<M>, scope?: string, init?: QueryOptionsInit): CrudQueryOptions<M>;
130
+ export interface InfiniteListInit extends QueryOptionsInit {
131
+ /** Page size; default 100 (the server's default). */
132
+ readonly limit?: number;
133
+ /**
134
+ * Keys of the paging parameters in the query object handed to `api.list`.
135
+ * Default `skip`/`limit`, which is what `tanstackApi` (the client's
136
+ * `ListOptions`) reads; change them only for a hand-written `ListApi`. The
137
+ * client maps them to the manifest's `skip_param`/`limit_param` itself.
138
+ */
139
+ readonly skipKey?: string;
140
+ readonly limitKey?: string;
141
+ }
142
+ /** Offset paging: the next page starts at `skip + limit`, unless the last page was short. */
143
+ export declare function infiniteListOptions<T>(resource: string, api: ListApi<T>, query?: CrudQuery, init?: InfiniteListInit): CrudInfiniteQueryOptions<T>;
144
+ export type Invalidator = Pick<QueryClient, "invalidateQueries" | "removeQueries" | "setQueryData">;
145
+ export interface CreateMutationOptions<T, C> {
146
+ readonly mutationKey: readonly ["crud", string, "create"];
147
+ readonly mutationFn: (body: C) => Promise<T>;
148
+ readonly onSuccess: () => Promise<void>;
149
+ }
150
+ export interface UpdateMutationOptions<T, P> {
151
+ readonly mutationKey: readonly ["crud", string, "update"];
152
+ readonly mutationFn: (variables: UpdateVariables<P>) => Promise<T>;
153
+ readonly onSuccess: (record: T, variables: UpdateVariables<P>) => Promise<void>;
154
+ }
155
+ export interface DeleteMutationOptions {
156
+ readonly mutationKey: readonly ["crud", string, "delete"];
157
+ readonly mutationFn: (id: number) => Promise<unknown>;
158
+ readonly onSuccess: (result: unknown, id: number) => Promise<void>;
159
+ }
160
+ /** Create: invalidate lists, stats and predict. */
161
+ export declare function createMutationOptions<T, C>(client: Invalidator, resource: string, api: CreateApi<T, C>): CreateMutationOptions<T, C>;
162
+ export interface UpdateVariables<P> {
163
+ readonly id: number;
164
+ readonly patch: P;
165
+ /** Sent as `If-Match`; a stale one fails with 412. */
166
+ readonly ifMatch?: string;
167
+ }
168
+ /** Update: `setQueryData` from the PATCH response, invalidate lists, stats, predict and revisions. */
169
+ export declare function updateMutationOptions<T, P>(client: Invalidator, resource: string, api: UpdateApi<T, P>): UpdateMutationOptions<T, P>;
170
+ /** Delete: drop the record query, invalidate lists, stats, predict and revisions. */
171
+ export declare function deleteMutationOptions(client: Invalidator, resource: string, api: DeleteApi): DeleteMutationOptions;
172
+ /**
173
+ * Invalidate TanStack queries from the resource's event stream. Events
174
+ * invalidate and never apply snapshots: `create` invalidates lists, stats and
175
+ * predict; `update`/`delete`/`restore` also the record and its revisions; a
176
+ * reconnect (or an event with no usable record id) invalidates the resource.
177
+ * Returns the unsubscribe.
178
+ */
179
+ export declare function bridgeEvents(client: Pick<QueryClient, "invalidateQueries">, hub: EventHub, resource: string): () => void;
180
+ //#endregion
181
+ export { type CachePolicy, type CrudEvent, type EventHandlers, type EventHub, type EventHubOptions, type EventsConfig, type ManifestCacheHints, type SubscribeEventsOptions, type TanstackApi, getEventHub, subscribeEvents, tanstackCachePolicy };
182
+ //# sourceMappingURL=index.d.mts.map