@volter/twin-fal 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/LICENSE +202 -0
- package/README.md +51 -0
- package/dist/src/cli.d.ts +2 -0
- package/dist/src/cli.js +27 -0
- package/dist/src/fal-budget.d.ts +85 -0
- package/dist/src/fal-budget.js +410 -0
- package/dist/src/fal-capabilities.d.ts +4 -0
- package/dist/src/fal-capabilities.js +419 -0
- package/dist/src/fal-conformance.d.ts +7 -0
- package/dist/src/fal-conformance.js +38 -0
- package/dist/src/fal-connector.d.ts +58 -0
- package/dist/src/fal-connector.js +91 -0
- package/dist/src/fal-scenario.d.ts +26 -0
- package/dist/src/fal-scenario.js +100 -0
- package/dist/src/fal-server.d.ts +18 -0
- package/dist/src/fal-server.js +53 -0
- package/dist/src/fal-twin.d.ts +36 -0
- package/dist/src/fal-twin.js +414 -0
- package/dist/src/fal-webhooks.d.ts +60 -0
- package/dist/src/fal-webhooks.js +202 -0
- package/dist/src/index.d.ts +13 -0
- package/dist/src/index.js +55 -0
- package/package.json +51 -0
- package/src/cli.ts +26 -0
- package/src/fal-budget.ts +456 -0
- package/src/fal-capabilities.ts +448 -0
- package/src/fal-conformance.ts +42 -0
- package/src/fal-connector.ts +123 -0
- package/src/fal-scenario.ts +112 -0
- package/src/fal-server.ts +64 -0
- package/src/fal-twin.ts +479 -0
- package/src/fal-webhooks.ts +234 -0
- package/src/index.ts +100 -0
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
// fal's CLIENT-SIDE RATE BUDGET — the pack's DECLARATION (the numbers) plus `guardFalClient`,
|
|
2
|
+
// the choke point every live fal 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 FAL NEEDS ONE ───────────────────────────────────────────────────────────────
|
|
10
|
+
// fal publishes CONCURRENCY, not a requests-per-second limit: "New accounts start with 2 concurrent
|
|
11
|
+
// requests" scaling to 40 for self-serve (fal.ai/docs/documentation/model-apis/concurrency-limits),
|
|
12
|
+
// above which it is contact-sales. Critically for this connector, fal also documents that requests in
|
|
13
|
+
// the IN_QUEUE state do NOT count toward that limit — only IN_PROGRESS does — so `queue.status` /
|
|
14
|
+
// `queue.result` polling is not documented as consuming the concurrency budget, and no separate
|
|
15
|
+
// polling rate limit is published either. That is the dangerous shape: an endpoint with no published
|
|
16
|
+
// ceiling that a completion-polling loop calls as fast as it can. fal's 429 carries type
|
|
17
|
+
// `concurrent_requests_limit` and an `X-Fal-needs-retry: 1` header rather than `Retry-After`.
|
|
18
|
+
//
|
|
19
|
+
// ── HOW THE CEILING WAS CHOSEN ──────────────────────────────────────────────────────────────
|
|
20
|
+
// NO DOCUMENTED REQUESTS-PER-SECOND OR PER-MINUTE LIMIT was found for the queue endpoints, so this
|
|
21
|
+
// budget does NOT claim one. It is pinned to the kernel's conservative fallback (DEFAULT_RATE_BUDGET:
|
|
22
|
+
// 60 weighted units / 60s at weight 2 = 30 calls/minute) — no more permissive than an undeclared
|
|
23
|
+
// vendor already gets. The lowest documented fal number is 2 concurrent requests on a new account,
|
|
24
|
+
// which bounds in-flight work, not call rate.
|
|
25
|
+
//
|
|
26
|
+
// ── WHAT THIS DOES NOT DO: PACE ─────────────────────────────────────────────────────────────
|
|
27
|
+
// It bounds the 60s AVERAGE; it does NOT bound the instantaneous rate. The window has no
|
|
28
|
+
// spacing, so a tight `await` loop can legitimately fire the whole allowance in a fraction of a
|
|
29
|
+
// second. In that shape the vendor's own 429 can arrive BEFORE this ceiling does, and the backstop
|
|
30
|
+
// is then the COOLDOWN: the guard reads the back-off off the thrown error (or the response's
|
|
31
|
+
// exhaustion headers) and refuses every later call without touching the vendor. So the honest claim
|
|
32
|
+
// is "bounds the 60s average, and converts the vendor's first 429 into a hard stop" — never
|
|
33
|
+
// "refuses before the vendor ever 429s". Pacing is the CALLER's job; this module REFUSES, it never
|
|
34
|
+
// sleeps (see the kernel header: it is deliberately not a scheduler). A tighter window would not
|
|
35
|
+
// close the gap, it would only turn every legitimate multi-page pull into a cascade of refusals.
|
|
36
|
+
//
|
|
37
|
+
// ── HOW THE WEIGHTS WERE CHOSEN (and what is a judgement call) ──────────────────────────────
|
|
38
|
+
// `queue.status` costs 4, twice `queue.result`. A JUDGEMENT CALL, not a published cost — fal
|
|
39
|
+
// documents no per-endpoint price. It is priced up because status is the POLLED endpoint: a caller
|
|
40
|
+
// waiting for a request to finish calls it in a loop with no natural bound, whereas `result` is
|
|
41
|
+
// fetched at most once per completed handle. Doubling the poll price halves how long a runaway
|
|
42
|
+
// poll loop can run before it is stopped, and barely touches a normal pull (one status plus one
|
|
43
|
+
// result per handle).
|
|
44
|
+
import { declareRateBudget, rateBudgetPath, rateBudgetWeight, RateBudget, RateBudgetError, } from '@volter/world-core';
|
|
45
|
+
const VENDOR = 'fal';
|
|
46
|
+
/** Rolling window, in ms. Spend older than this is pruned. */
|
|
47
|
+
export const FAL_BUDGET_WINDOW_MS = 60_000;
|
|
48
|
+
/** Weighted units allowed inside one window. See the header for where this number comes from. */
|
|
49
|
+
export const FAL_BUDGET_CEILING = 60;
|
|
50
|
+
/** Seconds. A `Retry-After` above this means the credential is throttled hard — fail loudly. */
|
|
51
|
+
export const FAL_BUDGET_MAX_RETRY_AFTER_S = 300;
|
|
52
|
+
/** Per-call cost, keyed by the client method the guard is about to invoke. See the header. */
|
|
53
|
+
export const FAL_CALL_WEIGHTS = {
|
|
54
|
+
/** `queue.status` — the endpoint a completion-polling loop hammers. */
|
|
55
|
+
poll: 4,
|
|
56
|
+
/** Every other modeled call (`queue.result`, and anything unclassified). */
|
|
57
|
+
other: 2,
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* The client methods this pack PRICES BY NAME, as dotted paths into the injected client.
|
|
61
|
+
*
|
|
62
|
+
* Two kinds of entry: (a) every method this connector actually calls, and (b) an endpoint the
|
|
63
|
+
* VENDOR documents in a distinct tier which a consumer can reach through the guarded client even
|
|
64
|
+
* though this connector never calls it (see the weights section of the header). Used to build the
|
|
65
|
+
* guarded surface — and, in the pack's own suite, the counting fake.
|
|
66
|
+
*
|
|
67
|
+
* NOT a closed list, and not a claim about the injected client's shape. A path the real client does
|
|
68
|
+
* not have is SKIPPED (this connector's members are optional; inventing one would turn "observe
|
|
69
|
+
* nothing" into "call something that isn't there"), and a method absent from this list is still
|
|
70
|
+
* PRICED at `defaultWeight` when a caller reaches for it — an unmodeled endpoint must never be
|
|
71
|
+
* free, and dropping one would be worse than free because it would be invisible.
|
|
72
|
+
*/
|
|
73
|
+
export const FAL_BUDGETED_METHODS = [
|
|
74
|
+
'queue.status',
|
|
75
|
+
'queue.result',
|
|
76
|
+
];
|
|
77
|
+
/** THE PACK'S DECLARATION — pure data, the only fal-specific thing in the whole budget. */
|
|
78
|
+
export const FAL_RATE_BUDGET = {
|
|
79
|
+
windowMs: FAL_BUDGET_WINDOW_MS,
|
|
80
|
+
ceiling: FAL_BUDGET_CEILING,
|
|
81
|
+
defaultWeight: FAL_CALL_WEIGHTS.other,
|
|
82
|
+
maxRetryAfterSeconds: FAL_BUDGET_MAX_RETRY_AFTER_S,
|
|
83
|
+
// Ordered: the kernel prices FIRST-MATCH-WINS, so the tightest tier is listed first.
|
|
84
|
+
rules: [
|
|
85
|
+
{ match: "(^|\\.)status$", weight: FAL_CALL_WEIGHTS.poll },
|
|
86
|
+
],
|
|
87
|
+
reason: "fal publishes CONCURRENCY limits, not a request rate: 2 concurrent requests on a new account rising to 40 " +
|
|
88
|
+
"self-serve, and it documents that IN_QUEUE requests do not count toward that limit — so queue.status / " +
|
|
89
|
+
"queue.result polling has NO published ceiling at all. With no documented figure to aim at, this ceiling is " +
|
|
90
|
+
"pinned to the kernel's conservative fallback (60 units / 60s at weight 2 = 30 calls/min) rather than " +
|
|
91
|
+
"invented — no more permissive than an undeclared vendor already gets. queue.status costs 4 because it is " +
|
|
92
|
+
"the endpoint a completion-polling loop hammers without bound — a judgement call, not a published cost. " +
|
|
93
|
+
"fal signals back-off with X-Fal-needs-retry rather than Retry-After; the 429 cooldown is the backstop.",
|
|
94
|
+
};
|
|
95
|
+
// Declared at module load, so merely importing this module (which `fal-connector.ts` does) is
|
|
96
|
+
// enough to arm the real ceiling. A budget constructed BEFORE this runs falls back to the kernel's
|
|
97
|
+
// DEFAULT_RATE_BUDGET — which is tighter in call COUNT but prices every call at 2, so for a vendor
|
|
98
|
+
// with an expensive endpoint the fallback is CHEAPER there, not safer. `RateBudget` reads its policy
|
|
99
|
+
// LIVE precisely so this declaration takes effect the moment it lands, and constructing through the
|
|
100
|
+
// subclass below (whose module IS this one) makes the ordering a non-issue in practice.
|
|
101
|
+
declareRateBudget(VENDOR, FAL_RATE_BUDGET);
|
|
102
|
+
/** Price one fal call by its client method key (a dotted path, e.g. `queue.status`). */
|
|
103
|
+
export function falCallWeight(method) {
|
|
104
|
+
return rateBudgetWeight(VENDOR, method);
|
|
105
|
+
}
|
|
106
|
+
/** Where fal's ledger lives. Token-keyed and cwd-independent by default (the vendor limits per
|
|
107
|
+
* credential, so a cwd-scoped ledger would hand the same credential a fresh allowance in every
|
|
108
|
+
* checkout, worktree and CI matrix leg); pass `root` to opt into world-scoped accounting. */
|
|
109
|
+
export function falBudgetPath(opts = {}) {
|
|
110
|
+
const o = typeof opts === 'string' ? { root: opts } : opts;
|
|
111
|
+
// VENDOR spread LAST: a loosely-typed `{ vendor: 'other', … }` slipping through (TypeScript's
|
|
112
|
+
// excess-property check only catches object literals) must not redirect this pack's ledger to
|
|
113
|
+
// another vendor's file.
|
|
114
|
+
return rateBudgetPath({ ...o, vendor: VENDOR });
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* fal's budget — the shared kernel guard bound to this vendor's declaration. A real subclass,
|
|
118
|
+
* not an alias, so `budget instanceof FalBudget` means "a budget that accounts against this
|
|
119
|
+
* vendor's ledger under this vendor's ceiling": another vendor's `RateBudget` (with its own,
|
|
120
|
+
* possibly larger, ceiling) is NOT assignable where one of these is required.
|
|
121
|
+
*/
|
|
122
|
+
export class FalBudget extends RateBudget {
|
|
123
|
+
constructor(opts = {}) {
|
|
124
|
+
super({ ...opts, vendor: VENDOR });
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
export { RateBudgetError as FalBudgetError } from '@volter/world-core';
|
|
128
|
+
/** Pull the budget wiring out of a caller's opts bag, so an entrypoint can forward it verbatim. */
|
|
129
|
+
export function falBudgetOf(opts) {
|
|
130
|
+
return {
|
|
131
|
+
...(opts.budget !== undefined ? { budget: opts.budget } : {}),
|
|
132
|
+
...(opts.budgetOptions !== undefined ? { budgetOptions: opts.budgetOptions } : {}),
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
// ── the choke point ─────────────────────────────────────────────────────────────────────────
|
|
136
|
+
/**
|
|
137
|
+
* Marks a client this module has already wrapped, so guarding twice cannot charge twice.
|
|
138
|
+
*
|
|
139
|
+
* A MODULE-PRIVATE `Symbol()`, deliberately not `Symbol.for()`: a global-registry symbol is
|
|
140
|
+
* reachable BY NAME, so any caller could stamp `client[Symbol.for(…)] = anything` on a RAW client and
|
|
141
|
+
* the guard would hand it straight back UNGUARDED — a one-line bypass of the whole budget. With a
|
|
142
|
+
* private symbol the only way to be branded is to have been wrapped by this function. The cost is
|
|
143
|
+
* that two copies of this module in one dependency tree would each wrap (double-charging a call);
|
|
144
|
+
* that is the SAFE direction, and over-charging is the tradeoff this module takes everywhere else.
|
|
145
|
+
*/
|
|
146
|
+
const GUARDED = Symbol('@volter/twin-fal.budget.guarded');
|
|
147
|
+
/** Is this client already behind a budget? Returns the budget it is behind, if so. */
|
|
148
|
+
export function falClientBudget(client) {
|
|
149
|
+
const mark = client?.[GUARDED];
|
|
150
|
+
// Belt and braces: only a REAL budget counts as "already guarded". A non-RateBudget value here
|
|
151
|
+
// could only come from a forged brand, and the answer to a forgery is to wrap anyway.
|
|
152
|
+
return mark instanceof RateBudget ? mark : undefined;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Wrap an INJECTED fal client so EVERY call it makes is charged against the shared budget
|
|
156
|
+
* BEFORE the request goes out. This pack's connector never constructs the transport itself (the
|
|
157
|
+
* consumer injects a client that satisfies `FalLikeClient` structurally), so the guard is a
|
|
158
|
+
* DECORATOR rather than a factory — which is exactly why every connector entrypoint applies it
|
|
159
|
+
* UNCONDITIONALLY instead of trusting the caller to have done it.
|
|
160
|
+
*
|
|
161
|
+
* IDEMPOTENT: wrapping an already-guarded client returns it unchanged, so a caller who forgot is
|
|
162
|
+
* protected and a caller who wrapped deliberately is not double-charged.
|
|
163
|
+
*
|
|
164
|
+
* A method that THROWS is still inspected: an SDK typically RAISES on a 429 rather than returning
|
|
165
|
+
* it, and that error's back-off is exactly the signal that must become a persisted cooldown. Losing
|
|
166
|
+
* it would leave the ledger cheerfully spending into a throttled credential. The original error is
|
|
167
|
+
* always re-raised afterwards — the budget never swallows a vendor failure — EXCEPT when the
|
|
168
|
+
* back-off is beyond the cap, where the budget's own louder "stop calling" error takes precedence.
|
|
169
|
+
*/
|
|
170
|
+
export function guardFalClient(client, opts = {}) {
|
|
171
|
+
// There is no value a caller can pass to end up with an UNGUARDED client. `null`/`undefined` (or
|
|
172
|
+
// omitting it) build the default budget; anything that is not a REAL `FalBudget` is refused
|
|
173
|
+
// loudly rather than trusted — a duck-typed stand-in with a no-op `checkBudget` would otherwise be
|
|
174
|
+
// the one clean way around the guard. Validated BEFORE the already-guarded early return, so
|
|
175
|
+
// `guardFalClient(alreadyGuarded, { budget: impostor })` is refused too rather than silently
|
|
176
|
+
// ignoring the impostor.
|
|
177
|
+
if (opts.budget !== undefined && opts.budget !== null && !(opts.budget instanceof FalBudget)) {
|
|
178
|
+
throw new Error('guardFalClient: `budget` must be a FalBudget — refusing to guard a fal client with an unverified rate guard');
|
|
179
|
+
}
|
|
180
|
+
if (falClientBudget(client))
|
|
181
|
+
return client;
|
|
182
|
+
const budget = opts.budget instanceof FalBudget
|
|
183
|
+
? opts.budget
|
|
184
|
+
: new FalBudget({
|
|
185
|
+
// The default ledger is keyed by a hash of the credential — the vendor limits per credential,
|
|
186
|
+
// so a cwd-scoped ledger would hand it a fresh allowance per worktree/CI leg.
|
|
187
|
+
//
|
|
188
|
+
// HONESTLY: this pack does NOT hold the credential — the consumer's injected client does — so
|
|
189
|
+
// `FAL_KEY` is a BEST-EFFORT stand-in for it, not the real thing. If that env var names a
|
|
190
|
+
// different account than the injected client, spend is booked against the wrong ledger; if it
|
|
191
|
+
// is unset, every unattributed fal credential on the machine shares one (over-tight,
|
|
192
|
+
// which is the safe direction). A caller who knows the credential should say so:
|
|
193
|
+
// `budgetOptions: { token }` overrides this, and does so deliberately last in the spread.
|
|
194
|
+
...(process.env.FAL_KEY !== undefined ? { token: process.env.FAL_KEY } : {}),
|
|
195
|
+
...(opts.budgetOptions ?? {}),
|
|
196
|
+
});
|
|
197
|
+
/** Settle a reservation from whatever the call produced. May THROW (a back-off past the cap). */
|
|
198
|
+
const settle = (weight, reservation, v) => {
|
|
199
|
+
const status = responseStatus(v);
|
|
200
|
+
const headers = responseHeaders(v);
|
|
201
|
+
if (status !== undefined || headers !== undefined)
|
|
202
|
+
budget.recordCall(weight, headers, { status, reservation });
|
|
203
|
+
else
|
|
204
|
+
budget.recordCall(weight, undefined, { reservation });
|
|
205
|
+
};
|
|
206
|
+
/**
|
|
207
|
+
* Settle once the call RESOLVED: the vendor has answered. recordCall arms any cooldown before
|
|
208
|
+
* it throws (a back-off beyond the cap), so that refusal is swallowed and the answer kept — a
|
|
209
|
+
* write the vendor accepted is never reported failed and performed again on retry. A resolved
|
|
210
|
+
* answer that carries a non-2xx status still lets the louder refusal win.
|
|
211
|
+
*/
|
|
212
|
+
const settleAnswered = (weight, reservation, v) => {
|
|
213
|
+
try {
|
|
214
|
+
settle(weight, reservation, v);
|
|
215
|
+
}
|
|
216
|
+
catch (e) {
|
|
217
|
+
const status = responseStatus(v);
|
|
218
|
+
if (!(e instanceof RateBudgetError) || (status !== undefined && (status < 200 || status >= 300)))
|
|
219
|
+
throw e;
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
/**
|
|
223
|
+
* Charge, call, settle — for a MODELED method, whose interface declares it `async`. Refusing
|
|
224
|
+
* REJECTS rather than throwing synchronously, so `client.x().catch(…)` behaves exactly as it does
|
|
225
|
+
* on an unguarded client. `checkBudget` RESERVES under lock, so nothing after its line runs when
|
|
226
|
+
* the budget refuses: the request is never made.
|
|
227
|
+
*/
|
|
228
|
+
const chargeAsync = (method, invoke) => async (...args) => {
|
|
229
|
+
const weight = budget.weightFor(method);
|
|
230
|
+
const reservation = budget.checkBudget(weight);
|
|
231
|
+
try {
|
|
232
|
+
const res = await invoke(...args);
|
|
233
|
+
settleAnswered(weight, reservation, res);
|
|
234
|
+
return res;
|
|
235
|
+
}
|
|
236
|
+
catch (e) {
|
|
237
|
+
settle(weight, reservation, e); // may throw its own louder refusal, which wins
|
|
238
|
+
throw e;
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
/**
|
|
242
|
+
* Charge, call, settle — for an UNMODELED member reached through the passthrough Proxy, where the
|
|
243
|
+
* shape is unknown.
|
|
244
|
+
*
|
|
245
|
+
* Deliberately NOT `async`. Some vendor SDKs (twilio-shaped ones) build requests through
|
|
246
|
+
* SYNCHRONOUS chained accessors — `client.a.b('sid').c.create()` — where the intermediate calls
|
|
247
|
+
* return a resource context, not a promise. An `async` wrapper would turn every one of those into
|
|
248
|
+
* a `Promise` and `.c` would come back `undefined`: the guard would BREAK the client instead of
|
|
249
|
+
* guarding it. So a non-thenable return is treated as an accessor — still charged (we cannot know
|
|
250
|
+
* before calling, and over-charging is the safe direction) and wrapped, so the eventual async leaf
|
|
251
|
+
* is charged too rather than escaping the budget. The cost of the sync shape is that a REFUSAL on
|
|
252
|
+
* this path throws synchronously instead of rejecting; that is the honest signal for an accessor,
|
|
253
|
+
* and the modeled surface above (every method this connector actually calls) does not have it.
|
|
254
|
+
*/
|
|
255
|
+
const charge = (method, invoke) => (...args) => {
|
|
256
|
+
const weight = budget.weightFor(method);
|
|
257
|
+
const reservation = budget.checkBudget(weight);
|
|
258
|
+
let out;
|
|
259
|
+
try {
|
|
260
|
+
out = invoke(...args);
|
|
261
|
+
}
|
|
262
|
+
catch (e) {
|
|
263
|
+
settle(weight, reservation, e); // may throw its own louder refusal, which wins
|
|
264
|
+
throw e;
|
|
265
|
+
}
|
|
266
|
+
if (!isThenable(out)) {
|
|
267
|
+
settle(weight, reservation, undefined);
|
|
268
|
+
return out !== null && (typeof out === 'object' || typeof out === 'function')
|
|
269
|
+
? proxyThrough({}, out, method, charge)
|
|
270
|
+
: out;
|
|
271
|
+
}
|
|
272
|
+
return out.then((res) => { settleAnswered(weight, reservation, res); return res; }, (e) => { settle(weight, reservation, e); throw e; });
|
|
273
|
+
};
|
|
274
|
+
// Build the charged surface from FAL_BUDGETED_METHODS (see its docstring for why an absent path is
|
|
275
|
+
// SKIPPED rather than stubbed).
|
|
276
|
+
const guarded = {};
|
|
277
|
+
for (const path of FAL_BUDGETED_METHODS) {
|
|
278
|
+
const segs = path.split('.');
|
|
279
|
+
const leaf = segs[segs.length - 1];
|
|
280
|
+
let owner = client;
|
|
281
|
+
for (const seg of segs.slice(0, -1))
|
|
282
|
+
owner = owner?.[seg];
|
|
283
|
+
if (typeof owner?.[leaf] !== 'function')
|
|
284
|
+
continue;
|
|
285
|
+
const realOwner = owner;
|
|
286
|
+
let node = guarded;
|
|
287
|
+
for (const seg of segs.slice(0, -1))
|
|
288
|
+
node = (node[seg] ??= {});
|
|
289
|
+
// The method is resolved at CALL time, not here, so a client whose method is swapped later is
|
|
290
|
+
// still charged for whatever it actually runs.
|
|
291
|
+
node[leaf] = chargeAsync(path, (...args) => realOwner[leaf].apply(realOwner, args));
|
|
292
|
+
}
|
|
293
|
+
Object.defineProperty(guarded, GUARDED, { value: budget, enumerable: false });
|
|
294
|
+
// The surface above is what this connector calls. A real client has MORE — and a consumer who
|
|
295
|
+
// needs any of it must not be forced to keep the RAW client alongside, because every call through
|
|
296
|
+
// that would be unbudgeted. So the guarded object is a Proxy: known members come from the map
|
|
297
|
+
// above, anything else is taken from the real client and PRICED at `defaultWeight`.
|
|
298
|
+
return proxyThrough(guarded, client, '', charge);
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Members JavaScript itself asks for. Wrapping any of these turns the object into something that
|
|
302
|
+
* looks thenable / mis-reports its own identity, which breaks `await`, `instanceof` and logging —
|
|
303
|
+
* so they always come from the target untouched, never priced.
|
|
304
|
+
*/
|
|
305
|
+
const NEVER_WRAP = new Set(['then', 'catch', 'finally', 'constructor', 'prototype', 'toJSON', 'toString', 'valueOf', 'inspect']);
|
|
306
|
+
/** Does this look like a promise? (Only a thenable gets the settle-on-resolution treatment.) */
|
|
307
|
+
function isThenable(v) {
|
|
308
|
+
return v !== null && (typeof v === 'object' || typeof v === 'function') && typeof v.then === 'function';
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Symbols that name an ITERATION PROTOCOL. Reaching for one of these on a vendor object is how a
|
|
312
|
+
* paginator is driven (`for await (const page of client.things.list())`), i.e. it is the doorway to
|
|
313
|
+
* an unbounded sequence of REQUESTS — exactly what this budget exists to bound — so they are charged
|
|
314
|
+
* and their result is kept behind the proxy. Every other symbol (`Symbol.toStringTag`,
|
|
315
|
+
* `nodejs.util.inspect.custom`, …) is metadata rather than a request and passes through untouched.
|
|
316
|
+
*/
|
|
317
|
+
const ITERATOR_SYMBOLS = new Set([Symbol.asyncIterator, Symbol.iterator]);
|
|
318
|
+
/**
|
|
319
|
+
* Serve `known` where it has the member; otherwise price a passthrough to `real`. Applied
|
|
320
|
+
* recursively, so a namespace member this pack never modeled is charged at `defaultWeight` rather
|
|
321
|
+
* than coming back `undefined`.
|
|
322
|
+
*
|
|
323
|
+
* CALLABLE NAMESPACES (§9 finding): a member can be BOTH a function and a namespace — twilio's
|
|
324
|
+
* `client.messages` is called as `client.messages(sid)` to get one message's context AND read as
|
|
325
|
+
* `client.messages.list()`. An earlier version returned the modeled node as a plain object whenever
|
|
326
|
+
* this pack modeled any child of it, which silently DROPPED the call signature and every unmodeled
|
|
327
|
+
* sibling — the module's own docstring calls a dropped member "worse than free, because it is
|
|
328
|
+
* invisible", and that is what it was doing. So when `real` is callable the proxy target is a
|
|
329
|
+
* function and an `apply` trap charges the call, while `known` stays the source of modeled members.
|
|
330
|
+
*/
|
|
331
|
+
function proxyThrough(known, real, prefix, charge, owner) {
|
|
332
|
+
const callable = typeof real === 'function';
|
|
333
|
+
// The target must itself be callable for the `apply` trap to exist at all. `known` stays the
|
|
334
|
+
// source of modeled members, read explicitly below rather than through the target.
|
|
335
|
+
const target = callable ? function proxied() { } : known;
|
|
336
|
+
return new Proxy(target, {
|
|
337
|
+
apply(_t, _thisArg, args) {
|
|
338
|
+
// Calling the namespace is itself a request-builder hop: charge it, and keep the result
|
|
339
|
+
// behind the proxy (charge() re-proxies a non-thenable) so the eventual leaf is charged too.
|
|
340
|
+
// `owner` is the object the function was read from — dropping it would silently break every
|
|
341
|
+
// method that relies on `this`.
|
|
342
|
+
return charge(prefix || 'call', (...a) => real.apply(owner, a))(...args);
|
|
343
|
+
},
|
|
344
|
+
get(_t, prop, receiver) {
|
|
345
|
+
if (typeof prop === 'symbol') {
|
|
346
|
+
const ownSym = Reflect.get(known, prop, receiver);
|
|
347
|
+
if (ownSym !== undefined)
|
|
348
|
+
return ownSym; // the GUARDED brand, and anything we model
|
|
349
|
+
const fromSym = real?.[prop];
|
|
350
|
+
if (ITERATOR_SYMBOLS.has(prop) && typeof fromSym === 'function') {
|
|
351
|
+
return charge(`${prefix}[${prop.description ?? 'iterator'}]`, (...args) => fromSym.apply(real, args));
|
|
352
|
+
}
|
|
353
|
+
return fromSym;
|
|
354
|
+
}
|
|
355
|
+
const name = String(prop);
|
|
356
|
+
if (NEVER_WRAP.has(name))
|
|
357
|
+
return Reflect.get(known, prop, receiver);
|
|
358
|
+
const key = prefix ? `${prefix}.${name}` : name;
|
|
359
|
+
const own = Reflect.get(known, prop, receiver);
|
|
360
|
+
const from = real?.[name];
|
|
361
|
+
// A member we model: the charged wrapper (a function) or a namespace we must keep descending
|
|
362
|
+
// into, so an unmodeled sibling is still priced rather than dropped.
|
|
363
|
+
if (typeof own === 'function')
|
|
364
|
+
return own;
|
|
365
|
+
if (own && typeof own === 'object') {
|
|
366
|
+
// `from` may be an object OR a CALLABLE namespace — both keep descending, which is what
|
|
367
|
+
// preserves `client.messages(sid)` alongside the modeled `client.messages.list()`.
|
|
368
|
+
return from && (typeof from === 'object' || typeof from === 'function')
|
|
369
|
+
? proxyThrough(own, from, key, charge, real)
|
|
370
|
+
: own;
|
|
371
|
+
}
|
|
372
|
+
if (own !== undefined)
|
|
373
|
+
return own;
|
|
374
|
+
// A member only the real client has. Functions go through proxyThrough too, so one that also
|
|
375
|
+
// carries members (a callable namespace) keeps both its call signature and its siblings.
|
|
376
|
+
if (typeof from === 'function')
|
|
377
|
+
return proxyThrough({}, from, key, charge, real);
|
|
378
|
+
if (from && typeof from === 'object')
|
|
379
|
+
return proxyThrough({}, from, key, charge, real);
|
|
380
|
+
return from;
|
|
381
|
+
},
|
|
382
|
+
has(_t, prop) {
|
|
383
|
+
return Reflect.has(known, prop) || (real !== null && Reflect.has(real, prop));
|
|
384
|
+
},
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
/** The HTTP status a value carries, if it looks like one (an SDK error, or a raw response). */
|
|
388
|
+
function responseStatus(v) {
|
|
389
|
+
const s = v?.status;
|
|
390
|
+
return typeof s === 'number' && Number.isFinite(s) ? s : undefined;
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* Response/error headers as a plain lower-cased record, or `undefined` when there are none. Accepts
|
|
394
|
+
* a `Headers` instance, a `Map`, or a plain object — an SDK's error type changes shape across
|
|
395
|
+
* versions and none of the three is worth depending on.
|
|
396
|
+
*/
|
|
397
|
+
function responseHeaders(v) {
|
|
398
|
+
const h = v?.headers;
|
|
399
|
+
if (!h || typeof h !== 'object')
|
|
400
|
+
return undefined;
|
|
401
|
+
const out = {};
|
|
402
|
+
if (typeof h.forEach === 'function') {
|
|
403
|
+
h.forEach((value, key) => { out[String(key).toLowerCase()] = String(value); });
|
|
404
|
+
}
|
|
405
|
+
else {
|
|
406
|
+
for (const [k, value] of Object.entries(h))
|
|
407
|
+
out[k.toLowerCase()] = String(value);
|
|
408
|
+
}
|
|
409
|
+
return Object.keys(out).length > 0 ? out : undefined;
|
|
410
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { type CapabilityReport, type CapabilitySpec } from '@volter/world-tooling';
|
|
2
|
+
export declare const FAL_CAPABILITIES: CapabilitySpec[];
|
|
3
|
+
export declare const FAL_AREAS: readonly ["queue", "sync", "streaming", "realtime", "webhooks", "storage", "apps", "proxy", "auth", "errors", "connector", "conformance", "safety", "state"];
|
|
4
|
+
export declare function falCapabilities(): Promise<CapabilityReport>;
|