mnemonica 1.3.3 → 1.3.6

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.
@@ -20,7 +20,36 @@ const instance = await new AsyncType('tada');
20
20
  console.log(instance.data); // 'tada'
21
21
  ```
22
22
 
23
- The `awaitReturn` option (default: `true`) ensures `await new Constructor()` returns the resolved instance. If you set `awaitReturn: false`, the raw Promise is returned instead.
23
+ The `unchain` option (default: `false`) requires `await new Constructor()` to resolve to its instance. With `unchain: true`, a non-object resolution (`undefined`, a primitive, `null`) drops the chain — that value is the result.
24
+
25
+ ---
26
+
27
+ ## The `return this` rule
28
+
29
+ An async constructor must resolve to the instance it was given as `this`.
30
+ Fields assigned to `this` are invisible to the chain unless the constructor
31
+ returns it — `return this`, or a Promise resolving to it (promises resolve to
32
+ their final depth by the ECMAScript standard).
33
+
34
+ When the resolution breaks the rule, the error names the cause and the fix:
35
+
36
+ ```
37
+ // resolved to undefined / a primitive / null (with unchain: false):
38
+ wrong modification pattern : async constructor AsyncType must `return this` (it resolved to undefined)
39
+
40
+ // resolved to a different object:
41
+ wrong modification pattern : async constructor AsyncType must resolve to its own instance (`return this`), got Object
42
+ ```
43
+
44
+ With `unchain: true` the first case is not an error at all — the non-object
45
+ value IS the result (see Configuration below). `null` is a legitimate value
46
+ either way: `undefined` says "no construction after this", `null` says "the
47
+ chain ends here, but an object is possible".
48
+
49
+ > **Write async constructors as `async function`.** Only that form supports
50
+ > the `this`-substitution dance. Arrow functions never see the instance
51
+ > (their `this` is lexical); the shape rules below reject the sync forms at
52
+ > define time, and the `no-arrow-this` ESLint plugin is the early guard.
24
53
 
25
54
  ---
26
55
 
@@ -228,25 +257,25 @@ Each async subtype returns a Promise that resolves to the next instance in the c
228
257
 
229
258
  ---
230
259
 
231
- ## Configuration: `awaitReturn`
260
+ ## Configuration: `unchain`
232
261
 
233
262
  | Option | Default | Behavior |
234
263
  |--------|---------|----------|
235
- | `awaitReturn` | `true` | `await new AsyncType()` returns the resolved instance |
236
- | `awaitReturn` | `false` | `await new AsyncType()` returns the raw Promise |
264
+ | `unchain` | `false` (default) | `await new AsyncType()` must resolve to the instance |
265
+ | `unchain` | `true` | a non-object resolution drops the chain — the value itself is the result |
237
266
 
238
267
  ```js
239
268
  const AsyncType = define('AsyncType', async function () {
240
269
  await sleep(100);
241
270
  this.done = true;
242
- return this;
243
- }, { awaitReturn: false });
271
+ // no return: resolves to undefined
272
+ }, { unchain: true });
244
273
 
245
274
  const result = await new AsyncType();
