mnemonica 1.4.6 → 1.4.7

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.
@@ -99,6 +99,8 @@ the only names a declaration file (`.d.ts`) built on mnemonica ever needs:
99
99
 
100
100
  - `RegistryEntry<Shape, Path>` — what the builder stores per defined path
101
101
  and what typed lookups read back;
102
+ - `AsyncRegistryEntry<Shape, Path>` — the same for an `async` handler: its
103
+ construction is typed `Promise<Shape>`, its instances and hooks `Shape`;
102
104
  - `LookedUpConstructor<Registry, Path>` — the type of a `lookup()` result:
103
105
  a constructor whose instances carry their registered subtypes, plus a
104
106
  `lookup()` scoped to its own path;
@@ -181,6 +183,23 @@ const admin2 = new Admin({ role: 'root' }); // fails: no parent instance
181
183
 
182
184
  Direct `new` on a constructor returned by `.define()` works for **root types** only. For subtypes the parent instance is required (or use `apply(parentInstance, Ctor, args)`). With `strictChain: true` (the default) the parent must be the immediate type; with `strictChain: false` ancestor instances further up the chain are also accepted.
183
185
 
186
+ An `async` handler makes construction a Promise at runtime, and the types say so:
187
+
188
+ ```typescript
189
+ const Sessions = App.lookup('User').define('Session', async function (this: SessionShape, token: string) {
190
+ this.token = token;
191
+ return this;
192
+ });
193
+
194
+ const user = new (Sessions.lookup('User'))({ name: 'Ada' });
195
+ const pending = new user.Session('t'); // Promise<…>: no `token` until awaited
196
+ const session = await pending;
197
+ session.token; // string
198
+ session.name; // string, inherited from User
199
+ ```
200
+
201
+ The handler must `return this` (mnemonica rejects the construction otherwise). The registry stores the type as an `AsyncRegistryEntry`; hooks registered on it receive the resolved instance.
202
+
184
203
  ---
185
204
 
186
205
  ## Constructor arguments
@@ -348,6 +367,23 @@ Rule: thread the chain through exports and keep imports tree-shaped (no
348
367
  cycles). Each file sees exactly the types registered up to its point in the
349
368
  chain.
350
369
 
370
+ A subtype defined in a later statement, on a looked-up constructor, joins
371
+ the registry it was looked up from, so the returned value carries
372
+ everything before it plus the new type:
373
+
374
+ ```typescript
375
+ export const App = mnemonica.define('User', …).define('Admin', …);
376
+ export const Sessions = App.lookup('User').define('Session', …);
377
+
378
+ const User = Sessions.lookup('User');
379
+ const user = new User({ name: 'Ada' });
380
+ new user.Admin({ role: 'root' }); // typed
381
+ new user.Session('t'); // typed
382
+ ```
383
+
384
+ `App` itself does not learn about `Session`: its type was fixed when it was
385
+ declared. Look up from the latest value in the chain.
386
+
351
387
  ---
352
388
 
353
389
  ## The registry bridge: `RegistryOf`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mnemonica",
3
- "version": "1.4.6",
3
+ "version": "1.4.7",
4
4
  "description": "AI-agent ready instance inheritance system for JavaScript/TypeScript via prototype chains",
5
5
  "type": "commonjs",
6
6
  "main": "./build/index.js",
@@ -127,7 +127,7 @@
127
127
  "typescript": "^6.0.3"
128
128
  },
129
129
  "engines": {
130
- "node": ">=18 <26"
130
+ "node": ">=22 <27"
131
131
  },
