better-call 0.0.0-experimental.01ff4b77

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.
Files changed (115) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +265 -0
  3. package/dist/capability.cjs +417 -0
  4. package/dist/capability.cjs.map +1 -0
  5. package/dist/capability.d.cts +189 -0
  6. package/dist/capability.d.mts +189 -0
  7. package/dist/capability.mjs +401 -0
  8. package/dist/capability.mjs.map +1 -0
  9. package/dist/error.cjs +76 -0
  10. package/dist/error.cjs.map +1 -0
  11. package/dist/error.d.cts +51 -0
  12. package/dist/error.d.mts +51 -0
  13. package/dist/error.mjs +72 -0
  14. package/dist/error.mjs.map +1 -0
  15. package/dist/fn.cjs +350 -0
  16. package/dist/fn.cjs.map +1 -0
  17. package/dist/fn.d.cts +378 -0
  18. package/dist/fn.d.mts +378 -0
  19. package/dist/fn.mjs +350 -0
  20. package/dist/fn.mjs.map +1 -0
  21. package/dist/index.cjs +43 -0
  22. package/dist/index.cjs.map +1 -0
  23. package/dist/index.d.cts +50 -0
  24. package/dist/index.d.mts +50 -0
  25. package/dist/index.mjs +24 -0
  26. package/dist/index.mjs.map +1 -0
  27. package/dist/module.cjs +176 -0
  28. package/dist/module.cjs.map +1 -0
  29. package/dist/module.d.cts +283 -0
  30. package/dist/module.d.mts +283 -0
  31. package/dist/module.mjs +166 -0
  32. package/dist/module.mjs.map +1 -0
  33. package/dist/plugins/db.cjs +24 -0
  34. package/dist/plugins/db.cjs.map +1 -0
  35. package/dist/plugins/db.d.cts +18 -0
  36. package/dist/plugins/db.d.mts +18 -0
  37. package/dist/plugins/db.mjs +19 -0
  38. package/dist/plugins/db.mjs.map +1 -0
  39. package/dist/plugins/http/attrs.cjs +91 -0
  40. package/dist/plugins/http/attrs.cjs.map +1 -0
  41. package/dist/plugins/http/attrs.d.cts +26 -0
  42. package/dist/plugins/http/attrs.d.mts +26 -0
  43. package/dist/plugins/http/attrs.mjs +87 -0
  44. package/dist/plugins/http/attrs.mjs.map +1 -0
  45. package/dist/plugins/http/cookie.cjs +117 -0
  46. package/dist/plugins/http/cookie.cjs.map +1 -0
  47. package/dist/plugins/http/cookie.d.cts +637 -0
  48. package/dist/plugins/http/cookie.d.mts +637 -0
  49. package/dist/plugins/http/cookie.mjs +113 -0
  50. package/dist/plugins/http/cookie.mjs.map +1 -0
  51. package/dist/plugins/http/error.cjs +39 -0
  52. package/dist/plugins/http/error.cjs.map +1 -0
  53. package/dist/plugins/http/error.d.cts +38 -0
  54. package/dist/plugins/http/error.d.mts +38 -0
  55. package/dist/plugins/http/error.mjs +35 -0
  56. package/dist/plugins/http/error.mjs.map +1 -0
  57. package/dist/plugins/http/handle.cjs +73 -0
  58. package/dist/plugins/http/handle.cjs.map +1 -0
  59. package/dist/plugins/http/handle.d.cts +955 -0
  60. package/dist/plugins/http/handle.d.mts +955 -0
  61. package/dist/plugins/http/handle.mjs +72 -0
  62. package/dist/plugins/http/handle.mjs.map +1 -0
  63. package/dist/plugins/http/redirect.cjs +82 -0
  64. package/dist/plugins/http/redirect.cjs.map +1 -0
  65. package/dist/plugins/http/redirect.d.cts +67 -0
  66. package/dist/plugins/http/redirect.d.mts +67 -0
  67. package/dist/plugins/http/redirect.mjs +79 -0
  68. package/dist/plugins/http/redirect.mjs.map +1 -0
  69. package/dist/plugins/http/request.cjs +63 -0
  70. package/dist/plugins/http/request.cjs.map +1 -0
  71. package/dist/plugins/http/request.d.cts +142 -0
  72. package/dist/plugins/http/request.d.mts +142 -0
  73. package/dist/plugins/http/request.mjs +61 -0
  74. package/dist/plugins/http/request.mjs.map +1 -0
  75. package/dist/plugins/http/response.cjs +13 -0
  76. package/dist/plugins/http/response.cjs.map +1 -0
  77. package/dist/plugins/http/response.d.cts +18 -0
  78. package/dist/plugins/http/response.d.mts +18 -0
  79. package/dist/plugins/http/response.mjs +13 -0
  80. package/dist/plugins/http/response.mjs.map +1 -0
  81. package/dist/plugins/http.cjs +64 -0
  82. package/dist/plugins/http.cjs.map +1 -0
  83. package/dist/plugins/http.d.cts +945 -0
  84. package/dist/plugins/http.d.mts +945 -0
  85. package/dist/plugins/http.mjs +37 -0
  86. package/dist/plugins/http.mjs.map +1 -0
  87. package/dist/plugins/read-only.cjs +19 -0
  88. package/dist/plugins/read-only.cjs.map +1 -0
  89. package/dist/plugins/read-only.d.cts +17 -0
  90. package/dist/plugins/read-only.d.mts +17 -0
  91. package/dist/plugins/read-only.mjs +19 -0
  92. package/dist/plugins/read-only.mjs.map +1 -0
  93. package/dist/schema.cjs +245 -0
  94. package/dist/schema.cjs.map +1 -0
  95. package/dist/schema.d.cts +411 -0
  96. package/dist/schema.d.mts +411 -0
  97. package/dist/schema.mjs +235 -0
  98. package/dist/schema.mjs.map +1 -0
  99. package/dist/scope.d.cts +31 -0
  100. package/dist/scope.d.mts +31 -0
  101. package/dist/storage.cjs +308 -0
  102. package/dist/storage.cjs.map +1 -0
  103. package/dist/storage.d.cts +220 -0
  104. package/dist/storage.d.mts +220 -0
  105. package/dist/storage.mjs +302 -0
  106. package/dist/storage.mjs.map +1 -0
  107. package/dist/types.d.cts +8 -0
  108. package/dist/types.d.mts +8 -0
  109. package/dist/var.cjs +186 -0
  110. package/dist/var.cjs.map +1 -0
  111. package/dist/var.d.cts +46 -0
  112. package/dist/var.d.mts +46 -0
  113. package/dist/var.mjs +177 -0
  114. package/dist/var.mjs.map +1 -0
  115. package/package.json +114 -0
