mnemonica 1.3.6 → 1.3.8

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 (52) hide show
  1. package/FOR_HUMANS.md +17 -2
  2. package/build/api/errors/exceptionConstructor.js +3 -3
  3. package/build/api/errors/index.js +1 -1
  4. package/build/api/errors/throwModificationError.js +1 -1
  5. package/build/api/hooks/flowCheckers.d.ts +1 -1
  6. package/build/api/hooks/flowCheckers.js +1 -1
  7. package/build/api/hooks/invokeHook.js +1 -1
  8. package/build/api/types/InstanceCreator.js +26 -9
  9. package/build/api/types/InstanceModificator.js +6 -3
  10. package/build/api/types/TypeProxy.js +2 -2
  11. package/build/api/types/compileNewModificatorFunctionBody.js +1 -1
  12. package/build/api/types/index.js +18 -5
  13. package/build/constants/index.js +4 -1
  14. package/build/descriptors/errors/index.js +1 -1
  15. package/build/descriptors/types/index.js +14 -1
  16. package/build/index.js +6 -7
  17. package/build/types/index.d.ts +47 -2
  18. package/build/types/index.js +1 -1
  19. package/build/utils/deepParse.d.ts +2 -0
  20. package/build/utils/deepParse.js +21 -0
  21. package/build/utils/index.js +5 -1
  22. package/build/utils/lineage.d.ts +2 -0
  23. package/build/utils/lineage.js +156 -0
  24. package/build/utils/parent.d.ts +1 -1
  25. package/build/utils/parent.js +9 -4
  26. package/build/utils/parse.d.ts +3 -2
  27. package/build/utils/parse.js +19 -6
  28. package/build/utils/toJSON.js +21 -18
  29. package/docs/UTILS.md +86 -9
  30. package/docs/async-constructors.md +6 -0
  31. package/package.json +4 -2
  32. package/src/api/errors/exceptionConstructor.ts +7 -5
  33. package/src/api/errors/index.ts +5 -1
  34. package/src/api/errors/throwModificationError.ts +1 -1
  35. package/src/api/hooks/flowCheckers.ts +3 -1
  36. package/src/api/hooks/invokeHook.ts +1 -1
  37. package/src/api/types/InstanceCreator.ts +45 -12
  38. package/src/api/types/InstanceModificator.ts +19 -4
  39. package/src/api/types/TypeProxy.ts +11 -2
  40. package/src/api/types/compileNewModificatorFunctionBody.ts +6 -0
  41. package/src/api/types/index.ts +58 -5
  42. package/src/constants/index.ts +6 -0
  43. package/src/descriptors/errors/index.ts +3 -0
  44. package/src/descriptors/types/index.ts +24 -1
  45. package/src/index.ts +33 -14
  46. package/src/types/index.ts +75 -3
  47. package/src/utils/deepParse.ts +28 -0
  48. package/src/utils/index.ts +7 -0
  49. package/src/utils/lineage.ts +220 -0
  50. package/src/utils/parent.ts +20 -5
  51. package/src/utils/parse.ts +42 -6
  52. package/src/utils/toJSON.ts +35 -36
@@ -0,0 +1,28 @@
1
+ 'use strict';
2
+
3
+ import { parse } from './parse';
4
+ import type { Parsed } from '../types';
5
+
6
+ // the lineage walker (lineage-export plan, layer 2): from the instance to
7
+ // its root through the REAL parent instances — parse().parent hops directly
8
+ // from instance to instance, so the per-type prototype layers between them
9
+ // never enter the picture. The result is the ordered list of parsed levels,
10
+ // index 0 being the instance itself, the last level its root (parent null).
11
+ export const deepParse = <T extends object>( instance: T ): Array<Parsed<T>> => {
12
+
13
+ const levels: Array<Parsed<object>> = [];
14
+ let current: object = instance;
15
+ for ( ;; ) {
16
+ const parsed: Parsed<object> = parse( current );
17
+ levels.push( parsed );
18
+ const next: object | null = parsed.parent;
19
+ if ( next === null ) {
20
+ break;
21
+ }
22
+ current = next;
23
+ }
24
+
25
+ const result = levels as Array<Parsed<T>>;
26
+ return result;
27
+
28
+ };
@@ -15,6 +15,8 @@ import { fork } from './fork';
15
15
  import { clone } from './clone';
16
16
  import { toJSON } from './toJSON';
17
17
  import { parse } from './parse';
