mnemonica 1.4.8 → 1.5.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.
Files changed (41) hide show
  1. package/FOR_HUMANS.md +95 -31
  2. package/README.md +10 -9
  3. package/SKILL.md +4 -4
  4. package/build/api/hooks/hookTypes.d.ts +2 -0
  5. package/build/api/hooks/hookTypes.js +25 -0
  6. package/build/api/hooks/index.d.ts +2 -1
  7. package/build/api/hooks/index.js +6 -2
  8. package/build/api/hooks/registerHook.d.ts +1 -1
  9. package/build/api/hooks/registerHook.js +4 -15
  10. package/build/api/hooks/unregisterHook.d.ts +2 -0
  11. package/build/api/hooks/unregisterHook.js +18 -0
  12. package/build/api/index.d.ts +4 -3
  13. package/build/api/index.js +2 -1
  14. package/build/api/types/compileNewModificatorFunctionBody.d.ts +4 -2
  15. package/build/api/types/compileNewModificatorFunctionBody.js +16 -7
  16. package/build/api/types/index.d.ts +2 -2
  17. package/build/api/types/index.js +21 -18
  18. package/build/api/utils/index.d.ts +1 -2
  19. package/build/api/utils/index.js +37 -13
  20. package/build/descriptors/types/index.js +19 -12
  21. package/build/index.d.ts +25 -17
  22. package/build/index.js +35 -50
  23. package/build/types/index.d.ts +242 -225
  24. package/build/types/index.js +1 -1
  25. package/docs/UTILS.md +4 -5
  26. package/docs/async-constructors.md +32 -13
  27. package/docs/hott-correspondence.md +1 -1
  28. package/docs/typed-lookup.md +31 -37
  29. package/module/index.js +2 -0
  30. package/package.json +2 -2
  31. package/src/api/hooks/hookTypes.ts +37 -0
  32. package/src/api/hooks/index.ts +8 -1
  33. package/src/api/hooks/registerHook.ts +6 -19
  34. package/src/api/hooks/unregisterHook.ts +36 -0
  35. package/src/api/index.ts +2 -0
  36. package/src/api/types/compileNewModificatorFunctionBody.ts +79 -18
  37. package/src/api/types/index.ts +64 -54
  38. package/src/api/utils/index.ts +5 -51
  39. package/src/descriptors/types/index.ts +31 -22
  40. package/src/index.ts +271 -161
  41. package/src/types/index.ts +812 -590
@@ -4,11 +4,10 @@
4
4
  import type { TypeRegistry } from '../index';
5
5
  import type { constants } from '../constants';
6
6
 
7
- // Props type for getProps/setProps
8
- export type PropsType = Record<string, unknown>;
9
-
10
7
  // Core type definitions for mnemonica
11
8
 
9
+ // --- handler and callable shapes -------------------------------------------
10
+
12
11
  // Base constructor function type - can be a class constructor or a function.
13
12
  // Args defaults to unknown[] so IDEF<T> is backwards compatible;
14
13
  // supply Args to get typed constructor params: IDEF<MyType, [string, number]>
@@ -16,13 +15,22 @@ export type IDEF<T, Args extends unknown[] = unknown[]> =
16
15
  | { new(...args: Args): T }
17
16
  | { (this: T, ...args: Args): void };
18
17
 
19
- // Construction-function parameter for the .call/.apply/.bind family:
20
- // anything IDEF accepts PLUS any required-argument constructor shape.
18
+ // An async handler: a function returning a Promise, or a declared constructor
19
+ // of one. TypeScript refuses to write such a class (TS2409), so the second
20
+ // comes from a declaration.
21
+ export type AsyncIDEF<T, Args extends unknown[] = unknown[]> =
22
+ | { (this: T, ...args: Args): PromiseLike<unknown> }
23
+ | { new (...args: Args): PromiseLike<T> };
24
+
25
+ // Construction-function parameter for the .call/.apply/.bind family: a
26
+ // constructor, never the plain function a user gives define(). TypeName is
27
+ // not required here: a decorated class is a mnemonica constructor at
28
+ // runtime, and its binding keeps the type of the class as written.
21
29
  // The never[] rest accepts every parameter list by contravariance (every
22
30
  // parameter type is a supertype of never) while keeping the constructed
23
31
  // result typed; unknown[] would reject required params under
24
32
  // strictFunctionTypes.
25
- export type CtorParameter<T, Args extends unknown[] = never[]> = IDEF<T, Args> | { new (...args: Args): T };
33
+ export type CtorParameter<T, Args extends unknown[] = never[]> = { new (...args: Args): T };
26
34
 
27
35
  // Lazy getter type - a zero-arg factory that returns a constructor.
28
36
  // Used by the explicit .lazy() API.
@@ -55,41 +63,7 @@ export type DefineNewableOrCallable = DefineNewable | DefineCallable;
55
63
  // that reference must stay assignable here.
56
64
  export interface InstanceConstructor extends NewableFunction {}
57
65
 
58
- // A hook callback as seen by a REGISTERING surface that only forwards it
59
- // (HookableConstructor's registerHook, the WithHookRegister member check):
60
- // it consumes whatever opts the caller's typed hook carries and returns
61
- // unknown. never[] parameters keep every hook shape assignable by
62
- // contravariance, including generic typedHook<HT> instantiations (a
63
- // parameter typed as the plain `hook` interface would reject those).
64
- export interface AnyHookCallback extends CallableFunction {
65
- (...args: never[]): unknown;
66
- }
67
-
68
- // A utility method as exposed on the `utils` collection — the
69
- // index-signature fallback for utilities beyond the declared set. Plain
70
- // callables: any argument list, unknown result.
71
- export interface UtilFunction extends CallableFunction {
72
- (...args: never[]): unknown;
73
- }
74
-
75
- // The minimal source shape the free lookup() resolves against: any value
76
- // carrying a lookup method with the untyped fallback signature
77
- // (a TypesCollection, a type constructor, or the mnemonica module object).
78
- export interface LookupSource {
79
- lookup(path: string): TypeClass | undefined;
80
- }
81
-
82
- // The modification-error sink handed through the creator object: consumes
83
- // the construction error, produces nothing (the construction aborts).
84
- export interface ThrowModificationError extends CallableFunction {
85
- (error: Error): void;
86
- }
87
-
88
- // The bound fork invoker that instance.fork() returns: consumes fork
89
- // arguments, produces a fresh instance of the forked type.
90
- export interface ForkInvoker<T extends object> extends CallableFunction {
91
- (this: object | void, ...forkArgs: unknown[]): T;
92
- }
66
+ // --- errors ----------------------------------------------------------------
93
67
 
94
68
  // Error message types - all error messages are strings
95
69
  export type ErrorMessageKey =
@@ -111,21 +85,6 @@ export type ErrorMessageKey =
111
85
  // Error messages object type
112
86
  export type ErrorMessages = Record<ErrorMessageKey, string>;
113
87
 
114
- // Hook callback as STORED and invoked by invokeHook — its parameter is the
115
- // DELIVERED payload (deliveredHookOpts: HookInvocation.build()'s output).
116
- // The registration surface (registerHook) types callbacks per hookType via
117
- // typedHook instead.
118
- export interface hook extends CallableFunction {
119
- (opts: deliveredHookOpts): unknown;
120
- }
121
-
122
- // Flow checker callback registered via registerFlowChecker: invoked with
123
- // the hook invocation record after each hook run; its return value is
124
- // collected into the invocation results but otherwise unused.
125
- export interface FlowChecker extends CallableFunction {
126
- (opts: object): unknown;
127
- }
128
-
129
88
  // An error class made by constructError(name, message) — the lib.es5
130
89
  // ErrorConstructor idiom, `new`-only (a class cannot be called without it).
131
90
  // Each class carries one fixed message (constants ErrorMessages); `addition`
@@ -136,9 +95,6 @@ export interface MnemonicaErrorConstructor extends NewableFunction {
136
95
  readonly prototype: MnemonicaError;
137
96
  }
138
97
 
139
- // Errors types map - indexable record of error constructors
140
- export type ErrorsTypesMap = Record<string, MnemonicaErrorConstructor>;
141
-
142
98
  // Mnemonica-processed error. It carries no custom properties of its own:
143
99
  // the error data lives in the external props storage (WeakMap) — read it
144
100
  // via getProps(error), typed as ErrorProps below.