package/dist/fn.mjs ADDED
@@ -0,0 +1,350 @@
1
+ import { ControlFlow, FnError, UnexpectedError, ValidationError } from "./error.mjs";
2
+ import { asType, isVar, outputContract, vTypes, validate } from "./schema.mjs";
3
+ import { collectMergeSeeds, collectUsable, isFn, isNamespace, isOn, isVarExtension, matchesTarget, on, resolveModules } from "./module.mjs";
4
+ import { contextScope, getCell, readVar, readVarThrough, viewMergeVar, writeVar } from "./var.mjs";
5
+ //#region src/fn.ts
6
+ const isThenable = (value) => typeof value?.then === "function";
7
+ const STORE = Symbol("var-store");
8
+ const ACTIVE = Symbol("active-plugins");
9
+ const EXTS = Symbol("active-var-extensions");
10
+ const READONLY = Symbol("readonly-lock");
11
+ const WITH = Symbol("with-overrides");
12
+ const defineFn = (key, options, declared) => {
13
+ const modules = resolveModules(options.use ?? []);
14
+ const own = [];
15
+ const ownExts = [];
16
+ const scanMembers = (mod) => {
17
+ for (const value of Object.values(mod)) if (isOn(value) && !own.includes(value)) own.push(value);
18
+ else if (isVarExtension(value)) ownExts.push(value);
19
+ else if (isNamespace(value)) scanMembers(value);
20
+ };
21
+ for (const mod of modules) scanMembers(mod);
22
+ const usable = collectUsable(modules);
23
+ const mergeSeeds = collectMergeSeeds(modules);
24
+ const tupleInput = Array.isArray(options.input) ? options.input : void 0;
25
+ const declaredErrors = options.errors;
26
+ const outputValidation = outputContract(options.output).validation;
27
+ const errorTypes = declaredErrors ? Object.fromEntries(Object.entries(declaredErrors).map(([tag, schema]) => [tag, asType(schema)])) : void 0;
28
+ const inputVars = [];
29
+ const declaredInput = options.input;
30
+ const wholeVar = declaredInput && isVar(declaredInput) ? declaredInput.name : void 0;
31
+ if (declaredInput && !wholeVar) {
32
+ for (const [field, def] of Object.entries(declaredInput)) if (isVar(def)) inputVars.push([field, def.name]);
33
+ }
34
+ if (options.readonly) {
35
+ if (options.provides?.length) throw new ValidationError(`${key}.readonly`, "a readonly fn cannot declare provides - it promises writes");
36
+ if (wholeVar !== void 0 || inputVars.length > 0) throw new ValidationError(`${key}.readonly`, "a readonly fn cannot bind input to vars - that is a write");
37
+ }
38
+ const callable = (...callArgs) => {
39
+ const input = tupleInput ? callArgs.slice(0, tupleInput.length) : callArgs[0];
40
+ const parent = tupleInput ? callArgs[tupleInput.length] : callArgs[1];
41
+ const cells = parent?.[STORE] ?? {};
42
+ if (!parent?.[STORE]) for (const [name, value] of Object.entries(mergeSeeds)) {
43
+ const cell = getCell(cells, name);
44
+ cell.value = value;
45
+ cell.accumulate = true;
46
+ }
47
+ const lockedBy = options.readonly ? key : parent?.[READONLY];
48
+ const inherited = parent?.[ACTIVE] ?? [];
49
+ const active = own.length === 0 ? inherited : [...inherited, ...own.filter((e) => !inherited.includes(e))];
50
+ const chain = active.filter((entry) => matchesTarget(entry.target, key));
51
+ const withFns = parent?.[WITH];
52
+ const inheritedExts = parent?.[EXTS] ?? [];
53
+ const exts = ownExts.length === 0 ? inheritedExts : [...inheritedExts, ...ownExts.filter((e) => !inheritedExts.includes(e))];
54
+ let ctx;
55
+ const frame = {
56
+ cells,
57
+ key,
58
+ lockedBy,
59
+ entries: active
60
+ };
61
+ const extendValue = (name, raw, value) => {
62
+ let merged = value;
63
+ for (const ext of exts) {
64
+ if (ext.name !== name) continue;
65
+ const extra = validate(asType(ext.schema), raw, `${key}.${name}`);
66
+ merged = {
67
+ ...merged,
68
+ ...extra
69
+ };
70
+ }
71
+ return merged;
72
+ };
73
+ let parsed;
74
+ if (tupleInput) {
75
+ const issues = [];
76
+ parsed = tupleInput.map((def, index) => {
77
+ try {
78
+ return validate(asType(def), input[index], `${key}[${index}]`);
79
+ } catch (thrown) {
80
+ if (!(thrown instanceof ValidationError)) throw thrown;
81
+ issues.push(...thrown.issues);
82
+ return;
83
+ }
84
+ });
85
+ const firstIssue = issues[0];
86
+ if (firstIssue) throw new ValidationError(firstIssue.path, firstIssue.message, issues);
87
+ } else parsed = options.input === void 0 ? input : validate(asType(options.input), input, key);
88
+ for (const entry of chain) {
89
+ if (!entry.extend?.input || tupleInput) continue;
90
+ const extra = validate(asType(entry.extend.input), input, `${key}.on`);
91
+ parsed = {
92
+ ...parsed ?? {},
93
+ ...extra
94
+ };
95
+ }
96
+ if (wholeVar !== void 0 && parsed !== void 0) {
97
+ parsed = extendValue(wholeVar, input, parsed);
98
+ writeVar(frame, wholeVar, parsed);
99
+ }
100
+ for (const [field, name] of inputVars) {
101
+ const raw = input?.[field];
102
+ const value = parsed?.[field];
103
+ if (value === void 0) continue;
104
+ const merged = extendValue(name, raw, value);
105
+ parsed[field] = merged;
106
+ writeVar(frame, name, merged);
107
+ }
108
+ const base = {
109
+ input: parsed,
110
+ error: (tag, data) => {
111
+ const schema = errorTypes?.[tag];
112
+ if (!schema) throw new ValidationError(`${key}.errors.${tag}`, errorTypes ? `"${tag}" is not a declared error of "${key}"` : `"${key}" declares no errors`);
113
+ return new FnError(tag, validate(schema, data ?? {}, `${key}.errors.${tag}`), key);
114
+ },
115
+ [STORE]: cells,
116
+ [ACTIVE]: active,
117
+ [EXTS]: exts,
118
+ [READONLY]: lockedBy,
119
+ [WITH]: withFns,
120
+ fn: builderFn(key === "anonymous" ? "" : key, { use: options.use ?? [] }),
121
+ types: vTypes
122
+ };
123
+ ctx = contextScope(frame, base);
124
+ const bindUsable = (target, map, overrides) => {
125
+ for (const [name, used] of Object.entries(map)) {
126
+ const override = overrides?.[name];
127
+ if (isVar(used)) {
128
+ const varName = used.name;
129
+ Object.defineProperty(target, name, {
130
+ get: () => viewMergeVar(varName, readVarThrough(frame, varName), ctx),
131
+ set: (value) => writeVar(frame, varName, value),
132
+ enumerable: true,
133
+ configurable: true
134
+ });
135
+ continue;
136
+ }
137
+ if (typeof used === "object" && used !== null && "$models" in used && typeof used.$adapter === "function") {
138
+ target[name] = override !== void 0 ? override : used;
139
+ continue;
140
+ }
141
+ if (!isFn(used)) {
142
+ const group = {};
143
+ bindUsable(group, used, isFn(override) ? void 0 : override);
144
+ target[name] = group;
145
+ continue;
146
+ }
147
+ if (override !== void 0) {
148
+ target[name] = isFn(override) ? (i) => override(i, ctx) : override;
149
+ continue;
150
+ }
151
+ const usedArity = used.$arity;
152
+ target[name] = usedArity === void 0 ? (i) => used(i, ctx) : (...args) => {
153
+ const padded = args.slice(0, usedArity);
154
+ while (padded.length < usedArity) padded.push(void 0);
155
+ return used(...padded, ctx);
156
+ };
157
+ }
158
+ };
159
+ bindUsable(base, usable, withFns);
160
+ const missing = (name) => {
161
+ const value = readVar(cells, name);
162
+ return value === void 0 || value === null;
163
+ };
164
+ const checkRequires = () => {
165
+ for (const name of options.requires ?? []) if (missing(name)) throw new ValidationError(`${key}.requires.${name}`, `required var "${name}" is not set${parent === void 0 ? " - called without a parent context" : ""}`);
166
+ };
167
+ let bodyRan = false;
168
+ const declaredTracked = (c) => {
169
+ bodyRan = true;
170
+ return declared(c);
171
+ };
172
+ const body = chain.reduceRight((next, entry) => (c) => entry.handler(c, () => next(c)), declaredTracked);
173
+ const finish = (result) => {
174
+ if (outputValidation !== void 0) validate(asType(outputValidation), result, `${key}.output`);
175
+ if (bodyRan) {
176
+ for (const name of options.provides ?? []) if (missing(name)) throw new ValidationError(`${key}.provides.${name}`, `declared to provide "${name}" but it was left unset`);
177
+ }
178
+ return result;
179
+ };
180
+ const decorate = (thrown) => {
181
+ if (thrown instanceof ControlFlow) return thrown;
182
+ if (thrown instanceof FnError || thrown instanceof UnexpectedError) {
183
+ if (thrown.trail[thrown.trail.length - 1] !== key) thrown.trail.push(key);
184
+ return thrown;
185
+ }
186
+ return errorTypes ? new UnexpectedError(thrown, key) : thrown;
187
+ };
188
+ const run = () => {
189
+ checkRequires();
190
+ let result;
191
+ try {
192
+ result = body(ctx);
193
+ } catch (thrown) {
194
+ throw decorate(thrown);
195
+ }
196
+ return isThenable(result) ? result.then(finish, (thrown) => {
197
+ throw decorate(thrown);
198
+ }) : finish(result);
199
+ };
200
+ return run();
201
+ };
202
+ /** `.try`: declared errors as a value, everything else still throws. */
203
+ const tryCall = (...callArgs) => {
204
+ const settle = (thrown) => {
205
+ if (thrown instanceof FnError) return {
206
+ ok: false,
207
+ error: thrown
208
+ };
209
+ throw thrown;
210
+ };
211
+ try {
212
+ const result = callable(...callArgs);
213
+ return isThenable(result) ? result.then((value) => ({
214
+ ok: true,
215
+ value
216
+ }), settle) : {
217
+ ok: true,
218
+ value: result
219
+ };
220
+ } catch (thrown) {
221
+ return settle(thrown);
222
+ }
223
+ };
224
+ /**
225
+ * `.with`: a hand-built context. Keys naming one of this fn's `use`
226
+ * fns become OVERRIDES (carried by the subtree via `WITH`); everything
227
+ * else SEEDS a var in a fresh store. A parent given to the bound call
228
+ * is forked - its cells are copied, so seeds and writes inside never
229
+ * leak back into it.
230
+ */
231
+ const withCall = (context) => {
232
+ const makeParent = (given) => {
233
+ const source = given?.[STORE] ?? {};
234
+ const cells = Object.fromEntries(Object.entries(source).map(([name, cell]) => [name, { ...cell }]));
235
+ const seedFrame = {
236
+ cells,
237
+ key: `${key}.with`,
238
+ lockedBy: void 0,
239
+ entries: []
240
+ };
241
+ const overrides = { ...given?.[WITH] };
242
+ const applyWith = (map, entries, target) => {
243
+ for (const [name, value] of Object.entries(entries)) {
244
+ const member = map?.[name];
245
+ if (member === void 0) writeVar(seedFrame, name, value);
246
+ else if (isVar(member)) writeVar(seedFrame, member.name, value);
247
+ else if (isFn(member) || typeof value !== "object" || !value) target[name] = value;
248
+ else {
249
+ const existing = target[name];
250
+ const sub = existing && typeof existing === "object" ? existing : {};
251
+ target[name] = sub;
252
+ applyWith(member, value, sub);
253
+ }
254
+ }
255
+ };
256
+ applyWith(usable, context, overrides);
257
+ return {
258
+ [STORE]: cells,
259
+ [ACTIVE]: given?.[ACTIVE],
260
+ [EXTS]: given?.[EXTS],
261
+ [READONLY]: given?.[READONLY],
262
+ [WITH]: Object.keys(overrides).length > 0 ? overrides : void 0
263
+ };
264
+ };
265
+ const rewrite = (callArgs) => {
266
+ if (tupleInput) {
267
+ const padded = callArgs.slice(0, tupleInput.length);
268
+ while (padded.length < tupleInput.length) padded.push(void 0);
269
+ return [...padded, makeParent(callArgs[tupleInput.length])];
270
+ }
271
+ return [callArgs[0], makeParent(callArgs[1])];
272
+ };
273
+ const bound = (...callArgs) => callable(...rewrite(callArgs));
274
+ bound.try = (...callArgs) => tryCall(...rewrite(callArgs));
275
+ return bound;
276
+ };
277
+ return Object.assign(callable, {
278
+ $fn: true,
279
+ key,
280
+ provides: options.provides ?? [],
281
+ try: tryCall,
282
+ with: withCall,
283
+ ...tupleInput ? { $arity: tupleInput.length } : {},
284
+ $schema: {
285
+ ...options.input !== void 0 ? { input: options.input } : {},
286
+ ...options.output !== void 0 ? { output: options.output } : {},
287
+ ...declaredErrors ? { errors: declaredErrors } : {},
288
+ ...options.requires?.length ? { requires: options.requires } : {},
289
+ ...options.idempotent === true ? { idempotent: true } : {}
290
+ }
291
+ });
292
+ };
293
+ /**
294
+ * The builder half of `v.fn`: no handler yet, so calls accumulate. Keys
295
+ * CONCATENATE ("auth" then ".create" -> "auth.create"), `use`/`requires`/
296
+ * `provides` merge, other options child-wins - and the returned `.fn`
297
+ * follows the same one rule recursively: a handler terminates, anything
298
+ * else keeps building.
299
+ */
300
+ const mergeOptions = (base, child) => ({
301
+ ...base,
302
+ ...child,
303
+ use: [...base.use ?? [], ...child.use ?? []],
304
+ requires: [...base.requires ?? [], ...child.requires ?? []],
305
+ provides: [...base.provides ?? [], ...child.provides ?? []],
306
+ ...base.errors || child.errors ? { errors: {
307
+ ...base.errors ?? {},
308
+ ...child.errors ?? {}
309
+ } } : {}
310
+ });
311
+ const builderFn = (baseKey, base) => {
312
+ const build = (...args) => {
313
+ const hasKey = typeof args[0] === "string";
314
+ const childKey = hasKey ? args[0] : "";
315
+ const rest = hasKey ? args.slice(1) : args;
316
+ const first = rest[0];
317
+ const handler = typeof first === "function" ? first : rest[1];
318
+ const childOptions = typeof first === "function" ? {} : first ?? {};
319
+ const key = baseKey + childKey;
320
+ const options = mergeOptions(base, childOptions);
321
+ if (typeof handler !== "function") return {
322
+ fn: builderFn(key, options),
323
+ $fnSchema: {
324
+ input: options.input,
325
+ output: options.output
326
+ },
327
+ on: (target, a, b) => on(typeof target === "string" && !target.startsWith("var.") && !target.startsWith("scope.") ? key + target : target, a, b)
328
+ };
329
+ return defineFn(key || "anonymous", options, handler);
330
+ };
331
+ return Object.assign(build, {
332
+ $fnSchema: {
333
+ input: base.input,
334
+ output: base.output
335
+ },
336
+ type: (signature = {}) => ({
337
+ $fnSchema: {
338
+ input: signature.input,
339
+ output: signature.output
340
+ },
341
+ ...signature.optional ? { optional: true } : {},
342
+ ...signature.default !== void 0 ? { default: signature.default } : {}
343
+ })
344
+ });
345
+ };
346
+ const fnImpl = builderFn("", {});
347
+ //#endregion
348
+ export { fnImpl };
349
+
350
+ //# sourceMappingURL=fn.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fn.mjs","names":["onImpl"],"sources":["../src/fn.ts"],"sourcesContent":["import {\n\tControlFlow,\n\tFnError,\n\ttype Issue,\n\tUnexpectedError,\n\tValidationError,\n} from \"./error\";\nimport {\n\ttype ApplyOns,\n\tcollectMergeSeeds,\n\tcollectUsable,\n\ttype InputVarExtra,\n\ttype InputVarExtraOut,\n\tisFn,\n\tisNamespace,\n\tisOn,\n\tisVarExtension,\n\ttype Module,\n\ttype ModuleFns,\n\tmatchesTarget,\n\ttype OnEntry,\n\ton as onImpl,\n\tresolveModules,\n\ttype TargetMatches,\n\ttype VarExtension,\n\ttype VarGetContext,\n\ttype VarSetContext,\n\ttype WithDerived,\n} from \"./module\";\nimport {\n\tasType,\n\ttype InferArgs,\n\ttype InferInput,\n\tisVar,\n\ttype OutputSchemaOf,\n\toutputContract,\n\ttype TypeDefination,\n\tvalidate,\n\tvTypes,\n} from \"./schema\";\nimport type { ResolvedVars, ScopeOf, VarName, VarScope } from \"./scope\";\nimport type { LiteralString, Prettify } from \"./types\";\nimport {\n\ttype Cells,\n\tcontextScope,\n\ttype Frame,\n\tgetCell,\n\treadVar,\n\treadVarThrough,\n\ttype VarDefination,\n\tviewMergeVar,\n\twriteVar,\n} from \"./var\";\n\nexport type ParentContext = Record<string, any>;\n\n/**\n * `{}` assignable to `A`, and `A` is not an open index signature\n * (`Record<string, …>` / `v.object()` with no shape). Those accept any\n * object, so omitting the arg is not the same as sending one.\n */\ntype EmptyExtendsArgs<A> =\n\tRecord<never, never> extends A\n\t\t? string extends keyof A\n\t\t\t? false\n\t\t\t: true\n\t\t: false;\n\n/**\n * Callers may omit a non-tuple input when the schema is optional or\n * defaulted, or every field is already optional to send.\n */\ntype InputOmittable<A, I> = I extends { $var: true; schema?: infer S }\n\t? InputOmittable<A, NonNullable<S>>\n\t: I extends TypeDefination<any, any, infer D>\n\t\t? [D] extends [never]\n\t\t\t? EmptyExtendsArgs<A>\n\t\t\t: true\n\t\t: EmptyExtendsArgs<A>;\n\n/** The call shape: a TUPLE input spreads - one parameter per position,\n * the parent context last. No input, or an omittable one, takes\n * `(input?, parent?)`; required inputs stay required. */\ntype CallArgs<A, I> = I extends readonly unknown[]\n\t? A extends readonly unknown[]\n\t\t? [...A] | [...A, ParentContext]\n\t\t: never\n\t: [A] extends [void]\n\t\t? [input?: undefined, parent?: ParentContext]\n\t\t: InputOmittable<A, I> extends true\n\t\t\t? [input?: A, parent?: ParentContext]\n\t\t\t: [input: A, parent?: ParentContext];\n\n/** The union of a fn's DECLARED errors, as thrown values. */\nexport type FnErrorsOf<Er> = {\n\t[T in keyof Er & string]: FnError<T, InferInput<Er[T]>>;\n}[keyof Er & string];\n\n/** The declared-error union of a fn - for typing catch sites. */\nexport type FnErrors<F> =\n\tF extends FnDefination<any, any, any, any, any, infer Er>\n\t\t? FnErrorsOf<Er>\n\t\t: never;\n\n/** Non-distributive `never` guard first: a naked `R extends Promise`\n * distributes over `never` into `never`, and `[never] extends [Promise<_>]`\n * is also true (bottom type). Always-throwing bodies need a sync result. */\ntype TryResult<R, Er> = [R] extends [never]\n\t? { ok: true; value: never } | { ok: false; error: FnErrorsOf<Er> }\n\t: R extends Promise<infer V>\n\t\t? Promise<{ ok: true; value: V } | { ok: false; error: FnErrorsOf<Er> }>\n\t\t: { ok: true; value: R } | { ok: false; error: FnErrorsOf<Er> };\n\n/** No declared errors - the default error channel. */\ntype NoErrors = Record<never, never>;\n\n/** The `use` half of `.with`: fn overrides by name, recursing into\n * GROUPS so a nested binding can be overridden too. A var alias takes a\n * SEED for the var it points at. */\ntype WithFns<U> = {\n\t[K in keyof U]?: U[K] extends FnDefination<any, any, any, any, any, any>\n\t\t? BoundFn<U[K]>\n\t\t: U[K] extends VarDefination<any, infer T, any, any>\n\t\t\t? T\n\t\t\t: WithFns<U[K]>;\n};\n\n/** The context `.with` accepts: any var of the fn's WHOLE chain scope\n * (the builder's `use` included, not just the fn's own), plus any `use`\n * fn as an override - and nothing else. Kept as PLAIN mapped types: with\n * `RV`/`U` unknown both halves collapse to `{}`, which keeps every\n * `extends FnDefination<any, ...>` structural check passing.\n *\n * Prefer {@link WithSeed} for values stored on {@link FnDefination} - it\n * is what `v.fn` returns, and stays declaration-emit safe. */\nexport type WithContext<RV, U> = { [K in keyof RV]?: RV[K] } & WithFns<U>;\n\n/** Storage (or the FnEntries slice of one): `$models` plus callable\n * `$adapter`. Nested under a module as `{ db }`, it must not flow into\n * `.with` seeds - model schemas alone blow past declaration serialize\n * limits. ModuleFns keeps collections; WithSeed still drops storage. */\ntype StorageLike = {\n\t$models: object;\n\t$adapter: (...args: never[]) => unknown;\n};\n\n/** Flatten `use` members to `.with` overrides: bound call signatures, var\n * alias values, nested groups. Storage is dropped (mount-only). */\ntype WithFnsSeed<U> = {\n\t[K in keyof U as U[K] extends StorageLike\n\t\t? never\n\t\t: K]?: U[K] extends FnDefination<any, any, any, any, any, any>\n\t\t? BoundFn<U[K]>\n\t\t: U[K] extends VarDefination<any, infer T, any, any>\n\t\t\t? T\n\t\t\t: WithFnsSeed<U[K]>;\n};\n\n/**\n * Flat `.with` seed map stored on exported fns. Evaluating ScopeOf /\n * ModuleFns here (instead of embedding those wrappers as type arguments)\n * keeps declaration emit small: `.d.ts` shows leaf var shapes and bound\n * call signatures, not `ScopeOf<ResolvedVars<entire module graph>>`.\n */\nexport type WithSeed<RV, U> = Prettify<\n\t{ [K in keyof RV]?: RV[K] } & WithFnsSeed<U>\n>;\n\n/** What `v.fn` / `e.fn` returns: contract params plus a flat {@link WithSeed}\n * for `.with`, never the raw ScopeOf / ModuleFns graph. */\ntype PublicFn<\n\tA,\n\tR,\n\tK extends string,\n\tI,\n\tP extends readonly string[],\n\tEr,\n\tRV,\n\tU,\n\tO = unknown,\n> = FnDefination<A, R, K, I, P, Er, WithSeed<RV, U>, O>;\n\n/** What `.with` returns: the same callable, context baked in. */\nexport interface BoundCall<A, R, I, Er> {\n\t(...args: CallArgs<A, I>): R;\n\ttry(...args: CallArgs<A, I>): TryResult<R, Er>;\n}\n\nexport interface FnDefination<\n\tA,\n\tR,\n\tK extends string = string,\n\tI = unknown,\n\tP extends readonly string[] = readonly string[],\n\tEr = NoErrors,\n\t/** `.with` seed map ({@link WithSeed}). Defaults keep structural\n\t * `extends FnDefination<any, ...>` checks passing. */\n\tW = unknown,\n\tO = unknown,\n> {\n\t(...args: CallArgs<A, I>): R;\n\t/**\n\t * Call with DECLARED errors caught as a value: `{ ok: true, value }`\n\t * or `{ ok: false, error }`, narrowed by `error.tag`. Only tagged,\n\t * expected errors become results - defects and contract violations\n\t * still throw, exactly as they should.\n\t */\n\ttry(...args: CallArgs<A, I>): TryResult<R, Er>;\n\t/**\n\t * Call with a HAND-BUILT context. Keys naming a var SEED that var in a\n\t * fresh scope; keys naming a `use` fn OVERRIDE that binding for the\n\t * whole subtree below. Both are typed from the fn's chain - what the\n\t * BUILDER mounted counts, so `signOut.with({ user })` type-checks even\n\t * though `signOut` itself never says `use: [user]`. A parent passed to\n\t * the bound call is FORKED: its vars are copied in, never written back.\n\t */\n\twith(context: W): BoundCall<A, R, I, Er>;\n\t/** Brand, so a plugin module can be scanned for its fns. */\n\treadonly $fn: true;\n\t/** The name interceptors target - literal, so `ApplyOn` can match it. */\n\treadonly key: K;\n\t/** The declared contract, retained AS WRITTEN for runtime\n\t * introspection (tool cards, docs renderers): the raw input/output\n\t * schemas, error tag map, and required vars. Optional so structural\n\t * `extends FnDefination` checks keep passing for hand-built fns. */\n\treadonly $schema?: {\n\t\tinput?: unknown;\n\t\toutput?: unknown;\n\t\terrors?: Record<string, unknown>;\n\t\trequires?: readonly string[];\n\t\t/** Declared idempotence - same args, same result, safe to repeat. */\n\t\tidempotent?: boolean;\n\t};\n\t/** Vars this fn promises to set when ITS OWN body runs - the literal\n\t * list, readable by graph tooling at both type and runtime level. */\n\treadonly provides: P;\n\t/** Phantom: the raw declared input, so extensions of the vars it\n\t * references can widen used-fn call sites. Never set at runtime. */\n\treadonly $input?: I;\n\t/** Phantom: the raw declared output, the counterpart of `$input` - the\n\t * schema as written, for type-level introspection. Never set at runtime. */\n\treadonly $output?: O;\n\t/** Phantom: declared error tags -> payload schemas. */\n\treadonly $errors?: Er;\n}\n\nexport type ArgsOf<I> = I extends readonly unknown[]\n\t? { -readonly [K in keyof I]: InferArgs<I[K]> }\n\t: unknown extends I\n\t\t? void\n\t\t: InferArgs<I>;\n\n/**\n * Call args of a declaring fn: the declared input, plus whatever mounted\n * `v.extend` / same-name shadows add for vars that input references.\n * Mirrors {@link ApplyOn} so `input: user` + `use: [userWithEmail]` types\n * the door the same way a used call site would.\n */\nexport type WidenedArgs<I, ExtPL> =\n\tunknown extends InputVarExtra<ExtPL, I>\n\t\t? ArgsOf<I>\n\t\t: Prettify<\n\t\t\t\t([ArgsOf<I>] extends [void] ? unknown : ArgsOf<I>) &\n\t\t\t\t\tInputVarExtra<ExtPL, I>\n\t\t\t>;\n\nexport type OptionType<\n\tI,\n\tO,\n\tP,\n\tQ,\n\tPL,\n\tRO extends boolean = boolean,\n\tEr = any,\n> = {\n\t/**\n\t * The fn's DECLARED failures: tag -> payload schema. The THIRD\n\t * contract door - input validates on entry, output on exit, errors at\n\t * `throw c.error(tag, data)`. Once declared, any UNTAGGED throw\n\t * escaping the body is a defect and comes out as `UnexpectedError` -\n\t * callers can tell a domain refusal from a bug without string\n\t * matching.\n\t */\n\terrors?: Er;\n\t/**\n\t * A readonly fn cannot write vars - not in its handler, not in\n\t * anything it calls, not from interceptors mounted on it. Enforced at\n\t * the type level (vars readonly on `c`, declared writers uncallable)\n\t * and at runtime (the whole subtree's store locks).\n\t */\n\treadonly?: RO;\n\t/**\n\t * Declared idempotence: calling with the same args always produces the\n\t * same result and repeating the call is harmless - a read, a lookup, a\n\t * pure computation. Part of the retained contract (`$schema`), so\n\t * hosts may DEDUPE calls: the script engine serves repeated\n\t * same-args calls to an idempotent fn from one dispatch per session.\n\t * Note this is a different promise than `readonly` (writes no vars) -\n\t * an fn can be readonly and still hit a non-idempotent API.\n\t */\n\tidempotent?: boolean;\n\tinput?: I;\n\t/**\n\t * The fn's return contract. A bare schema is BOTH the signature and\n\t * the exit check; the wrapper `{ def?, validation? }` splits them -\n\t * `{ def }` documents the return (tool cards, handler typing) without\n\t * runtime validation, `validation` is the schema the exit check runs\n\t * (defaults to none in the wrapper form).\n\t */\n\toutput?: O;\n\t/** Vars this fn guarantees to set. Checked on exit. */\n\tprovides?: P;\n\t/** Vars that must already be set. Checked on entry, before the body. */\n\trequires?: Q;\n\t/**\n\t * Module namespaces to pull in. Their vars come into scope, their fns\n\t * land directly on `c` already bound to this context (a plain-record\n\t * member nests as a NAMESPACE: `c.cookies.setCookie`), and their `on`\n\t * entries stay active for everything below.\n\t */\n\tuse?: PL;\n};\n\n/** A used fn, with the parent context already applied. A tuple-input fn\n * keeps its positional signature. Omittable inputs match {@link CallArgs}. */\ntype BoundFn<F> =\n\tF extends FnDefination<infer A, infer R, string, infer I, any, any>\n\t\t? I extends readonly unknown[]\n\t\t\t? A extends readonly unknown[]\n\t\t\t\t? (...args: [...A]) => R\n\t\t\t\t: never\n\t\t\t: [A] extends [void]\n\t\t\t\t? () => R\n\t\t\t\t: InputOmittable<A, I> extends true\n\t\t\t\t\t? (input?: A) => R\n\t\t\t\t\t: (input: A) => R\n\t\t: never;\n\n/** Keys of a usable map whose member is a VAR alias. */\ntype UseVarKeys<U> = {\n\t[K in keyof U]: U[K] extends VarDefination<any, any, any, any> ? K : never;\n}[keyof U];\n\n/**\n * VarDefination surface keys. ModuleFns intersects a merge var with\n * same-key namespace helpers (`VarDef & { createUser }`); stripping these\n * leaves the helper group for {@link UseApi}.\n */\ntype VarSurfaceKeys =\n\t| \"$var\"\n\t| \"name\"\n\t| \"default\"\n\t| \"schema\"\n\t| \"type\"\n\t| \"$source\"\n\t| \"$attrs\"\n\t| \"$merge\"\n\t| \"customize\";\n\ntype MergeHelpersOnVar<V> = Omit<V, VarSurfaceKeys>;\n\n/** Bound helpers intersected onto a merge var in ModuleFns, if any. */\ntype UseApiMergeExtras<V> = V extends { $merge: true }\n\t? [keyof MergeHelpersOnVar<V>] extends [never]\n\t\t? never\n\t\t: UseApi<MergeHelpersOnVar<V>>\n\t: never;\n\n/**\n * A var alias' surface: the var's VALUE, plus same-key namespace helpers\n * when the var is `merge: true` (mirrors {@link collectMergeSeeds} /\n * {@link viewMergeVar}).\n */\ntype UseVarValue<V> =\n\tV extends VarDefination<any, infer T, any, any>\n\t\t? UseApiMergeExtras<V> extends infer H\n\t\t\t? [H] extends [never]\n\t\t\t\t? T\n\t\t\t\t: Prettify<T & H>\n\t\t\t: T\n\t\t: never;\n\n/**\n * Fold merge-var helpers from the usable map `U` onto scope values keyed\n * by DECLARED name (so `c.vt_merge_db.byTag` types when the export key\n * was `db`).\n */\ntype MergeIntoScope<RV, U> = {\n\t[K in keyof RV]: HelpersForDeclaredName<K & string, U> extends infer H\n\t\t? [H] extends [never]\n\t\t\t? RV[K]\n\t\t\t: Prettify<RV[K] & H>\n\t\t: RV[K];\n};\n\ntype HelpersForDeclaredName<N extends string, U> = {\n\t[K in keyof U]: U[K] extends VarDefination<N, any, any, any>\n\t\t? UseApiMergeExtras<U[K]>\n\t\t: never;\n}[keyof U];\n\nexport type UseApi<U> = Prettify<\n\t{\n\t\t[K in Exclude<keyof U, UseVarKeys<U>>]: U[K] extends FnDefination<\n\t\t\tany,\n\t\t\tany,\n\t\t\tany,\n\t\t\tany,\n\t\t\tany,\n\t\t\tany\n\t\t>\n\t\t\t? BoundFn<U[K]>\n\t\t\t: U[K] extends StorageLike\n\t\t\t\t? U[K]\n\t\t\t\t: UseApi<U[K]>;\n\t} & { [K in UseVarKeys<U>]: UseVarValue<U[K]> }\n>;\n\n/** Used fns inside a readonly fn: declared writers become uncallable,\n * with the reason on hover instead of a generic type error; var aliases\n * become readonly properties. */\ntype ReadUseApi<U> = Prettify<\n\t{\n\t\t[K in Exclude<keyof U, UseVarKeys<U>>]: U[K] extends FnDefination<\n\t\t\tany,\n\t\t\tany,\n\t\t\tany,\n\t\t\tany,\n\t\t\tinfer P,\n\t\t\tany\n\t\t>\n\t\t\t? P extends readonly []\n\t\t\t\t? BoundFn<U[K]>\n\t\t\t\t: `writes \"${P[number] & string}\" - not callable from a readonly fn`\n\t\t\t: U[K] extends StorageLike\n\t\t\t\t? U[K]\n\t\t\t\t: ReadUseApi<U[K]>;\n\t} & { readonly [K in UseVarKeys<U>]: UseVarValue<U[K]> }\n>;\n\nexport type Context<\n\tI,\n\tRV,\n\tRequired,\n\tU = unknown,\n\tFnApi = Fn,\n\tRO extends boolean = false,\n\tErrs = NoErrors,\n\t/** Modules that widen var-bound input (this fn's `use` + builder chain). */\n\tExtPL = unknown,\n> = {\n\tinput: unknown extends InputVarExtraOut<ExtPL, I>\n\t\t? InferInput<I>\n\t\t: Prettify<InferInput<I> & InputVarExtraOut<ExtPL, I>>;\n\t/**\n\t * Mint a DECLARED error - tag-checked, payload validated at creation:\n\t * `throw c.error(\"invalid_credentials\", { attempts: 3 })`. Only tags\n\t * from this fn's `errors` exist; the payload validates like input.\n\t */\n\terror: <T extends keyof Errs & string>(\n\t\ttag: T,\n\t\t...data: Record<never, never> extends InferArgs<Errs[T]>\n\t\t\t? [data?: InferArgs<Errs[T]>]\n\t\t\t: [data: InferArgs<Errs[T]>]\n\t) => FnError<T, InferInput<Errs[T]>>;\n\t/** Define fns from inside: this fn's scope and key carry over, so\n\t * anything built here is typed exactly like a chained builder. */\n\tfn: FnApi;\n\t/** The schema constructors (string, number, object, ...). */\n\ttypes: typeof vTypes;\n} & /** Every var in scope, directly on `c`: read `c.session`, write by\n * plain assignment (`c.session = {...}`). Every var is a readonly\n * property on a readonly fn. Merge vars also expose same-key helpers\n * folded from `U` (declared-name access). */ VarScope<\n\tMergeIntoScope<RV, U>,\n\tRequired,\n\tRO\n> &\n\t/** Fns from `use`, directly on `c` and already threaded with this\n\t * context: `c.createUser({...})`. */\n\t(RO extends true ? ReadUseApi<U> : UseApi<U>);\n\nexport type InferReturn<O> = unknown extends O\n\t? unknown\n\t: InferInput<OutputSchemaOf<O>>;\n\nexport interface Fn<\n\tBase = unknown,\n\tBaseFns = unknown,\n\tBasePL extends readonly Module[] = [],\n\tPrefix extends string = \"\",\n> {\n\t/**\n\t * The builder FN is a schema too: `create: v.fn` (never called) declares\n\t * \"any function\" - typed `(...args: any[]) => any`, runtime checks only\n\t * `typeof value === \"function\"`.\n\t */\n\treadonly $fnSchema: { input?: unknown; output?: unknown };\n\t/**\n\t * \"A fn with THIS signature\", as a schema: `create: v.fn.type({ input,\n\t * output })` types the field as that fn and validates what a signature\n\t * CAN be validated for - the value is a function, and a plain closure\n\t * gets the declared input checked at its door on every call.\n\t *\n\t * `optional` / `default` work like on `v.string()` etc., so a prop in\n\t * `v.object({...})` can be a fn type and still omittable.\n\t *\n\t * This exists apart from a handler-less `v.fn({ input, output })` for\n\t * INLINE use: `v.fn`'s handler overloads return a callable, which makes\n\t * TypeScript defer any inline `v.fn(...)` call inside another generic\n\t * call's arguments (higher-order inference) - the enclosing `v.object`/\n\t * `v.var` then loses its shape inference entirely. `v.fn.type` returns a\n\t * plain carrier, so it composes inline anywhere.\n\t */\n\treadonly type: <\n\t\tI = unknown,\n\t\tO = unknown,\n\t\tD = never,\n\t\tOpt extends boolean = false,\n\t>(signature?: {\n\t\tinput?: I;\n\t\toutput?: O;\n\t\tdefault?: D;\n\t\toptional?: Opt;\n\t}) => { readonly $fnSchema: { input?: I; output?: O } } & ([Opt] extends [\n\t\ttrue,\n\t]\n\t\t? { readonly optional: true }\n\t\t: unknown) &\n\t\t([D] extends [never] ? unknown : { readonly default: D });\n\n\t/* ---- a handler TERMINATES: these four produce a callable fn ---- */\n\t<R>(\n\t\tfn: (\n\t\t\tctx: Context<\n\t\t\t\tunknown,\n\t\t\t\tScopeOf<[], Base, BasePL>,\n\t\t\t\tnever,\n\t\t\t\tBaseFns,\n\t\t\t\tFn<Base, BaseFns, BasePL, Prefix>\n\t\t\t>,\n\t\t) => R,\n\t): PublicFn<\n\t\tvoid,\n\t\tR,\n\t\tPrefix extends \"\" ? string : Prefix,\n\t\tunknown,\n\t\treadonly string[],\n\t\tNoErrors,\n\t\tScopeOf<[], Base, BasePL>,\n\t\tBaseFns\n\t>;\n\t<K extends LiteralString, R>(\n\t\tkey: K,\n\t\tfn: (\n\t\t\tctx: Context<\n\t\t\t\tunknown,\n\t\t\t\tScopeOf<[], Base, BasePL>,\n\t\t\t\tnever,\n\t\t\t\tBaseFns,\n\t\t\t\tFn<Base, BaseFns, BasePL, `${Prefix}${K}`>\n\t\t\t>,\n\t\t) => R,\n\t): PublicFn<\n\t\tvoid,\n\t\tR,\n\t\t`${Prefix}${K}`,\n\t\tunknown,\n\t\treadonly string[],\n\t\tNoErrors,\n\t\tScopeOf<[], Base, BasePL>,\n\t\tBaseFns\n\t>;\n\n\t<\n\t\tconst I,\n\t\tO,\n\t\tR extends InferReturn<O> | Promise<InferReturn<O>>,\n\t\tconst PL extends readonly Module[] = [],\n\t\tconst P extends readonly VarName<ScopeOf<PL, Base>>[] = readonly [],\n\t\tconst Q extends readonly VarName<ScopeOf<PL, Base>>[] = readonly [],\n\t\tRO extends boolean = false,\n\t\tEr extends Record<string, unknown> = NoErrors,\n\t>(\n\t\toptions: OptionType<I, O, P, Q, PL, RO, Er>,\n\t\tfn: (\n\t\t\tctx: Context<\n\t\t\t\tI,\n\t\t\t\tScopeOf<PL, Base, readonly [...BasePL, ...PL]>,\n\t\t\t\tWithDerived<PL, BasePL, Q[number]>,\n\t\t\t\tApplyOns<ModuleFns<PL>, PL> & BaseFns,\n\t\t\t\tFn<\n\t\t\t\t\tBase & ResolvedVars<PL>,\n\t\t\t\t\tApplyOns<ModuleFns<PL>, PL> & BaseFns,\n\t\t\t\t\treadonly [...BasePL, ...PL],\n\t\t\t\t\tPrefix\n\t\t\t\t>,\n\t\t\t\tRO,\n\t\t\t\tEr,\n\t\t\t\treadonly [...BasePL, ...PL]\n\t\t\t>,\n\t\t) => R,\n\t): PublicFn<\n\t\tWidenedArgs<I, readonly [...BasePL, ...PL]>,\n\t\tR,\n\t\tPrefix extends \"\" ? string : Prefix,\n\t\tI,\n\t\tP,\n\t\tEr,\n\t\tScopeOf<PL, Base, readonly [...BasePL, ...PL]>,\n\t\tApplyOns<ModuleFns<PL>, PL> & BaseFns,\n\t\tO\n\t>;\n\t<\n\t\tK extends LiteralString,\n\t\tconst I,\n\t\tO,\n\t\tR extends InferReturn<O> | Promise<InferReturn<O>>,\n\t\tconst PL extends readonly Module[] = [],\n\t\tconst P extends readonly VarName<ScopeOf<PL, Base>>[] = readonly [],\n\t\tconst Q extends readonly VarName<ScopeOf<PL, Base>>[] = readonly [],\n\t\tRO extends boolean = false,\n\t\tEr extends Record<string, unknown> = NoErrors,\n\t>(\n\t\tkey: K,\n\t\toptions: OptionType<I, O, P, Q, PL, RO, Er>,\n\t\tfn: (\n\t\t\tctx: Context<\n\t\t\t\tI,\n\t\t\t\tScopeOf<PL, Base, readonly [...BasePL, ...PL]>,\n\t\t\t\tWithDerived<PL, BasePL, Q[number]>,\n\t\t\t\tApplyOns<ModuleFns<PL>, PL> & BaseFns,\n\t\t\t\tFn<\n\t\t\t\t\tBase & ResolvedVars<PL>,\n\t\t\t\t\tApplyOns<ModuleFns<PL>, PL> & BaseFns,\n\t\t\t\t\treadonly [...BasePL, ...PL],\n\t\t\t\t\t`${Prefix}${K}`\n\t\t\t\t>,\n\t\t\t\tRO,\n\t\t\t\tEr,\n\t\t\t\treadonly [...BasePL, ...PL]\n\t\t\t>,\n\t\t) => R,\n\t): PublicFn<\n\t\tWidenedArgs<I, readonly [...BasePL, ...PL]>,\n\t\tR,\n\t\t`${Prefix}${K}`,\n\t\tI,\n\t\tP,\n\t\tEr,\n\t\tScopeOf<PL, Base, readonly [...BasePL, ...PL]>,\n\t\tApplyOns<ModuleFns<PL>, PL> & BaseFns,\n\t\tO\n\t>;\n\n\t/* ---- NO handler: a builder. Keys concatenate, `use` accumulates,\n\t and its `.fn` follows the same rule recursively. ---- */\n\t<K extends LiteralString>(\n\t\tkey: K,\n\t): Instance<Base, BaseFns, BasePL, `${Prefix}${K}`>;\n\t<\n\t\tI,\n\t\tO,\n\t\tconst PL extends readonly Module[] = [],\n\t\tconst P extends readonly VarName<ScopeOf<PL, Base>>[] = readonly [],\n\t\tconst Q extends readonly VarName<ScopeOf<PL, Base>>[] = readonly [],\n\t>(\n\t\toptions: OptionType<I, O, P, Q, PL>,\n\t): Instance<\n\t\tBase & ResolvedVars<PL>,\n\t\tBaseFns & ApplyOns<ModuleFns<PL>, PL>,\n\t\treadonly [...BasePL, ...PL],\n\t\tPrefix,\n\t\tI,\n\t\tO\n\t>;\n\t<\n\t\tK extends LiteralString,\n\t\tI,\n\t\tO,\n\t\tconst PL extends readonly Module[] = [],\n\t\tconst P extends readonly VarName<ScopeOf<PL, Base>>[] = readonly [],\n\t\tconst Q extends readonly VarName<ScopeOf<PL, Base>>[] = readonly [],\n\t>(\n\t\tkey: K,\n\t\toptions: OptionType<I, O, P, Q, PL>,\n\t): Instance<\n\t\tBase & ResolvedVars<PL>,\n\t\tBaseFns & ApplyOns<ModuleFns<PL>, PL>,\n\t\treadonly [...BasePL, ...PL],\n\t\t`${Prefix}${K}`,\n\t\tI,\n\t\tO\n\t>;\n}\n\nconst isThenable = (value: any): value is Promise<unknown> =>\n\ttypeof value?.then === \"function\";\n\nconst STORE = Symbol(\"var-store\");\nconst ACTIVE = Symbol(\"active-plugins\");\nconst EXTS = Symbol(\"active-var-extensions\");\nconst READONLY = Symbol(\"readonly-lock\");\nconst WITH = Symbol(\"with-overrides\");\n\nconst defineFn = (\n\tkey: string,\n\toptions: OptionType<any, any, any, any, any>,\n\tdeclared: (c: any) => any,\n) => {\n\tconst modules = resolveModules((options.use ?? []) as Module[]);\n\n\t// Interceptors and var extensions this fn brings, from its modules -\n\t// nested GROUPS included. The SAME entry mounted twice (two views of\n\t// one storage, a module and its re-export) applies once - identity\n\t// dedup, like inheritance.\n\tconst own: OnEntry<string>[] = [];\n\tconst ownExts: VarExtension<string, any>[] = [];\n\tconst scanMembers = (mod: Record<string, unknown>) => {\n\t\tfor (const value of Object.values(mod)) {\n\t\t\tif (isOn(value) && !own.includes(value)) own.push(value);\n\t\t\telse if (isVarExtension(value)) ownExts.push(value);\n\t\t\telse if (isNamespace(value)) scanMembers(value);\n\t\t}\n\t};\n\tfor (const mod of modules) scanMembers(mod);\n\n\tconst usable = collectUsable(modules);\n\tconst mergeSeeds = collectMergeSeeds(modules);\n\n\t// A tuple input means POSITIONAL args: the callable takes one arg per\n\t// declared position, then the parent context.\n\tconst tupleInput = Array.isArray(options.input)\n\t\t? (options.input as unknown[])\n\t\t: undefined;\n\n\t// Declared errors: tag -> payload schema, the THIRD contract door\n\t// (input on entry, output on exit, errors at throw). Declaring any\n\t// also flips the defect rule on: untagged throws come out wrapped.\n\tconst declaredErrors = options.errors as Record<string, unknown> | undefined;\n\n\t// Only the VALIDATION half of the output contract is checked on exit -\n\t// a `{ def }`-only output is a documented promise, never a check.\n\tconst outputValidation = outputContract(options.output).validation;\n\tconst errorTypes = declaredErrors\n\t\t? Object.fromEntries(\n\t\t\t\tObject.entries(declaredErrors).map(([tag, schema]) => [\n\t\t\t\t\ttag,\n\t\t\t\t\tasType(schema),\n\t\t\t\t]),\n\t\t\t)\n\t\t: undefined;\n\n\t// Input that references vars: a var FIELD sets that var from the field\n\t// value; a whole-var input (`input: user`) sets it from the whole args.\n\t// For a tuple the \"fields\" are the positions (\"0\", \"1\", ...).\n\tconst inputVars: Array<[field: string, name: string]> = [];\n\tconst declaredInput = options.input as Record<string, any> | undefined;\n\tconst wholeVar: string | undefined =\n\t\tdeclaredInput && isVar(declaredInput)\n\t\t\t? (declaredInput as { name: string }).name\n\t\t\t: undefined;\n\tif (declaredInput && !wholeVar) {\n\t\tfor (const [field, def] of Object.entries(declaredInput)) {\n\t\t\tif (isVar(def)) inputVars.push([field, def.name]);\n\t\t}\n\t}\n\n\t// Contradictions caught at DEFINITION, not first call: a readonly fn\n\t// promising to set vars, or binding input into vars, makes no sense.\n\tif (options.readonly) {\n\t\tif (options.provides?.length) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t`${key}.readonly`,\n\t\t\t\t\"a readonly fn cannot declare provides - it promises writes\",\n\t\t\t);\n\t\t}\n\t\tif (wholeVar !== undefined || inputVars.length > 0) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t`${key}.readonly`,\n\t\t\t\t\"a readonly fn cannot bind input to vars - that is a write\",\n\t\t\t);\n\t\t}\n\t}\n\n\tconst callable = (...callArgs: any[]) => {\n\t\tconst input: unknown = tupleInput\n\t\t\t? callArgs.slice(0, tupleInput.length)\n\t\t\t: callArgs[0];\n\t\tconst parent: any = tupleInput ? callArgs[tupleInput.length] : callArgs[1];\n\t\tconst cells: Cells = parent?.[STORE] ?? {};\n\t\t// Root scope: fold merge-var contributions from `use` into cells\n\t\t// before anything reads them (storage default + helper namespaces).\n\t\tif (!parent?.[STORE]) {\n\t\t\tfor (const [name, value] of Object.entries(mergeSeeds)) {\n\t\t\t\tconst cell = getCell(cells, name);\n\t\t\t\tcell.value = value;\n\t\t\t\tcell.accumulate = true;\n\t\t\t}\n\t\t}\n\t\t// The lock travels the whole subtree: once any frame above is\n\t\t// readonly, every write below throws - handlers, nested fns,\n\t\t// interceptors, input-var seeding, all of it.\n\t\tconst lockedBy: string | undefined = options.readonly\n\t\t\t? key\n\t\t\t: parent?.[READONLY];\n\n\t\t// The active set travels down the call tree, so a fn that declares\n\t\t// plugins keeps them in force for everything it calls with `c`.\n\t\t// Deduped by identity: an instance mounts its modules on every fn,\n\t\t// so a nested call would otherwise stack the same entry twice.\n\t\tconst inherited: OnEntry<string>[] = parent?.[ACTIVE] ?? [];\n\t\tconst active =\n\t\t\town.length === 0\n\t\t\t\t? inherited\n\t\t\t\t: [...inherited, ...own.filter((e) => !inherited.includes(e))];\n\t\tconst chain = active.filter((entry) => matchesTarget(entry.target, key));\n\n\t\t// Fn overrides from `.with`, travelling down like the active set: a\n\t\t// mocked `use` fn stays mocked for the whole subtree.\n\t\tconst withFns: Record<string, unknown> | undefined = parent?.[WITH];\n\n\t\tconst inheritedExts: VarExtension<string, any>[] = parent?.[EXTS] ?? [];\n\t\tconst exts =\n\t\t\townExts.length === 0\n\t\t\t\t? inheritedExts\n\t\t\t\t: [\n\t\t\t\t\t\t...inheritedExts,\n\t\t\t\t\t\t...ownExts.filter((e) => !inheritedExts.includes(e)),\n\t\t\t\t\t];\n\n\t\tlet ctx: any;\n\t\tconst frame: Frame = {\n\t\t\tcells,\n\t\t\tkey,\n\t\t\tlockedBy,\n\t\t\tentries: active,\n\t\t};\n\n\t\t// Widen a var-referencing input with the mounted extensions of that\n\t\t// var: their fields validate off the same raw value and merge in.\n\t\tconst extendValue = (name: string, raw: unknown, value: unknown) => {\n\t\t\tlet merged = value;\n\t\t\tfor (const ext of exts) {\n\t\t\t\tif (ext.name !== name) continue;\n\t\t\t\tconst extra = validate(asType(ext.schema), raw, `${key}.${name}`);\n\t\t\t\tmerged = { ...(merged as Record<string, unknown>), ...extra };\n\t\t\t}\n\t\t\treturn merged;\n\t\t};\n\n\t\t// Tuple positions validate like object fields: every bad position\n\t\t// reports, together, in one error.\n\t\tlet parsed: any;\n\t\tif (tupleInput) {\n\t\t\tconst issues: Issue[] = [];\n\t\t\tparsed = tupleInput.map((def, index) => {\n\t\t\t\ttry {\n\t\t\t\t\treturn validate(\n\t\t\t\t\t\tasType(def),\n\t\t\t\t\t\t(input as unknown[])[index],\n\t\t\t\t\t\t`${key}[${index}]`,\n\t\t\t\t\t);\n\t\t\t\t} catch (thrown) {\n\t\t\t\t\tif (!(thrown instanceof ValidationError)) throw thrown;\n\t\t\t\t\tissues.push(...thrown.issues);\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t});\n\t\t\tconst firstIssue = issues[0];\n\t\t\tif (firstIssue) {\n\t\t\t\tthrow new ValidationError(firstIssue.path, firstIssue.message, issues);\n\t\t\t}\n\t\t} else {\n\t\t\tparsed =\n\t\t\t\toptions.input === undefined\n\t\t\t\t\t? input\n\t\t\t\t\t: validate(asType(options.input), input, key);\n\t\t}\n\n\t\t// Mounted extensions widen the accepted input: each validates its\n\t\t// own fields off the same raw input and merges onto `parsed`.\n\t\t// Extensions extend RECORD inputs - positional args have no field\n\t\t// to merge into, so a tuple fn skips them.\n\t\tfor (const entry of chain) {\n\t\t\tif (!entry.extend?.input || tupleInput) continue;\n\t\t\tconst extra = validate(asType(entry.extend.input), input, `${key}.on`);\n\t\t\tparsed = { ...((parsed as Record<string, unknown>) ?? {}), ...extra };\n\t\t}\n\n\t\t// A whole-var input IS the var: the merged value becomes both the\n\t\t// parsed input and the var for the rest of the call tree.\n\t\tif (wholeVar !== undefined && parsed !== undefined) {\n\t\t\tparsed = extendValue(wholeVar, input, parsed);\n\t\t\twriteVar(frame, wholeVar, parsed);\n\t\t}\n\n\t\t// An absent field leaves the var alone, so its default (or whatever\n\t\t// a parent already set) survives. Only `undefined` counts as absent -\n\t\t// an explicit `null` is a value and does overwrite.\n\t\tfor (const [field, name] of inputVars) {\n\t\t\tconst raw = (input as Record<string, unknown>)?.[field];\n\t\t\tconst value = (parsed as Record<string, unknown>)?.[field];\n\t\t\tif (value === undefined) continue;\n\t\t\tconst merged = extendValue(name, raw, value);\n\t\t\t(parsed as Record<string, unknown>)[field] = merged;\n\t\t\twriteVar(frame, name, merged);\n\t\t}\n\n\t\t// The context's FIXED surface; everything not on it is a var, read\n\t\t// and written straight on `c` through the proxy below.\n\t\tconst base: any = {\n\t\t\tinput: parsed,\n\t\t\t// Mint a declared error: tag must be declared, payload validates\n\t\t\t// at creation - an error is a contract too.\n\t\t\terror: (tag: string, data?: unknown) => {\n\t\t\t\tconst schema = errorTypes?.[tag];\n\t\t\t\tif (!schema) {\n\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t`${key}.errors.${tag}`,\n\t\t\t\t\t\terrorTypes\n\t\t\t\t\t\t\t? `\"${tag}\" is not a declared error of \"${key}\"`\n\t\t\t\t\t\t\t: `\"${key}\" declares no errors`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn new FnError(\n\t\t\t\t\ttag,\n\t\t\t\t\tvalidate(schema, data ?? {}, `${key}.errors.${tag}`),\n\t\t\t\t\tkey,\n\t\t\t\t);\n\t\t\t},\n\t\t\t[STORE]: cells,\n\t\t\t[ACTIVE]: active,\n\t\t\t[EXTS]: exts,\n\t\t\t[READONLY]: lockedBy,\n\t\t\t[WITH]: withFns,\n\t\t\tfn: builderFn(key === \"anonymous\" ? \"\" : key, {\n\t\t\t\tuse: options.use ?? [],\n\t\t\t}),\n\t\t\ttypes: vTypes,\n\t\t};\n\t\tctx = contextScope(frame, base);\n\t\t// Used fns land DIRECTLY on the context (`c.createUser(...)`), bound\n\t\t// to `ctx` so they share this store and active set without the caller\n\t\t// having to thread `c` by hand. A GROUP binds recursively and lands\n\t\t// as a namespace (`c.cookie.setCookie(...)`); a VAR member becomes a\n\t\t// live ALIAS under its export name (`c.cookie.options` reads and\n\t\t// writes the var, hooks and readonly lock included). A tuple-input\n\t\t// fn gets its args padded to full arity so the context always lands\n\t\t// in the parent slot, however many args the caller actually passed.\n\t\tconst bindUsable = (\n\t\t\ttarget: any,\n\t\t\tmap: Record<string, unknown>,\n\t\t\toverrides: Record<string, unknown> | undefined,\n\t\t) => {\n\t\t\tfor (const [name, used] of Object.entries(map)) {\n\t\t\t\tconst override = overrides?.[name];\n\t\t\t\tif (isVar(used)) {\n\t\t\t\t\tconst varName = (used as { name: string }).name;\n\t\t\t\t\tObject.defineProperty(target, name, {\n\t\t\t\t\t\tget: () =>\n\t\t\t\t\t\t\tviewMergeVar(varName, readVarThrough(frame, varName), ctx),\n\t\t\t\t\t\tset: (value: unknown) => writeVar(frame, varName, value),\n\t\t\t\t\t\tenumerable: true,\n\t\t\t\t\t\tconfigurable: true,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t// Storage mounts whole - do not walk `$models` as a namespace.\n\t\t\t\tif (\n\t\t\t\t\ttypeof used === \"object\" &&\n\t\t\t\t\tused !== null &&\n\t\t\t\t\t\"$models\" in used &&\n\t\t\t\t\ttypeof (used as { $adapter?: unknown }).$adapter === \"function\"\n\t\t\t\t) {\n\t\t\t\t\ttarget[name] = override !== undefined ? override : used;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!isFn(used)) {\n\t\t\t\t\tconst group: any = {};\n\t\t\t\t\tbindUsable(\n\t\t\t\t\t\tgroup,\n\t\t\t\t\t\tused as Record<string, unknown>,\n\t\t\t\t\t\tisFn(override) ? undefined : (override as any),\n\t\t\t\t\t);\n\t\t\t\t\ttarget[name] = group;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t// A `.with` override REPLACES the binding - a fn override still\n\t\t\t\t// joins this context, a plain function is called as given.\n\t\t\t\tif (override !== undefined) {\n\t\t\t\t\ttarget[name] = isFn(override)\n\t\t\t\t\t\t? (i?: unknown) => (override as any)(i, ctx)\n\t\t\t\t\t\t: override;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst usedArity = (used as { $arity?: number }).$arity;\n\t\t\t\ttarget[name] =\n\t\t\t\t\tusedArity === undefined\n\t\t\t\t\t\t? (i?: unknown) => (used as any)(i, ctx)\n\t\t\t\t\t\t: (...args: unknown[]) => {\n\t\t\t\t\t\t\t\tconst padded = args.slice(0, usedArity);\n\t\t\t\t\t\t\t\twhile (padded.length < usedArity) padded.push(undefined);\n\t\t\t\t\t\t\t\treturn (used as any)(...padded, ctx);\n\t\t\t\t\t\t\t};\n\t\t\t}\n\t\t};\n\t\tbindUsable(base, usable, withFns);\n\n\t\tconst missing = (name: string) => {\n\t\t\tconst value = readVar(cells, name);\n\t\t\treturn value === undefined || value === null;\n\t\t};\n\t\tconst checkRequires = () => {\n\t\t\tfor (const name of options.requires ?? []) {\n\t\t\t\tif (missing(name)) {\n\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t`${key}.requires.${name}`,\n\t\t\t\t\t\t`required var \"${name}\" is not set${parent === undefined ? \" - called without a parent context\" : \"\"}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\t// Interceptors replace the BODY. `provides` is only enforced when\n\t\t// the DECLARED body actually ran: an interceptor that returns\n\t\t// without `next()` visibly takes the contract over - that is a\n\t\t// veto, not a bug - while an author whose own body forgets to set\n\t\t// a promised var still fails loudly.\n\t\tlet bodyRan = false;\n\t\tconst declaredTracked = (c: any) => {\n\t\t\tbodyRan = true;\n\t\t\treturn declared(c);\n\t\t};\n\t\tconst body = chain.reduceRight<(c: any) => any>(\n\t\t\t(next, entry) => (c) => entry.handler(c, () => next(c)),\n\t\t\tdeclaredTracked,\n\t\t);\n\n\t\t// Exit contracts run after the body, whether or not it was async.\n\t\tconst finish = (result: unknown) => {\n\t\t\tif (outputValidation !== undefined) {\n\t\t\t\tvalidate(asType(outputValidation), result, `${key}.output`);\n\t\t\t}\n\t\t\tif (bodyRan) {\n\t\t\t\tfor (const name of options.provides ?? []) {\n\t\t\t\t\tif (missing(name)) {\n\t\t\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t\t\t`${key}.provides.${name}`,\n\t\t\t\t\t\t\t`declared to provide \"${name}\" but it was left unset`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t};\n\n\t\t// Errors crossing this frame: tagged errors and defects collect the\n\t\t// TRAIL (origin fn first, then every frame outward). Once a fn\n\t\t// declares `errors`, anything untagged escaping its body is a\n\t\t// DEFECT - wrapped with the cause kept - so a domain refusal and a\n\t\t// bug are never the same shape.\n\t\tconst decorate = (thrown: unknown): unknown => {\n\t\t\t// Redirects and other transport control must cross frames that\n\t\t\t// declare `errors` without becoming UnexpectedError.\n\t\t\tif (thrown instanceof ControlFlow) return thrown;\n\t\t\tif (thrown instanceof FnError || thrown instanceof UnexpectedError) {\n\t\t\t\tif (thrown.trail[thrown.trail.length - 1] !== key) {\n\t\t\t\t\tthrown.trail.push(key);\n\t\t\t\t}\n\t\t\t\treturn thrown;\n\t\t\t}\n\t\t\treturn errorTypes ? new UnexpectedError(thrown, key) : thrown;\n\t\t};\n\n\t\tconst run = () => {\n\t\t\tcheckRequires();\n\t\t\tlet result: unknown;\n\t\t\ttry {\n\t\t\t\tresult = body(ctx);\n\t\t\t} catch (thrown) {\n\t\t\t\tthrow decorate(thrown);\n\t\t\t}\n\t\t\t// A sync handler stays sync: only chain when something is thenable.\n\t\t\treturn isThenable(result)\n\t\t\t\t? result.then(finish, (thrown) => {\n\t\t\t\t\t\tthrow decorate(thrown);\n\t\t\t\t\t})\n\t\t\t\t: finish(result);\n\t\t};\n\n\t\treturn run();\n\t};\n\n\t/** `.try`: declared errors as a value, everything else still throws. */\n\tconst tryCall = (...callArgs: any[]) => {\n\t\tconst settle = (thrown: unknown) => {\n\t\t\tif (thrown instanceof FnError) {\n\t\t\t\treturn { ok: false as const, error: thrown };\n\t\t\t}\n\t\t\tthrow thrown;\n\t\t};\n\t\ttry {\n\t\t\tconst result = callable(...callArgs);\n\t\t\treturn isThenable(result)\n\t\t\t\t? result.then((value) => ({ ok: true as const, value }), settle)\n\t\t\t\t: { ok: true as const, value: result };\n\t\t} catch (thrown) {\n\t\t\treturn settle(thrown);\n\t\t}\n\t};\n\n\t/**\n\t * `.with`: a hand-built context. Keys naming one of this fn's `use`\n\t * fns become OVERRIDES (carried by the subtree via `WITH`); everything\n\t * else SEEDS a var in a fresh store. A parent given to the bound call\n\t * is forked - its cells are copied, so seeds and writes inside never\n\t * leak back into it.\n\t */\n\tconst withCall = (context: Record<string, unknown>) => {\n\t\tconst makeParent = (given: any) => {\n\t\t\tconst source: Cells = given?.[STORE] ?? {};\n\t\t\tconst cells: Cells = Object.fromEntries(\n\t\t\t\tObject.entries(source).map(([name, cell]) => [name, { ...cell }]),\n\t\t\t);\n\t\t\tconst seedFrame: Frame = {\n\t\t\t\tcells,\n\t\t\t\tkey: `${key}.with`,\n\t\t\t\tlockedBy: undefined,\n\t\t\t\tentries: [],\n\t\t\t};\n\t\t\tconst overrides: Record<string, unknown> = { ...given?.[WITH] };\n\t\t\t// Walk the given context against the usable tree: a fn member is\n\t\t\t// an OVERRIDE, a var member (top-level or inside a group) SEEDS\n\t\t\t// the var under its DECLARED name, a group recurses, and anything\n\t\t\t// unknown seeds a var by the given key.\n\t\t\tconst applyWith = (\n\t\t\t\tmap: Record<string, unknown> | undefined,\n\t\t\t\tentries: Record<string, unknown>,\n\t\t\t\ttarget: Record<string, unknown>,\n\t\t\t) => {\n\t\t\t\tfor (const [name, value] of Object.entries(entries)) {\n\t\t\t\t\tconst member = map?.[name];\n\t\t\t\t\tif (member === undefined) {\n\t\t\t\t\t\twriteVar(seedFrame, name, value);\n\t\t\t\t\t} else if (isVar(member)) {\n\t\t\t\t\t\twriteVar(seedFrame, (member as { name: string }).name, value);\n\t\t\t\t\t} else if (isFn(member) || typeof value !== \"object\" || !value) {\n\t\t\t\t\t\ttarget[name] = value;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst existing = target[name];\n\t\t\t\t\t\tconst sub =\n\t\t\t\t\t\t\texisting && typeof existing === \"object\"\n\t\t\t\t\t\t\t\t? (existing as Record<string, unknown>)\n\t\t\t\t\t\t\t\t: {};\n\t\t\t\t\t\ttarget[name] = sub;\n\t\t\t\t\t\tapplyWith(\n\t\t\t\t\t\t\tmember as Record<string, unknown>,\n\t\t\t\t\t\t\tvalue as Record<string, unknown>,\n\t\t\t\t\t\t\tsub,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t\tapplyWith(usable, context, overrides);\n\t\t\treturn {\n\t\t\t\t[STORE]: cells,\n\t\t\t\t[ACTIVE]: given?.[ACTIVE],\n\t\t\t\t[EXTS]: given?.[EXTS],\n\t\t\t\t[READONLY]: given?.[READONLY],\n\t\t\t\t[WITH]: Object.keys(overrides).length > 0 ? overrides : undefined,\n\t\t\t};\n\t\t};\n\t\tconst rewrite = (callArgs: any[]) => {\n\t\t\tif (tupleInput) {\n\t\t\t\tconst padded = callArgs.slice(0, tupleInput.length);\n\t\t\t\twhile (padded.length < tupleInput.length) padded.push(undefined);\n\t\t\t\treturn [...padded, makeParent(callArgs[tupleInput.length])];\n\t\t\t}\n\t\t\treturn [callArgs[0], makeParent(callArgs[1])];\n\t\t};\n\t\tconst bound = (...callArgs: any[]) => callable(...rewrite(callArgs));\n\t\tbound.try = (...callArgs: any[]) => tryCall(...rewrite(callArgs));\n\t\treturn bound;\n\t};\n\n\treturn Object.assign(callable, {\n\t\t$fn: true as const,\n\t\tkey,\n\t\tprovides: (options.provides ?? []) as readonly string[],\n\t\ttry: tryCall,\n\t\twith: withCall,\n\t\t// Positional arg count, so used-fn bindings know where ctx goes.\n\t\t...(tupleInput ? { $arity: tupleInput.length } : {}),\n\t\t// The declared contract, as written - introspectable by hosts that\n\t\t// render the fn to an authorizer or an authoring model.\n\t\t$schema: {\n\t\t\t...(options.input !== undefined ? { input: options.input } : {}),\n\t\t\t...(options.output !== undefined ? { output: options.output } : {}),\n\t\t\t...(declaredErrors ? { errors: declaredErrors } : {}),\n\t\t\t...(options.requires?.length\n\t\t\t\t? { requires: options.requires as readonly string[] }\n\t\t\t\t: {}),\n\t\t\t...(options.idempotent === true ? { idempotent: true } : {}),\n\t\t},\n\t});\n};\n\n/* --------------------------------- create --------------------------------- */\n\n/** Every target worth suggesting on a builder's `on`: the mounted fns'\n * keys (prefix-stripped, so they are valid RELATIVE targets), the scope's\n * var-write events by name, and the two wildcards. Arbitrary strings stay\n * legal - these only feed completion. */\ntype OnTargetSuggest<Base, BaseFns, Prefix extends string> =\n\t| FnTargetSuggest<BaseFns, Prefix>\n\t| `var.set.${keyof ScopeOf<[], Base> & string}`\n\t| \"var.set.*\"\n\t| `var.get.${keyof ScopeOf<[], Base> & string}`\n\t| \"var.get.*\"\n\t| \"*\";\n\ntype FnTargetSuggest<Fns, Prefix extends string> = {\n\t[K in keyof Fns]: Fns[K] extends FnDefination<\n\t\tany,\n\t\tany,\n\t\tinfer FK,\n\t\tany,\n\t\tany,\n\t\tany\n\t>\n\t\t? FK extends `${Prefix}${infer Rest}`\n\t\t\t? Rest\n\t\t\t: never\n\t\t: never;\n}[keyof Fns];\n\ntype VarNameOfT<T extends string> = T extends `var.${\"set\" | \"get\"}.${infer N}`\n\t? N extends `${string}*${string}`\n\t\t? string\n\t\t: N\n\t: string;\n\n/** The scope's value for a var-event target - `unknown` when inexact. */\ntype VarValueOfT<T extends string, Base> =\n\tVarNameOfT<T> extends keyof ScopeOf<[], Base>\n\t\t? ScopeOf<[], Base>[VarNameOfT<T>]\n\t\t: unknown;\n\n/** The fns among `Fns` whose key the (already prefixed) target hits. */\ntype MatchedFn<Fns, T extends string> = {\n\t[K in keyof Fns]: Fns[K] extends FnDefination<\n\t\tany,\n\t\tany,\n\t\tinfer FK,\n\t\tany,\n\t\tany,\n\t\tany\n\t>\n\t\t? TargetMatches<T, FK & string> extends true\n\t\t\t? Fns[K]\n\t\t\t: never\n\t\t: never;\n}[keyof Fns];\n\n/** The intercepted input: the matched fn's (a union under wildcards),\n * or an open record when the target names nothing the builder knows. */\ntype MatchedInput<F> = [F] extends [never]\n\t? Record<string, any>\n\t: F extends FnDefination<any, any, any, infer I, any, any>\n\t\t? InferInput<I>\n\t\t: never;\n\n/** What `next()` resolves to: the matched fn's own result. */\ntype MatchedResult<F> = [F] extends [never]\n\t? any\n\t: F extends FnDefination<any, infer R, any, any, any, any>\n\t\t? Awaited<R>\n\t\t: never;\n\n/** What a builder-scoped `on` handler sees: vars and `use` fns directly\n * on `c` from the builder, `input` from the TARGET fn when known. */\ntype OnContext<Base, BaseFns, F, Ext = unknown> = {\n\tinput: MatchedInput<F> & (unknown extends Ext ? unknown : InferInput<Ext>);\n\ttypes: typeof vTypes;\n\tfn: unknown;\n} & VarScope<ScopeOf<[], Base>, never> &\n\tUseApi<BaseFns>;\n\n/** `v.on`, scoped: string targets get the builder's key prefix; the\n * handler's `c` and `next()` are typed against the matched target fn. */\nexport interface InstanceOn<Base, BaseFns, Prefix extends string> {\n\t/** A fn REFERENCE targets its own key - never prefixed, fully typed\n\t * from the fn itself plus the builder's scope. */\n\t<F extends FnDefination<any, any, string, any, any, any>>(\n\t\ttarget: F,\n\t\thandler: (\n\t\t\tc: OnContext<Base, BaseFns, F>,\n\t\t\tnext: () => Promise<MatchedResult<F>>,\n\t\t) => any,\n\t): OnEntry<F[\"key\"]>;\n\t/** Var-write events: never prefixed (vars are global), and `value`\n\t * is typed from the builder's scope when the target is exact. */\n\t<\n\t\tT extends\n\t\t\t| `var.set.${keyof ScopeOf<[], Base> & string}`\n\t\t\t| \"var.set.*\"\n\t\t\t| `var.set.${string}`,\n\t>(\n\t\ttarget: T,\n\t\thandler: (\n\t\t\tc: VarSetContext<VarNameOfT<T>> & { value: VarValueOfT<T, Base> },\n\t\t\tnext: () => void,\n\t\t) => void,\n\t): OnEntry<T>;\n\t/** Var-read events: `next()` yields the stored value and the handler's\n\t * return becomes the read result - typed from the scope when exact. */\n\t<\n\t\tT extends\n\t\t\t| `var.get.${keyof ScopeOf<[], Base> & string}`\n\t\t\t| \"var.get.*\"\n\t\t\t| `var.get.${string}`,\n\t>(\n\t\ttarget: T,\n\t\thandler: (\n\t\t\tc: VarGetContext<VarNameOfT<T>>,\n\t\t\tnext: () => VarValueOfT<T, Base>,\n\t\t) => VarValueOfT<T, Base>,\n\t): OnEntry<T>;\n\t(\n\t\ttarget: RegExp,\n\t\thandler: (\n\t\t\tc: OnContext<Base, BaseFns, never>,\n\t\t\tnext: () => Promise<any>,\n\t\t) => any,\n\t): OnEntry<string>;\n\t<N extends OnTargetSuggest<Base, BaseFns, Prefix> | LiteralString>(\n\t\ttarget: N,\n\t\thandler: (\n\t\t\tc: OnContext<Base, BaseFns, MatchedFn<BaseFns, `${Prefix}${N}`>>,\n\t\t\tnext: () => Promise<MatchedResult<MatchedFn<BaseFns, `${Prefix}${N}`>>>,\n\t\t) => any,\n\t): OnEntry<`${Prefix}${N}`>;\n\t<const Ext>(\n\t\ttarget: RegExp,\n\t\textend: { input: Ext },\n\t\thandler: (\n\t\t\tc: OnContext<Base, BaseFns, never, Ext>,\n\t\t\tnext: () => Promise<any>,\n\t\t) => any,\n\t): OnEntry<string, Ext>;\n\t<N extends OnTargetSuggest<Base, BaseFns, Prefix> | LiteralString, const Ext>(\n\t\ttarget: N,\n\t\textend: { input: Ext },\n\t\thandler: (\n\t\t\tc: OnContext<Base, BaseFns, MatchedFn<BaseFns, `${Prefix}${N}`>, Ext>,\n\t\t\tnext: () => Promise<MatchedResult<MatchedFn<BaseFns, `${Prefix}${N}`>>>,\n\t\t) => any,\n\t): OnEntry<`${Prefix}${N}`, Ext>;\n}\n\nexport type Instance<\n\tBase,\n\tBaseFns,\n\tPL extends readonly Module[] = [],\n\tPrefix extends string = \"\",\n\tI = unknown,\n\tO = unknown,\n> = {\n\t/** Same as `v.fn`, with this builder's key prefix and options baked in. */\n\tfn: Fn<Base, BaseFns, PL, Prefix>;\n\t/**\n\t * A handler-less builder doubles as an input SCHEMA: used as `input`\n\t * (or an input field) it declares \"a FN from `input` to `output`\" -\n\t * the value crossing is the fn itself. Carries the declared schemas\n\t * for inference here and validation at runtime (see `isFnSchema`).\n\t */\n\treadonly $fnSchema: { input?: I; output?: O };\n\t/** Same as `v.on`, with the prefix on string targets and the handler\n\t * typed against the matched target fn. */\n\ton: InstanceOn<Base, BaseFns, Prefix>;\n\t/**\n\t * The context a handler on this builder receives - a TYPE carrier for\n\t * `typeof f.ctx` (helper signatures, plugin contracts). Every handler\n\t * context on this builder is assignable to it: `input` and `fn` are\n\t * loosened since they vary per fn. A real context only exists per\n\t * invocation, so this is `undefined` at runtime.\n\t */\n\treadonly ctx: Context<\n\t\tunknown,\n\t\tScopeOf<[], Base, PL>,\n\t\tnever,\n\t\tBaseFns,\n\t\tunknown\n\t>;\n};\n\n/**\n * The builder half of `v.fn`: no handler yet, so calls accumulate. Keys\n * CONCATENATE (\"auth\" then \".create\" -> \"auth.create\"), `use`/`requires`/\n * `provides` merge, other options child-wins - and the returned `.fn`\n * follows the same one rule recursively: a handler terminates, anything\n * else keeps building.\n */\nconst mergeOptions = (\n\tbase: Record<string, any>,\n\tchild: Record<string, any>,\n) => ({\n\t...base,\n\t...child,\n\tuse: [...(base.use ?? []), ...(child.use ?? [])],\n\trequires: [...(base.requires ?? []), ...(child.requires ?? [])],\n\tprovides: [...(base.provides ?? []), ...(child.provides ?? [])],\n\t// Error declarations accumulate tag-wise, child wins per tag. Only\n\t// materialized when declared somewhere - an empty `errors` would flip\n\t// the defect-wrapping rule on for every fn.\n\t...(base.errors || child.errors\n\t\t? { errors: { ...(base.errors ?? {}), ...(child.errors ?? {}) } }\n\t\t: {}),\n});\n\nconst builderFn = (baseKey: string, base: Record<string, any>) => {\n\tconst build = (...args: any[]) => {\n\t\tconst hasKey = typeof args[0] === \"string\";\n\t\tconst childKey: string = hasKey ? args[0] : \"\";\n\t\tconst rest = hasKey ? args.slice(1) : args;\n\t\tconst first = rest[0];\n\t\tconst handler = typeof first === \"function\" ? first : rest[1];\n\t\tconst childOptions = typeof first === \"function\" ? {} : (first ?? {});\n\t\tconst key = baseKey + childKey;\n\t\tconst options = mergeOptions(base, childOptions);\n\t\tif (typeof handler !== \"function\") {\n\t\t\treturn {\n\t\t\t\tfn: builderFn(key, options),\n\t\t\t\t// A handler-less builder doubles as an input schema: \"a fn\n\t\t\t\t// from `input` to `output`\" (see `isFnSchema`).\n\t\t\t\t$fnSchema: {\n\t\t\t\t\tinput: (options as OptionType<any, any, any, any, any>).input,\n\t\t\t\t\toutput: (options as OptionType<any, any, any, any, any>).output,\n\t\t\t\t},\n\t\t\t\ton: (target: any, a?: any, b?: any) =>\n\t\t\t\t\t(onImpl as any)(\n\t\t\t\t\t\t// var and scope events live in a global namespace - no prefix.\n\t\t\t\t\t\ttypeof target === \"string\" &&\n\t\t\t\t\t\t\t!target.startsWith(\"var.\") &&\n\t\t\t\t\t\t\t!target.startsWith(\"scope.\")\n\t\t\t\t\t\t\t? key + target\n\t\t\t\t\t\t\t: target,\n\t\t\t\t\t\ta,\n\t\t\t\t\t\tb,\n\t\t\t\t\t),\n\t\t\t};\n\t\t}\n\t\treturn defineFn(key || \"anonymous\", options, handler);\n\t};\n\t// The builder FN doubles as a schema itself: bare `v.fn` (never called)\n\t// declares \"any function\", `v.fn.type({ input, output })` a specific\n\t// signature, and a chained builder's `.fn` carries whatever input/output\n\t// it has accumulated - same contract as the handler-less builder object\n\t// (see `isFnSchema`).\n\treturn Object.assign(build, {\n\t\t$fnSchema: { input: base.input, output: base.output },\n\t\ttype: (\n\t\t\tsignature: {\n\t\t\t\tinput?: unknown;\n\t\t\t\toutput?: unknown;\n\t\t\t\toptional?: boolean;\n\t\t\t\tdefault?: unknown;\n\t\t\t} = {},\n\t\t) => ({\n\t\t\t$fnSchema: { input: signature.input, output: signature.output },\n\t\t\t...(signature.optional ? { optional: true as const } : {}),\n\t\t\t...(signature.default !== undefined\n\t\t\t\t? { default: signature.default }\n\t\t\t\t: {}),\n\t\t}),\n\t});\n};\n\nexport const fnImpl = builderFn(\"\", {});\n"],"mappings":";;;;;AAwrBA,MAAM,cAAc,UACnB,OAAO,OAAO,SAAS;AAExB,MAAM,QAAQ,OAAO,WAAW;AAChC,MAAM,SAAS,OAAO,gBAAgB;AACtC,MAAM,OAAO,OAAO,uBAAuB;AAC3C,MAAM,WAAW,OAAO,eAAe;AACvC,MAAM,OAAO,OAAO,gBAAgB;AAEpC,MAAM,YACL,KACA,SACA,aACI;CACJ,MAAM,UAAU,eAAgB,QAAQ,OAAO,CAAC,CAAc;CAM9D,MAAM,MAAyB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ACD,CAAC;AACF;AAEA,MAAa,SAAS,UAAU,IAAI,CAAC,CAAC"}
package/dist/index.cjs ADDED
@@ -0,0 +1,43 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_error = require("./error.cjs");
3
+ const require_schema = require("./schema.cjs");
4
+ const require_module = require("./module.cjs");
5
+ const require_var = require("./var.cjs");
6
+ const require_fn = require("./fn.cjs");
7
+ const require_storage = require("./storage.cjs");
8
+ //#region src/index.ts
9
+ const v = {
10
+ fn: require_fn.fnImpl,
11
+ var: require_var.makeVar,
12
+ record: ((name, options = {}) => require_var.makeVar(name, {
13
+ ...options,
14
+ accessor: true
15
+ })),
16
+ derive: require_var.deriveVar,
17
+ storage: require_storage.makeStorage,
18
+ on: require_module.on,
19
+ extend: require_module.extendVar,
20
+ ...require_schema.vTypes
21
+ };
22
+ //#endregion
23
+ exports.ControlFlow = require_error.ControlFlow;
24
+ exports.FnError = require_error.FnError;
25
+ exports.UnexpectedError = require_error.UnexpectedError;
26
+ exports.ValidationError = require_error.ValidationError;
27
+ exports.attrsOf = require_schema.attrsOf;
28
+ exports.collectFns = require_module.collectFns;
29
+ exports.collectUsable = require_module.collectUsable;
30
+ exports.conditionsOf = require_storage.conditionsOf;
31
+ exports.fieldsFromSchema = require_storage.fieldsFromSchema;
32
+ exports.isFn = require_module.isFn;
33
+ exports.isNamespace = require_module.isNamespace;
34
+ exports.isOn = require_module.isOn;
35
+ exports.isStorage = require_storage.isStorage;
36
+ exports.isVarExtension = require_module.isVarExtension;
37
+ exports.matchesWhere = require_storage.matchesWhere;
38
+ exports.memoryAdapter = require_storage.memoryAdapter;
39
+ exports.resolveModelFields = require_storage.resolveModelFields;
40
+ exports.v = v;
41
+ exports.withAttrs = require_schema.withAttrs;
42
+
43
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["fnImpl","makeVar","deriveVar","makeStorage","extendVar","vTypes"],"sources":["../src/index.ts"],"sourcesContent":["import { type Fn, fnImpl } from \"./fn\";\nimport { extendVar, on } from \"./module\";\n\nimport { type InferInput, vTypes } from \"./schema\";\nimport { makeStorage } from \"./storage\";\nimport type { LiteralString } from \"./types\";\nimport {\n\tderiveVar,\n\tmakeVar,\n\ttype NameOfVar,\n\ttype ValueOfVar,\n\ttype VarDefination,\n} from \"./var\";\n\ninterface V {\n\tfn: Fn;\n\tvar: <\n\t\tN extends LiteralString,\n\t\tS = undefined,\n\t\tD = undefined,\n\t\tconst M extends boolean | undefined = undefined,\n\t>(\n\t\tname: N,\n\t\toptions?: { default?: D; schema?: S; merge?: M },\n\t\t// A default the schema already covers (e.g. `{}` against an\n\t\t// all-optional shape) is absorbed; `default: null` still unions in.\n\t\t// `merge: true` - object contributions from `use` modules (same-name\n\t\t// defaults, same-key namespaces) shallow-merge onto the value;\n\t\t// writes accumulate the same way. Brand `$merge: true` so scope\n\t\t// types can fold those helpers onto the var.\n\t) => VarDefination<\n\t\tN,\n\t\t[S] extends [undefined]\n\t\t\t? D\n\t\t\t: InferInput<S> | ([D] extends [InferInput<S>] ? never : D),\n\t\tS\n\t> &\n\t\t(M extends true ? { $merge: true } : unknown);\n\t/** A var you accumulate into: `set()` merges instead of replacing. */\n\trecord: <N extends LiteralString, S = undefined>(\n\t\tname: N,\n\t\toptions?: { schema?: S },\n\t) => VarDefination<\n\t\tN,\n\t\t[S] extends [undefined] ? Record<string, unknown> : Partial<InferInput<S>>,\n\t\tS\n\t>;\n\t/**\n\t * A var computed from another. Reads run the getter against the current\n\t * source; `requires` on the SOURCE makes derived vars non-null too.\n\t */\n\tderive: <\n\t\tN extends LiteralString,\n\t\tSV extends VarDefination<any, any, any, any>,\n\t\tR,\n\t>(\n\t\tname: N,\n\t\tsource: SV,\n\t\tget: (value: NonNullable<ValueOfVar<SV>>) => R,\n\t) => VarDefination<\n\t\tN,\n\t\tR | Extract<ValueOfVar<SV>, null | undefined>,\n\t\tunknown,\n\t\tNameOfVar<SV>\n\t>;\n\t/**\n\t * MANY instances of a var, queryable: each named var becomes a\n\t * COLLECTION of rows shaped like its value - `db.user.create(row)`,\n\t * `db.user.findOne({ email })`, findMany/update/delete/count. The\n\t * adapter is the translation seam a real database implements;\n\t * `memoryAdapter()` is the built-in dummy.\n\t */\n\tstorage: typeof makeStorage;\n\ton: typeof on;\n\textend: typeof extendVar;\n\tstring: (typeof vTypes)[\"string\"];\n\tnumber: (typeof vTypes)[\"number\"];\n\tboolean: (typeof vTypes)[\"boolean\"];\n\tdate: (typeof vTypes)[\"date\"];\n\tobject: (typeof vTypes)[\"object\"];\n\tarray: (typeof vTypes)[\"array\"];\n\tunion: (typeof vTypes)[\"union\"];\n\tany: (typeof vTypes)[\"any\"];\n}\n\nexport const v: V = {\n\tfn: fnImpl as Fn,\n\tvar: makeVar as V[\"var\"],\n\trecord: ((name: string, options: any = {}) =>\n\t\tmakeVar(name, { ...options, accessor: true })) as V[\"record\"],\n\tderive: deriveVar as V[\"derive\"],\n\tstorage: makeStorage,\n\ton,\n\textend: extendVar,\n\t...vTypes,\n};\n\nexport {\n\tControlFlow,\n\tFnError,\n\ttype Issue,\n\tUnexpectedError,\n\tValidationError,\n} from \"./error\";\nexport type {\n\tContext,\n\tFn,\n\tFnDefination,\n\tFnErrors,\n\tInstance,\n\tOptionType,\n\tParentContext,\n\tUseApi,\n\tWidenedArgs,\n\tWithContext,\n\tWithSeed,\n} from \"./fn\";\nexport {\n\ttype ApplyOn,\n\ttype ApplyOns,\n\tcollectFns,\n\tcollectUsable,\n\ttype ExtendedArgs,\n\ttype InputVarExtra,\n\ttype InputVarExtraOut,\n\ttype Interceptor,\n\tisFn,\n\tisNamespace,\n\tisOn,\n\tisVarExtension,\n\ttype Module,\n\ttype ModuleFns,\n\ttype ModuleVars,\n\ttype OnDefaultContext,\n\ttype OnEntry,\n\ttype VarExtension,\n\ttype VarExtensionsFor,\n\ttype VarGetContext,\n\ttype VarSetContext,\n\ttype VarsFrom,\n} from \"./module\";\nexport {\n\ttype AttrBag,\n\tattrsOf,\n\ttype InferArgs,\n\ttype InferInput,\n\ttype InferOutput,\n\ttype InferType,\n\ttype TypeDefination,\n\twithAttrs,\n} from \"./schema\";\nexport type {\n\tResolvedVars,\n\tRowInScope,\n\tScopeOf,\n\tVarName,\n\tVarScope,\n} from \"./scope\";\nexport {\n\ttype Collection,\n\ttype Condition,\n\tconditionsOf,\n\ttype FieldMeta,\n\ttype FindManyOptions,\n\tfieldsFromSchema,\n\tisStorage,\n\ttype ModelConfig,\n\tmatchesWhere,\n\tmemoryAdapter,\n\tresolveModelFields,\n\ttype Storage,\n\ttype StorageAdapter,\n\ttype StorageApi,\n\ttype StorageHook,\n\ttype StorageHookContext,\n\ttype StorageModels,\n\ttype StorageOp,\n\ttype StorageTarget,\n\ttype Where,\n\ttype WhereOp,\n\ttype WhereOps,\n} from \"./storage\";\nexport type { LiteralString, Prettify } from \"./types\";\nexport type { VarCustomizer, VarDefination, VarMap } from \"./var\";\n"],"mappings":";;;;;;;;AAqFA,MAAa,IAAO;CACnB,IAAIA,WAAAA;CACJ,KAAKC,YAAAA;CACL,UAAU,MAAc,UAAe,CAAC,MACvCA,YAAAA,QAAQ,MAAM;EAAE,GAAG;EAAS,UAAU;CAAK,CAAC;CAC7C,QAAQC,YAAAA;CACR,SAASC,gBAAAA;CACT,IAAA,eAAA;CACA,QAAQC,eAAAA;CACR,GAAGC,eAAAA;AACJ"}
@@ -0,0 +1,50 @@
1
+ import { ControlFlow, FnError, Issue, UnexpectedError, ValidationError } from "./error.cjs";
2
+ import { LiteralString, Prettify } from "./types.cjs";
3
+ import { AttrBag, InferArgs, InferInput, InferOutput, InferType, TypeDefination, attrsOf, vTypes, withAttrs } from "./schema.cjs";
4
+ import { Collection, Condition, FieldMeta, FindManyOptions, ModelConfig, Storage, StorageAdapter, StorageApi, StorageHook, StorageHookContext, StorageModels, StorageOp, StorageTarget, Where, WhereOp, WhereOps, conditionsOf, fieldsFromSchema, isStorage, makeStorage, matchesWhere, memoryAdapter, resolveModelFields } from "./storage.cjs";
5
+ import { ResolvedVars, RowInScope, ScopeOf, VarName, VarScope } from "./scope.cjs";
6
+ import { ApplyOn, ApplyOns, ExtendedArgs, InputVarExtra, InputVarExtraOut, Interceptor, Module, ModuleFns, ModuleVars, OnDefaultContext, OnEntry, VarExtension, VarExtensionsFor, VarGetContext, VarSetContext, VarsFrom, collectFns, collectUsable, extendVar, isFn, isNamespace, isOn, isVarExtension, on } from "./module.cjs";
7
+ import { Context, Fn, FnDefination, FnErrors, Instance, OptionType, ParentContext, UseApi, WidenedArgs, WithContext, WithSeed } from "./fn.cjs";
8
+ import { NameOfVar, ValueOfVar, VarCustomizer, VarDefination, VarMap } from "./var.cjs";
9
+ //#region src/index.d.ts
10
+ interface V {
11
+ fn: Fn;
12
+ var: <N extends LiteralString, S = undefined, D = undefined, const M extends boolean | undefined = undefined>(name: N, options?: {
13
+ default?: D;
14
+ schema?: S;
15
+ merge?: M;
16
+ }) => VarDefination<N, [S] extends [undefined] ? D : InferInput<S> | ([D] extends [InferInput<S>] ? never : D), S> & (M extends true ? {
17
+ $merge: true;
18
+ } : unknown);
19
+ /** A var you accumulate into: `set()` merges instead of replacing. */
20
+ record: <N extends LiteralString, S = undefined>(name: N, options?: {
21
+ schema?: S;
22
+ }) => VarDefination<N, [S] extends [undefined] ? Record<string, unknown> : Partial<InferInput<S>>, S>;
23
+ /**
24
+ * A var computed from another. Reads run the getter against the current
25
+ * source; `requires` on the SOURCE makes derived vars non-null too.
26
+ */
27
+ derive: <N extends LiteralString, SV extends VarDefination<any, any, any, any>, R>(name: N, source: SV, get: (value: NonNullable<ValueOfVar<SV>>) => R) => VarDefination<N, R | Extract<ValueOfVar<SV>, null | undefined>, unknown, NameOfVar<SV>>;
28
+ /**
29
+ * MANY instances of a var, queryable: each named var becomes a
30
+ * COLLECTION of rows shaped like its value - `db.user.create(row)`,
31
+ * `db.user.findOne({ email })`, findMany/update/delete/count. The
32
+ * adapter is the translation seam a real database implements;
33
+ * `memoryAdapter()` is the built-in dummy.
34
+ */
35
+ storage: typeof makeStorage;
36
+ on: typeof on;
37
+ extend: typeof extendVar;
38
+ string: (typeof vTypes)["string"];
39
+ number: (typeof vTypes)["number"];
40
+ boolean: (typeof vTypes)["boolean"];
41
+ date: (typeof vTypes)["date"];
42
+ object: (typeof vTypes)["object"];
43
+ array: (typeof vTypes)["array"];
44
+ union: (typeof vTypes)["union"];
45
+ any: (typeof vTypes)["any"];
46
+ }
47
+ declare const v: V;
48
+ //#endregion
49
+ export { type ApplyOn, type ApplyOns, type AttrBag, type Collection, type Condition, type Context, ControlFlow, type ExtendedArgs, type FieldMeta, type FindManyOptions, type Fn, type FnDefination, FnError, type FnErrors, type InferArgs, type InferInput, type InferOutput, type InferType, type InputVarExtra, type InputVarExtraOut, type Instance, type Interceptor, type Issue, type LiteralString, type ModelConfig, type Module, type ModuleFns, type ModuleVars, type OnDefaultContext, type OnEntry, type OptionType, type ParentContext, type Prettify, type ResolvedVars, type RowInScope, type ScopeOf, type Storage, type StorageAdapter, type StorageApi, type StorageHook, type StorageHookContext, type StorageModels, type StorageOp, type StorageTarget, type TypeDefination, UnexpectedError, type UseApi, ValidationError, type VarCustomizer, type VarDefination, type VarExtension, type VarExtensionsFor, type VarGetContext, type VarMap, type VarName, type VarScope, type VarSetContext, type VarsFrom, type Where, type WhereOp, type WhereOps, type WidenedArgs, type WithContext, type WithSeed, attrsOf, collectFns, collectUsable, conditionsOf, fieldsFromSchema, isFn, isNamespace, isOn, isStorage, isVarExtension, matchesWhere, memoryAdapter, resolveModelFields, v, withAttrs };
50
+ //# sourceMappingURL=index.d.cts.map