18
+ import { deepParse } from './deepParse';
19
+ import { lineage } from './lineage';
18
20
  import { merge } from './merge';
19
21
 
20
22
  const utilsUnWrapped = {
@@ -31,6 +33,8 @@ const utilsUnWrapped = {
31
33
  toJSON,
32
34
 
33
35
  parse,
36
+ deepParse,
37
+ lineage,
34
38
  merge,
35
39
 
36
40
  collectConstructors,
@@ -42,6 +46,9 @@ const wrapThis = ( method: WrappableMethod ) => {
42
46
  const instanceContext = instance !== undefined ? instance : this;
43
47
  let wrapResult: unknown;
44
48
  if ( new.target ) {
49
+ // wrapThis forwards `new` to the util; WrappableMethod (a plain
50
+ // function type) declares no construct signature, so the cast
51
+ // bridges that construct call
45
52
  wrapResult = new (method as unknown as new (...a: unknown[]) => unknown)(
46
53
  instanceContext,
47
54
  ...args
@@ -0,0 +1,220 @@
1
+ 'use strict';
2
+
3
+ // utils.lineage — the lineage walker (lineage-export plan, layer 3).
4
+ // Exports the lineage graph of the given instances in the lethe format —
5
+ // the cross-language contract (@mnemonica/lethe): what survives when live
6
+ // instances are forgotten. Built on the parse() primitive (the one-level
7
+ // snapshot deepParse walks): the recursion follows parse().parent, the
8
+ // REAL parent-instance links, so the per-type prototype hops never appear.
9
+
10
+ import { parse } from './parse';
11
+ import {
12
+ _getProps as getPropsRef, Props
13
+ } from '../api/types/Props';
14
+ import { constants } from '../constants';
15
+
16
+ const { SymbolConfig } = constants;
17
+
18
+ import type {
19
+ LineageGraph,
20
+ LineageNode,
21
+ LineageOptions,
22
+ LineageValue
23
+ } from '../types';
24
+
25
+ // Instance ids are implementation-specific by contract: a per-realm random
26
+ // prefix plus a process-local counter, held in a WeakMap — stable within
27
+ // one realm, never reused, nothing retained, and never compared across
28
+ // processes or languages (the fixture comparison maps them 1:1 in
29
+ // first-encounter order — see @mnemonica/lethe testdata README)
30
+ const realmPrefix = Math.random().toString( 16 )
31
+ .slice( 2, 10 );
32
+ let idCounter = 0;
33
+ const instanceIds = new WeakMap<object, string>();
34
+ const idOf = ( instance: object ): string => {
35
+ let id = instanceIds.get( instance );
36
+ if ( id === undefined ) {
37
+ idCounter += 1;
38
+ id = `${realmPrefix}:${idCounter}`;
39
+ instanceIds.set( instance, id );
40
+ }
41
+ return id;
42
+ };
43
+
44
+ const unsupported = ( kind: string ): LineageValue => {
45
+ const result: LineageValue = {
46
+ '$mnemonica' : 'unsupported',
47
+ kind
48
+ };
49
+ return result;
50
+ };
51
+
52
+ const isInstance = ( value: object ): boolean => {
53
+ const instanceCheck = getPropsRef( value ) !== undefined;
54
+ return instanceCheck;
55
+ };
56
+
57
+ export const lineage = ( instances: object[], options?: LineageOptions ): LineageGraph => {
58
+
59
+ const nodes: Record<string, LineageNode> = {};
60
+ const nodePaths: Record<string, string> = {};
61
+ const visiting = new Set<string>();
62
+
63
+ const exportValue = ( value: unknown, seen: Set<unknown> ): LineageValue => {
64
+
65
+ if ( value === null || value === undefined ) {
66
+ return null;
67
+ }
68
+
69
+ if ( typeof value === 'boolean' || typeof value === 'string' ) {
70
+ return value;
71
+ }
72
+
73
+ if ( typeof value === 'number' ) {
74
+ if ( Number.isNaN( value ) ) {
75
+ const nanResult = unsupported( 'nan' );
76
+ return nanResult;
77
+ }
78
+ if ( value === Infinity ) {
79
+ const infResult = unsupported( '+inf' );
80
+ return infResult;
81
+ }
82
+ if ( value === -Infinity ) {
83
+ const ninfResult = unsupported( '-inf' );
84
+ return ninfResult;
85
+ }
86
+ return value;
87
+ }
88
+
89
+ // the schema's kind enum is the cross-language set: JS-only shapes
90
+ // (symbols, bigints) report as 'invalid' — never an error
91
+ if ( typeof value === 'bigint' || typeof value === 'symbol' ) {
92
+ const invalidResult = unsupported( 'invalid' );
93
+ return invalidResult;
94
+ }
95
+ if ( typeof value === 'function' ) {
96
+ const funcResult = unsupported( 'func' );
97
+ return funcResult;
98
+ }
99
+
100
+ // a field holding another mnemonica instance exports as $ref; the
101
+ // referenced instance joins the graph at first encounter
102
+ if ( isInstance( value as object ) ) {
103
+ const refResult: LineageValue = {
104
+ $ref : visit( value as object )
105
+ };
106
+ return refResult;
107
+ }
108
+
109
+ if ( seen.has( value ) ) {
110
+ const cycleResult = unsupported( 'cycle' );
111
+ return cycleResult;
112
+ }
113
+ seen.add( value );
114
+
115
+ let objectResult: LineageValue;
116
+ if ( Array.isArray( value ) ) {
117
+ const arrayResult: LineageValue[] = [];
118
+ value.forEach( ( item ) => {
119
+ arrayResult.push( exportValue( item, seen ) );
120
+ } );
121
+ objectResult = arrayResult;
122
+ } else {
123
+ const recordResult: { [ key: string ]: LineageValue } = {};
124
+ Object.keys( value as object ).forEach( ( key ) => {
125
+ recordResult[ key ] = exportValue(
126
+ ( value as Record<string, unknown> )[ key ],
127
+ seen
128
+ );
129
+ } );
130
+ objectResult = recordResult;
131
+ }
132
+ seen.delete( value );
133
+ return objectResult;
134
+ };
135
+
136
+ const visit = ( instance: object ): string => {
137
+
138
+ const id = idOf( instance );
139
+ // dedup at any depth; the visiting set also breaks instance-valued
140
+ // field cycles (a field pointing at its own instance)
141
+ if ( nodes[ id ] !== undefined || visiting.has( id ) ) {
142
+ return id;
143
+ }
144
+ visiting.add( id );
145
+
146
+ const parsed = parse( instance );
147
+
148
+ // own fields in declaration order FIRST — a $ref target is exported
149
+ // at first encounter, before the parent link (the encounter order
150
+ // the cross-language comparison maps ids by)
151
+ const own: { [ key: string ]: LineageValue } = {};
152
+ const ownProps = parsed.props as Record<string, unknown>;
153
+ Object.keys( ownProps ).forEach( ( key ) => {
154
+ own[ key ] = exportValue( ownProps[ key ], new Set() );
155
+ } );
156
+
157
+ const baseProps = getPropsRef( instance ) as Props;
158
+
159
+ let nodeArgs: LineageValue | undefined;
160
+ if ( options && options.args ) {
161
+ nodeArgs = exportValue( baseProps.__args__, new Set() );
162
+ }
163
+
164
+ let nodeProps: { [ key: string ]: LineageValue } | undefined;
165
+ if ( options && Array.isArray( options.props ) ) {
166
+ nodeProps = {};
167
+ options.props.forEach( ( key ) => {
168
+ nodeProps![ key ] = exportValue( baseProps[ key ], new Set() );
169
+ } );
170
+ }
171
+
172
+ // then the parent — the type path is the parent's path plus this
173
+ // level's name (names alone collide across levels and collections)
174
+ let parentId: string | null = null;
175
+ let path = parsed.name;
176
+ if ( parsed.parent !== null ) {
177
+ parentId = visit( parsed.parent );
178
+ path = `${nodePaths[ parentId ]}.${parsed.name}`;
179
+ }
180
+
181
+ const { __collection__: collection } = baseProps;
182
+ // every collection carries a name by construction (the default
183
+ // collection is 'defaultTypes', unnamed customs are auto-named), so
184
+ // no fallback is needed here
185
+ const collectionConfig = ( collection as unknown as { [ SymbolConfig ]?: { name?: string } } )[
186
+ SymbolConfig
187
+ ]!;
188
+ const collectionName: string = collectionConfig.name!;
189
+
190
+ const node: LineageNode = {
191
+ type : {
192
+ collection : collectionName,
193
+ path
194
+ },
195
+ own,
196
+ parent : parentId
197
+ };
198
+ if ( nodeArgs !== undefined ) {
199
+ node.args = nodeArgs;
200
+ }
201
+ if ( nodeProps !== undefined ) {
202
+ node.props = nodeProps;
203
+ }
204
+
205
+ nodes[ id ] = node;
206
+ nodePaths[ id ] = path;
207
+ visiting.delete( id );
208
+ return id;
209
+ };
210
+
211
+ const heads = instances.map( ( instance ) => visit( instance ) );
212
+
213
+ const result: LineageGraph = {
214
+ version : '1',
215
+ heads,
216
+ nodes
217
+ };
218
+ return result;
219
+
220
+ };
@@ -15,13 +15,13 @@ import {
15
15
  // seek for firts parent instance
16
16
  // of instance prototype chain
17
17
  // with constructors of path
18
- export function parent <T extends object> (instance: T): object | undefined;
18
+ export function parent <T extends object> (instance: T): object | null;
19
19
  export function parent <T extends object, K extends ParentPathOfInstance<T> & string> (
20
20
  instance: T,
21
21
  path: K
22
22
  ): InstanceOfTypeRegistry<K> | undefined;
23
23
  export function parent (instance: object, path: string): object | undefined;
24
- export function parent <T extends object> (instance: T, path?: string): object | undefined {
24
+ export function parent <T extends object> (instance: T, path?: string): object | null | undefined {
25
25
 
26
26
  // at this situation this check is enough
27
27
  if ( instance !== Object( instance ) ) {
@@ -30,14 +30,29 @@ export function parent <T extends object> (instance: T, path?: string): object |
30
30
 
31
31
  const props = _getProps(instance) as Props;
32
32
 
33
+ // no construction props at all — nothing to seek from. NO PARENT IS
34
+ // null (object-typed, the end of a chain — like Object.getPrototypeOf
35
+ // at the top); undefined is reserved for the path form's "searched,
36
+ // not found" — and a props-less object cannot match any path either
33
37
  if ( !props ) {
34
- return;
38
+ const result = path ? undefined : null;
39
+ return result;
35
40
  }
36
41
 
37
42
  const { __parent__: p } = props;
38
43
 
44
+ // a root instance's __parent__ points at mnemonica's internal root
45
+ // sentinel (an object with no construction props of its own) — that
46
+ // means there is no parent: null, not the sentinel itself
47
+ const parentInstance: object | null = p && _getProps( p ) ? p : null;
48
+
39
49
  if ( !path ) {
40
- return p;
50
+ return parentInstance;
51
+ }
52
+
53
+ if ( !parentInstance ) {
54
+ // searched (the chain exists) — nothing found
55
+ return;
41
56
  }
42
57
 
43
58
  const segments = path.split('.');
@@ -49,7 +64,7 @@ export function parent <T extends object> (instance: T, path?: string): object |
49
64
  // each leading segment must be the direct parent
50
65
  // of the instance matched by the next one,
51
66
  // and the instance itself is never a candidate
52
- let current = p as object;
67
+ let current = parentInstance;
53
68
  for ( ;; ) {
54
69
 
55
70
  const { constructor: { name } } = current as { constructor: { name: string } };
@@ -14,9 +14,32 @@ const {
14
14
  // } = constants;
15
15
 
16
16
  import { extract } from './extract';
17
- import type { Parsed } from '../types';
18
-
19
- export const parse = <T extends object>( self: T ): Parsed<T> => {
17
+ import type {
18
+ EmptyParsed, Parsed
19
+ } from '../types';
20
+
21
+ import {
22
+ _getProps, Props
23
+ } from '../api/types/Props';
24
+
25
+ export function parse<T extends object>( self: T ): Parsed<T>;
26
+ export function parse( self: null ): EmptyParsed;
27
+ export function parse<T extends object> ( self: T | null ): Parsed<T> | EmptyParsed {
28
+
29
+ if ( self === null ) {
30
+ // null is the one non-object input parse accepts: the empty shape —
31
+ // nothing was given. undefined and every other non-object keep
32
+ // throwing WRONG_MODIFICATION_PATTERN
33
+ const nullResult: EmptyParsed = {
34
+ name : undefined,
35
+ props : {},
36
+ self : null,
37
+ proto : undefined,
38
+ joint : {},
39
+ parent : undefined
40
+ };
41
+ return nullResult;
42
+ }
20
43
 
21
44
  if ( !self || !( self as { constructor?: CallableFunction } ).constructor ) {
22
45
  throw new WRONG_MODIFICATION_PATTERN;
@@ -58,14 +81,27 @@ export const parse = <T extends object>( self: T ): Parsed<T> => {
58
81
  ) as Record<string, unknown> );
59
82
  delete ( joint as { constructor?: unknown } ).constructor;
60
83
 
61
- const parent = protoProto as object | undefined;
62
- // TODO: deep parse
84
+ // parent is the PARENT INSTANCE — the same object utils.parent(self)
85
+ // returns (the __parent__ record of the construction props), not a
86
+ // prototype layer. A root instance's __parent__ points at mnemonica's
87
+ // internal root sentinel (an object with no construction props of its
88
+ // own) — parse reports NO parent for it, and NO PARENT IS null
89
+ // (object-typed, the end of a chain — like Object.getPrototypeOf at the
90
+ // top). Walking the whole lineage level by level is what
91
+ // utils.deepParse does — this function stays the one-level primitive.
92
+
93
+ // The explored recursive-parse alternative, kept as the record of what
94
+ // was considered before deepParse became the plan's next step:
63
95
  // let parent;
64
96
  // if ( protoProto[ SymbolConstructorName ] === MNEMONICA ) {
65
97
  // parent = parse( protoProto );
66
98
  // } else {
67
99
  // parent = Reflect.getPrototypeOf( protoProto );
68
100
  // }
101
+ const selfProps = _getProps( self ) as Props | undefined;
102
+ const parentRecord = selfProps ? selfProps.__parent__ : undefined;
103
+ const parent: object | null =
104
+ parentRecord && _getProps( parentRecord ) ? parentRecord : null;
69
105
 
70
106
  const result: Parsed<T> = {
71
107
 
@@ -83,4 +119,4 @@ export const parse = <T extends object>( self: T ): Parsed<T> => {
83
119
 
84
120
  };
85
121
  return result;
86
- };
122
+ }
@@ -1,45 +1,44 @@
1
1
  'use strict';
2
2
 
3
3
  import { extract } from './extract';
4
- export const toJSON = <T extends object>( instance: T ) => {
5
-
6
- const extracted = extract( instance );
7
- const result = Object.entries( extracted ).reduce(
8
- ( o: string, entry: [ string, unknown ] ) => {
9
-
10
- const [ name, _value ] = entry;
11
- if ( [ null, undefined ].includes( _value as null | undefined ) ) {
12
- return o;
13
- }
14
-
15
- let value: string;
16
4
 
17
- try {
18
- value = JSON.stringify( _value );
19
- } catch ( error: unknown ) {
20
- const description = 'This value type is not supported by JSON.stringify';
21
- const {
22
- stack,
23
- message
24
- } = error as Error;
25
-
26
- value = JSON.stringify( {
27
- description,
28
- stack,
29
- message
30
- } );
31
- }
5
+ const descriptionOf = ( error: unknown ) => {
6
+ const {
7
+ stack,
8
+ message
9
+ } = error as Error;
10
+ const description = {
11
+ description : 'This value type is not supported by JSON.stringify',
12
+ stack,
13
+ message
14
+ };
15
+ return description;
16
+ };
32
17
 
33
- o += `"${name}":${value},`;
34
- return o;
18
+ export const toJSON = <T extends object>( instance: T ) => {
35
19
 
36
- },
37
- '{'
38
- )
39
- .replace(
40
- /,$/,
41
- '}'
42
- );
20
+ const extracted = extract( instance );
21
+ // collect the fields into a plain object and stringify ONCE: the output
22
+ // is always valid JSON — keys escaped by the serializer itself, empty
23
+ // field sets become '{}', null/undefined fields omitted
24
+ const collected: Record<string, unknown> = {};
25
+ Object.entries( extracted ).forEach( ( [ name, value ] ) => {
26
+ if ( value === null || value === undefined ) {
27
+ return;
28
+ }
29
+ let checked: unknown;
30
+ try {
31
+ const probe = JSON.stringify( value );
32
+ // stringify returns undefined (no throw) for values JSON has no
33
+ // representation of — functions, symbols: unstringifiable too
34
+ checked = probe === undefined ? descriptionOf( value ) : value;
35
+ } catch ( error: unknown ) {
36
+ checked = descriptionOf( error );
37
+ }
38
+ collected[ name ] = checked;
39
+ } );
40
+
41
+ const result = JSON.stringify( collected );
43
42
  return result;
44
43
 
45
44
  };