@@ -179,6 +135,8 @@ export interface ErrorProps {
179
135
  */
180
136
  export type CreationError<T extends object> = ( T & Error ) | Error;
181
137
 
138
+ // --- constructor shapes ----------------------------------------------------
139
+
182
140
  /**
183
141
  * Internal Type Constructor.
184
142
  * "Type" here is used in the Computer Science sense — an interface/contract
@@ -225,72 +183,55 @@ export interface TypeConstructorBase {
225
183
  */
226
184
  export type AnyConstructor = new (...args: never[]) => unknown;
227
185
 
228
- /**
229
- * Instance type produced by a TypeRegistry constructor.
230
- */
231
- export type InstanceOfTypeRegistry<K extends keyof TypeRegistry> =
232
- TypeRegistry[K] extends new (...args: never[]) => infer R ? R : never;
233
-
186
+ // Constructor type for decorate function.
187
+ // Parameters are `never[]` for the same reason as AnyConstructor: under
188
+ // strictFunctionTypes an `unknown[]` constraint rejects classes with precise
189
+ // constructor parameters, so `@decorate()` could not be applied to them.
190
+ export type Constructor<T = object> = new (...args: never[]) => T;
234
191
 
235
- /**
236
- * Extract only the literal string keys of a type, filtering out generic
237
- * index signatures. This lets us iterate over augmented TypeRegistry keys
238
- * without picking up the `[key: string]` signature.
239
- */
240
- export type LiteralKeysOf<T> = keyof T extends infer K
241
- ? K extends string
242
- ? string extends K ? never : K
243
- : never
244
- : never;
192
+ // Name of a constructor as a string literal type.
193
+ export type ConstructorName<T extends Constructor<object>> =
194
+ T extends { name: infer N } ? N extends string ? N : string : string;
245
195
 
246
- /**
247
- * Given a dotted TypeRegistry key, extract the parent path.
248
- * `ParentPath<'A.B.C'>` → `'A.B'`.
249
- */
250
- export type ParentPath<K extends string> =
251
- K extends `${infer P}.${string}` ? P : never;
196
+ // --- hooks -----------------------------------------------------------------
252
197
 
253
- /**
254
- * Given a dotted TypeRegistry key, return the union of all ancestor prefixes.
255
- * `AllParentPrefixes<'A.B.C'>` → `'A' | 'A.B'`.
256
- */
257
- export type AllParentPrefixes<K extends string> =
258
- K extends `${infer P}.${string}` ? P | AllParentPrefixes<P> : never;
198
+ // A hook callback as seen by a REGISTERING surface that only forwards it
199
+ // (HookableConstructor's registerHook, the WithHookRegister member check):
200
+ // it consumes whatever opts the caller's typed hook carries and returns
201
+ // unknown. never[] parameters keep every hook shape assignable by
202
+ // contravariance, including generic typedHook<HT> instantiations (a
203
+ // parameter typed as the plain `hook` interface would reject those).
204
+ export interface AnyHookCallback extends CallableFunction {
205
+ (...args: never[]): unknown;
206
+ }
259
207
 
260
- /**
261
- * Given a parent path, return the union of TypeRegistry keys that are direct
262
- * or indirect children of that path.
263
- */
264
- export type ChildKeysOf<P extends string> = {
265
- [K in keyof TypeRegistry]: K extends `${P}.${string}` ? K : never
266
- }[keyof TypeRegistry];
208
+ // The modification-error sink handed through the creator object: consumes
209
+ // the construction error, produces nothing (the construction aborts).
210
+ export interface ThrowModificationError extends CallableFunction {
211
+ (error: Error): void;
212
+ }
267
213
 
268
- /**
269
- * Given an instance type, find the TypeRegistry key(s) whose constructor
270
- * returns that instance type. This inverts the registry at the type level
271
- * so utilities like `parent()` can derive an instance's path from its
272
- * type alone.
273
- */
274
- export type PathOfInstance<T extends object> = {
275
- [K in LiteralKeysOf<TypeRegistry>]: TypeRegistry[K] extends new (...args: never[]) => infer R
276
- ? T extends R ? K : never
277
- : never
278
- }[LiteralKeysOf<TypeRegistry>];
214
+ // Hook callback as STORED and invoked by invokeHook — its parameter is the
215
+ // DELIVERED payload (deliveredHookOpts: HookInvocation.build()'s output).
216
+ // The registration surface (registerHook) types callbacks per hookType via
217
+ // typedHook instead.
218
+ export interface hook extends CallableFunction {
219
+ (opts: deliveredHookOpts): unknown;
220
+ }
279
221
 
280
- /**
281
- * Given an instance type, return the union of TypeRegistry paths that are
282
- * valid parent lookups for that instance. Root types produce `never` because
283
- * they have no parent path.
284
- */
285
- export type ParentPathOfInstance<T extends object> = {
286
- [K in LiteralKeysOf<TypeRegistry>]: TypeRegistry[K] extends new (...args: never[]) => infer R
287
- ? T extends R ? AllParentPrefixes<K> : never
288
- : never
289
- }[LiteralKeysOf<TypeRegistry>];
222
+ // Flow checker callback registered via registerFlowChecker: invoked with
223
+ // the hook invocation record after each hook run; its return value is
224
+ // collected into the invocation results but otherwise unused.
225
+ export interface FlowChecker extends CallableFunction {
226
+ (opts: object): unknown;
227
+ }
290
228
 
291
229
  // Hook types
292
230
  export type hooksTypes = 'preCreation' | 'postCreation' | 'creationError';
293
231
 
232
+ // What the registering methods take: a hook type or its short name
233
+ export type hookName = hooksTypes | 'pre' | 'post' | 'error';
234
+
294
235
  // Hook options passed to hook callbacks
295
236
  // P = parent / existent instance (proto)
296
237
  // T = child / inherited instance (type being created)
@@ -335,8 +276,8 @@ export type deliveredHookOpts<P = object, T = P> = {
335
276
  // preCreation fires BEFORE the created instance exists, so its opts carry
336
277
  // no inheritedInstance and no throwModificationError — accessing them is a
337
278
  // compile error.
338
- export type typedHookOpts<HT extends hooksTypes, P extends object, T extends object> =
339
- HT extends 'preCreation'
279
+ export type typedHookOpts<HT extends hookName, P extends object, T extends object> =
280
+ HT extends 'preCreation' | 'pre'
340
281
  ? {
341
282
  TypeName: string;
342
283
  type: TypeDef;
@@ -360,23 +301,49 @@ export type typedHookOpts<HT extends hooksTypes, P extends object, T extends obj
360
301
  // a concrete instance is the callback's business (instanceof lookup('User'))
361
302
  // — but the preCreation/post payload split holds at both levels.
362
303
  export interface typedHook<
363
- HT extends hooksTypes,
304
+ HT extends hookName,
364
305
  P extends object = object,
365
306
  T extends object = object
366
307
  > extends CallableFunction {
367
308
  (opts: typedHookOpts<HT, P, T>): unknown;
368
309
  }
369
310
 
311
+ // The registering methods of a type (P = its parent instance, T = its own) or
312
+ // a collection (both stay `object`). on / off are registerHook / unregisterHook
313
+ // under short names. unregisterHook takes any callback: it only looks up the
314
+ // exact reference, and returns whether it was registered.
315
+ export interface HookMethods<P extends object = object, T extends object = object> {
316
+ registerHook<HT extends hookName>(hookType: HT, cb: typedHook<HT, P, T>): void;
317
+ unregisterHook(hookType: hookName, cb: AnyHookCallback): boolean;
318
+ on<HT extends hookName>(hookType: HT, cb: typedHook<HT, P, T>): void;
319
+ off(hookType: hookName, cb: AnyHookCallback): boolean;
320
+ }
321
+
370
322
  // Constructor surface the free registerHook() accepts: any constructor of T
371
323
  // instances with a registerHook method. Deliberately NOT DecoratedClass<T> —
372
324
  // inference through DecoratedClass's InstanceType<T> conditional picks a wrong
373
325
  // T candidate, and inferring from a generic registerHook member resets T to
374
326
  // its default; here T is inferred from Constructor<T>'s return position and
375
327
  // the precise cb typing comes from the free function's own cb parameter.
376
- export type HookableConstructor<T extends object> = Constructor<T> & {
377
- registerHook(hookType: hooksTypes, cb: AnyHookCallback): void;
328
+ // An async constructor's `new` gives Promise<T>: hooks see the resolved T.
329
+ export type HookableConstructor<T extends object> = Constructor<T | PromiseLike<T>> & {
330
+ registerHook(hookType: hookName, cb: AnyHookCallback): void;
378
331
  };
379
332
 
333
+ // Shared interface for objects that support hooks (TypeDef and CollectionDef).
334
+ // Collection-level registration: the payload split by hookType holds
335
+ // (preCreation has no inheritedInstance/throwModificationError; post
336
+ // hooks carry both, required) but P/T stay `object` — a collection
337
+ // mixes every registered type, so narrowing to a concrete instance
338
+ // happens in the callback.
339
+ export interface Hookable extends HookMethods {
340
+ hooks: Record<string, Set<hook>>;
341
+ invokeHook(hookType: hooksTypes, opts: hooksOpts): Set<unknown>;
342
+ registerFlowChecker(cb: FlowChecker): void;
343
+ }
344
+
345
+ // --- config and runtime internals ------------------------------------------
346
+
380
347
  // Callback passed into ModificationConstructor to attach internal props to the prototype
381
348
  export interface AddPropsCallback extends CallableFunction {
382
349
  (proto: object): void;
@@ -430,8 +397,23 @@ export type constructorOptions = {
430
397
  // with true a non-object resolution DROPS the chain and that value is
431
398
  // the result ("unchain on await")
432
399
  unchain?: boolean,
433
- // Force class mode (auto-detected by default)
434
- asClass?: boolean,
400
+ };
401
+
402
+ // What define(), lazy() and decorate() take in the config place: the options,
403
+ // strictChain alone, or ModificationConstructor alone.
404
+ export type DefineConfig = constructorOptions | boolean | ModificationConstructorFactory;
405
+
406
+ // The same where a function means something else: the handler of define(),
407
+ // the parent type of decorate().
408
+ export type NoHandlerConfig = constructorOptions | boolean;
409
+
410
+ // The config a type keeps for itself: the given options merged over the
411
+ // collection's, plus what define() detected from the handler. asClass is
412
+ // never an option: a class body or a plain function is a property of the
413
+ // handler, detected by isClass at every define and, for a lazy type, at
414
+ // every construction.
415
+ export type TypeConfig = constructorOptions & {
416
+ asClass: boolean,
435
417
  };
436
418
 
437
419
  // Subtypes map - represents the subtypes property
@@ -444,7 +426,7 @@ export type TypeDef = {
444
426
  isSubType: boolean;
445
427
  subtypes: SubtypesMap;
446
428
  collection: CollectionDef;
447
- config: constructorOptions;
429
+ config: TypeConfig;
448
430
  parentType?: TypeDef;
449
431
  constructHandler: MnemonicaConstructorFactory;
450
432
  title: string;
@@ -463,7 +445,6 @@ export interface CollectionLookup extends CallableFunction {
463
445
  (this: unknown, TypeNestedPath: string): TypeClass | undefined;
464
446
  }
465
447
 
466
- // Collection definition
467
448
  // A collection's config, stored under SymbolConfig. Every collection carries
468
449
  // a name by construction: 'defaultTypes' for the default one, the given or
469
450
  // auto-numbered name for custom ones (createTypesCollection).
@@ -472,6 +453,7 @@ export type CollectionConfig = {
472
453
  [key: string]: unknown;
473
454
  };
474
455
 
456
+ // Collection definition
475
457
  // the config key is SymbolConfig's own unique symbol type; a mapped type
476
458
  // over it keeps this module type-only (no runtime import of constants)
477
459
  export type CollectionDef = Hookable & {
@@ -483,82 +465,239 @@ export type CollectionDef = Hookable & {
483
465
  [K in typeof constants.SymbolConfig]: CollectionConfig;
484
466
  };
485
467
 
486
- // Type lookup function type: may have augmentation by Tactica re-definition
487
- // Global registry shape used as the default for TypeLookup. It combines any
488
- // augmented TypeRegistry entries with a broad string index signature so the
489
- // generic TypeLookup constraint is satisfied.
490
- // Internal on purpose: if you are here from a TS2883 error ("cannot be
491
- // named without a reference to 'GlobalRegistry'"), the consumer exports free
492
- // define() results without a TypeRegistry merge — see docs/typed-lookup.md,
493
- // "Declaration emit on TypeScript 6". Do not re-export this.
494
- export type GlobalRegistry = TypeRegistry & Record<string, TypeConstructorBase>;
468
+ // Specification for chained subtype creation with .then()
469
+ export interface ThenSpec {
470
+ subtype: object;
471
+ args: unknown[];
472
+ name?: string;
473
+ }
495
474
 
496
- // Extract the instance type returned by a mnemonica-compatible constructor.
497
- // Async entries construct a Promise, but inheritance, hooks, and subtype
498
- // lookup all operate on the resolved instance. Falls back to `object` so
499
- // generic helpers that require an object constraint do not fail when the
500
- // constructor shape is not yet narrowed.
501
- export type ExtractConstructorInstance<C> =
502
- C extends { new (...args: never[]): infer I }
503
- ? Awaited<I> extends object ? Awaited<I> : object
504
- : object;
475
+ // Context object passed through the InstanceCreator pipeline
476
+ export interface InstanceCreatorContext {
477
+ type: TypeDef;
478
+ TypeName: string;
479
+ existentInstance: object;
480
+ args: unknown[];
481
+ ModificationConstructor: ModificationConstructor;
482
+ ModificatorType: MnemonicaConstructor;
483
+ InstanceModificator: MnemonicaConstructor;
484
+ inheritedInstance: object | Promise<object>;
485
+ config: TypeConfig;
486
+ proto: object;
487
+ __proto_proto__?: object;
488
+ stack?: string[];
489
+ // a lazy type's gather outcome, snapshotted by runSetup before the cell
490
+ // is reset (see lazyDefinition.ts): failed is the explicit flag (a
491
+ // callback may throw undefined), lazyError the thrown value itself —
492
+ // passed through to throwModificationError exactly like a
493
+ // constructor-body throw
494
+ lazyFailed?: boolean;
495
+ lazyError?: unknown;
496
+ // set by throwModificationError once the post hooks have fired for this
497
+ // construction; postProcessing reads it to avoid a second firing when a
498
+ // creationError hook suppressed the throw
499
+ postHooksFired?: boolean;
505
500
 
506
- // Preserve the entry's construction kind when replacing its instance shape:
507
- // an async entry stays Promise-returning on both new and call signatures.
508
- export type ConstructResult<C, NewInstance extends object> =
509
- C extends { new (...args: never[]): PromiseLike<unknown> }
510
- ? Promise<NewInstance>
511
- : NewInstance;
501
+ getExistentAsyncStack(existentInstance: object): unknown;
502
+ postProcessing(continuationOf?: TypeDef): void;
503
+ makeAwaiter(type: TypeDef, then?: ThenSpec): Promise<object>;
504
+ addThen(then: ThenSpec): void;
505
+ invokePreHooks(): void;
506
+ invokePostHooks(): { type: Set<unknown>; collection: Set<unknown> };
507
+ throwModificationError(error: MnemonicaError): void;
508
+ }
512
509
 
513
- // Map dotted registry paths that extend `${Path}.${Child}` into child
514
- // constructor properties on the parent instance. This lets typed lookups
515
- // return a constructor whose instances carry their subtypes, e.g.
516
- // `new (App.lookup('User'))(...).Admin`.
517
- export type SubTypeConstructors<
518
- Registry extends object,
519
- Path extends string
520
- > = {
521
- [K in keyof Registry as K extends `${Path}.${infer Child}` ? Child : never]:
522
- LookedUpConstructor<Registry, K & string, true>;
510
+ // Internal instance properties (non-enumerable)
511
+ // These are always present on instances but accessed via getProps/setProps
512
+ export type InstanceInternalProps = {
513
+ __proto_proto__: object;
514
+ __args__: unknown[];
515
+ __collection__: CollectionDef;
516
+ __subtypes__: Map<string, object>;
517
+ __type__: TypeDef;
518
+ __parent__: object;
519
+ __stack__?: string;
520
+ __creator__: InstanceCreatorContext;
521
+ __timestamp__: number;
523
522
  };
524
523
 
525
- // Reconstruct a constructor with a new instance type while preserving every
526
- // non-`prototype`, non-`lookup` property (`define`, hooks, etc.). `lookup` is
527
- // replaced separately so it can be scoped to the constructor's own type path.
528
- // The match requires only the construct signature: tactica-emitted and
529
- // hand-written registry entries are bare newables (no call signature, no
530
- // declared `prototype`), and demanding those members collapses the lookup
531
- // result to `never` for precisely-typed registries. A call signature is
532
- // re-added only when the source constructor carries one.
533
- export type ReplaceConstructorInstance<
534
- C,
535
- NewInstance extends object,
536
- CallConstructs extends boolean = false
537
- > = C extends {
538
- new (...args: infer A): unknown;
539
- }
540
- ? {
541
- new (...args: A): ConstructResult<C, NewInstance>;
542
- readonly prototype: NewInstance & {
543
- readonly constructor: ReplaceConstructorInstance<C, NewInstance, CallConstructs>;
544
- };
545
- } & (C extends { (...args: infer A2): unknown }
546
- ? CallConstructs extends true
547
- // SubTypeProxy-backed member: the call form constructs the child
548
- // from the parent instance (the chain-tip form new R().A()), so
549
- // no `this` demand — detached bare calls construct too.
550
- ? { (...args: A2): ConstructResult<C, NewInstance> }
551
- // Raw looked-up constructor: the `this` guard honestly models
552
- // .call(childInstance, args); a bare call here is the decorator
553
- // path at runtime, not construction.
554
- : { (this: NewInstance, ...args: A2): ConstructResult<C, NewInstance> }
555
- : unknown)
556
- & Omit<C, 'prototype' | 'lookup'>
557
- : never;
524
+ // Combined Props type for internal use inside ./src
525
+ // Instance properties for __self__ reference
526
+ // This merges internal props with the __self__ reference and an open index
527
+ export type Props =InstanceInternalProps & {
528
+ __self__: InstanceInternalProps;
529
+ [key: string]: unknown;
530
+ };
558
531
 
559
- // Instance type produced by a typed lookup: the constructor's own instance
560
- // shape plus child-constructor properties for every registered subtype.
561
- // Kept as a named alias so hover tooltips show the base shape first instead of
532
+ // Mnemonica constructor — the constructor function returned by constructHandler()
533
+ // Has SymbolConstructorName attached and is both newable and callable
534
+ export interface MnemonicaConstructor extends NewableFunction {
535
+ new (...args: unknown[]): object;
536
+ [key: symbol]: unknown;
537
+ }
538
+
539
+ // Type descriptor instance — internal shape of TypeDescriptor objects
540
+ export interface TypeDescriptorDefine extends CallableFunction {
541
+ (
542
+ TypeOrTypeName: string | DefineNewableOrCallable,
543
+ constructHandlerOrConfig?: DefineNewableOrCallable | object | boolean,
544
+ config?: object | boolean
545
+ ): TypeClass;
546
+ }
547
+
548
+ export interface TypeDescriptorLazy extends CallableFunction {
549
+ (
550
+ TypeName: string,
551
+ getter: LazyDef<object>,
552
+ config?: object | boolean
553
+ ): TypeClass;
554
+ }
555
+
556
+ export interface TypeDescriptorLookup extends CallableFunction {
557
+ (TypeNestedPath: string): TypeClass | undefined;
558
+ }
559
+
560
+ export type TypeDescriptorInstance = {
561
+ define: TypeDescriptorDefine;
562
+ lazy: TypeDescriptorLazy;
563
+ decorate: (config?: DefineConfig) => <U extends Constructor<object>>(cstr: U) => DecoratedClass<U>;
564
+ lookup: TypeDescriptorLookup;
565
+ subtypes: Map<string, object>;
566
+ TypeName: string;
567
+ collection: CollectionDef;
568
+ };
569
+
570
+ // --- registry and lookup ---------------------------------------------------
571
+
572
+ // The minimal source shape the free lookup() resolves against: any value
573
+ // carrying a lookup method with the untyped fallback signature
574
+ // (a TypesCollection, a type constructor, or the mnemonica module object).
575
+ export interface LookupSource {
576
+ lookup(path: string): TypeClass | undefined;
577
+ }
578
+
579
+ /**
580
+ * Instance type produced by a TypeRegistry constructor.
581
+ */
582
+ export type InstanceOfTypeRegistry<K extends keyof TypeRegistry> =
583
+ TypeRegistry[K] extends new (...args: never[]) => infer R ? R : never;
584
+
585
+ /**
586
+ * Extract only the literal string keys of a type, filtering out generic
587
+ * index signatures. This lets us iterate over augmented TypeRegistry keys
588
+ * without picking up the `[key: string]` signature.
589
+ */
590
+ export type LiteralKeysOf<T> = keyof T extends infer K
591
+ ? K extends string
592
+ ? string extends K ? never : K
593
+ : never
594
+ : never;
595
+
596
+ /**
597
+ * Given a dotted TypeRegistry key, return the union of all ancestor prefixes.
598
+ * `AllParentPrefixes<'A.B.C'>` → `'A' | 'A.B'`.
599
+ */
600
+ export type AllParentPrefixes<K extends string> =
601
+ K extends `${infer P}.${string}` ? P | AllParentPrefixes<P> : never;
602
+
603
+ /**
604
+ * Given an instance type, return the union of TypeRegistry paths that are
605
+ * valid parent lookups for that instance: the registry is inverted at the
606
+ * type level (the key(s) whose constructor returns that instance type), so
607
+ * utilities like `parent()` derive an instance's parent paths from its type
608
+ * alone. Root types produce `never` because they have no parent path.
609
+ */
610
+ export type ParentPathOfInstance<T extends object> = {
611
+ [K in LiteralKeysOf<TypeRegistry>]: TypeRegistry[K] extends new (...args: never[]) => infer R
612
+ ? T extends R ? AllParentPrefixes<K> : never
613
+ : never
614
+ }[LiteralKeysOf<TypeRegistry>];
615
+
616
+ // Global registry shape used as the default for TypeLookup. It combines any
617
+ // augmented TypeRegistry entries with a broad string index signature so the
618
+ // generic TypeLookup constraint is satisfied.
619
+ // Internal on purpose: if you are here from a TS2883 error ("cannot be
620
+ // named without a reference to 'GlobalRegistry'"), the consumer exports free
621
+ // define() results without a TypeRegistry merge — see docs/typed-lookup.md,
622
+ // "Declaration emit on TypeScript 6". Do not re-export this.
623
+ export type GlobalRegistry = TypeRegistry & Record<string, TypeConstructorBase>;
624
+
625
+ // Extract the instance type returned by a mnemonica-compatible constructor.
626
+ // Async entries construct a Promise, but inheritance, hooks, and subtype
627
+ // lookup all operate on the resolved instance. Falls back to `object` so
628
+ // generic helpers that require an object constraint do not fail when the
629
+ // constructor shape is not yet narrowed.
630
+ export type ExtractConstructorInstance<C> =
631
+ C extends { new (...args: never[]): infer I }
632
+ ? Awaited<I> extends object ? Awaited<I> : object
633
+ : object;
634
+
635
+ // Preserve the entry's construction kind when replacing its instance shape:
636
+ // an async entry stays Promise-returning on both new and call signatures.
637
+ export type ConstructResult<C, NewInstance extends object> =
638
+ C extends { new (...args: never[]): PromiseLike<unknown> }
639
+ ? Promise<NewInstance>
640
+ : NewInstance;
641
+
642
+ // Map dotted registry paths that extend `${Path}.${Child}` into child
643
+ // constructor properties on the parent instance. This lets typed lookups
644
+ // return a constructor whose instances carry their subtypes, e.g.
645
+ // `new (App.lookup('User'))(...).Admin`.
646
+ export type SubTypeConstructors<
647
+ Registry extends object,
648
+ Path extends string
649
+ > = {
650
+ [K in keyof Registry as K extends `${Path}.${infer Child}` ? Child : never]:
651
+ LookedUpConstructor<Registry, K & string, true>;
652
+ };
653
+
654
+ // Reconstruct a constructor with a new instance type while preserving every
655
+ // non-`prototype`, non-`lookup` property (`define`, hooks, etc.). `lookup` is
656
+ // replaced separately so it can be scoped to the constructor's own type path.
657
+ // The match requires only the construct signature: tactica-emitted and
658
+ // hand-written registry entries are bare newables (no call signature, no
659
+ // declared `prototype`), and demanding those members collapses the lookup
660
+ // result to `never` for precisely-typed registries. A call signature is
661
+ // re-added only when the source constructor carries one
662
+ // (ReplacedCallSignature).
663
+ export type ReplaceConstructorInstance<
664
+ C,
665
+ NewInstance extends object,
666
+ CallConstructs extends boolean = false
667
+ > = C extends {
668
+ new (...args: infer A): unknown;
669
+ }
670
+ ? {
671
+ new (...args: A): ConstructResult<C, NewInstance>;
672
+ readonly prototype: NewInstance & {
673
+ readonly constructor: ReplaceConstructorInstance<C, NewInstance, CallConstructs>;
674
+ };
675
+ }
676
+ & ReplacedCallSignature<C, NewInstance, CallConstructs>
677
+ & Omit<C, 'prototype' | 'lookup'>
678
+ : never;
679
+
680
+ // The call signature ReplaceConstructorInstance keeps: none (unknown) when
681
+ // the source constructor has no call signature, otherwise one of two forms.
682
+ export type ReplacedCallSignature<
683
+ C,
684
+ NewInstance extends object,
685
+ CallConstructs extends boolean
686
+ > = C extends { (...args: infer A): unknown }
687
+ ? CallConstructs extends true
688
+ // SubTypeProxy-backed member: the call form constructs the child
689
+ // from the parent instance (the chain-tip form new R().A()), so
690
+ // no `this` demand — detached bare calls construct too.
691
+ ? { (...args: A): ConstructResult<C, NewInstance> }
692
+ // Raw looked-up constructor: the `this` guard honestly models
693
+ // .call(childInstance, args); a bare call here is the decorator
694
+ // path at runtime, not construction.
695
+ : { (this: NewInstance, ...args: A): ConstructResult<C, NewInstance> }
696
+ : unknown;
697
+
698
+ // Instance type produced by a typed lookup: the constructor's own instance
699
+ // shape plus child-constructor properties for every registered subtype.
700
+ // Kept as a named alias so hover tooltips show the base shape first instead of
562
701
  // expanding the whole registry.
563
702
  export type WithSubTypes<
564
703
  Instance extends object,
@@ -633,12 +772,12 @@ export type LookedUpConstructor<
633
772
  export type WithHookRegister<C> = C extends { registerHook: AnyHookCallback }
634
773
  ? C
635
774
  : C extends { new (...args: never[]): infer R }
636
- ? R extends object
637
- ? C & { registerHook<HT extends hooksTypes>(hookType: HT, cb: typedHook<HT, object, R>): void }
775
+ ? Awaited<R> extends infer A extends object
776
+ ? C & HookMethods<object, A>
638
777
  : C
639
778
  : C extends { (...args: never[]): infer R }
640
779
  ? R extends object
641
- ? C & { registerHook<HT extends hooksTypes>(hookType: HT, cb: typedHook<HT, object, R>): void }
780
+ ? C & HookMethods<object, R>
642
781
  : C
643
782
  : C;
644
783
 
@@ -660,6 +799,7 @@ export type LookupResult<
660
799
  ? LookedUpConstructor<Registry, Path>
661
800
  : never;
662
801
 
802
+ // Type lookup function type: may have augmentation by Tactica re-definition
663
803
  export interface TypeLookup<T extends object = GlobalRegistry> extends CallableFunction {
664
804
  <const K extends keyof T & string>(this: unknown, TypeNestedPath: K): LookedUpConstructor<T, K>;
665
805
  (this: unknown, TypeNestedPath: string): TypeClass | undefined;
@@ -681,7 +821,8 @@ export type RegistryOf<T> =
681
821
  infer Registry,
682
822
  string,
683
823
  object,
684
- never[]
824
+ never[],
825
+ object
685
826
  > ? Registry
686
827
  : T extends TypesCollection<infer Registry, object, string> ? Registry
687
828
  : T extends MnemonicaModule<infer Registry> ? Registry
@@ -698,13 +839,6 @@ export type RelativeKeys<
698
839
  ? K extends `${Path}.${infer Child}` ? Child : never
699
840
  : never);
700
841
 
701
- // Full registry key that corresponds to a relative key `K` under `Path`.
702
- export type FullKey<
703
- Registry extends object,
704
- Path extends string,
705
- K extends string
706
- > = Path extends '' ? K : Extract<keyof Registry & string, `${Path}.${K}`>;
707
-
708
842
  // Lookup function type for constructors and registry holders that know their
709
843
  // own dotted type path. Root holders use `Path = ''` and behave like the global
710
844
  // `TypeLookup`; child constructors use their own path for relative lookups.
@@ -724,275 +858,51 @@ export type NestedTypeLookup<
724
858
  (this: unknown, TypeNestedPath: string): TypeClass | undefined;
725
859
  };
726
860
 
727
- // Specification for chained subtype creation with .then()
728
- export interface ThenSpec {
729
- subtype: object;
730
- args: unknown[];
731
- name?: string;
732
- }
861
+ // --- builder holders and collections ---------------------------------------
733
862
 
734
- // Context object passed through the InstanceCreator pipeline
735
- export interface InstanceCreatorContext {
736
- type: TypeDef;
737
- TypeName: string;
738
- existentInstance: object;
739
- args: unknown[];
740
- ModificationConstructor: ModificationConstructor;
741
- ModificatorType: MnemonicaConstructor;
742
- InstanceModificator: MnemonicaConstructor;
743
- inheritedInstance: object | Promise<object>;
744
- config: constructorOptions;
745
- proto: object;
746
- __proto_proto__?: object;
747
- stack?: string[];
748
- // a lazy type's gather outcome, snapshotted by runSetup before the cell
749
- // is reset (see lazyDefinition.ts): failed is the explicit flag (a
750
- // callback may throw undefined), lazyError the thrown value itself —
751
- // passed through to throwModificationError exactly like a
752
- // constructor-body throw
753
- lazyFailed?: boolean;
754
- lazyError?: unknown;
755
- // set by throwModificationError once the post hooks have fired for this
756
- // construction; postProcessing reads it to avoid a second firing when a
757
- // creationError hook suppressed the throw
758
- postHooksFired?: boolean;
863
+ // The registry VALUE as public vocabulary: what a builder chain stores per
864
+ // defined path and what typed lookups read back. Interface (not alias) so
865
+ // consumer declaration emit names it instead of expanding the intersection.
866
+ // It preserves the dotted `Path` so that `.define()` on a looked-up constructor
867
+ // computes the correct child path, but it omits the full `GlobalRegistry`
868
+ // generic to keep hover tooltips readable.
869
+ // `Parent` is the instance type of the type's parent (object for root types),
870
+ // threaded so looked-up constructors type their registerHook callbacks'
871
+ // existentInstance.
872
+ export interface RegistryEntry<
873
+ F extends object,
874
+ Path extends string = '',
875
+ Parent extends object = object,
876
+ Args extends unknown[] = unknown[]
877
+ >
878
+ // typed hook registration — preserved through ReplaceConstructorInstance's
879
+ // member preservation, so lookup() results of builder-typed registries
880
+ // get registerHook with inferred opts
881
+ extends _Internal_TC_<F, Args>, RegistryHolderBase<{}, F, Path>, HookMethods<Parent, F> {}
759
882
 
760
- getExistentAsyncStack(existentInstance: object): unknown;
761
- postProcessing(continuationOf?: TypeDef): void;
762
- makeAwaiter(type: TypeDef, then?: ThenSpec): Promise<object>;
763
- addThen(then: ThenSpec): void;
764
- invokePreHooks(): void;
765
- invokePostHooks(): { type: Set<unknown>; collection: Set<unknown> };
766
- throwModificationError(error: MnemonicaError): void;
883
+ // Async registry VALUE: the same public vocabulary as RegistryEntry, with
884
+ // construction returning the Promise that the runtime always produces for an
885
+ // async handler. The resolved F remains the instance used by hooks and
886
+ // subtypes; only construction is deferred.
887
+ export interface AsyncRegistryEntry<
888
+ F extends object,
889
+ Path extends string = '',
890
+ Parent extends object = object,
891
+ Args extends unknown[] = unknown[]
892
+ > extends RegistryHolderBase<{}, F, Path>, HookMethods<Parent, F> {
893
+ new (...args: Args): Promise<F>;
894
+ (this: F, ...args: Args): Promise<F>;
895
+ readonly prototype: F & {
896
+ readonly constructor: AsyncRegistryEntry<F, Path, Parent, Args>;
897
+ };
767
898
  }
768
899
 
769
- /**
770
- * Proto merge type - combines parent and child types without property conflicts.
771
- *
772
- * When a subtype is defined from a parent instance, we want the child properties
773
- * to take precedence. `Exclude<keyof P, keyof T>` removes overlapping keys from P,
774
- * so `Pick<P, ...>` only brings in parent properties that don't clash with child.
775
- *
776
- * Result: child T gets all its own props, plus parent's non-overlapping props.
777
- */
778
- // When the parent contributes no properties, collapse to the child type so
779
- // hover tooltips stay readable.
780
- export type Proto<P extends object, T extends object> =
781
- [Exclude<keyof P, keyof T>] extends [never]
782
- ? T
783
- : T & Pick<P, Exclude<keyof P, keyof T>>;
784
-
785
-
786
- // export type ProtoFlat<
787
- // P extends object,
788
- // T extends object,
789
- // F extends Proto<P, T> = Proto<P, T>
790
- // > = { [key in keyof F]: F[key]} ;
791
-
792
- export type ProtoFlat<
793
- P extends object,
794
- T extends object,
795
- L extends Exclude<keyof P, keyof T> = Exclude<keyof P, keyof T>,
796
- > = {
797
- [key in keyof T]: T[key];
798
- } & {
799
- [key in L]: P[key];
800
- };
801
-
802
- // Mnemonica instance method keys. These are filtered out of extracted/merged
803
- // field-only views because they belong to the prototype, not to the user's
804
- // enumerable data properties.
805
- export type MnemonicaInstanceMethodKeys =
806
- 'extract' | 'pick' | 'parent' | 'clone' | 'fork' | 'exception' | 'sibling';
807
-
808
- export type Flatten<F> = { [key in keyof F]: F[key] }
809
-
810
- // Extracted<T>: the shape returned by utils.extract(instance).
811
- // It contains the enumerable string-keyed user properties of the instance,
812
- // omitting MnemonicaInstance methods (extract, pick, parent, clone, fork,
813
- // exception, sibling). Optionality is preserved from the source type.
814
- // The `& {}` trick forces TypeScript to expand the alias in hover tooltips
815
- // so it renders as a plain object literal instead of "Extracted<{...}>".
816
- export type Extracted<T extends object> = {
817
- [K in keyof T as K extends string ? (K extends MnemonicaInstanceMethodKeys ? never : K) : never]: T[K];
818
- } & {};
819
-
820
- // Parsed<T>: the shape returned by utils.parse(instance).
821
- // It is a one-level snapshot of the instance's prototype chain.
822
- // `props` contains the instance's enumerable user properties;
823
- // `joint` contains enumerable properties copied from the immediate prototype;
824
- // `parent` is the parent INSTANCE — the same object utils.parent(instance)
825
- // returns; null for no parent. Not recursively parsed — walking the whole
826
- // lineage level by level is what utils.deepParse does — this function stays
827
- // the one-level primitive.
828
- // The three "no parent" readings, stated once:
829
- // parent == null — no parent at all (covers both below);
830
- // parent === null — the end of a REAL chain (a root instance);
831
- // parent === undefined — nothing was given (utils.parse(null)).
832
- export type Parsed<T extends object> = {
833
- name: string;
834
- props: Extracted<T>;
835
- self: T;
836
- proto: object;
837
- joint: Record<string, unknown>;
838
- parent: object | null;
839
- };
840
-
841
- // EmptyParsed: the shape utils.parse(null) returns — the one non-object
842
- // input parse accepts. "Nothing was given": every field is its empty value,
843
- // and parent is undefined (see the readings above).
844
- export interface EmptyParsed {
845
- name: undefined;
846
- props: {};
847
- self: null;
848
- proto: undefined;
849
- joint: {};
850
- parent: undefined;
851
- }
852
-
853
- // --- lineage (the lethe cross-language export) -----------------------------
854
-
855
- // A JSON-safe value in the lethe lineage graph: instances export as $ref,
856
- // non-JSON values as tagged placeholders — never an error.
857
- export type LineageValue =
858
- | null
859
- | boolean
860
- | string
861
- | number
862
- | LineageValue[]
863
- | { $ref: string }
864
- | { '$mnemonica': 'unsupported'; kind: string }
865
- | { [ key: string ]: LineageValue };
866
-
867
- // Where a level's type was DECLARED — not just its name (names collide
868
- // across levels and collections).
869
- export interface LineageTypeRef {
870
- collection: string;
871
- path: string;
872
- }
873
-
874
- export interface LineageNode {
875
- type: LineageTypeRef;
876
- // the fields this level set itself — shadowed values stay with their
877
- // writer
878
- own: { [ key: string ]: LineageValue };
879
- // the parent's id, null at the root
880
- parent: string | null;
881
- // construction args — present only when lineage() gets { args: true }
882
- args?: LineageValue;
883
- // opt-in metadata (e.g. __timestamp__) — present only when
884
- // lineage() gets { props: [...] }
885
- props?: { [ key: string ]: LineageValue };
886
- }
887
-
888
- // The lethe lineage graph: version "1", heads in argument order, every
889
- // reachable instance deduplicated at any depth.
890
- export interface LineageGraph {
891
- version: '1';
892
- heads: string[];
893
- nodes: { [ id: string ]: LineageNode };
894
- }
895
-
896
- export interface LineageOptions {
897
- /** include construction args as node.args */
898
- args?: boolean;
899
- /** opt-in getProps keys exported as node.props (e.g. [ '__timestamp__' ]) */
900
- props?: string[];
901
- }
902
-
903
- // Sibling type accessor
904
- export interface SiblingAccessor {
905
- (SiblingTypeName: string): TypeClass | undefined;
906
- [key: string]: TypeClass | undefined;
907
- }
908
-
909
- // Mnemonica instance methods interface (opt-in).
910
- // These methods used to be auto-injected onto every instance. They are now
911
- // available only when a type explicitly adds them to its prototype.
912
- // Users can still use this interface to type their own root-level helpers.
913
- export interface MnemonicaInstance<T extends object = object> {
914
- extract(): Extracted<T>;
915
- pick<K extends keyof T>(...keys: (K | K[])[]): { [P in K]: T[P] } & {};
916
- pick(...keys: string[]): Record<string, unknown>;
917
- parent(): object | undefined;
918
- parent<K extends ParentPathOfInstance<this> & string>(
919
- constructorLookupPath: K
920
- ): InstanceOfTypeRegistry<K> | undefined;
921
- parent(constructorLookupPath: string): object | undefined;
922
- readonly clone: this;
923
- fork(...forkArgs: unknown[]): this;
924
- exception(error: Error, ...args: unknown[]): Error;
925
- readonly sibling: SiblingAccessor;
926
- }
927
-
928
- // Instance properties for __self__ reference
929
- // This merges internal props with the instance methods
930
- // Internal instance properties (non-enumerable)
931
- // These are always present on instances but accessed via getProps/setProps
932
- export type InstanceInternalProps = {
933
- __proto_proto__: object;
934
- __args__: unknown[];
935
- __collection__: CollectionDef;
936
- __subtypes__: Map<string, object>;
937
- __type__: TypeDef;
938
- __parent__: object;
939
- __stack__?: string;
940
- __creator__: InstanceCreatorContext;
941
- __timestamp__: number;
942
- };
943
-
944
- // Combined Props type for internal use inside ./src
945
- export type Props = InstanceInternalProps & {
946
- __self__: InstanceInternalProps;
947
- [key: string]: unknown;
948
- };
949
-
950
- // Combined instance type: plain object with the user's fields only.
951
- // Instance methods (extract, pick, fork, etc.) are no longer auto-injected.
952
- // The inline mapped type is used instead of the Flatten alias so that hover
953
- // tooltips show the actual field object literal first, not "Flatten<{...}>".
954
- export type InstanceResult<
955
- N extends object,
956
- > = { [K in keyof N]: N[K] };
957
-
958
- // The registry VALUE as public vocabulary: what a builder chain stores per
959
- // defined path and what typed lookups read back. Interface (not alias) so
960
- // consumer declaration emit names it instead of expanding the intersection.
961
- // It preserves the dotted `Path` so that `.define()` on a looked-up constructor
962
- // computes the correct child path, but it omits the full `GlobalRegistry`
963
- // generic to keep hover tooltips readable.
964
- // `Parent` is the instance type of the type's parent (object for root types),
965
- // threaded so looked-up constructors type their registerHook callbacks'
966
- // existentInstance.
967
- export interface RegistryEntry<
968
- F extends object,
969
- Path extends string = '',
970
- Parent extends object = object,
971
- Args extends unknown[] = unknown[]
972
- > extends _Internal_TC_<F, Args>, RegistryHolderBase<{}, F, Path> {
973
- // typed hook registration — preserved through ReplaceConstructorInstance's
974
- // member preservation, so lookup() results of builder-typed registries
975
- // get registerHook with inferred opts
976
- registerHook<HT extends hooksTypes>(hookType: HT, cb: typedHook<HT, Parent, F>): void;
977
- }
978
-
979
- // Async registry VALUE: the same public vocabulary as RegistryEntry, with
980
- // construction returning the Promise that the runtime always produces for an
981
- // async handler. The resolved F remains the instance used by hooks and
982
- // subtypes; only construction is deferred.
983
- export interface AsyncRegistryEntry<
984
- F extends object,
985
- Path extends string = '',
986
- Parent extends object = object,
987
- Args extends unknown[] = unknown[]
988
- > extends RegistryHolderBase<{}, F, Path> {
989
- new (...args: Args): Promise<F>;
990
- (this: F, ...args: Args): Promise<F>;
991
- readonly prototype: F & {
992
- readonly constructor: AsyncRegistryEntry<F, Path, Parent, Args>;
993
- };
994
- registerHook<HT extends hooksTypes>(hookType: HT, cb: typedHook<HT, Parent, F>): void;
995
- }
900
+ // The dotted path of a type named `Name` defined on a holder at `Path`:
901
+ // the bare name on a root holder (`Path = ''`), `${Path}.${Name}` below it.
902
+ // The default of every define()/lazy() overload's ChildPath; resolved at the
903
+ // call site, so consumers see the literal path, never this name.
904
+ export type ChildPathOf<Path extends string, Name extends string> =
905
+ Path extends '' ? Name : `${Path}.${Name}`;
996
906
 
997
907
  // Registry holder base - provides the accumulating .define() method.
998
908
  // `Parent` tracks the instance type of the last defined constructor, so chained
@@ -1003,49 +913,157 @@ export interface RegistryHolderBase<
1003
913
  Parent extends object = object,
1004
914
  Path extends string = ''
1005
915
  > {
1006
- // Legacy overload: define(constructHandler, config?)
1007
- define<SubType extends object>(
916
+ // define() has three forms, the same on every level, and the config is
917
+ // always the last argument:
918
+ // define(constructHandler, config?) TypeName is its own name
919
+ // define(TypeName, constructHandler, config?)
920
+ // define(TypeName, config?) no handler
921
+ //
922
+ // In the first form TypeScript sees the handler's name only as `string`,
923
+ // so nothing is added to the registry: Path is never, and so is the path
924
+ // of every type defined on the result.
925
+ //
926
+ // The order inside a form: a `=> never` handler (one that only throws) goes
927
+ // before the async one, whose Promise it would match, and so would an `any`
928
+ // handler; the async one goes before IDEF, whose callable void result
929
+ // otherwise accepts async functions and erases their Promise.
930
+ define<
931
+ N extends object,
932
+ Args extends unknown[] = unknown[],
933
+ F extends Proto<Parent, N> = Proto<Parent, N>
934
+ >(
935
+ this: RegistryHolderBase<T, Parent, Path>,
936
+ constructHandler: (this: N, ...args: Args) => never,
937
+ config?: DefineConfig
938
+ ): IDefinitorInstance<
939
+ F,
940
+ InstanceResult<F>,
941
+ T,
942
+ never,
943
+ Parent,
944
+ Args
945
+ >;
946
+ define<
947
+ N extends object,
948
+ Args extends unknown[] = unknown[],
949
+ F extends Proto<Parent, N> = Proto<Parent, N>
950
+ >(
951
+ this: RegistryHolderBase<T, Parent, Path>,
952
+ constructHandler: AsyncIDEF<N, Args>,
953
+ config?: DefineConfig
954
+ ): IDefinitorInstance<
955
+ F,
956
+ InstanceResult<F>,
957
+ T,
958
+ never,
959
+ Parent,
960
+ Args,
961
+ Promise<InstanceResult<F>>
962
+ >;
963
+ define<
964
+ N extends object,
965
+ Args extends unknown[] = unknown[],
966
+ F extends Proto<Parent, N> = Proto<Parent, N>
967
+ >(
968
+ this: RegistryHolderBase<T, Parent, Path>,
969
+ constructHandler: IDEF<N, Args>,
970
+ config?: DefineConfig
971
+ ): IDefinitorInstance<
972
+ F,
973
+ InstanceResult<F>,
974
+ T,
975
+ never,
976
+ Parent,
977
+ Args
978
+ >;
979
+ // the instance type given explicitly: define<Shape>(constructHandler)
980
+ define<
981
+ N extends object,
982
+ F extends Proto<Parent, N> = Proto<Parent, N>
983
+ >(
1008
984
  this: RegistryHolderBase<T, Parent, Path>,
1009
- TypeOrTypeName: DefineNewableOrCallable,
1010
- constructHandlerOrConfig?: IDEF<SubType> | object | boolean | DefineNewableOrCallable,
1011
- configOrUndefined?: constructorOptions | DefineNewableOrCallable | boolean
1012
- ): IDefinitorInstance<SubType>;
1013
-
1014
- // Async modern overload: a Promise-returning callable handler stores an
1015
- // async entry. It must precede the IDEF overload, whose callable void
1016
- // result otherwise accepts async functions and erases their Promise.
985
+ constructHandler: DefineNewableOrCallable,
986
+ config?: DefineConfig
987
+ ): IDefinitorInstance<
988
+ F,
989
+ InstanceResult<F>,
990
+ T,
991
+ never,
992
+ Parent
993
+ >;
994
+
995
+ // Named overloads: define(TypeName, constructHandler, config?). An async
996
+ // handler stores an async entry.
1017
997
  define<
1018
998
  const Name extends string,
1019
999
  N extends object,
1020
1000
  Args extends unknown[] = unknown[],
1021
1001
  F extends Proto<Parent, N> = Proto<Parent, N>,
1022
- ChildPath extends string = Path extends '' ? Name : `${Path}.${Name}`
1002
+ ChildPath extends string = ChildPathOf<Path, Name>
1023
1003
  >(
1024
1004
  this: RegistryHolderBase<T, Parent, Path>,
1025
1005
  TypeName: Name,
1026
- constructHandler: (this: N, ...args: Args) => PromiseLike<unknown>,
1027
- config?: constructorOptions
1006
+ constructHandler: (this: N, ...args: Args) => never,
1007
+ config?: DefineConfig
1008
+ ): IDefinitorInstance<
1009
+ F,
1010
+ InstanceResult<F>,
1011
+ T & Record<ChildPath, RegistryEntry<F, ChildPath, Parent, Args>>,
1012
+ ChildPath,
1013
+ Parent,
1014
+ Args
1015
+ >;
1016
+ define<
1017
+ const Name extends string,
1018
+ N extends object,
1019
+ Args extends unknown[] = unknown[],
1020
+ F extends Proto<Parent, N> = Proto<Parent, N>,
1021
+ ChildPath extends string = ChildPathOf<Path, Name>
1022
+ >(
1023
+ this: RegistryHolderBase<T, Parent, Path>,
1024
+ TypeName: Name,
1025
+ constructHandler: AsyncIDEF<N, Args>,
1026
+ config?: DefineConfig
1028
1027
  ): IDefinitorInstance<
1029
1028
  F,
1030
1029
  InstanceResult<F>,
1031
1030
  T & Record<ChildPath, AsyncRegistryEntry<F, ChildPath, Parent, Args>>,
1032
1031
  ChildPath,
1033
1032
  Parent,
1033
+ Args,
1034
+ Promise<InstanceResult<F>>
1035
+ >;
1036
+ define<
1037
+ const Name extends string,
1038
+ N extends object,
1039
+ Args extends unknown[] = unknown[],
1040
+ F extends Proto<Parent, N> = Proto<Parent, N>,
1041
+ ChildPath extends string = ChildPathOf<Path, Name>
1042
+ >(
1043
+ this: RegistryHolderBase<T, Parent, Path>,
1044
+ TypeName: Name,
1045
+ constructHandler: IDEF<N, Args> | undefined,
1046
+ config?: DefineConfig
1047
+ ): IDefinitorInstance<
1048
+ F,
1049
+ InstanceResult<F>,
1050
+ T & Record<ChildPath, RegistryEntry<F, ChildPath, Parent, Args>>,
1051
+ ChildPath,
1052
+ Parent,
1034
1053
  Args
1035
1054
  >;
1036
1055
 
1037
- // Modern overload: define(TypeName, constructHandler, config?)
1056
+ // Named overload without a handler: define(TypeName, config?)
1038
1057
  define<
1039
1058
  const Name extends string,
1040
1059
  N extends object,
1041
1060
  Args extends unknown[] = unknown[],
1042
1061
  F extends Proto<Parent, N> = Proto<Parent, N>,
1043
- ChildPath extends string = Path extends '' ? Name : `${Path}.${Name}`
1062
+ ChildPath extends string = ChildPathOf<Path, Name>
1044
1063
  >(
1045
1064
  this: RegistryHolderBase<T, Parent, Path>,
1046
1065
  TypeName: Name,
1047
- constructHandler?: IDEF<N, Args>,
1048
- config?: constructorOptions
1066
+ config?: NoHandlerConfig
1049
1067
  ): IDefinitorInstance<
1050
1068
  F,
1051
1069
  InstanceResult<F>,
@@ -1055,27 +1073,48 @@ export interface RegistryHolderBase<
1055
1073
  Args
1056
1074
  >;
1057
1075
 
1058
- // Async lazy getter: the callback itself stays synchronous, but the
1059
- // constructor it returns may produce a Promise on every construction.
1076
+ // Lazy getters, in the same order. The callback itself stays synchronous,
1077
+ // but the constructor it returns may produce a Promise on every
1078
+ // construction (the async form).
1060
1079
  lazy<
1061
1080
  const Name extends string,
1062
1081
  N extends object,
1063
1082
  Args extends unknown[],
1064
1083
  F extends Proto<Parent, N> = Proto<Parent, N>,
1065
- ChildPath extends string = Path extends '' ? Name : `${Path}.${Name}`
1084
+ ChildPath extends string = ChildPathOf<Path, Name>
1066
1085
  >(
1067
1086
  this: RegistryHolderBase<T, Parent, Path>,
1068
1087
  TypeName: Name,
1069
- getter: () => (this: N, ...args: Args) => PromiseLike<unknown>,
1070
- config?: constructorOptions
1088
+ getter: () => (this: N, ...args: Args) => never,
1089
+ config?: DefineConfig
1071
1090
  ): IDefinitorInstance<
1072
1091
  F,
1073
1092
  InstanceResult<F>,
1074
- T & Record<ChildPath, AsyncRegistryEntry<F, ChildPath, Parent, Args>>,
1093
+ T & Record<ChildPath, RegistryEntry<F, ChildPath, Parent, Args>>,
1075
1094
  ChildPath,
1076
1095
  Parent,
1077
1096
  Args
1078
1097
  >;
1098
+ lazy<
1099
+ const Name extends string,
1100
+ N extends object,
1101
+ Args extends unknown[],
1102
+ F extends Proto<Parent, N> = Proto<Parent, N>,
1103
+ ChildPath extends string = ChildPathOf<Path, Name>
1104
+ >(
1105
+ this: RegistryHolderBase<T, Parent, Path>,
1106
+ TypeName: Name,
1107
+ getter: () => AsyncIDEF<N, Args>,
1108
+ config?: DefineConfig
1109
+ ): IDefinitorInstance<
1110
+ F,
1111
+ InstanceResult<F>,
1112
+ T & Record<ChildPath, AsyncRegistryEntry<F, ChildPath, Parent, Args>>,
1113
+ ChildPath,
1114
+ Parent,
1115
+ Args,
1116
+ Promise<InstanceResult<F>>
1117
+ >;
1079
1118
 
1080
1119
  // Lazy getter: .lazy(TypeName, () => Constructor, config?)
1081
1120
  // (the unnamed form is dropped: the callback is never called at define
@@ -1085,12 +1124,12 @@ export interface RegistryHolderBase<
1085
1124
  N extends object,
1086
1125
  Args extends unknown[],
1087
1126
  F extends Proto<Parent, N> = Proto<Parent, N>,
1088
- ChildPath extends string = Path extends '' ? Name : `${Path}.${Name}`
1127
+ ChildPath extends string = ChildPathOf<Path, Name>
1089
1128
  >(
1090
1129
  this: RegistryHolderBase<T, Parent, Path>,
1091
1130
  TypeName: Name,
1092
1131
  getter: LazyDef<N, Args>,
1093
- config?: constructorOptions
1132
+ config?: DefineConfig
1094
1133
  ): IDefinitorInstance<
1095
1134
  F,
1096
1135
  InstanceResult<F>,
@@ -1120,6 +1159,7 @@ export interface RegistryHolder<
1120
1159
  // Parent = instance type of the parent type (object for root types);
1121
1160
  // threaded into registerHook's existentInstance typing
1122
1161
  // Args = construction parameters declared by the handler
1162
+ // New = what `new` gives: the instance, or its Promise for an async handler
1123
1163
  export interface IDefinitorInstance<
1124
1164
  N extends object,
1125
1165
  R extends InstanceResult<N> = InstanceResult<N>,
@@ -1127,20 +1167,19 @@ export interface IDefinitorInstance<
1127
1167
  Path extends string = '',
1128
1168
  Parent extends object = object,
1129
1169
  Args extends unknown[] = unknown[],
1170
+ New extends object = R,
1130
1171
  >
1131
- extends RegistryHolderBase<Registry, N, Path> {
1172
+ extends RegistryHolderBase<Registry, N, Path>, HookMethods<Parent, N> {
1132
1173
 
1133
1174
  TypeName: string;
1134
1175
  prototype: N;
1135
1176
 
1136
-
1137
1177
  // the line below declares a `new ...` invocation,
1138
1178
  // so makes interface constructible
1139
1179
  // new(...args: unknown[]): { [key in keyof R]: R[key] };
1140
1180
  /** @throws {CreationError<R>} when construction fails */
1141
- new(...args: Args): R;
1181
+ new(...args: Args): New;
1142
1182
 
1143
-
1144
1183
  // TODO: need check if line below works
1145
1184
  // also TS hinting check as well
1146
1185
  // the line below should make is a @decorate decorator working
@@ -1148,9 +1187,7 @@ export interface IDefinitorInstance<
1148
1187
 
1149
1188
  lookup: TypeLookup<Registry>;
1150
1189
 
1151
- decorate: (config?: constructorOptions) => <U extends Constructor<object>>(cstr: U) => DecoratedClass<U, Registry>;
1152
-
1153
- registerHook<HT extends hooksTypes>(hookType: HT, cb: typedHook<HT, Parent, N>): void;
1190
+ decorate: (config?: DefineConfig) => <U extends Constructor<object>>(cstr: U) => DecoratedClass<U, Registry>;
1154
1191
 
1155
1192
  subtypes: SubtypesMap;
1156
1193
 
@@ -1164,18 +1201,62 @@ export interface IDefinitorInstance<
1164
1201
  */
1165
1202
  }
1166
1203
 
1167
- // Type absorber function type - used for defining subtypes
1168
- // Supports multiple calling conventions:
1169
- // 1. Modern: define(TypeName, constructHandler, config?)
1170
- // 2. Legacy: define(constructHandler, config?) - TypeName from constructor name
1171
- // 3. Nested: parentType.define(TypeName, constructHandler, config?)
1204
+ // Type absorber function type - define() without a local registry.
1205
+ // The same three forms as RegistryHolderBase.define; each form ends with the
1206
+ // overload for an instance type given explicitly.
1172
1207
  export interface TypeAbsorber extends CallableFunction {
1208
+ // define(TypeName, constructHandler, config?)
1209
+ <T extends object, Args extends unknown[] = unknown[]>(
1210
+ this: unknown,
1211
+ TypeName: string,
1212
+ constructHandler: (this: T, ...args: Args) => never,
1213
+ config?: DefineConfig
1214
+ ): IDefinitorInstance<T, InstanceResult<T>, GlobalRegistry, '', object, Args>;
1215
+ <T extends object, Args extends unknown[] = unknown[]>(
1216
+ this: unknown,
1217
+ TypeName: string,
1218
+ constructHandler: AsyncIDEF<T, Args>,
1219
+ config?: DefineConfig
1220
+ ): IDefinitorInstance<T, InstanceResult<T>, GlobalRegistry, '', object, Args, Promise<InstanceResult<T>>>;
1221
+ <T extends object, Args extends unknown[] = unknown[]>(
1222
+ this: unknown,
1223
+ TypeName: string,
1224
+ constructHandler: IDEF<T, Args> | undefined,
1225
+ config?: DefineConfig
1226
+ ): IDefinitorInstance<T, InstanceResult<T>, GlobalRegistry, '', object, Args>;
1227
+ <T extends object>(
1228
+ this: unknown,
1229
+ TypeName: string,
1230
+ constructHandler: DefineNewableOrCallable,
1231
+ config?: DefineConfig
1232
+ ): IDefinitorInstance<T>;
1233
+ // define(TypeName, config?)
1173
1234
  <T extends object, Args extends unknown[] = unknown[]>(
1174
1235
  this: unknown,
1175
- TypeOrTypeName: string | DefineNewableOrCallable,
1176
- constructHandlerOrConfig?: IDEF<T, Args> | object | boolean | DefineNewableOrCallable,
1177
- configOrUndefined?: constructorOptions | DefineNewableOrCallable | boolean
1236
+ TypeName: string,
1237
+ config?: NoHandlerConfig
1238
+ ): IDefinitorInstance<T, InstanceResult<T>, GlobalRegistry, '', object, Args>;
1239
+ // define(constructHandler, config?)
1240
+ <T extends object, Args extends unknown[] = unknown[]>(
1241
+ this: unknown,
1242
+ constructHandler: (this: T, ...args: Args) => never,
1243
+ config?: DefineConfig
1244
+ ): IDefinitorInstance<T, InstanceResult<T>, GlobalRegistry, '', object, Args>;
1245
+ <T extends object, Args extends unknown[] = unknown[]>(
1246
+ this: unknown,
1247
+ constructHandler: AsyncIDEF<T, Args>,
1248
+ config?: DefineConfig
1249
+ ): IDefinitorInstance<T, InstanceResult<T>, GlobalRegistry, '', object, Args, Promise<InstanceResult<T>>>;
1250
+ <T extends object, Args extends unknown[] = unknown[]>(
1251
+ this: unknown,
1252
+ constructHandler: IDEF<T, Args>,
1253
+ config?: DefineConfig
1178
1254
  ): IDefinitorInstance<T, InstanceResult<T>, GlobalRegistry, '', object, Args>;
1255
+ <T extends object>(
1256
+ this: unknown,
1257
+ constructHandler: DefineNewableOrCallable,
1258
+ config?: DefineConfig
1259
+ ): IDefinitorInstance<T>;
1179
1260
  }
1180
1261
 
1181
1262
  // Lazy absorber function type - used for explicit lazy getter definitions
@@ -1186,14 +1267,7 @@ export interface LazyAbsorber extends CallableFunction {
1186
1267
  this: unknown,
1187
1268
  TypeName: string,
1188
1269
  getter: LazyDef<T, Args>,
1189
- config?: constructorOptions
1190
- ): IDefinitorInstance<T, InstanceResult<T>, GlobalRegistry, '', object, Args>;
1191
- <T extends object, Args extends unknown[] = unknown[]>(
1192
- this: unknown,
1193
- source: RegistryHolderBase<object, object, string>,
1194
- TypeName: string,
1195
- getter: LazyDef<T, Args>,
1196
- config?: constructorOptions
1270
+ config?: DefineConfig
1197
1271
  ): IDefinitorInstance<T, InstanceResult<T>, GlobalRegistry, '', object, Args>;
1198
1272
  }
1199
1273
 
@@ -1210,7 +1284,7 @@ export interface TypesCollection<
1210
1284
  // Decorator factory: .decorate() or .decorate(config)
1211
1285
  // Returns a class decorator that registers the class in this collection's registry.
1212
1286
  decorate(
1213
- config?: constructorOptions
1287
+ config?: DefineConfig
1214
1288
  ): <U extends Constructor<object>>(cstr: U) => DecoratedClass<
1215
1289
  U,
1216
1290
  T & Record<ConstructorName<U>, RegistryEntry<InstanceType<U>, ConstructorName<U>>>
@@ -1219,19 +1293,6 @@ export interface TypesCollection<
1219
1293
  [key: string]: unknown;
1220
1294
  }
1221
1295
 
1222
- // Shared interface for objects that support hooks (TypeDef and CollectionDef)
1223
- export interface Hookable {
1224
- hooks: Record<string, Set<hook>>;
1225
- invokeHook(hookType: hooksTypes, opts: hooksOpts): Set<unknown>;
1226
- // Collection-level registration: the payload split by hookType holds
1227
- // (preCreation has no inheritedInstance/throwModificationError; post
1228
- // hooks carry both, required) but P/T stay `object` — a collection
1229
- // mixes every registered type, so narrowing to a concrete instance
1230
- // happens in the callback.
1231
- registerHook<HT extends hooksTypes>(hookType: HT, cb: typedHook<HT>): void;
1232
- registerFlowChecker(cb: FlowChecker): void;
1233
- }
1234
-
1235
1296
  // createTypesCollection function type
1236
1297
  export type CreateTypesCollectionFunction =
1237
1298
  <T extends object = {}, Parent extends object = object>(
@@ -1241,59 +1302,6 @@ export type CreateTypesCollectionFunction =
1241
1302
  // Type class - base type constructor
1242
1303
  export type TypeClass = IDefinitorInstance<object>;
1243
1304
 
1244
- // Generic registry map used by typed collections and the mnemonica builder.
1245
- // Keys are dotted type paths; values are mnemonica-compatible constructors.
1246
- export type TypeRegistryMap = Record<string, TypeConstructorBase>;
1247
-
1248
- // Mnemonica constructor — the constructor function returned by constructHandler()
1249
- // Has SymbolConstructorName attached and is both newable and callable
1250
- export interface MnemonicaConstructor extends NewableFunction {
1251
- new (...args: unknown[]): object;
1252
- (this: object, ...args: unknown[]): unknown;
1253
- [key: symbol]: unknown;
1254
- }
1255
-
1256
- // Type descriptor instance — internal shape of TypeDescriptor objects
1257
- export interface TypeDescriptorDefine extends CallableFunction {
1258
- (
1259
- TypeOrTypeName: string | DefineNewableOrCallable,
1260
- constructHandlerOrConfig?: DefineNewableOrCallable | object,
1261
- config?: object
1262
- ): TypeClass;
1263
- }
1264
-
1265
- export interface TypeDescriptorLazy extends CallableFunction {
1266
- (
1267
- TypeName: string,
1268
- getter: LazyDef<object>,
1269
- config?: object
1270
- ): TypeClass;
1271
- }
1272
-
1273
- export interface TypeDescriptorLookup extends CallableFunction {
1274
- (TypeNestedPath: string): TypeClass | undefined;
1275
- }
1276
-
1277
- export type TypeDescriptorInstance = {
1278
- define: TypeDescriptorDefine;
1279
- lazy: TypeDescriptorLazy;
1280
- decorate: (config?: constructorOptions) => <U extends Constructor<object>>(cstr: U) => DecoratedClass<U>;
1281
- lookup: TypeDescriptorLookup;
1282
- subtypes: Map<string, object>;
1283
- TypeName: string;
1284
- collection: CollectionDef;
1285
- };
1286
-
1287
- // Constructor type for decorate function.
1288
- // Parameters are `never[]` for the same reason as AnyConstructor: under
1289
- // strictFunctionTypes an `unknown[]` constraint rejects classes with precise
1290
- // constructor parameters, so `@decorate()` could not be applied to them.
1291
- export type Constructor<T = object> = new (...args: never[]) => T;
1292
-
1293
- // Name of a constructor as a string literal type.
1294
- export type ConstructorName<T extends Constructor<object>> =
1295
- T extends { name: infer N } ? N extends string ? N : string : string;
1296
-
1297
1305
  // Decorated class type - includes call signature for decorator pattern and
1298
1306
  // aligns with `IDefinitorInstance` so decorated classes expose the same
1299
1307
  // constructor/lookup surface as builder-created types.
@@ -1314,6 +1322,138 @@ export type DecoratedClass<
1314
1322
  lookup: TypeLookup<Registry>;
1315
1323
  };
1316
1324
 
1325
+ // --- instance shapes and utils ---------------------------------------------
1326
+
1327
+ // Props type for getProps/setProps
1328
+ export type PropsType = Record<string, unknown>;
1329
+
1330
+ // A utility method as exposed on the `utils` collection — the
1331
+ // index-signature fallback for utilities beyond the declared set. Plain
1332
+ // callables: any argument list, unknown result.
1333
+ export interface UtilFunction extends CallableFunction {
1334
+ (...args: never[]): unknown;
1335
+ }
1336
+
1337
+ // The bound fork invoker that instance.fork() returns: consumes fork
1338
+ // arguments, produces a fresh instance of the forked type.
1339
+ export interface ForkInvoker<T extends object> extends CallableFunction {
1340
+ (this: object | void, ...forkArgs: unknown[]): T;
1341
+ }
1342
+
1343
+ /**
1344
+ * Proto merge type - combines parent and child types without property conflicts.
1345
+ *
1346
+ * When a subtype is defined from a parent instance, we want the child properties
1347
+ * to take precedence. `Exclude<keyof P, keyof T>` removes overlapping keys from P,
1348
+ * so `Pick<P, ...>` only brings in parent properties that don't clash with child.
1349
+ *
1350
+ * Result: child T gets all its own props, plus parent's non-overlapping props.
1351
+ */
1352
+ // When the parent contributes no properties, collapse to the child type so
1353
+ // hover tooltips stay readable.
1354
+ export type Proto<P extends object, T extends object> =
1355
+ [Exclude<keyof P, keyof T>] extends [never]
1356
+ ? T
1357
+ : T & Pick<P, Exclude<keyof P, keyof T>>;
1358
+
1359
+ // export type ProtoFlat<
1360
+ // P extends object,
1361
+ // T extends object,
1362
+ // F extends Proto<P, T> = Proto<P, T>
1363
+ // > = { [key in keyof F]: F[key]} ;
1364
+
1365
+ export type ProtoFlat<
1366
+ P extends object,
1367
+ T extends object,
1368
+ L extends Exclude<keyof P, keyof T> = Exclude<keyof P, keyof T>,
1369
+ > = {
1370
+ [key in keyof T]: T[key];
1371
+ } & {
1372
+ [key in L]: P[key];
1373
+ };
1374
+
1375
+ // Mnemonica instance method keys. These are filtered out of extracted/merged
1376
+ // field-only views because they belong to the prototype, not to the user's
1377
+ // enumerable data properties.
1378
+ export type MnemonicaInstanceMethodKeys =
1379
+ 'extract' | 'pick' | 'parent' | 'clone' | 'fork' | 'exception' | 'sibling';
1380
+
1381
+ // Extracted<T>: the shape returned by utils.extract(instance).
1382
+ // It contains the enumerable string-keyed user properties of the instance,
1383
+ // omitting MnemonicaInstance methods (extract, pick, parent, clone, fork,
1384
+ // exception, sibling). Optionality is preserved from the source type.
1385
+ // The `& {}` trick forces TypeScript to expand the alias in hover tooltips
1386
+ // so it renders as a plain object literal instead of "Extracted<{...}>".
1387
+ export type Extracted<T extends object> = {
1388
+ [K in keyof T as K extends string ? (K extends MnemonicaInstanceMethodKeys ? never : K) : never]: T[K];
1389
+ } & {};
1390
+
1391
+ // Parsed<T>: the shape returned by utils.parse(instance).
1392
+ // It is a one-level snapshot of the instance's prototype chain.
1393
+ // `props` contains the instance's enumerable user properties;
1394
+ // `joint` contains enumerable properties copied from the immediate prototype;
1395
+ // `parent` is the parent INSTANCE — the same object utils.parent(instance)
1396
+ // returns; null for no parent. Not recursively parsed — walking the whole
1397
+ // lineage level by level is what utils.deepParse does — this function stays
1398
+ // the one-level primitive.
1399
+ // The three "no parent" readings, stated once:
1400
+ // parent == null — no parent at all (covers both below);
1401
+ // parent === null — the end of a REAL chain (a root instance);
1402
+ // parent === undefined — nothing was given (utils.parse(null)).
1403
+ export type Parsed<T extends object> = {
1404
+ name: string;
1405
+ props: Extracted<T>;
1406
+ self: T;
1407
+ proto: object;
1408
+ joint: Record<string, unknown>;
1409
+ parent: object | null;
1410
+ };
1411
+
1412
+ // EmptyParsed: the shape utils.parse(null) returns — the one non-object
1413
+ // input parse accepts. "Nothing was given": every field is its empty value,
1414
+ // and parent is undefined (see the readings above).
1415
+ export interface EmptyParsed {
1416
+ name: undefined;
1417
+ props: {};
1418
+ self: null;
1419
+ proto: undefined;
1420
+ joint: {};
1421
+ parent: undefined;
1422
+ }
1423
+
1424
+ // Sibling type accessor
1425
+ export interface SiblingAccessor {
1426
+ (SiblingTypeName: string): TypeClass | undefined;
1427
+ [key: string]: TypeClass | undefined;
1428
+ }
1429
+
1430
+ // Mnemonica instance methods interface (opt-in).
1431
+ // These methods used to be auto-injected onto every instance. They are now
1432
+ // available only when a type explicitly adds them to its prototype.
1433
+ // Users can still use this interface to type their own root-level helpers.
1434
+ export interface MnemonicaInstance<T extends object = object> {
1435
+ extract(): Extracted<T>;
1436
+ pick<K extends keyof T>(...keys: (K | K[])[]): { [P in K]: T[P] } & {};
1437
+ pick(...keys: string[]): Record<string, unknown>;
1438
+ parent(): object | undefined;
1439
+ parent<K extends ParentPathOfInstance<this> & string>(
1440
+ constructorLookupPath: K
1441
+ ): InstanceOfTypeRegistry<K> | undefined;
1442
+ parent(constructorLookupPath: string): object | undefined;
1443
+ readonly clone: this;
1444
+ fork(...forkArgs: unknown[]): this;
1445
+ exception(error: Error, ...args: unknown[]): Error;
1446
+ readonly sibling: SiblingAccessor;
1447
+ }
1448
+
1449
+ // Combined instance type: plain object with the user's fields only.
1450
+ // Instance methods (extract, pick, fork, etc.) are no longer auto-injected.
1451
+ // The inline mapped type is used instead of the Flatten alias so that hover
1452
+ // tooltips show the actual field object literal first, not "Flatten<{...}>".
1453
+ export type InstanceResult<
1454
+ N extends object,
1455
+ > = { [K in keyof N]: N[K] };
1456
+
1317
1457
  // Helper: merge parent entity (E) and child constructor instance (T) into a
1318
1458
  // single flat object type, filtering out MnemonicaInstance method names.
1319
1459
  // Used by apply/call/bind.
@@ -1322,11 +1462,22 @@ export type Merge<E extends object, T extends object> = {
1322
1462
  K extends keyof T ? T[K] : E[K & keyof E];
1323
1463
  };
1324
1464
 
1465
+ // Keeps an `any` constructor off the async overload of apply/call/bind
1466
+ // (`C & NotAny<C>`), which it would match first.
1467
+ export type NotAny<C> = 0 extends (1 & C) ? never : unknown;
1468
+
1325
1469
  // Apply/Call/Bind function types
1326
1470
  // The return type merges the parent entity fields with the child constructor
1327
1471
  // fields (filtering out MnemonicaInstance method names), producing the same
1328
1472
  // `{ fields }` hover style as `new Type()`.
1329
1473
  export interface ApplyFunction extends CallableFunction {
1474
+ <E extends object, C extends Constructor<PromiseLike<object>>>(
1475
+ entity: E,
1476
+ Constructor: C & NotAny<C>,
1477
+ ... [ args ]: [] extends ConstructorParameters<C>
1478
+ ? [args?: ConstructorParameters<C>]
1479
+ : [args: ConstructorParameters<C>]
1480
+ ): Promise<InstanceResult<Merge<E, Awaited<InstanceType<C>>>>>;
1330
1481
  <E extends object, T extends object, Args extends unknown[]>(
1331
1482
  entity: E,
1332
1483
  Constructor: CtorParameter<T, Args>,
@@ -1335,6 +1486,11 @@ export interface ApplyFunction extends CallableFunction {
1335
1486
  }
1336
1487
 
1337
1488
  export interface CallFunction extends CallableFunction {
1489
+ <E extends object, C extends Constructor<PromiseLike<object>>>(
1490
+ entity: E,
1491
+ Constructor: C & NotAny<C>,
1492
+ ...args: ConstructorParameters<C>
1493
+ ): Promise<InstanceResult<Merge<E, Awaited<InstanceType<C>>>>>;
1338
1494
  <E extends object, T extends object, Args extends unknown[]>(
1339
1495
  entity: E,
1340
1496
  Constructor: CtorParameter<T, Args>,
@@ -1343,6 +1499,10 @@ export interface CallFunction extends CallableFunction {
1343
1499
  }
1344
1500
 
1345
1501
  export interface BindFunction extends CallableFunction {
1502
+ <E extends object, C extends Constructor<PromiseLike<object>>>(
1503
+ entity: E,
1504
+ Constructor: C & NotAny<C>
1505
+ ): (...args: ConstructorParameters<C>) => Promise<InstanceResult<Merge<E, Awaited<InstanceType<C>>>>>;
1346
1506
  <E extends object, T extends object, Args extends unknown[]>(
1347
1507
  entity: E,
1348
1508
  Constructor: CtorParameter<T, Args>
@@ -1357,7 +1517,11 @@ export interface UtilsCollection {
1357
1517
  clone<T extends object>(instance: T): T;
1358
1518
  fork<T extends object>(instance: T): ForkInvoker<T>;
1359
1519
  sibling(instance: object): SiblingAccessor;
1360
- collectConstructors: (instance: object, flat?: boolean) => (DefineNewableOrCallable | string)[];
1520
+ // the second argument picks the result: the ordered names for true, a
1521
+ // { name : true } lookup object by default
1522
+ collectConstructors(instance: object, asSequence: true): string[];
1523
+ collectConstructors(instance: object, asSequence?: false): Record<string, boolean>;
1524
+ collectConstructors(instance: object, asSequence?: boolean): string[] | Record<string, boolean>;
1361
1525
  merge<A extends object, B extends object>(
1362
1526
  a: A,
1363
1527
  b: B,
@@ -1377,6 +1541,58 @@ export interface UtilsCollection {
1377
1541
  [key: string]: UtilFunction;
1378
1542
  }
1379
1543
 
1544
+ // --- lineage (the lethe cross-language export) -----------------------------
1545
+
1546
+ // A JSON-safe value in the lethe lineage graph: instances export as $ref,
1547
+ // non-JSON values as tagged placeholders — never an error.
1548
+ export type LineageValue =
1549
+ | null
1550
+ | boolean
1551
+ | string
1552
+ | number
1553
+ | LineageValue[]
1554
+ | { $ref: string }
1555
+ | { '$mnemonica': 'unsupported'; kind: string }
1556
+ | { [ key: string ]: LineageValue };
1557
+
1558
+ // Where a level's type was DECLARED — not just its name (names collide
1559
+ // across levels and collections).
1560
+ export interface LineageTypeRef {
1561
+ collection: string;
1562
+ path: string;
1563
+ }
1564
+
1565
+ export interface LineageNode {
1566
+ type: LineageTypeRef;
1567
+ // the fields this level set itself — shadowed values stay with their
1568
+ // writer
1569
+ own: { [ key: string ]: LineageValue };
1570
+ // the parent's id, null at the root
1571
+ parent: string | null;
1572
+ // construction args — present only when lineage() gets { args: true }
1573
+ args?: LineageValue;
1574
+ // opt-in metadata (e.g. __timestamp__) — present only when
1575
+ // lineage() gets { props: [...] }
1576
+ props?: { [ key: string ]: LineageValue };
1577
+ }
1578
+
1579
+ // The lethe lineage graph: version "1", heads in argument order, every
1580
+ // reachable instance deduplicated at any depth.
1581
+ export interface LineageGraph {
1582
+ version: '1';
1583
+ heads: string[];
1584
+ nodes: { [ id: string ]: LineageNode };
1585
+ }
1586
+
1587
+ export interface LineageOptions {
1588
+ /** include construction args as node.args */
1589
+ args?: boolean;
1590
+ /** opt-in getProps keys exported as node.props (e.g. [ '__timestamp__' ]) */
1591
+ props?: string[];
1592
+ }
1593
+
1594
+ // --- the module object -----------------------------------------------------
1595
+
1380
1596
  // Main mnemonica module interface - represents the exported module object.
1381
1597
  // The optional Registry generic lets the object act as a typed registry holder
1382
1598
  // when chaining .define() calls.
@@ -1386,14 +1602,19 @@ export interface MnemonicaModule<Registry extends object = {}>
1386
1602
  apply: ApplyFunction;
1387
1603
  call: CallFunction;
1388
1604
  bind: BindFunction;
1389
- decorate: <T extends Constructor<object> | constructorOptions | undefined = undefined>(
1605
+ decorate: <T extends Constructor<object> | NoHandlerConfig | undefined = undefined>(
1390
1606
  target?: T,
1391
- config?: constructorOptions
1607
+ config?: DefineConfig
1392
1608
  ) => <U extends Constructor<object>>(cstr: U) => DecoratedClass<U, Registry>;
1393
1609
  registerHook: <
1394
1610
  T extends object,
1395
- HT extends hooksTypes = hooksTypes
1396
- >(Constructor: IDEF<T>, hookType: HT, cb: typedHook<HT, object, T>) => void;
1611
+ HT extends hookName = hooksTypes
1612
+ >(Constructor: HookableConstructor<T>, hookType: HT, cb: typedHook<HT, object, T>) => void;
1613
+ unregisterHook: (
1614
+ Constructor: Pick<HookMethods, 'unregisterHook'>,
1615
+ hookType: hookName,
1616
+ cb: AnyHookCallback
1617
+ ) => boolean;
1397
1618
 
1398
1619
  // Descriptors
1399
1620
  defaultTypes: TypesCollection<Registry>;
@@ -1415,6 +1636,7 @@ export interface MnemonicaModule<Registry extends object = {}>
1415
1636
  WRONG_STACK_CLEANER: MnemonicaErrorConstructor;
1416
1637
 
1417
1638
  // Constants
1639
+ defaultOptions: Required<constructorOptions>;
1418
1640
  MNEMONICA: string;
1419
1641
  MNEMOSYNE: string;
1420
1642
  SymbolParentType: symbol;