246
- // result is a Promise, not the instance
275
+ // result is undefined — the chain is dropped, no error
247
276
  ```
248
277
 
249
- Use `awaitReturn: false` only if you need to handle the Promise manually (e.g., for custom `.then()` chains).
278
+ Use `unchain: true` when a data-flow chain is meant to end in a plain value — step back and re-construct from `.parent` if an object is needed.
250
279
 
251
280
  ---
252
281
 
@@ -282,14 +311,36 @@ The error's composite stack keeps its three sections for async failures too. The
282
311
 
283
312
  | Pattern | Works? | Notes |
284
313
  |---------|--------|-------|
285
- | `define('Name', async function () { ... })` | ✅ | Standard async constructor |
314
+ | `define('Name', async function () { ... })` | ✅ | Standard async constructor — must `return this` |
286
315
  | `define('Name', MyAsyncClass)` | ✅ | Native async class wrapped via `class extends` |
287
- | `await new AsyncType()` | ✅ | Returns resolved instance (with `awaitReturn: true`) |
316
+ | `await new AsyncType()` | ✅ | Returns resolved instance (with `unchain: false`, the default) |
317
+ | `await new AsyncType()` with `unchain: true` | ✅ | A non-object resolution drops the chain — the value is the result |
288
318
  | `await parent.AsyncSubType()` | ✅ | Correct subtype invocation pattern |
289
319
  | `await new AsyncSubType()` | ❌ | Fails `strictChain` — no parent instance |
290
320
  | Native `instanceof` through chain | ⚠️ | Follows mnemonica's graph, not native class hierarchy |
291
321
  | `super()` returning Promise | ✅ | Standard JS; mnemonica's wrapper preserves it |
322
+ | `define('Name', () => { ... })` — arrow, method, bound fn | ❌ | Define-time error: must be a regular function or a class |
323
+ | `define('Name', function* () { ... })` — generators | ❌ | Define-time error: not supported as a constructor |
324
+ | Generators CONSUMING constructions (`yield new X()`) | ✅ | The yielded value is the instance; async generators even resolve un-awaited construction promises |
325
+
326
+ ---
327
+
328
+ ## Detection limits — why mnemonica does not support all function machinery
329
+
330
+ mnemonica classifies construct handlers with two cheap runtime facts only —
331
+ `constructor.name` and own `prototype` — and no `fn.toString()` (overhead,
332
+ and fragile under transpilers). That buys:
333
+
334
+ | Detection | Reliability |
335
+ |-----------|-------------|
336
+ | class vs function (`isClass`) | Partial — syntax-based, unaware of transpiled/polyfilled output |
337
+ | async vs sync (`constructor.name === 'AsyncFunction'`) | ✅ any async form (function, arrow, method) |
338
+ | `async function` vs `async () =>` | ❌ indistinguishable — accepted: async arrows take the async path; write `async function`, use the `no-arrow-this` ESLint plugin |
339
+ | sync arrow / method / bound function (no own `prototype`) | ✅ rejected at define time — the three forms are indistinguishable, all rejected with one readable error |
340
+ | generators / async generators | ✅ rejected at define time as constructor handlers; as CONSUMERS (`yield new X()`, `for await`) they fully work |
341
+ | async getters/setters | ❌ not distinguished — a getter returning an async function looks like a value |
342
+ | transpiled / polyfilled code | Partial — downleveling can rename constructors and erase generator identities (demonstrated: ts-jest at ES6 target turns `async function*` into a plain function); the runtime signals degrade gracefully to the readable errors above |
292
343
 
293
344
  ---
294
345
 
295
- > **Key takeaway:** Async constructors in mnemonica work because mnemonica treats the constructor's return value — Promise or not — as the instance seed. The `class extends` wrapper ensures `super()` propagates the Promise, and mnemonica's async pipeline resolves it into a properly chained instance. Use `parent.AsyncChild()` for subtypes, not standalone `new AsyncChild()`.
346
+ > **Key takeaway:** Async constructors in mnemonica work because mnemonica treats the constructor's return value — Promise or not — as the instance seed. The `class extends` wrapper ensures `super()` propagates the Promise, and mnemonica's async pipeline resolves it into a properly chained instance. Use `parent.AsyncChild()` for subtypes, not standalone `new AsyncChild()`. Write async constructors as `async function` and `return this`.
@@ -17,6 +17,16 @@ TypeScript, however, cannot see a type graph built by runtime calls. There are
17
17
  > types work out of the box. Add the one-line bridge the moment you want free
18
18
  > `lookup()` typed. Reach for Tactica when you need `@decorate()`, or when a
19
19
  > large codebase already uses free `define()` calls everywhere.
20
+ >
21
+ > **The third thing only Tactica solves — async-vs-sync detection.** An async
22
+ > constructor returns a Promise at runtime, but `new` is typed as the finished
23
+ > instance on BOTH builder and free-define paths, and neither TypeScript's
24
+ > checks nor the runtime can see the difference (an async class constructor
25
+ > returning a Promise is invisible to both). Only an AST reader sees it:
26
+ > Tactica detects `async function`/async-class handlers from the source and
27
+ > can type `new` as `Promise<X>` (see [`async-constructors.md`](./async-constructors.md)).
28
+ > Together with `@decorate()` and declaration merging, this is the third
29
+ > capability the builder pattern fundamentally cannot provide.
20
30
 
21
31
  ---
22
32
 
@@ -84,6 +94,16 @@ const user = new User({ name: 'Ada' });
84
94
  const admin = new user.Admin({ role: 'root' });
85
95
  ```
