@volter/twin-algolia 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.
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@volter/twin-algolia",
3
+ "version": "0.1.0",
4
+ "description": "Local Algolia twin for the hosted-search surface: index list/delete/clear, record CRUD (add-auto-objectID/add-replace/get/partial/delete/batch), browse-adjacent record listing, a REAL search engine (tokenize + Damerau-Levenshtein typo tolerance + a faithful-subset ranking + REAL filter/facetFilters evaluation + exact facet-count aggregation + customRanking tie-breaks + basic bidirectional synonym expansion), settings get/set, multi-index, and a host-tolerant router, built on @volter/world-core.",
5
+ "author": "Volter (https://github.com/volter-ai)",
6
+ "license": "Apache-2.0",
7
+ "files": [
8
+ "src",
9
+ "README.md",
10
+ "LICENSE",
11
+ "!**/*.test.ts",
12
+ "dist"
13
+ ],
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/volter-ai/twin.git",
17
+ "directory": "packages/twin/algolia"
18
+ },
19
+ "homepage": "https://github.com/volter-ai/twin/tree/main/packages/twin/algolia#readme",
20
+ "type": "module",
21
+ "exports": {
22
+ ".": {
23
+ "types": "./dist/src/index.d.ts",
24
+ "default": "./dist/src/index.js"
25
+ }
26
+ },
27
+ "bin": {
28
+ "world-algolia": "dist/src/cli.js"
29
+ },
30
+ "scripts": {
31
+ "test": "bun test src/*.test.ts",
32
+ "typecheck": "tsc --noEmit",
33
+ "build": "node ../../../scripts/publish/build.mjs",
34
+ "prepack": "node ../../../scripts/publish/prepare-publish.mjs prepack",
35
+ "postpack": "node ../../../scripts/publish/prepare-publish.mjs postpack"
36
+ },
37
+ "peerDependencies": {
38
+ "@volter/world-core": "2.0.0"
39
+ },
40
+ "devDependencies": {
41
+ "@types/bun": "^1.2.20",
42
+ "@types/node": "^24.0.0",
43
+ "@volter/world-core": "2.0.0",
44
+ "@volter/world-tooling": "0.1.0",
45
+ "algoliasearch": "4.27.0",
46
+ "typescript": "^5.9.0"
47
+ },
48
+ "engines": {
49
+ "node": ">=22.3"
50
+ }
51
+ }
@@ -0,0 +1,462 @@
1
+ // Algolia's CLIENT-SIDE RATE BUDGET — the pack's DECLARATION (the numbers) plus `guardAlgoliaClient`,
2
+ // the choke point every live Algolia call goes through. The MECHANISM — the durable token-keyed
3
+ // ledger, the rolling window, reserve-under-lock, the `Retry-After`/429 cooldown, fail-CLOSED on a
4
+ // corrupt ledger — lives ONCE in the vendor-agnostic kernel (`@volter/world-core` → `rateBudget.ts`).
5
+ // Read that module's header for the full rationale AND for the honest list of what the guard does
6
+ // NOT guarantee (an injected clock or ledger path still defeats it — it guards carelessness, not
7
+ // malice). This module is modeled on notion-budget.ts, the reference injected-client decorator.
8
+ //
9
+ // ── WHY ALGOLIA NEEDS ONE ───────────────────────────────────────────────────────────
10
+ // Algolia does NOT publish a scalar rate limit for the endpoints this connector uses.
11
+ // The published limits table (algolia.com/doc/guides/scaling/algolia-service-limits) covers ADJACENT
12
+ // APIs only — Connectors Push and Observability at 2000 calls/min/IP, "all other" Connectors
13
+ // endpoints at 200/min/IP, the Analytics API at 100 calls/min/app, DocSearch at 3 queries/second —
14
+ // and the Search REST reference has no rate-limit or 429 section at all. Per-plan max QPS is
15
+ // plan-derived and explicitly "reach out to Support to find out"; `maxQueriesPerIPPerHour` is a
16
+ // CUSTOMER-SET restriction whose default is 0 (meaning no limit), so it is not a vendor limit either.
17
+ // Algolia additionally documents that `browse` is EXCLUDED from search-QPS accounting — which means
18
+ // the endpoint this connector leans on hardest is the one with the least published ceiling of all.
19
+ // That combination — no number to aim at, plus an unmetered fan-out endpoint — is exactly when a
20
+ // conservative client-side ceiling matters most.
21
+ //
22
+ // ── HOW THE CEILING WAS CHOSEN ──────────────────────────────────────────────────────────────
23
+ // NO DOCUMENTED SCALAR LIMIT was found for search/browse/listIndices, so this budget does NOT
24
+ // claim one. It is pinned to the kernel's own conservative fallback (DEFAULT_RATE_BUDGET: 60 weighted
25
+ // units per 60s at a default weight of 2, i.e. 30 calls/minute) — identical in call count, strictly
26
+ // TIGHTER on the browse aggregation. Nothing here is more permissive than what an undeclared vendor
27
+ // already gets; the value the declaration adds is the per-endpoint pricing below, plus a `reason`
28
+ // that records honestly that the number is prudence and not vendor fact.
29
+ //
30
+ // ── WHAT THIS DOES NOT DO: PACE ─────────────────────────────────────────────────────────────
31
+ // It bounds the 60s AVERAGE; it does NOT bound the instantaneous rate. The window has no
32
+ // spacing, so a tight `await` loop can legitimately fire the whole allowance in a fraction of a
33
+ // second. In that shape the vendor's own 429 can arrive BEFORE this ceiling does, and the backstop
34
+ // is then the COOLDOWN: the guard reads the back-off off the thrown error (or the response's
35
+ // exhaustion headers) and refuses every later call without touching the vendor. So the honest claim
36
+ // is "bounds the 60s average, and converts the vendor's first 429 into a hard stop" — never
37
+ // "refuses before the vendor ever 429s". Pacing is the CALLER's job; this module REFUSES, it never
38
+ // sleeps (see the kernel header: it is deliberately not a scheduler). A tighter window would not
39
+ // close the gap, it would only turn every legitimate multi-page pull into a cascade of refusals.
40
+ //
41
+ // ── HOW THE WEIGHTS WERE CHOSEN (and what is a judgement call) ──────────────────────────────
42
+ // `listRecords` costs 4, twice everything else. This is a JUDGEMENT CALL, not a published cost:
43
+ // Algolia charges per operation, not per browse. It is priced up because it is this connector's only
44
+ // UNBOUNDED endpoint — a real implementation loops `listIndices()` then browses every index's objects
45
+ // and flattens the result, so one innocent call fans out into as many requests as the account has
46
+ // indexes times pages. Doubling its price halves the depth at which a runaway browse is stopped while
47
+ // barely touching a normal pull, which is one `listIndices` plus one aggregation. Called out here
48
+ // rather than dressed up as vendor fact.
49
+ import {
50
+ declareRateBudget,
51
+ rateBudgetPath,
52
+ rateBudgetWeight,
53
+ RateBudget,
54
+ RateBudgetError,
55
+ type RateBudgetDeclaration,
56
+ type RateBudgetOptions,
57
+ type RateBudgetReservation,
58
+ type RateBudgetSnapshot,
59
+ } from '@volter/world-core';
60
+ import type { AlgoliaLikeClient } from './algolia-connector.ts';
61
+
62
+ const VENDOR = 'algolia';
63
+
64
+ /** Rolling window, in ms. Spend older than this is pruned. */
65
+ export const ALGOLIA_BUDGET_WINDOW_MS = 60_000;
66
+
67
+ /** Weighted units allowed inside one window. See the header for where this number comes from. */
68
+ export const ALGOLIA_BUDGET_CEILING = 60;
69
+
70
+ /** Seconds. A `Retry-After` above this means the credential is throttled hard — fail loudly. */
71
+ export const ALGOLIA_BUDGET_MAX_RETRY_AFTER_S = 300;
72
+
73
+ /** Per-call cost, keyed by the client method the guard is about to invoke. See the header. */
74
+ export const ALGOLIA_CALL_WEIGHTS = {
75
+ /** `listRecords` — the cross-index browse aggregation, the unbounded fan-out. */
76
+ browse: 4,
77
+ /** Every other modeled call (`listIndices`, and anything unclassified). */
78
+ other: 2,
79
+ } as const;
80
+
81
+ /**
82
+ * The client methods this pack PRICES BY NAME, as dotted paths into the injected client.
83
+ *
84
+ * Two kinds of entry: (a) every method this connector actually calls, and (b) an endpoint the
85
+ * VENDOR documents in a distinct tier which a consumer can reach through the guarded client even
86
+ * though this connector never calls it (see the weights section of the header). Used to build the
87
+ * guarded surface — and, in the pack's own suite, the counting fake.
88
+ *
89
+ * NOT a closed list, and not a claim about the injected client's shape. A path the real client does
90
+ * not have is SKIPPED (this connector's members are optional; inventing one would turn "observe
91
+ * nothing" into "call something that isn't there"), and a method absent from this list is still
92
+ * PRICED at `defaultWeight` when a caller reaches for it — an unmodeled endpoint must never be
93
+ * free, and dropping one would be worse than free because it would be invisible.
94
+ */
95
+ export const ALGOLIA_BUDGETED_METHODS = [
96
+ 'listIndices',
97
+ 'listRecords',
98
+ ] as const;
99
+
100
+ /** THE PACK'S DECLARATION — pure data, the only Algolia-specific thing in the whole budget. */
101
+ export const ALGOLIA_RATE_BUDGET: RateBudgetDeclaration = {
102
+ windowMs: ALGOLIA_BUDGET_WINDOW_MS,
103
+ ceiling: ALGOLIA_BUDGET_CEILING,
104
+ defaultWeight: ALGOLIA_CALL_WEIGHTS.other,
105
+ maxRetryAfterSeconds: ALGOLIA_BUDGET_MAX_RETRY_AFTER_S,
106
+ // Ordered: the kernel prices FIRST-MATCH-WINS, so the tightest tier is listed first.
107
+ rules: [
108
+ { match: "(^|\\.)listRecords$", weight: ALGOLIA_CALL_WEIGHTS.browse },
109
+ ],
110
+ reason:
111
+ "Algolia publishes NO scalar rate limit for the Search API, browse, or listIndices — the documented " +
112
+ "limits table covers only the Connectors (2000/min/IP push, 200/min/IP other), Analytics (100/min/app) " +
113
+ "and DocSearch (3 q/s) surfaces, per-plan max QPS is \"contact Support\", and browse is explicitly " +
114
+ "EXCLUDED from search-QPS accounting. With no published figure to aim at, this ceiling is pinned to the " +
115
+ "kernel's conservative fallback (60 units / 60s at weight 2 = 30 calls/min) rather than invented: it is " +
116
+ "no more permissive than an undeclared vendor already gets. listRecords costs 4 because it is the " +
117
+ "cross-index browse aggregation a pagination bug turns into hundreds of calls — a judgement call, not a " +
118
+ "published cost. Algolia does not document Retry-After; the 429/exhaustion cooldown is the backstop.",
119
+ };
120
+
121
+ // Declared at module load, so merely importing this module (which `algolia-connector.ts` does) is
122
+ // enough to arm the real ceiling. A budget constructed BEFORE this runs falls back to the kernel's
123
+ // DEFAULT_RATE_BUDGET — which is tighter in call COUNT but prices every call at 2, so for a vendor
124
+ // with an expensive endpoint the fallback is CHEAPER there, not safer. `RateBudget` reads its policy
125
+ // LIVE precisely so this declaration takes effect the moment it lands, and constructing through the
126
+ // subclass below (whose module IS this one) makes the ordering a non-issue in practice.
127
+ declareRateBudget(VENDOR, ALGOLIA_RATE_BUDGET);
128
+
129
+ /** Price one Algolia call by its client method key (a dotted path, e.g. `listIndices`). */
130
+ export function algoliaCallWeight(method: string): number {
131
+ return rateBudgetWeight(VENDOR, method);
132
+ }
133
+
134
+ /** Where Algolia's ledger lives. Token-keyed and cwd-independent by default (the vendor limits per
135
+ * credential, so a cwd-scoped ledger would hand the same credential a fresh allowance in every
136
+ * checkout, worktree and CI matrix leg); pass `root` to opt into world-scoped accounting. */
137
+ export function algoliaBudgetPath(opts: { root?: string; token?: string } | string = {}): string {
138
+ const o = typeof opts === 'string' ? { root: opts } : opts;
139
+ // VENDOR spread LAST: a loosely-typed `{ vendor: 'other', … }` slipping through (TypeScript's
140
+ // excess-property check only catches object literals) must not redirect this pack's ledger to
141
+ // another vendor's file.
142
+ return rateBudgetPath({ ...o, vendor: VENDOR });
143
+ }
144
+
145
+ /** Construction options for Algolia's budget. The vendor is fixed; everything else may only TIGHTEN. */
146
+ export type AlgoliaBudgetOptions = Omit<RateBudgetOptions, 'vendor'>;
147
+
148
+ /**
149
+ * Algolia's budget — the shared kernel guard bound to this vendor's declaration. A real subclass,
150
+ * not an alias, so `budget instanceof AlgoliaBudget` means "a budget that accounts against this
151
+ * vendor's ledger under this vendor's ceiling": another vendor's `RateBudget` (with its own,
152
+ * possibly larger, ceiling) is NOT assignable where one of these is required.
153
+ */
154
+ export class AlgoliaBudget extends RateBudget {
155
+ constructor(opts: AlgoliaBudgetOptions = {}) {
156
+ super({ ...opts, vendor: VENDOR });
157
+ }
158
+ }
159
+
160
+ export type { RateBudgetErrorKind as AlgoliaBudgetErrorKind } from '@volter/world-core';
161
+ export { RateBudgetError as AlgoliaBudgetError } from '@volter/world-core';
162
+ export type AlgoliaBudgetReservation = RateBudgetReservation;
163
+ export type AlgoliaBudgetSnapshot = RateBudgetSnapshot;
164
+
165
+ /** What every budgeted connector entrypoint accepts. There is deliberately no option that turns the
166
+ * guard OFF — only ones that say WHICH ledger and clock to account against. */
167
+ export type AlgoliaBudgetedOptions = {
168
+ /** An existing budget to share across calls. Omit and one is constructed. Cannot be null. */
169
+ budget?: AlgoliaBudget;
170
+ /** Construction options for the default budget (ledger path, clock). Cannot loosen it. */
171
+ budgetOptions?: AlgoliaBudgetOptions;
172
+ };
173
+
174
+ /** Pull the budget wiring out of a caller's opts bag, so an entrypoint can forward it verbatim. */
175
+ export function algoliaBudgetOf(opts: AlgoliaBudgetedOptions): AlgoliaBudgetedOptions {
176
+ return {
177
+ ...(opts.budget !== undefined ? { budget: opts.budget } : {}),
178
+ ...(opts.budgetOptions !== undefined ? { budgetOptions: opts.budgetOptions } : {}),
179
+ };
180
+ }
181
+
182
+ // ── the choke point ─────────────────────────────────────────────────────────────────────────
183
+
184
+ /**
185
+ * Marks a client this module has already wrapped, so guarding twice cannot charge twice.
186
+ *
187
+ * A MODULE-PRIVATE `Symbol()`, deliberately not `Symbol.for()`: a global-registry symbol is
188
+ * reachable BY NAME, so any caller could stamp `client[Symbol.for(…)] = anything` on a RAW client and
189
+ * the guard would hand it straight back UNGUARDED — a one-line bypass of the whole budget. With a
190
+ * private symbol the only way to be branded is to have been wrapped by this function. The cost is
191
+ * that two copies of this module in one dependency tree would each wrap (double-charging a call);
192
+ * that is the SAFE direction, and over-charging is the tradeoff this module takes everywhere else.
193
+ */
194
+ const GUARDED: unique symbol = Symbol('@volter/twin-algolia.budget.guarded');
195
+
196
+ type Guarded = { [GUARDED]?: unknown };
197
+
198
+ /** Is this client already behind a budget? Returns the budget it is behind, if so. */
199
+ export function algoliaClientBudget(client: unknown): RateBudget | undefined {
200
+ const mark = (client as Guarded | null)?.[GUARDED];
201
+ // Belt and braces: only a REAL budget counts as "already guarded". A non-RateBudget value here
202
+ // could only come from a forged brand, and the answer to a forgery is to wrap anyway.
203
+ return mark instanceof RateBudget ? mark : undefined;
204
+ }
205
+
206
+ /** Charge a call keyed by `method`, invoke it, settle. Returns whatever the call returned. */
207
+ type Charge = (method: string, invoke: (...args: unknown[]) => unknown) => (...args: unknown[]) => unknown;
208
+
209
+ /**
210
+ * Wrap an INJECTED Algolia client so EVERY call it makes is charged against the shared budget
211
+ * BEFORE the request goes out. This pack's connector never constructs the transport itself (the
212
+ * consumer injects a client that satisfies `AlgoliaLikeClient` structurally), so the guard is a
213
+ * DECORATOR rather than a factory — which is exactly why every connector entrypoint applies it
214
+ * UNCONDITIONALLY instead of trusting the caller to have done it.
215
+ *
216
+ * IDEMPOTENT: wrapping an already-guarded client returns it unchanged, so a caller who forgot is
217
+ * protected and a caller who wrapped deliberately is not double-charged.
218
+ *
219
+ * A method that THROWS is still inspected: an SDK typically RAISES on a 429 rather than returning
220
+ * it, and that error's back-off is exactly the signal that must become a persisted cooldown. Losing
221
+ * it would leave the ledger cheerfully spending into a throttled credential. The original error is
222
+ * always re-raised afterwards — the budget never swallows a vendor failure — EXCEPT when the
223
+ * back-off is beyond the cap, where the budget's own louder "stop calling" error takes precedence.
224
+ */
225
+ export function guardAlgoliaClient(client: AlgoliaLikeClient, opts: AlgoliaBudgetedOptions = {}): AlgoliaLikeClient {
226
+ // There is no value a caller can pass to end up with an UNGUARDED client. `null`/`undefined` (or
227
+ // omitting it) build the default budget; anything that is not a REAL `AlgoliaBudget` is refused
228
+ // loudly rather than trusted — a duck-typed stand-in with a no-op `checkBudget` would otherwise be
229
+ // the one clean way around the guard. Validated BEFORE the already-guarded early return, so
230
+ // `guardAlgoliaClient(alreadyGuarded, { budget: impostor })` is refused too rather than silently
231
+ // ignoring the impostor.
232
+ if (opts.budget !== undefined && opts.budget !== null && !(opts.budget instanceof AlgoliaBudget)) {
233
+ throw new Error('guardAlgoliaClient: `budget` must be a AlgoliaBudget — refusing to guard a Algolia client with an unverified rate guard');
234
+ }
235
+ if (algoliaClientBudget(client)) return client;
236
+ const budget = opts.budget instanceof AlgoliaBudget
237
+ ? opts.budget
238
+ : new AlgoliaBudget({
239
+ // The default ledger is keyed by a hash of the credential — the vendor limits per credential,
240
+ // so a cwd-scoped ledger would hand it a fresh allowance per worktree/CI leg.
241
+ //
242
+ // HONESTLY: this pack does NOT hold the credential — the consumer's injected client does — so
243
+ // `ALGOLIA_API_KEY` is a BEST-EFFORT stand-in for it, not the real thing. If that env var names a
244
+ // different account than the injected client, spend is booked against the wrong ledger; if it
245
+ // is unset, every unattributed Algolia credential on the machine shares one (over-tight,
246
+ // which is the safe direction). A caller who knows the credential should say so:
247
+ // `budgetOptions: { token }` overrides this, and does so deliberately last in the spread.
248
+ ...(process.env.ALGOLIA_API_KEY !== undefined ? { token: process.env.ALGOLIA_API_KEY } : {}),
249
+ ...(opts.budgetOptions ?? {}),
250
+ });
251
+
252
+ /** Settle a reservation from whatever the call produced. May THROW (a back-off past the cap). */
253
+ const settle = (weight: number, reservation: RateBudgetReservation, v: unknown): void => {
254
+ const status = responseStatus(v);
255
+ const headers = responseHeaders(v);
256
+ if (status !== undefined || headers !== undefined) budget.recordCall(weight, headers, { status, reservation });
257
+ else budget.recordCall(weight, undefined, { reservation });
258
+ };
259
+
260
+ /**
261
+ * Settle once the call RESOLVED: the vendor has answered. recordCall arms any cooldown before
262
+ * it throws (a back-off beyond the cap), so that refusal is swallowed and the answer kept — a
263
+ * write the vendor accepted is never reported failed and performed again on retry. A resolved
264
+ * answer that carries a non-2xx status still lets the louder refusal win.
265
+ */
266
+ const settleAnswered = (weight: number, reservation: RateBudgetReservation, v: unknown): void => {
267
+ try {
268
+ settle(weight, reservation, v);
269
+ } catch (e) {
270
+ const status = responseStatus(v);
271
+ if (!(e instanceof RateBudgetError) || (status !== undefined && (status < 200 || status >= 300))) throw e;
272
+ }
273
+ };
274
+
275
+ /**
276
+ * Charge, call, settle — for a MODELED method, whose interface declares it `async`. Refusing
277
+ * REJECTS rather than throwing synchronously, so `client.x().catch(…)` behaves exactly as it does
278
+ * on an unguarded client. `checkBudget` RESERVES under lock, so nothing after its line runs when
279
+ * the budget refuses: the request is never made.
280
+ */
281
+ const chargeAsync = (method: string, invoke: (...args: unknown[]) => unknown) =>
282
+ async (...args: unknown[]): Promise<unknown> => {
283
+ const weight = budget.weightFor(method);
284
+ const reservation = budget.checkBudget(weight);
285
+ try {
286
+ const res = await invoke(...args);
287
+ settleAnswered(weight, reservation, res);
288
+ return res;
289
+ } catch (e) {
290
+ settle(weight, reservation, e); // may throw its own louder refusal, which wins
291
+ throw e;
292
+ }
293
+ };
294
+
295
+ /**
296
+ * Charge, call, settle — for an UNMODELED member reached through the passthrough Proxy, where the
297
+ * shape is unknown.
298
+ *
299
+ * Deliberately NOT `async`. Some vendor SDKs (twilio-shaped ones) build requests through
300
+ * SYNCHRONOUS chained accessors — `client.a.b('sid').c.create()` — where the intermediate calls
301
+ * return a resource context, not a promise. An `async` wrapper would turn every one of those into
302
+ * a `Promise` and `.c` would come back `undefined`: the guard would BREAK the client instead of
303
+ * guarding it. So a non-thenable return is treated as an accessor — still charged (we cannot know
304
+ * before calling, and over-charging is the safe direction) and wrapped, so the eventual async leaf
305
+ * is charged too rather than escaping the budget. The cost of the sync shape is that a REFUSAL on
306
+ * this path throws synchronously instead of rejecting; that is the honest signal for an accessor,
307
+ * and the modeled surface above (every method this connector actually calls) does not have it.
308
+ */
309
+ const charge: Charge = (method, invoke) => (...args) => {
310
+ const weight = budget.weightFor(method);
311
+ const reservation = budget.checkBudget(weight);
312
+ let out: unknown;
313
+ try {
314
+ out = invoke(...args);
315
+ } catch (e) {
316
+ settle(weight, reservation, e); // may throw its own louder refusal, which wins
317
+ throw e;
318
+ }
319
+ if (!isThenable(out)) {
320
+ settle(weight, reservation, undefined);
321
+ return out !== null && (typeof out === 'object' || typeof out === 'function')
322
+ ? proxyThrough({}, out as object, method, charge)
323
+ : out;
324
+ }
325
+ return out.then(
326
+ (res) => { settleAnswered(weight, reservation, res); return res; },
327
+ (e: unknown) => { settle(weight, reservation, e); throw e; },
328
+ );
329
+ };
330
+
331
+ // Build the charged surface from ALGOLIA_BUDGETED_METHODS (see its docstring for why an absent path is
332
+ // SKIPPED rather than stubbed).
333
+ const guarded: Record<string, unknown> & Guarded = {};
334
+ for (const path of ALGOLIA_BUDGETED_METHODS) {
335
+ const segs = path.split('.');
336
+ const leaf = segs[segs.length - 1]!;
337
+ let owner: Record<string, unknown> | undefined = client as unknown as Record<string, unknown>;
338
+ for (const seg of segs.slice(0, -1)) owner = owner?.[seg] as Record<string, unknown> | undefined;
339
+ if (typeof owner?.[leaf] !== 'function') continue;
340
+ const realOwner = owner;
341
+ let node: Record<string, unknown> = guarded;
342
+ for (const seg of segs.slice(0, -1)) node = (node[seg] ??= {}) as Record<string, unknown>;
343
+ // The method is resolved at CALL time, not here, so a client whose method is swapped later is
344
+ // still charged for whatever it actually runs.
345
+ node[leaf] = chargeAsync(path, (...args) => (realOwner[leaf] as (...a: unknown[]) => unknown).apply(realOwner, args));
346
+ }
347
+ Object.defineProperty(guarded, GUARDED, { value: budget, enumerable: false });
348
+
349
+ // The surface above is what this connector calls. A real client has MORE — and a consumer who
350
+ // needs any of it must not be forced to keep the RAW client alongside, because every call through
351
+ // that would be unbudgeted. So the guarded object is a Proxy: known members come from the map
352
+ // above, anything else is taken from the real client and PRICED at `defaultWeight`.
353
+ return proxyThrough(guarded, client as object, '', charge) as AlgoliaLikeClient;
354
+ }
355
+
356
+ /**
357
+ * Members JavaScript itself asks for. Wrapping any of these turns the object into something that
358
+ * looks thenable / mis-reports its own identity, which breaks `await`, `instanceof` and logging —
359
+ * so they always come from the target untouched, never priced.
360
+ */
361
+ const NEVER_WRAP = new Set(['then', 'catch', 'finally', 'constructor', 'prototype', 'toJSON', 'toString', 'valueOf', 'inspect']);
362
+
363
+ /** Does this look like a promise? (Only a thenable gets the settle-on-resolution treatment.) */
364
+ function isThenable(v: unknown): v is Promise<unknown> {
365
+ return v !== null && (typeof v === 'object' || typeof v === 'function') && typeof (v as { then?: unknown }).then === 'function';
366
+ }
367
+
368
+ /**
369
+ * Symbols that name an ITERATION PROTOCOL. Reaching for one of these on a vendor object is how a
370
+ * paginator is driven (`for await (const page of client.things.list())`), i.e. it is the doorway to
371
+ * an unbounded sequence of REQUESTS — exactly what this budget exists to bound — so they are charged
372
+ * and their result is kept behind the proxy. Every other symbol (`Symbol.toStringTag`,
373
+ * `nodejs.util.inspect.custom`, …) is metadata rather than a request and passes through untouched.
374
+ */
375
+ const ITERATOR_SYMBOLS = new Set<symbol>([Symbol.asyncIterator, Symbol.iterator]);
376
+
377
+ /**
378
+ * Serve `known` where it has the member; otherwise price a passthrough to `real`. Applied
379
+ * recursively, so a namespace member this pack never modeled is charged at `defaultWeight` rather
380
+ * than coming back `undefined`.
381
+ *
382
+ * CALLABLE NAMESPACES (§9 finding): a member can be BOTH a function and a namespace — twilio's
383
+ * `client.messages` is called as `client.messages(sid)` to get one message's context AND read as
384
+ * `client.messages.list()`. An earlier version returned the modeled node as a plain object whenever
385
+ * this pack modeled any child of it, which silently DROPPED the call signature and every unmodeled
386
+ * sibling — the module's own docstring calls a dropped member "worse than free, because it is
387
+ * invisible", and that is what it was doing. So when `real` is callable the proxy target is a
388
+ * function and an `apply` trap charges the call, while `known` stays the source of modeled members.
389
+ */
390
+ function proxyThrough(known: object, real: object, prefix: string, charge: Charge, owner?: object): object {
391
+ const callable = typeof real === 'function';
392
+ // The target must itself be callable for the `apply` trap to exist at all. `known` stays the
393
+ // source of modeled members, read explicitly below rather than through the target.
394
+ const target: object = callable ? function proxied() { /* every call goes through the trap */ } : known;
395
+ return new Proxy(target, {
396
+ apply(_t, _thisArg, args: unknown[]) {
397
+ // Calling the namespace is itself a request-builder hop: charge it, and keep the result
398
+ // behind the proxy (charge() re-proxies a non-thenable) so the eventual leaf is charged too.
399
+ // `owner` is the object the function was read from — dropping it would silently break every
400
+ // method that relies on `this`.
401
+ return charge(prefix || 'call', (...a) => (real as (...x: unknown[]) => unknown).apply(owner, a))(...args);
402
+ },
403
+ get(_t, prop, receiver) {
404
+ if (typeof prop === 'symbol') {
405
+ const ownSym = Reflect.get(known, prop, receiver);
406
+ if (ownSym !== undefined) return ownSym; // the GUARDED brand, and anything we model
407
+ const fromSym = (real as Record<symbol, unknown> | null)?.[prop];
408
+ if (ITERATOR_SYMBOLS.has(prop) && typeof fromSym === 'function') {
409
+ return charge(`${prefix}[${prop.description ?? 'iterator'}]`, (...args) => (fromSym as (...a: unknown[]) => unknown).apply(real, args));
410
+ }
411
+ return fromSym;
412
+ }
413
+ const name = String(prop);
414
+ if (NEVER_WRAP.has(name)) return Reflect.get(known, prop, receiver);
415
+ const key = prefix ? `${prefix}.${name}` : name;
416
+ const own = Reflect.get(known, prop, receiver);
417
+ const from = (real as Record<string, unknown> | null)?.[name];
418
+ // A member we model: the charged wrapper (a function) or a namespace we must keep descending
419
+ // into, so an unmodeled sibling is still priced rather than dropped.
420
+ if (typeof own === 'function') return own;
421
+ if (own && typeof own === 'object') {
422
+ // `from` may be an object OR a CALLABLE namespace — both keep descending, which is what
423
+ // preserves `client.messages(sid)` alongside the modeled `client.messages.list()`.
424
+ return from && (typeof from === 'object' || typeof from === 'function')
425
+ ? proxyThrough(own, from, key, charge, real)
426
+ : own;
427
+ }
428
+ if (own !== undefined) return own;
429
+ // A member only the real client has. Functions go through proxyThrough too, so one that also
430
+ // carries members (a callable namespace) keeps both its call signature and its siblings.
431
+ if (typeof from === 'function') return proxyThrough({}, from, key, charge, real);
432
+ if (from && typeof from === 'object') return proxyThrough({}, from, key, charge, real);
433
+ return from;
434
+ },
435
+ has(_t, prop) {
436
+ return Reflect.has(known, prop) || (real !== null && Reflect.has(real, prop));
437
+ },
438
+ });
439
+ }
440
+
441
+ /** The HTTP status a value carries, if it looks like one (an SDK error, or a raw response). */
442
+ function responseStatus(v: unknown): number | undefined {
443
+ const s = (v as { status?: unknown } | null)?.status;
444
+ return typeof s === 'number' && Number.isFinite(s) ? s : undefined;
445
+ }
446
+
447
+ /**
448
+ * Response/error headers as a plain lower-cased record, or `undefined` when there are none. Accepts
449
+ * a `Headers` instance, a `Map`, or a plain object — an SDK's error type changes shape across
450
+ * versions and none of the three is worth depending on.
451
+ */
452
+ function responseHeaders(v: unknown): Record<string, string> | undefined {
453
+ const h = (v as { headers?: unknown } | null)?.headers;
454
+ if (!h || typeof h !== 'object') return undefined;
455
+ const out: Record<string, string> = {};
456
+ if (typeof (h as Headers).forEach === 'function') {
457
+ (h as Headers).forEach((value: string, key: string) => { out[String(key).toLowerCase()] = String(value); });
458
+ } else {
459
+ for (const [k, value] of Object.entries(h as Record<string, unknown>)) out[k.toLowerCase()] = String(value);
460
+ }
461
+ return Object.keys(out).length > 0 ? out : undefined;
462
+ }