132
132
  "overrides": {
133
133
  "serialize-javascript": "^7.0.5",
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  import type {
4
- constructorOptions, _Internal_TC_, TypeDef, TypeDescriptorDefine
4
+ constructorOptions, _Internal_TC_, TypeDef, TypeDescriptorDefine, TypeClass
5
5
  } from '../../types';
6
6
 
7
7
  import TypesUtils from '../utils';
@@ -187,7 +187,8 @@ const subTypeApply = (
187
187
  parentType: TypeProxyType,
188
188
  cfg?: constructorOptions
189
189
  ) => {
190
- const decorator = function <T extends { new (): unknown }>(cstr: T): T {
190
+ function decorator <T extends { new (): unknown }>(cstr: T): T;
191
+ function decorator (cstr: { new (): unknown }): TypeClass {
191
192
  const { name } = cstr;
192
193
  const defineResult = parentType.define(
193
194
  name,
@@ -197,9 +198,10 @@ const subTypeApply = (
197
198
  // decorator contract: define() returns the constructor wrapping cstr
198
199
  // (construction still runs through cstr); the class binding is
199
200
  // replaced by that constructor, so it is presented as T
200
- const result = defineResult as unknown as T;
201
+ // The overload carries T; the implementation returns TypeClass directly.
202
+ const result = defineResult;
201
203
  return result;
202
- };
204
+ }
203
205
  return decorator;
204
206
  };
205
207
 
@@ -145,7 +145,7 @@ const getFunctionConstructor = (
145
145
  // !!! it MUST be strict replacement !!!
146
146
  // !!! this is the only way to keep Prototype Chain correct !!!
147
147
  // ConstructHandler.prototype = this.constructor.prototype;
148
- // answer = new (ConstructHandler as unknown as new (...args: unknown[]) => object)( ...args );
148
+ // answer = new ConstructHandler(...args);
149
149
  // ConstructHandler.prototype = _proto;
150
150
 
151
151
  const constructResult = Reflect.construct(
@@ -178,6 +178,8 @@ const compileNewModificatorFunctionBody = function ( FunctionName: string, asCla
178
178
  // this branch runs only when isClass() verified at define
179
179
  // time that the handler is a class — the cast names the class
180
180
  // view (construct signature) of that same function value
181
+ // ConstructHandler has no construct signature; the boolean cannot
182
+ // narrow it without a runtime guard or a changed public signature.
181
183
  ModificationBody = getClassConstructor(
182
184
  ConstructHandler as unknown as ClassConstructHandler,
183
185
  CreationHandler
@@ -189,6 +191,8 @@ const compileNewModificatorFunctionBody = function ( FunctionName: string, asCla
189
191
  // the compiled body is invoked with `new` by the pipeline;
190
192
  // a function expression carries no construct signature, so
191
193
  // the `new`-able view of the same value is named here
194
+ // CreationHandler returns unknown; ModificationBody must construct
195
+ // object, so a direct return annotation cannot replace this cast.
192
196
  ModificationBody = getFunctionConstructor(
193
197
  ConstructHandler,
194
198
  CreationHandler
@@ -14,7 +14,7 @@ export default function () {
14
14
  const CreateInstanceModificator = function (
15
15
  this: object,
16
16
  ModificatorType: MnemonicaConstructor,
17
- ModificatorTypePrototype: { [index: string]: unknown },
17
+ ModificatorTypePrototype: { [index: string]: unknown; constructor: unknown },
18
18
  _addProps: AddPropsCallback
19
19
  ) {
20
20
 
@@ -59,7 +59,6 @@ export default function () {
59
59
  // so now we have to copy all constructor props
60
60
  const props = Object.getOwnPropertyDescriptors(ModificatorTypePrototype);
61
61
  props.constructor = {
62
- // @ts-expect-error I'm too lazy for that
63
62
  value : ModificatorType
64
63
  };
65
64
  Object.defineProperties(
@@ -379,6 +379,8 @@ const typeDescriptorCreator = function (
379
379
  // below); a function expression carries no construct signature, so it is
380
380
  // named once as the constructor interface it is used through — the
381
381
  // prototype contract is attached immediately below
382
+ // The registered result is a TypeProxy, not the descriptor's declared
383
+ // TypeDescriptorInstance shape.
382
384
  const TypeDescriptor = typeDescriptorCreator as _Internal_TC_<TypeDescriptorInstance>;
383
385
 
384
386
  Object.assign(
@@ -607,6 +609,8 @@ const createFromDirectHandler = function (
607
609
  // new TypeDescriptor() returns the TypeProxy it registers in the
608
610
  // subtypes map — a Proxy materializing the TypeClass surface
609
611
  // dynamically — so the public constructor contract is named here
612
+ // The declared descriptor result and dynamic proxy surface differ;
613
+ // changing the producing signature breaks descriptor prototype methods.
610
614
  ) as unknown as TypeClass;
611
615
  return result;
612
616
  };
@@ -18,7 +18,8 @@ import {
18
18
  } from '../types/Props';
19
19
  import type {
20
20
  InstanceConstructor,
21
- MnemonicaConstructor
21
+ MnemonicaConstructor,
22
+ TypeClass
22
23
  } from '../../types';
23
24
 
24
25
  import compileNewModificatorFunctionBody, { ConstructHandler } from '../types/compileNewModificatorFunctionBody';
@@ -39,22 +40,25 @@ const checkProto = (proto: unknown) => {
39
40
  };
40
41
 
41
42
  const getTypeChecker = (TypeName: string) => {
42
- const seeker: unknown = (instance: object) => {
43
+ const seeker: unknown = (instance: object & { [SymbolConstructorName]?: string }) => {
43
44
 
44
- if (typeof instance !== 'object') {
45
+ if (typeof instance !== 'object' || instance === null) {
45
46
  return false;
46
47
  }
47
48
 
48
49
 
49
- if (!instance!.constructor) {
50
+ if (!instance.constructor) {
50
51
  return false;
51
52
  }
52
53
 
53
- // @ts-expect-error I'm too lazy for that
54
- if (Reflect.getPrototypeOf(instance).constructor.name === 'Promise') {
54
+ const prototype = Reflect.getPrototypeOf(instance);
55
+ if (prototype === null) {
56
+ return false;
57
+ }
58
+
59
+ if (prototype.constructor && prototype.constructor.name === 'Promise') {
55
60
  // if ( instance instanceof Promise ) {
56
61
 
57
- // @ts-expect-error I'm too lazy for that
58
62
  const checkResult = instance[ SymbolConstructorName ] === TypeName;
59
63
  return checkResult;
60
64
  }
@@ -185,8 +189,8 @@ export type parentSub = {
185
189
  __parent__: parentSub
186
190
  }
187
191
 
188
- const findSubTypeFromParent = (instance: parentSub | object | undefined, subType: string): parentSub | null => {
189
- let subtype = null;
192
+ const findSubTypeFromParent = (instance: parentSub | object | undefined, subType: string): TypeClass | null => {
193
+ let subtype: TypeClass | null = null;
190
194
 
191
195
  if (!instance) {
192
196
  return null;
@@ -195,8 +199,8 @@ const findSubTypeFromParent = (instance: parentSub | object | undefined, subType
195
199
  const props = _getProps(instance) as Props;
196
200
 
197
201
  if (props) {
198
- if (props.__type__.subtypes.has(subType)) {
199
- const _subtype = props.__type__.subtypes.get(subType);
202
+ const _subtype = props.__type__.subtypes.get(subType);
203
+ if (_subtype !== undefined) {
200
204
  subtype = _subtype;
201
205
  } else {
202
206
  subtype = findSubTypeFromParent(
@@ -206,7 +210,6 @@ const findSubTypeFromParent = (instance: parentSub | object | undefined, subType
206
210
  }
207
211
  }
208
212
 
209
- // @ts-expect-error I'm too lazy for that
210
213
  return subtype;
211
214
  };
212
215
 
@@ -103,7 +103,9 @@ export const constants = {
103
103
  return SymbolDefaultTypesCollection;
104
104
  },
105
105
 
106
- get 'SymbolConfig' () {
106
+ // typed as the declared symbol itself (unique symbol), so it can key a
107
+ // typed property such as CollectionDef's config
108
+ get 'SymbolConfig' (): typeof SymbolConfig {
107
109
  return SymbolConfig;
108
110
  },
109
111
 
@@ -80,6 +80,9 @@ const TypesCollection = function (_config: Record<string, unknown>) {
80
80
  {
81
81
  get () {
82
82
  const result = (instance: { [SymbolConstructorName]?: string }) => {
83
+ if (typeof instance !== 'object' || instance === null) {
84
+ return false;
85
+ }
83
86
  const checkResult = instance[ SymbolConstructorName ] === MNEMONICA;
84
87
  return checkResult;
85
88
  };
package/src/index.ts CHANGED
@@ -67,9 +67,10 @@ export type {
67
67
  RegistryOf,
68
68
  MnemonicaModule,
69
69
  // Deliberate public vocabulary for builder-mode consumers (TS 6
70
- // declaration emit names ONLY entry exports; these three stand in
70
+ // declaration emit names ONLY entry exports; these four stand in
71
71
  // for the internal registry/lookup machinery):
72
72
  RegistryEntry,
73
+ AsyncRegistryEntry,
73
74
  LookedUpConstructor,
74
75
  LookedUpInstance,
75
76
  typedHook,
@@ -207,25 +208,13 @@ export function define <
207
208
  constructHandler?: IDEF<T> | DefineNewableOrCallable | object | boolean,
208
209
  config?: constructorOptions,
209
210
  ): R;
210
- export function define <
211
- T extends object,
212
- P extends object = object,
213
- N extends Proto<P, T> = Proto<P, T>,
214
- R extends IDefinitorInstance<
215
- N,
216
- InstanceResult<N>,
217
- GlobalRegistry,
218
- '',
219
- object,
220
- never[]
221
- > = IDefinitorInstance<N>,
222
- >(
211
+ export function define <T extends object>(
223
212
  this: unknown,
224
213
  TypeNameOrSource?: string | DefineNewableOrCallable | RegistryHolderBase<object, object, string>,
225
214
  constructHandlerOrName?: IDEF<T> | DefineNewableOrCallable | object | boolean | string,
226
215
  configOrHandler?: constructorOptions | IDEF<T> | DefineNewableOrCallable | object | boolean,
227
216
  config?: constructorOptions,
228
- ): R {
217
+ ): IDefinitorInstance<T> {
229
218
 
230
219
  // explicit-source form: define(source, name, handler, config?)
231
220
  // the source may be a TypesCollection (object) or a TypeProxy (function),
@@ -238,28 +227,25 @@ export function define <
238
227
  if (mayBeSource && typeof constructHandlerOrName === 'string') {
239
228
  // .define was verified callable above; the cast only adds its signature
240
229
  const source = sourceCandidate as { define: TypeAbsorber };
230
+ // The implementation returns the delegated constructor directly;
231
+ // caller-specific R views live only on the overloads.
241
232
  const sourceDefineResult = source.define(
242
233
  constructHandlerOrName,
243
234
  configOrHandler as IDEF<T>,
244
235
  config
245
- // facade return: the overload promises R (the caller's constructor
246
- // view); the delegated define produces that same runtime
247
- // constructor under a different generic instantiation
248
- ) as unknown as R;
236
+ );
249
237
  return sourceDefineResult;
250
238
  }
251
239
 
252
240
  const types = checkThis(this) ? defaultTypes : this || defaultTypes;
253
241
  // Type assertion needed because TypesCollectionProxy is a Proxy
242
+ // The implementation returns the delegated constructor directly.
254
243
  const defineResult = (types as { define: TypeAbsorber })
255
244
  .define(
256
245
  TypeNameOrSource as string,
257
246
  constructHandlerOrName as IDEF<T>,
258
247
  configOrHandler as constructorOptions
259
- // facade return: the overload promises R (the caller's constructor
260
- // view); the delegated define produces that same runtime
261
- // constructor under a different generic instantiation
262
- ) as unknown as R;
248
+ );
263
249
  return defineResult;
264
250
  }
265
251
 
@@ -357,7 +343,10 @@ const $run = function <E extends object, T extends object, S extends Proto<E, T>
357
343
  } {
358
344
 
359
345
  // debugger;
360
- // @ts-expect-error - extracting TypeName from function
346
+ // CtorParameter deliberately accepts constructors without a TypeName
347
+ // declaration; runtime mnemonica constructors carry it. Widening that
348
+ // public input type would change the API, so this property read stays.
349
+ // @ts-expect-error -- runtime mnemonica constructors carry TypeName
361
350
  const { TypeName } = Ctor;
362
351
  // the returned SubTypeProxy is a plain function at runtime — constructable —
363
352
  // so TypeConstructorBase (the named minimal constructor shape) is its
@@ -370,7 +359,10 @@ const $run = function <E extends object, T extends object, S extends Proto<E, T>
370
359
  throw new WRONG_MODIFICATION_PATTERN(`[ ${TypeName} ] is not defined as a Type Constructor on used instance`);
371
360
  }
372
361
  const runResult = new Cstr(...args);
373
- // @ts-expect-error - returning result as merged proto type
362
+ // new Cstr returns object here; S is the caller's merged entity/constructor
363
+ // shape and cannot be recovered by narrowing without changing the public
364
+ // result type, so the return stays suppressed.
365
+ // @ts-expect-error -- the merged result shape cannot be recovered by narrowing
374
366
  return runResult;
375
367
  };
376
368
 
@@ -447,7 +439,12 @@ export const decorate = function <
447
439
  ? target as Constructor<object> & { define: TypeAbsorber }
448
440
  : undefined;
449
441
 
450
- const decorator = function <U extends Constructor<object>>(cstr: U): DecoratedClass<U> {
442
+ // decorator contract: define() returns the constructor that wraps cstr;
443
+ // the decorator replaces the class binding with it, so callers see the
444
+ // result as DecoratedClass<U>. The overload states that contract; the
445
+ // implementation signature (not emitted) returns what define() gives.
446
+ function decorator <U extends Constructor<object>>(cstr: U): DecoratedClass<U>;
447
+ function decorator (cstr: Constructor<object>): object {
451
448
  const { name } = cstr;
452
449
  const handler: IDEF<object, never[]> = cstr;
453
450
  if (parentType === undefined) {
@@ -455,20 +452,17 @@ export const decorate = function <
455
452
  name,
456
453
  handler,
457
454
  opts
458
- // decorator contract: define() returns the constructor that
459
- // wraps cstr; the decorator replaces the class binding with
460
- // it, so the result is presented as DecoratedClass<U>
461
- ) as unknown as DecoratedClass<U>;
455
+ );
462
456
  return decoratorResult;
463
457
  }
458
+ // same decorator contract as the branch above
464
459
  const defineResult = parentType.define(
465
460
  name,
466
461
  handler,
467
462
  opts
468
- // same decorator contract as the branch above
469
- ) as unknown as DecoratedClass<U>;
463
+ );
470
464
  return defineResult;
471
- };
465
+ }
472
466
  return decorator;
473
467
  };
474
468
 
@@ -2,6 +2,7 @@
2
2
  /* eslint no-unused-vars: "off" */
3
3
 
4
4
  import type { TypeRegistry } from '../index';
5
+ import type { constants } from '../constants';
5
6
 
6
7
  // Props type for getProps/setProps
7
8
  export type PropsType = Record<string, unknown>;
@@ -87,7 +88,7 @@ export interface ThrowModificationError extends CallableFunction {
87
88
  // The bound fork invoker that instance.fork() returns: consumes fork
88
89
  // arguments, produces a fresh instance of the forked type.
89
90
  export interface ForkInvoker<T extends object> extends CallableFunction {
90
- (this: object, ...forkArgs: unknown[]): T;
91
+ (this: object | void, ...forkArgs: unknown[]): T;
91
92
  }
92
93
 
93
94
  // Error message types - all error messages are strings
@@ -463,11 +464,23 @@ export interface CollectionLookup extends CallableFunction {
463
464
  }
464
465
 
465
466
  // Collection definition
467
+ // A collection's config, stored under SymbolConfig. Every collection carries
468
+ // a name by construction: 'defaultTypes' for the default one, the given or
469
+ // auto-numbered name for custom ones (createTypesCollection).
470
+ export type CollectionConfig = {
471
+ name: string;
472
+ [key: string]: unknown;
473
+ };
474
+
475
+ // the config key is SymbolConfig's own unique symbol type; a mapped type
476
+ // over it keeps this module type-only (no runtime import of constants)
466
477
  export type CollectionDef = Hookable & {
467
478
  define: TypeAbsorber;
468
479
  lookup: CollectionLookup;
469
480
  subtypes: SubtypesMap;
470
481
  [key: string]: unknown;
482
+ } & {
483
+ [K in typeof constants.SymbolConfig]: CollectionConfig;
471
484
  };
472
485
 
473
486
  // Type lookup function type: may have augmentation by Tactica re-definition
@@ -481,13 +494,22 @@ export type CollectionDef = Hookable & {
481
494
  export type GlobalRegistry = TypeRegistry & Record<string, TypeConstructorBase>;
482
495
 
483
496
  // Extract the instance type returned by a mnemonica-compatible constructor.
484
- // Falls back to `object` so generic helpers that require an object constraint
485
- // do not fail when the constructor shape is not yet narrowed.
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.
486
501
  export type ExtractConstructorInstance<C> =
487
502
  C extends { new (...args: never[]): infer I }
488
- ? I extends object ? I : object
503
+ ? Awaited<I> extends object ? Awaited<I> : object
489
504
  : object;
490
505
 
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;
512
+
491
513
  // Map dotted registry paths that extend `${Path}.${Child}` into child
492
514
  // constructor properties on the parent instance. This lets typed lookups
493
515
  // return a constructor whose instances carry their subtypes, e.g.
@@ -516,7 +538,7 @@ export type ReplaceConstructorInstance<
516
538
  new (...args: infer A): unknown;
517
539
  }
518
540
  ? {
519
- new (...args: A): NewInstance;
541
+ new (...args: A): ConstructResult<C, NewInstance>;
520
542
  readonly prototype: NewInstance & {
521
543
  readonly constructor: ReplaceConstructorInstance<C, NewInstance, CallConstructs>;
522
544
  };
@@ -525,11 +547,11 @@ export type ReplaceConstructorInstance<
525
547
  // SubTypeProxy-backed member: the call form constructs the child
526
548
  // from the parent instance (the chain-tip form new R().A()), so
527
549
  // no `this` demand — detached bare calls construct too.
528
- ? { (...args: A2): NewInstance }
550
+ ? { (...args: A2): ConstructResult<C, NewInstance> }
529
551
  // Raw looked-up constructor: the `this` guard honestly models
530
552
  // .call(childInstance, args); a bare call here is the decorator
531
553
  // path at runtime, not construction.
532
- : { (this: NewInstance, ...args: A2): NewInstance }
554
+ : { (this: NewInstance, ...args: A2): ConstructResult<C, NewInstance> }
533
555
  : unknown)
534
556
  & Omit<C, 'prototype' | 'lookup'>
535
557
  : never;
@@ -567,19 +589,20 @@ export type LookedUpInstance<
567
589
  Path extends string
568
590
  > = WithSubTypes<ExtractConstructorInstance<Registry[Path & keyof Registry]>, Registry, Path>;
569
591
 
570
- // Lookup result type (public vocabulary): the augmented constructor plus a
571
- // lookup method scoped to the constructor's own type path. Non-conditional
572
- // on purpose: a conditional alias resolves during inference and its
573
- // expansion (internal helpers) would leak into consumer declaration emit.
574
- // CallConstructs mirrors the SubTypeProxy distinction (true drops the this
575
- // demand for instance-carried child constructors).
592
+ // Lookup result type (public vocabulary): the full-registry definition
593
+ // surface plus the augmented constructor and a lookup method scoped to the
594
+ // constructor's own type path. Non-conditional on purpose: a conditional
595
+ // alias resolves during inference and its expansion (internal helpers) would
596
+ // leak into consumer declaration emit. CallConstructs mirrors the SubTypeProxy
597
+ // distinction (true drops the this demand for instance-carried child constructors).
576
598
  export type LookedUpConstructor<
577
599
  Registry extends object,
578
600
  Path extends keyof Registry & string,
579
601
  CallConstructs extends boolean = false
580
- > = AugmentedConstructor<Registry, Path, CallConstructs> & {
581
- lookup: NestedTypeLookup<Registry, Path>;
582
- };
602
+ > = RegistryHolderBase<Registry, ExtractConstructorInstance<Registry[Path]>, Path> &
603
+ AugmentedConstructor<Registry, Path, CallConstructs> & {
604
+ lookup: NestedTypeLookup<Registry, Path>;
605
+ };
583
606
 
584
607
  // Typed registerHook surface for lookup results whose registry entries are
585
608
  // bare constructors (tactica-emitted or hand-written TypeRegistry entries):
@@ -933,6 +956,24 @@ export interface RegistryEntry<
933
956
  registerHook<HT extends hooksTypes>(hookType: HT, cb: typedHook<HT, Parent, F>): void;
934
957
  }
935
958
 
959
+ // Async registry VALUE: the same public vocabulary as RegistryEntry, with
960
+ // construction returning the Promise that the runtime always produces for an
961
+ // async handler. The resolved F remains the instance used by hooks and
962
+ // subtypes; only construction is deferred.
963
+ export interface AsyncRegistryEntry<
964
+ F extends object,
965
+ Path extends string = '',
966
+ Parent extends object = object,
967
+ Args extends unknown[] = unknown[]
968
+ > extends RegistryHolderBase<{}, F, Path> {
969
+ new (...args: Args): Promise<F>;
970
+ (this: F, ...args: Args): Promise<F>;
971
+ readonly prototype: F & {
972
+ readonly constructor: AsyncRegistryEntry<F, Path, Parent, Args>;
973
+ };
974
+ registerHook<HT extends hooksTypes>(hookType: HT, cb: typedHook<HT, Parent, F>): void;
975
+ }
976
+
936
977
  // Registry holder base - provides the accumulating .define() method.
937
978
  // `Parent` tracks the instance type of the last defined constructor, so chained
938
979
  // subtypes get the correct merged `Proto<Parent, N>` instance type.
@@ -950,6 +991,29 @@ export interface RegistryHolderBase<
950
991
  configOrUndefined?: constructorOptions | DefineNewableOrCallable | boolean
951
992
  ): IDefinitorInstance<SubType>;
952
993
 
994
+ // Async modern overload: a Promise-returning callable handler stores an
995
+ // async entry. It must precede the IDEF overload, whose callable void
996
+ // result otherwise accepts async functions and erases their Promise.
997
+ define<
998
+ const Name extends string,
999
+ N extends object,
1000
+ Args extends unknown[] = unknown[],
1001
+ F extends Proto<Parent, N> = Proto<Parent, N>,
1002
+ ChildPath extends string = Path extends '' ? Name : `${Path}.${Name}`
1003
+ >(
1004
+ this: RegistryHolderBase<T, Parent, Path>,
1005
+ TypeName: Name,
1006
+ constructHandler: (this: N, ...args: Args) => PromiseLike<unknown>,
1007
+ config?: constructorOptions
1008
+ ): IDefinitorInstance<
1009
+ F,
1010
+ InstanceResult<F>,
1011
+ T & Record<ChildPath, AsyncRegistryEntry<F, ChildPath, Parent, Args>>,
1012
+ ChildPath,
1013
+ Parent,
1014
+ Args
1015
+ >;
1016
+
953
1017
  // Modern overload: define(TypeName, constructHandler, config?)
954
1018
  define<
955
1019
  const Name extends string,
@@ -971,6 +1035,28 @@ export interface RegistryHolderBase<
971
1035
  Args
972
1036
  >;
973
1037
 
1038
+ // Async lazy getter: the callback itself stays synchronous, but the
1039
+ // constructor it returns may produce a Promise on every construction.
1040
+ lazy<
1041
+ const Name extends string,
1042
+ N extends object,
1043
+ Args extends unknown[],
1044
+ F extends Proto<Parent, N> = Proto<Parent, N>,
1045
+ ChildPath extends string = Path extends '' ? Name : `${Path}.${Name}`
1046
+ >(
1047
+ this: RegistryHolderBase<T, Parent, Path>,
1048
+ TypeName: Name,
1049
+ getter: () => (this: N, ...args: Args) => PromiseLike<unknown>,
1050
+ config?: constructorOptions
1051
+ ): IDefinitorInstance<
1052
+ F,
1053
+ InstanceResult<F>,
1054
+ T & Record<ChildPath, AsyncRegistryEntry<F, ChildPath, Parent, Args>>,
1055
+ ChildPath,
1056
+ Parent,
1057
+ Args
1058
+ >;
1059
+
974
1060
  // Lazy getter: .lazy(TypeName, () => Constructor, config?)
975
1061
  // (the unnamed form is dropped: the callback is never called at define
976
1062
  // time, so there is nothing to derive the name from)
package/src/utils/fork.ts CHANGED
@@ -4,6 +4,7 @@ import {
4
4
  getProps, Props
5
5
  } from '../api/types/Props';
6
6
  import { InstanceCreator } from '../api/types/InstanceCreator';
7
+ import { gatherLazyDefinition } from '../api/types/lazyDefinition';
7
8
  import TypesUtils from '../api/utils/index';
8
9
  import type { ForkInvoker } from '../types';
9
10
 
@@ -26,7 +27,7 @@ export const fork = <T extends object>(instance: T): ForkInvoker<T> => {
26
27
  TypeName
27
28
  } = type;
28
29
 
29
- const result = function (this: object, ...forkArgs: unknown[]) {
30
+ const result = function (this: object | void, ...forkArgs: unknown[]) {
30
31
 
31
32
  let forked;
32
33
  const Constructor = isSubType ?
@@ -36,15 +37,21 @@ export const fork = <T extends object>(instance: T): ForkInvoker<T> => {
36
37
  const args = forkArgs.length ? forkArgs : __args__;
37
38
 
38
39
 
39
- if (this === __self__) {
40
+ if (this === __self__ || this === undefined) {
40
41
 
41
- // @ts-expect-error this is definitely a constructor
42
+ // Constructor is the parent instance (subtype proxy) or the collection,
43
+ // both indexed dynamically, so Constructor[TypeName] is unknown statically.
44
+ // At runtime it is always the registered type, since TypeName comes from
45
+ // this instance's own type; a guard would be an unreachable branch.
46
+ // @ts-expect-error -- the registered subtype is only dynamically indexed
42
47
  forked = new (Constructor[ TypeName ])(...args);
43
48
  } else {
44
49
  // fork.call ? let's do it !
50
+ const wrappedInstance = reflectPrimitiveWrappers(this);
51
+ gatherLazyDefinition(type, wrappedInstance);
45
52
  forked = new InstanceCreator(
46
53
  type,
47
- reflectPrimitiveWrappers(this),
54
+ wrappedInstance,
48
55
  args
49
56
  );
50
57
  }
@@ -50,12 +50,11 @@ const wrapThis = ( collection: object, method: WrappableMethod ) => {
50
50
  : ( this !== collection ? this : undefined );
51
51
  let wrapResult: unknown;
52
52
  if ( new.target ) {
53
- // wrapThis forwards `new` to the util; WrappableMethod (a plain
54
- // function type) declares no construct signature, so the cast
55
- // bridges that construct call
56
- wrapResult = new (method as unknown as new (...a: unknown[]) => unknown)(
57
- instanceContext,
58
- ...args
53
+ // wrapThis forwards `new` with Reflect.construct: without a third
54
+ // argument new.target is method, exactly as in new method(...args)
55
+ wrapResult = Reflect.construct(
56
+ method,
57
+ [ instanceContext, ...args ]
59
58
  );
60
59
  } else {
61
60
  wrapResult = method(