86
96
 
97
+ The types that make this work are a small deliberate public vocabulary —
98
+ the only names a declaration file (`.d.ts`) built on mnemonica ever needs:
99
+
100
+ - `RegistryEntry<Shape, Path>` — what the builder stores per defined path
101
+ and what typed lookups read back;
102
+ - `LookedUpConstructor<Registry, Path>` — the type of a `lookup()` result:
103
+ a constructor whose instances carry their registered subtypes, plus a
104
+ `lookup()` scoped to its own path;
105
+ - `LookedUpInstance<Registry, Path>` — the instance side of the same idea.
106
+
87
107
  ### Custom collections
88
108
 
89
109
  `createTypesCollection()` works the same way and is fully isolated from the default collection.
@@ -160,6 +180,97 @@ Direct `new` on a constructor returned by `.define()` works for **root types** o
160
180
 
161
181
  ---
162
182
 
183
+ ## Declaration emit on TypeScript 6 (the TS2883 symptom)
184
+
185
+ Builder mode compiles cleanly with `declaration: true` on TypeScript 6:
186
+ the exported builder value, `lookup()` results, and instances built
187
+ through them emit declarations that name only the public vocabulary
188
+ above. This is checked by the `test:ts:consumers` suite in the mnemonica
189
+ repository.
190
+
191
+ The compiler error below is **not** a missing export, and adding one is
192
+ never the fix:
193
+
194
+ ```
195
+ error TS2883: The inferred type of 'Widget' cannot be named without a reference
196
+ to 'GlobalRegistry' from '…/mnemonica/build/types'. This is likely not portable.
197
+ A type annotation is necessary.
198
+ ```
199
+
200
+ ### What the error really means
201
+
202
+ The project exports the result of the free `define()` (or of
203
+ `Type.define()`) and uses it as its API:
204
+
205
+ ```typescript
206
+ export const Widget = define('Widget', function (this: WidgetInstance) { … });
207
+ export const Gadget = Widget.define('Gadget', function (this: GadgetInstance) { … });
208
+ ```
209
+
210
+ That path has no `TypeRegistry` augmentation, so everything types through
211
+ the catch-all half of the internal `GlobalRegistry`
212
+ (`TypeRegistry & Record<string, TypeConstructorBase>`). The internal
213
+ registry names stay private on purpose: under TypeScript 6 a project that
214
+ emits declarations cannot name them, and the build fails. That failure
215
+ is the guard rail. Exporting the internals would make the wrong pattern
216
+ compile everywhere, and every project after yours copies it.
217
+
218
+ ### Why this is proven impossible, not just discouraged
219
+
220
+ A free `define()` + free `lookup()` pair cannot be typed without
221
+ declaration merging and without casts — in TypeScript as a language, not
222
+ only in mnemonica. A type never depends on which calls ran: a free
223
+ function's return type depends only on its arguments' types, so
224
+ `lookup('Widget')` sees the literal `'Widget'` and nothing else. The
225
+ only global string→type map TypeScript has is an interface you merge
226
+ into — `TypeRegistry`.
227
+
228
+ Checked against mnemonica (TypeScript 6, no augmentation; `Gadget`
229
+ defined in a separate statement from `Widget`, as projects write it):
230
+
231
+ | form | typed without casts? |
232
+ |---|---|
233
+ | `new Widget(…)`, `new Gadget(…)` — the define() return values | yes |
234
+ | `new widget.Gadget(…)` — construction from a parent instance | **no** — `Property 'Gadget' does not exist on type 'InstanceResult<…>'` |
235
+ | `Widget.lookup('Gadget')` → instance fields | **no** — the instance is an unresolved internal type |
236
+ | free `lookup('Widget')` → instance fields | **no** — the instance is `object` |
237
+
238
+ So the "working" naive path can only use the define() return values — it
239
+ throws away construction from a parent instance, which is what mnemonica
240
+ exists for — or it casts (`as unknown as`), which the mnemonica agent
241
+ guidelines forbid.
242
+
243
+ Checked in plain TypeScript, no mnemonica — three ways to connect a free
244
+ `define()` and `lookup()`:
245
+
246
+ | mechanism | lookup free? | typed without casts? |
247
+ |---|---|---|
248
+ | truly free functions over an implicit registry | yes | **no** — the lookup result is `unknown` |
249
+ | assertion function narrowing an explicit registry (`asserts reg is R & {…}`) | no — the registry is an argument | only after the define call, in the same control flow; `unknown` anywhere else |
250
+ | chained values, each define returning a grown registry type (the builder shape) | no — the value is threaded | yes |
251
+
252
+ Every cast-free option gives up "free". That is why the three typing
253
+ paths exist, and why tactica exists for the free lineage: it generates
254
+ the declaration merge the language requires, derived from the handlers
255
+ so it cannot drift.
256
+
257
+ ### The fixes that ARE right
258
+
259
+ - **Tactica:** run `npx tactica`, include `.tactica/` in the tsconfig, and
260
+ export `lookup('Widget')` results — never the define() results.
261
+ - **Hand-written augmentation:** merge the entries into `TypeRegistry`
262
+ yourself (`test-ts/typed-utils-registry.ts` in the mnemonica repository
263
+ is the pattern) and export `lookup()` results. Works, but the
264
+ hand-written types can drift from the handlers.
265
+ - **Builder mode:** chain `.define()` on `mnemonica`; the exported
266
+ builder value IS the API (registry threading), and declaration emit
267
+ works on TypeScript 6.
268
+
269
+ If none of these fits, ask before changing anything. Never fix this
270
+ symptom with casts, re-exports, or type annotations on the exports.
271
+
272
+ ---
273
+
163
274
  ## Multi-file usage: registry threading
164
275
 
165
276
  **Yes — an exported builder value works across files.** Two reasons:
package/package.json CHANGED
@@ -1,135 +1,137 @@
1
1
  {
2
- "name": "mnemonica",
3
- "version": "1.3.3",
4
- "description": "AI-agent ready instance inheritance system for JavaScript/TypeScript via prototype chains",
5
- "type": "commonjs",
6
- "main": "./build/index.js",
7
- "types": "./build/index.d.ts",
8
- "exports": {
9
- ".": {
10
- "types": "./build/index.d.ts",
11
- "default": "./build/index.js"
12
- },
13
- "./module": {
14
- "types": "./build/index.d.ts",
15
- "import": "./module/index.js",
16
- "browser": "./module/index.js",
17
- "require": "./build/index.js",
18
- "default": "./build/index.js"
19
- },
20
- "./package.json": "./package.json"
21
- },
22
- "files": [
23
- "README.md",
24
- "SKILL.md",
25
- "FOR_HUMANS.md",
26
- "LICENSE",
27
- "docs",
28
- "src",
29
- "module",
30
- "build"
31
- ],
32
- "directories": {
33
- "build": "build/",
34
- "module": "module/"
35
- },
36
- "contributors": [
37
- "laplandin <laplandin.denis@gmail.com>",
38
- "petrgrishin <iam@petrgrishin.com>",
39
- "Mobydack <devzetsubou@gmail.com>"
40
- ],
41
- "scripts": {
42
- "build": "rm -rf ./build && npx tsc --pretty --project tsconfig.json",
43
- "build:all": "npm run build && npm run decorate:ts",
44
- "verify": "npm run build && npm run lint:check",
45
- "example": "npm run build && node ./test/example.js",
46
- "example:async": "npm run build && node ./examples/AsyncNewTest.js",
47
- "example:rename": "npm run build && node ./examples/ClassReName.js",
48
- "example:v8bug": "npm run build && node ./examples/v8bug.js",
49
- "example:ts": "npx tsc --ignoreConfig --noCheck --experimentalDecorators --target ES2021 --module CommonJS ./test-ts/test-decorate.ts ./test-ts/test-decorate-typings.ts ./test-ts/test-example.ts ./test-ts/test-no-types.ts ./test-ts/typed-collections.ts ./test-ts/typed-utils.ts ./test-ts/typed-utils-registry.ts && npx eslint --fix ./test-ts/*.js && node ./test-ts/test-no-types.js && node ./test-ts/test-decorate-typings.js",
50
- "test:ts:strict": "npx tsc -p ./test-ts/tsconfig.strict.json",
51
- "deopt": "node --trace-deopt --trace-opt ./node_modules/mocha/bin/mocha.js ./test/index.js",
52
- "decorate:ts": "npx tsc --ignoreConfig --target ES2021 --moduleResolution NodeNext --module NodeNext --sourceMap ./test/decorate.ts ./test/decorate-builder.ts",
53
- "lint:md": "node scripts/check-published-links.js && find . -name '*.md' -not -path '*/node_modules/*' | xargs markdown-link-check -q --config .markdown-link-check.json",
54
- "lint": "npx eslint",
55
- "lint:check": "npx eslint ./src ./test",
56
- "lint:src": "npx eslint --fix ./src",
57
- "lint:test": "npx eslint --fix ./test",
58
- "lint:fix": "npm run lint:src && npm run lint:test",
59
- "pretest": "npm run decorate:ts",
60
- "test": "mocha --allow-uncaught --enable-source-maps test/index.js",
61
- "test:cov": "npm run build:all && nyc --reporter=text-summary --reporter=lcov mocha --allow-uncaught --enable-source-maps --ui bdd --reporter spec ./test/index.js",
62
- "debug": "npx tsc --pretty --project tsconfig.json && npx mocha --allow-uncaught --enable-source-maps --reporter spec --inspect-brk test/index",
63
- "test:jest": "npx jest",
64
- "test:async_init": "mocha --allow-uncaught test_async/index.js",
65
- "test:jest:cov": "npx jest --collectCoverage",
66
- "test:jest:debug": "npx --node-options=--inspect-brk jest",
67
- "test:mjs": "npm run build && node --experimental-modules ./test/test.mjs",
68
- "watch": "npx tsc --pretty --project tsconfig.json -w",
69
- "prepare": "husky"
70
- },
71
- "repository": {
72
- "type": "git",
73
- "url": "git+https://github.com/wentout/mnemonica.git"
74
- },
75
- "keywords": [
76
- "ETL",
77
- "DFD",
78
- "inheritance",
79
- "instance-inheritance",
80
- "prototype-inheritance",
81
- "prototype-chain",
82
- "typescript",
83
- "nodejs",
84
- "decorator",
85
- "data-flow",
86
- "mnemonica",
87
- "ai-agents",
88
- "agent-ready"
89
- ],
90
- "author": "went.out@gmail.com",
91
- "license": "MIT",
92
- "bugs": {
93
- "url": "https://github.com/wentout/mnemonica/issues"
94
- },
95
- "homepage": "https://github.com/wentout/mnemonica#readme",
96
- "devDependencies": {
97
- "@eslint/eslintrc": "^3.3.7",
98
- "@eslint/js": "^9.21.0",
99
- "@mnemonica/tactica": "^0.1.15",
100
- "@types/jest": "^29.5.14",
101
- "@types/node": "^22.20.4",
102
- "@typescript-eslint/eslint-plugin": "^8.70.1",
103
- "@typescript-eslint/parser": "^8.70.1",
104
- "chai": "^5.3.3",
105
- "eslint": "^9.39.5",
106
- "eslint-plugin-import": "^2.32.0",
107
- "eslint-plugin-mocha": "^10.5.0",
108
- "eslint-plugin-no-arrow-this": "^1.3.0",
109
- "globals": "^15.15.0",
110
- "husky": "^9.1.7",
111
- "jest": "^29.7.0",
112
- "json5": "^2.2.3",
113
- "lint-staged": "^15.5.2",
114
- "markdown-link-check": "^3.15.0",
115
- "mocha": "^11.8.0",
116
- "mocha-lcov-reporter": "^1.3.0",
117
- "nyc": "^17.1.0",
118
- "oxlint": "^0.16.12",
119
- "ts-jest": "^29.4.14",
120
- "typeomatica": "^0.3.63",
121
- "typescript": "^6.0.3"
122
- },
123
- "engines": {
124
- "node": ">=18 <26"
125
- },
126
- "overrides": {
127
- "serialize-javascript": "^7.0.5",
128
- "uuid": "^11.1.1",
129
- "diff": "^9.0.0"
130
- },
131
- "lint-staged": {
132
- "src/**/*.ts": "eslint --fix",
133
- "test/**/*.js": "eslint --fix"
134
- }
2
+ "name": "mnemonica",
3
+ "version": "1.3.6",
4
+ "description": "AI-agent ready instance inheritance system for JavaScript/TypeScript via prototype chains",
5
+ "type": "commonjs",
6
+ "main": "./build/index.js",
7
+ "types": "./build/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./build/index.d.ts",
11
+ "default": "./build/index.js"
12
+ },
13
+ "./module": {
14
+ "types": "./build/index.d.ts",
15
+ "import": "./module/index.js",
16
+ "browser": "./module/index.js",
17
+ "require": "./build/index.js",
18
+ "default": "./build/index.js"
19
+ },
20
+ "./package.json": "./package.json"
21
+ },
22
+ "files": [
23
+ "README.md",
24
+ "SKILL.md",
25
+ "FOR_HUMANS.md",
26
+ "LICENSE",
27
+ "docs",
28
+ "src",
29
+ "module",
30
+ "build"
31
+ ],
32
+ "directories": {
33
+ "build": "build/",
34
+ "module": "module/"
35
+ },
36
+ "contributors": [
37
+ "laplandin <laplandin.denis@gmail.com>",
38
+ "petrgrishin <iam@petrgrishin.com>",
39
+ "Mobydack <devzetsubou@gmail.com>"
40
+ ],
41
+ "scripts": {
42
+ "build": "rm -rf ./build && npx tsc --pretty --project tsconfig.json",
43
+ "build:all": "npm run build && npm run decorate:ts",
44
+ "verify": "npm run build && npm run lint:check",
45
+ "example": "npm run build && node ./test/example.js",
46
+ "example:async": "npm run build && node ./examples/AsyncNewTest.js",
47
+ "example:rename": "npm run build && node ./examples/ClassReName.js",
48
+ "example:v8bug": "npm run build && node ./examples/v8bug.js",
49
+ "example:ts": "npx tsc --ignoreConfig --noCheck --experimentalDecorators --target ES2021 --module CommonJS ./test-ts/test-decorate.ts ./test-ts/test-decorate-typings.ts ./test-ts/test-example.ts ./test-ts/test-no-types.ts ./test-ts/typed-collections.ts ./test-ts/typed-utils.ts ./test-ts/typed-utils-registry.ts && npx eslint --fix ./test-ts/*.js && node ./test-ts/test-no-types.js && node ./test-ts/test-decorate-typings.js",
50
+ "test:ts:strict": "npx tsc -p ./test-ts/tsconfig.strict.json",
51
+ "test:ts:consumers": "node scripts/check-consumers.js",
52
+ "deopt": "node --trace-deopt --trace-opt ./node_modules/mocha/bin/mocha.js ./test/index.js",
53
+ "decorate:ts": "npx tsc --ignoreConfig --target ES2021 --moduleResolution NodeNext --module NodeNext --sourceMap ./test/decorate.ts ./test/decorate-builder.ts",
54
+ "lint:md": "node scripts/check-published-links.js && find . -name '*.md' -not -path '*/node_modules/*' | xargs markdown-link-check -q --config .markdown-link-check.json",
55
+ "lint": "npx eslint",
56
+ "lint:check": "npx eslint ./src ./test",
57
+ "lint:src": "npx eslint --fix ./src",
58
+ "lint:test": "npx eslint --fix ./test",
59
+ "lint:fix": "npm run lint:src && npm run lint:test",
60
+ "pretest": "npm run decorate:ts",
61
+ "test": "mocha --allow-uncaught --enable-source-maps test/index.js",
62
+ "test:cov": "npm run build:all && nyc --reporter=text-summary --reporter=lcov mocha --allow-uncaught --enable-source-maps --ui bdd --reporter spec ./test/index.js",
63
+ "debug": "npx tsc --pretty --project tsconfig.json && npx mocha --allow-uncaught --enable-source-maps --reporter spec --inspect-brk test/index",
64
+ "test:jest": "npx jest",
65
+ "test:async_init": "mocha --allow-uncaught test_async/index.js",
66
+ "test:yields": "mocha --allow-uncaught test_yields/index.js",
67
+ "test:jest:cov": "npx jest --collectCoverage",
68
+ "test:jest:debug": "npx --node-options=--inspect-brk jest",
69
+ "test:mjs": "npm run build && node --experimental-modules ./test/test.mjs",
70
+ "watch": "npx tsc --pretty --project tsconfig.json -w",
71
+ "prepare": "husky"
72
+ },
73
+ "repository": {
74
+ "type": "git",
75
+ "url": "git+https://github.com/wentout/mnemonica.git"
76
+ },
77
+ "keywords": [
78
+ "ETL",
79
+ "DFD",
80
+ "inheritance",
81
+ "instance-inheritance",
82
+ "prototype-inheritance",
83
+ "prototype-chain",
84
+ "typescript",
85
+ "nodejs",
86
+ "decorator",
87
+ "data-flow",
88
+ "mnemonica",
89
+ "ai-agents",
90
+ "agent-ready"
91
+ ],
92
+ "author": "went.out@gmail.com",
93
+ "license": "MIT",
94
+ "bugs": {
95
+ "url": "https://github.com/wentout/mnemonica/issues"
96
+ },
97
+ "homepage": "https://github.com/wentout/mnemonica#readme",
98
+ "devDependencies": {
99
+ "@eslint/eslintrc": "^3.3.7",
100
+ "@eslint/js": "^9.21.0",
101
+ "@mnemonica/tactica": "^0.4.4",
102
+ "@types/jest": "^29.5.14",
103
+ "@types/node": "^22.20.4",
104
+ "@typescript-eslint/eslint-plugin": "^8.70.1",
105
+ "@typescript-eslint/parser": "^8.70.1",
106
+ "chai": "^5.3.3",
107
+ "eslint": "^9.39.5",
108
+ "eslint-plugin-import": "^2.32.0",
109
+ "eslint-plugin-mocha": "^10.5.0",
110
+ "eslint-plugin-no-arrow-this": "^1.3.0",
111
+ "globals": "^15.15.0",
112
+ "husky": "^9.1.7",
113
+ "jest": "^29.7.0",
114
+ "json5": "^2.2.3",
115
+ "lint-staged": "^15.5.2",
116
+ "markdown-link-check": "^3.15.0",
117
+ "mocha": "^11.8.0",
118
+ "mocha-lcov-reporter": "^1.3.0",
119
+ "nyc": "^17.1.0",
120
+ "oxlint": "^0.16.12",
121
+ "ts-jest": "^29.4.14",
122
+ "typeomatica": "^0.3.63",
123
+ "typescript": "^6.0.3"
124
+ },
125
+ "engines": {
126
+ "node": ">=18 <26"
127
+ },
128
+ "overrides": {
129
+ "serialize-javascript": "^7.0.5",
130
+ "uuid": "^11.1.1",
131
+ "diff": "^9.0.0"
132
+ },
133
+ "lint-staged": {
134
+ "src/**/*.ts": "eslint --fix",
135
+ "test/**/*.js": "eslint --fix"
136
+ }
135
137
  }
@@ -248,26 +248,32 @@ const makeAwaiter = function ( this: InstanceCreatorContext, type: TypeDef, then
248
248
  self.inheritedInstance = (self.inheritedInstance as Promise<object>)
249
249
  .then( ( instance: unknown ) => {
250
250
 
251
- if ( typeof instance !== 'object' ) {
252
- if ( self.config.awaitReturn ) {
253
- const msg = `should inherit from ${type.TypeName}: ` +
254
- `seems async ${type.TypeName} has no return statement`;
251
+ // null has typeof 'object' in JS, but for the unchain decision it
252
+ // is a VALUE like any other non-object: with unchain:true it
253
+ // resolves as-is; with the default it takes the readable
254
+ // mnemonica error below — never the internal TypeError from
255
+ // reading `.constructor` of null
256
+ if ( typeof instance !== 'object' || instance === null ) {
257
+ if ( self.config.unchain ) {
258
+ return instance;
259
+ } else {
260
+ const msg = `async constructor ${type.TypeName} must \`return this\` ` +
261
+ `(it resolved to ${String( instance )})`;
255
262
  throw new WRONG_MODIFICATION_PATTERN(
256
263
  msg,
257
- self.stack
264
+ self.stack
258
265
  );
259
- } else {
260
- return instance;
261
266
  }
262
267
  }
263
268
 
264
- if ( instance === null || !( instance instanceof self.type ) ) {
265
-
269
+ if ( !( instance instanceof self.type ) ) {
270
+
266
271
  const icn = (instance as object).constructor.name;
267
- const msg = `should inherit from ${type.TypeName} but got ${icn}`;
272
+ const msg = `async constructor ${type.TypeName} must resolve to its own instance ` +
273
+ `(\`return this\`), got ${icn}`;
268
274
  throw new WRONG_MODIFICATION_PATTERN(
269
275
  msg,
270
- self.stack
276
+ self.stack
271
277
  );
272
278
  }
273
279
 
@@ -1,6 +1,9 @@
1
1
  'use strict';
2
2
 
3
3
  import { hop } from '../../utils/hop';
4
+ import { ErrorsTypes } from '../../descriptors/errors';
5
+
6
+ const { WRONG_MODIFICATION_PATTERN, } = ErrorsTypes;
4
7
  /*
5
8
 
6
9
  // it is not that easy
@@ -47,6 +50,37 @@ export interface CreationHandler extends CallableFunction {
47
50
  (this: object, answer: unknown): unknown;
48
51
  }
49
52
 
53
+ // Classify the construct handler ONCE at define time from two cheap
54
+ // facts only — constructor.name and own prototype — NO toString()
55
+ // (overhead, fragile under transpilers). Async forms are NOT
56
+ // separable beyond 'AsyncFunction' (async arrows and async methods
57
+ // take the async path, accepted by design); a sync Function without
58
+ // its own prototype is a sync arrow, a shorthand method or a bound
59
+ // function — the three are indistinguishable here and all are
60
+ // rejected with the readable error (the docs: write constructors as
61
+ // regular functions or classes).
62
+ export const classifyConstructHandler = ( FunctionName: string, ConstructHandler: ConstructHandler ) => {
63
+ const handlerKind = ConstructHandler.constructor.name;
64
+ const hasOwnPrototype = hop(
65
+ ConstructHandler,
66
+ 'prototype'
67
+ );
68
+
69
+ if (
70
+ handlerKind === 'GeneratorFunction' ||
71
+ handlerKind === 'AsyncGeneratorFunction'
72
+ ) {
73
+ const msg = `${FunctionName}: generator functions are not supported as a constructor`;
74
+ throw new WRONG_MODIFICATION_PATTERN( msg );
75
+ }
76
+
77
+ if ( handlerKind === 'Function' && !hasOwnPrototype ) {
78
+ const msg = `${FunctionName}: constructor must be a regular function or a class ` +
79
+ '(arrow functions, methods and bound functions are not supported)';
80
+ throw new WRONG_MODIFICATION_PATTERN( msg );
81
+ }
82
+ };
83
+
50
84
  const getClassConstructor = (
51
85
  ConstructHandler: ClassConstructHandler,
52
86
  CreationHandler: CreationHandler,