arktype 0.6.0 → 1.0.1-alpha

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 (82) hide show
  1. package/README.md +4 -2
  2. package/dist/api.cjs +2 -2
  3. package/dist/api.d.ts +2 -1
  4. package/dist/api.mjs +1 -1
  5. package/dist/cjs/nodes/compose.js +4 -4
  6. package/dist/cjs/nodes/discriminate.js +1 -1
  7. package/dist/cjs/nodes/node.js +30 -22
  8. package/dist/cjs/nodes/predicate.js +0 -1
  9. package/dist/cjs/nodes/rules/range.js +3 -3
  10. package/dist/cjs/parse/ast/config.js +4 -6
  11. package/dist/cjs/parse/ast/distributableFunction.js +6 -6
  12. package/dist/cjs/parse/ast/intersection.js +2 -2
  13. package/dist/cjs/parse/ast/keyof.js +3 -3
  14. package/dist/cjs/parse/ast/morph.js +2 -1
  15. package/dist/cjs/parse/ast/narrow.js +8 -1
  16. package/dist/cjs/parse/definition.js +2 -2
  17. package/dist/cjs/parse/string/reduce/dynamic.js +1 -1
  18. package/dist/cjs/parse/string/shift/operand/unenclosed.js +1 -1
  19. package/dist/cjs/parse/string/shift/scanner.js +1 -1
  20. package/dist/cjs/parse/string/string.js +2 -2
  21. package/dist/cjs/scopes/ark.js +6 -6
  22. package/dist/cjs/scopes/scope.js +47 -59
  23. package/dist/cjs/scopes/type.js +19 -14
  24. package/dist/cjs/scopes/validation/date.js +2 -3
  25. package/dist/cjs/scopes/validation/validation.js +14 -0
  26. package/dist/cjs/traverse/problems.js +3 -3
  27. package/dist/cjs/traverse/traverse.js +21 -3
  28. package/dist/cjs/utils/data.js +1 -1
  29. package/dist/cjs/utils/generics.js +16 -0
  30. package/dist/cjs/utils/serialize.js +29 -53
  31. package/dist/mjs/nodes/compose.js +5 -5
  32. package/dist/mjs/nodes/discriminate.js +1 -1
  33. package/dist/mjs/nodes/node.js +28 -22
  34. package/dist/mjs/nodes/predicate.js +0 -1
  35. package/dist/mjs/nodes/rules/range.js +3 -3
  36. package/dist/mjs/parse/ast/config.js +4 -6
  37. package/dist/mjs/parse/ast/distributableFunction.js +6 -6
  38. package/dist/mjs/parse/ast/intersection.js +2 -2
  39. package/dist/mjs/parse/ast/keyof.js +3 -3
  40. package/dist/mjs/parse/ast/morph.js +2 -1
  41. package/dist/mjs/parse/ast/narrow.js +9 -2
  42. package/dist/mjs/parse/definition.js +2 -2
  43. package/dist/mjs/parse/string/reduce/dynamic.js +1 -1
  44. package/dist/mjs/parse/string/shift/operand/unenclosed.js +1 -1
  45. package/dist/mjs/parse/string/shift/scanner.js +1 -1
  46. package/dist/mjs/parse/string/string.js +2 -2
  47. package/dist/mjs/scopes/ark.js +5 -5
  48. package/dist/mjs/scopes/scope.js +48 -60
  49. package/dist/mjs/scopes/type.js +16 -13
  50. package/dist/mjs/scopes/validation/date.js +2 -3
  51. package/dist/mjs/scopes/validation/validation.js +14 -0
  52. package/dist/mjs/traverse/problems.js +3 -3
  53. package/dist/mjs/traverse/traverse.js +21 -3
  54. package/dist/mjs/utils/data.js +1 -1
  55. package/dist/mjs/utils/generics.js +11 -0
  56. package/dist/mjs/utils/serialize.js +29 -52
  57. package/dist/tsconfig.temp.tsbuildinfo +1 -1
  58. package/dist/types/nodes/branch.d.ts +5 -3
  59. package/dist/types/nodes/node.d.ts +15 -8
  60. package/dist/types/nodes/predicate.d.ts +3 -3
  61. package/dist/types/nodes/rules/props.d.ts +8 -8
  62. package/dist/types/parse/ast/distributableFunction.d.ts +1 -1
  63. package/dist/types/parse/ast/intersection.d.ts +2 -2
  64. package/dist/types/parse/ast/morph.d.ts +3 -5
  65. package/dist/types/parse/ast/node.d.ts +6 -7
  66. package/dist/types/parse/ast/tuple.d.ts +4 -4
  67. package/dist/types/parse/definition.d.ts +2 -2
  68. package/dist/types/parse/string/reduce/dynamic.d.ts +5 -5
  69. package/dist/types/parse/string/shift/scanner.d.ts +1 -1
  70. package/dist/types/parse/string/string.d.ts +3 -3
  71. package/dist/types/scopes/ark.d.ts +28 -103
  72. package/dist/types/scopes/expressions.d.ts +9 -9
  73. package/dist/types/scopes/scope.d.ts +11 -10
  74. package/dist/types/scopes/type.d.ts +23 -14
  75. package/dist/types/scopes/validation/date.d.ts +1 -1
  76. package/dist/types/scopes/validation/validation.d.ts +10 -6
  77. package/dist/types/traverse/problems.d.ts +3 -3
  78. package/dist/types/traverse/traverse.d.ts +8 -68
  79. package/dist/types/utils/data.d.ts +2 -2
  80. package/dist/types/utils/generics.d.ts +5 -0
  81. package/dist/types/utils/serialize.d.ts +0 -1
  82. package/package.json +15 -15
@@ -4,12 +4,12 @@ import { parseOperand } from "./shift/operand/operand.js";
4
4
  import { parseOperator } from "./shift/operator/operator.js";
5
5
  export const parseString = (def, ctx)=>ctx.type.scope.parseCache.get(def) ?? ctx.type.scope.parseCache.set(def, maybeNaiveParse(def, ctx) ?? fullStringParse(def, ctx));
6
6
  export const maybeNaiveParse = (def, ctx)=>{
7
- if (ctx.type.scope.addReferenceIfResolvable(def, ctx)) {
7
+ if (ctx.type.scope.addParsedReferenceIfResolvable(def, ctx)) {
8
8
  return def;
9
9
  }
10
10
  if (def.endsWith("[]")) {
11
11
  const elementDef = def.slice(0, -2);
12
- if (ctx.type.scope.addReferenceIfResolvable(def, ctx)) {
12
+ if (ctx.type.scope.addParsedReferenceIfResolvable(def, ctx)) {
13
13
  return toArrayNode(elementDef);
14
14
  }
15
15
  }
@@ -2,7 +2,7 @@ import { jsObjects, jsObjectsScope } from "./jsObjects.js";
2
2
  import { rootScope, scope } from "./scope.js";
3
3
  import { tsKeywords, tsKeywordsScope } from "./tsKeywords.js";
4
4
  import { validation, validationScope } from "./validation/validation.js";
5
- export const ark = scope({}, {
5
+ export const arkscope = scope({}, {
6
6
  name: "standard",
7
7
  includes: [
8
8
  tsKeywords,
@@ -11,18 +11,18 @@ export const ark = scope({}, {
11
11
  ],
12
12
  standard: false
13
13
  });
14
- export const arktypes = ark.compile();
14
+ export const ark = arkscope.compile();
15
15
  export const scopes = {
16
16
  root: rootScope,
17
17
  tsKeywords: tsKeywordsScope,
18
18
  jsObjects: jsObjectsScope,
19
19
  validation: validationScope,
20
- ark
20
+ ark: arkscope
21
21
  };
22
22
  export const spaces = {
23
23
  tsKeywords,
24
24
  jsObjects,
25
25
  validation,
26
- ark: arktypes
26
+ ark
27
27
  };
28
- export const type = ark.type;
28
+ export const type = arkscope.type;
@@ -48,13 +48,14 @@ function _classPrivateMethodInit(obj, privateSet) {
48
48
  _checkPrivateRedeclaration(obj, privateSet);
49
49
  privateSet.add(obj);
50
50
  }
51
- var _ctx_type;
52
- import { flattenType } from "../nodes/node.js";
51
+ var _ctx_type, _ctx_type1;
52
+ import { flattenType, isConfigNode } from "../nodes/node.js";
53
53
  import { parseDefinition } from "../parse/definition.js";
54
54
  import { compileProblemWriters } from "../traverse/problems.js";
55
55
  import { chainableNoOpProxy } from "../utils/chainableNoOpProxy.js";
56
56
  import { throwInternalError, throwParseError } from "../utils/errors.js";
57
57
  import { deepFreeze } from "../utils/freeze.js";
58
+ import { hasKeys } from "../utils/generics.js";
58
59
  import { Path } from "../utils/paths.js";
59
60
  import { Cache, FreezingCache } from "./cache.js";
60
61
  import { initializeType } from "./type.js";
@@ -68,34 +69,17 @@ const spaceRegistry = {};
68
69
  export const isConfigTuple = (def)=>Array.isArray(def) && def[1] === ":";
69
70
  var _resolutions = /*#__PURE__*/ new WeakMap(), _exports = /*#__PURE__*/ new WeakMap(), _register = /*#__PURE__*/ new WeakSet(), _cacheSpaces = /*#__PURE__*/ new WeakSet(), _initializeContext = /*#__PURE__*/ new WeakSet(), _resolveRecurse = /*#__PURE__*/ new WeakSet();
70
71
  export class Scope {
71
- getAnonymousTypeName(ctx) {
72
- let base = ctx ? ctx.path.length ? `${ctx.path}` : ctx.type.name : "type";
73
- if (base[0] !== "λ") {
74
- base = `λ${base}`;
72
+ getAnonymousQualifiedName(base) {
73
+ let increment = 0;
74
+ let id = base;
75
+ while(this.isResolvable(id)){
76
+ id = `${base}${increment++}`;
75
77
  }
76
- let increment = 1;
77
- let name = base;
78
- while(this.isInternallyResolvable(name)){
79
- name = `${base}${++increment}`;
80
- }
81
- return name;
78
+ return `${this.name}.${id}`;
82
79
  }
83
- addAnonymous(type, ctx) {
84
- if (this.isInternallyResolvable(type.name)) {
85
- if (type === this.resolve(type.name)) {
86
- return type.name;
87
- }
88
- const name = this.getAnonymousTypeName(ctx);
89
- this.type([
90
- "node",
91
- type.node
92
- ], {
93
- name
94
- });
95
- return name;
96
- }
97
- _classPrivateFieldGet(this, _resolutions).set(type.name, type);
98
- return type.name;
80
+ addAnonymousTypeReference(referencedType, ctx) {
81
+ (_ctx_type = ctx.type).includesMorph || (_ctx_type.includesMorph = referencedType.includesMorph);
82
+ return referencedType.node;
99
83
  }
100
84
  get infer() {
101
85
  return chainableNoOpProxy;
@@ -109,21 +93,29 @@ export class Scope {
109
93
  }
110
94
  return _classPrivateFieldGet(this, _exports).root;
111
95
  }
112
- addReferenceIfResolvable(name, ctx) {
113
- const resolution = _classPrivateMethodGet(this, _resolveRecurse, resolveRecurse).call(this, name, "undefined", []);
96
+ addParsedReferenceIfResolvable(name, ctx) {
97
+ const resolution = _classPrivateMethodGet(this, _resolveRecurse, resolveRecurse).call(this, name, "undefined", [
98
+ name
99
+ ]);
114
100
  if (!resolution) {
115
101
  return false;
116
102
  }
117
- (_ctx_type = ctx.type).includesMorph || (_ctx_type.includesMorph = resolution.includesMorph);
103
+ (_ctx_type1 = ctx.type).includesMorph || (_ctx_type1.includesMorph = resolution.includesMorph);
118
104
  return true;
119
105
  }
120
106
  resolve(name) {
121
- return _classPrivateMethodGet(this, _resolveRecurse, resolveRecurse).call(this, name, "throw", []);
107
+ return _classPrivateMethodGet(this, _resolveRecurse, resolveRecurse).call(this, name, "throw", [
108
+ name
109
+ ]);
122
110
  }
123
111
  resolveNode(node) {
124
- return typeof node === "object" ? node : this.resolveNode(this.resolve(node).node);
112
+ return typeof node === "string" ? this.resolveNode(this.resolve(node).node) : node;
113
+ }
114
+ resolveTypeNode(node) {
115
+ const resolution = this.resolveNode(node);
116
+ return isConfigNode(resolution) ? resolution.node : resolution;
125
117
  }
126
- isInternallyResolvable(name) {
118
+ isResolvable(name) {
127
119
  return _classPrivateFieldGet(this, _resolutions).has(name) || this.aliases[name];
128
120
  }
129
121
  constructor(aliases, opts = {}){
@@ -193,16 +185,15 @@ export class Scope {
193
185
  this.instanceOf = this.expressions.instanceOf;
194
186
  this.narrow = this.expressions.narrow;
195
187
  this.morph = this.expressions.morph;
196
- this.type = Object.assign((def, opts)=>{
197
- const name = opts?.name ? this.isInternallyResolvable(opts.name) ? throwParseError(writeDuplicateAliasesMessage(opts.name)) : opts.name : this.getAnonymousTypeName();
198
- // remove name from opts since we've already used it and otherwise it will
199
- // interfere with traversal keys being ProblemOptions
200
- delete opts?.name;
201
- const t = initializeType(name, def, opts, this);
188
+ this.type = Object.assign((def, config = {})=>{
189
+ const t = initializeType("λtype", def, config, this);
202
190
  const ctx = _classPrivateMethodGet(this, _initializeContext, initializeContext).call(this, t);
203
- t.node = deepFreeze(parseDefinition(def, ctx));
191
+ const root = parseDefinition(def, ctx);
192
+ t.node = deepFreeze(hasKeys(config) ? {
193
+ config,
194
+ node: this.resolveTypeNode(root)
195
+ } : root);
204
196
  t.flat = deepFreeze(flattenType(t));
205
- _classPrivateFieldGet(this, _resolutions).set(t.name, t);
206
197
  return t;
207
198
  }, {
208
199
  from: this.expressions.node
@@ -251,32 +242,29 @@ function resolveRecurse(name, onUnresolvable, seen) {
251
242
  if (maybeCacheResult) {
252
243
  return maybeCacheResult;
253
244
  }
254
- const aliasValue = this.aliases[name];
255
- if (!aliasValue) {
245
+ const aliasDef = this.aliases[name];
246
+ if (!aliasDef) {
256
247
  return onUnresolvable === "throw" ? throwInternalError(`Unexpectedly failed to resolve alias '${name}'`) : undefined;
257
248
  }
258
- const type = initializeType(name, aliasValue, undefined, this);
259
- _classPrivateFieldGet(this, _resolutions).set(name, type);
260
- _classPrivateFieldGet(this, _exports).set(name, type);
261
- const ctx = _classPrivateMethodGet(this, _initializeContext, initializeContext).call(this, type);
262
- const resolution = parseDefinition(type.definition, ctx);
263
- if (typeof resolution === "string") {
264
- if (seen.includes(resolution)) {
249
+ const t = initializeType(name, aliasDef, {}, this);
250
+ const ctx = _classPrivateMethodGet(this, _initializeContext, initializeContext).call(this, t);
251
+ _classPrivateFieldGet(this, _resolutions).set(name, t);
252
+ _classPrivateFieldGet(this, _exports).set(name, t);
253
+ let node = parseDefinition(aliasDef, ctx);
254
+ if (typeof node === "string") {
255
+ if (seen.includes(node)) {
265
256
  return throwParseError(writeShallowCycleErrorMessage(name, seen));
266
257
  }
267
- seen.push(resolution);
268
- const resolvedType = _classPrivateMethodGet(this, _resolveRecurse, resolveRecurse).call(this, resolution, "throw", seen);
269
- type.node = resolvedType.node;
270
- type.flat = resolvedType.flat;
271
- return type;
258
+ seen.push(node);
259
+ node = _classPrivateMethodGet(this, _resolveRecurse, resolveRecurse).call(this, node, "throw", seen).node;
272
260
  }
273
- type.node = deepFreeze(resolution);
274
- type.flat = deepFreeze(flattenType(type));
275
- return type;
261
+ t.node = deepFreeze(node);
262
+ t.flat = deepFreeze(flattenType(t));
263
+ return t;
276
264
  }
277
265
  export const scope = (aliases, opts = {})=>new Scope(aliases, opts);
278
266
  export const rootScope = scope({}, {
279
- name: "empty",
267
+ name: "root",
280
268
  standard: false
281
269
  });
282
270
  export const rootType = rootScope.type;
@@ -1,6 +1,16 @@
1
1
  import { TraversalState, traverse } from "../traverse/traverse.js";
2
2
  import { chainableNoOpProxy } from "../utils/chainableNoOpProxy.js";
3
+ import { composeNamed, getNominalId } from "../utils/generics.js";
3
4
  export const initializeType = (name, definition, config, scope)=>{
5
+ const namedTraverse = composeNamed((data)=>{
6
+ const state = new TraversalState(data, t);
7
+ traverse(t.flat, state);
8
+ return state.problems.count ? {
9
+ problems: state.problems
10
+ } : {
11
+ data: state.data
12
+ };
13
+ }, name);
4
14
  const root = {
5
15
  // temporarily initialize node/flat to aliases that will be included in
6
16
  // the final type in case of cyclic resolutions
@@ -11,24 +21,17 @@ export const initializeType = (name, definition, config, scope)=>{
11
21
  name
12
22
  ]
13
23
  ],
24
+ allows: (data)=>!namedTraverse(data).problems,
14
25
  infer: chainableNoOpProxy,
15
- qualifiedName: `${scope.name}.${name}`,
26
+ qualifiedName: isAnonymousName(name) ? scope.getAnonymousQualifiedName(name) : `${scope.name}.${name}`,
16
27
  definition,
17
28
  scope,
18
29
  includesMorph: false,
19
30
  config
20
31
  };
21
- // dynamically assign a name to the primary traversal function
22
- const namedTraverse = {
23
- [name]: (data)=>{
24
- const state = new TraversalState(data, namedTraverse);
25
- return traverse(namedTraverse.flat, state) ? {
26
- data: state.data
27
- } : {
28
- problems: state.problems
29
- };
30
- }
31
- }[name];
32
- return Object.assign(namedTraverse, root);
32
+ const t = Object.assign(namedTraverse, root);
33
+ return t;
33
34
  };
34
35
  export const isType = (value)=>value?.infer === chainableNoOpProxy;
36
+ export const isCheckResult = (value)=>getNominalId(value) !== undefined;
37
+ export const isAnonymousName = (name)=>name[0] === "λ";
@@ -1,4 +1,5 @@
1
1
  import { rootType } from "../scope.js";
2
+ import { tsKeywords } from "../tsKeywords.js";
2
3
  const dayDelimiterMatcher = /^[./-]$/;
3
4
  // ISO 8601 date/time modernized from https://github.com/validatorjs/validator.js/blob/master/src/lib/isISO8601.js
4
5
  // Based on https://tc39.es/ecma262/#sec-date-time-string-format, the T
@@ -38,9 +39,7 @@ export const tryParseDate = (data, opts)=>{
38
39
  return writeFormattedMustBe(opts.format);
39
40
  };
40
41
  export const parsedDate = rootType([
41
- rootType.from({
42
- string: true
43
- }),
42
+ tsKeywords.string,
44
43
  "|>",
45
44
  (s, problems)=>{
46
45
  const result = tryParseDate(s);
@@ -1,5 +1,6 @@
1
1
  import { wellFormedIntegerMatcher, wellFormedNumberMatcher } from "../../utils/numericLiterals.js";
2
2
  import { rootType, scope } from "../scope.js";
3
+ import { tsKeywords } from "../tsKeywords.js";
3
4
  import { creditCard } from "./creditCard.js";
4
5
  import { parsedDate } from "./date.js";
5
6
  // Non-trivial expressions should have an explanation or attribution
@@ -25,6 +26,17 @@ const email = rootType(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/, {
25
26
  const uuid = rootType(/^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$/, {
26
27
  mustBe: "a valid UUID"
27
28
  });
29
+ // https://semver.org/
30
+ const semver = rootType(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/, {
31
+ mustBe: "a valid semantic version (see https://semver.org/)"
32
+ });
33
+ const json = rootType([
34
+ tsKeywords.string,
35
+ "|>",
36
+ (s)=>JSON.parse(s)
37
+ ], {
38
+ mustBe: "a JSON-parsable string"
39
+ });
28
40
  export const validationScope = scope({
29
41
  // Character sets
30
42
  alpha: [
@@ -61,6 +73,8 @@ export const validationScope = scope({
61
73
  parsedNumber,
62
74
  parsedInteger,
63
75
  parsedDate,
76
+ semver,
77
+ json,
64
78
  integer: [
65
79
  "node",
66
80
  {
@@ -48,7 +48,7 @@ import { Path } from "../utils/paths.js";
48
48
  import { stringify } from "../utils/serialize.js";
49
49
  export class ArkTypeError extends TypeError {
50
50
  constructor(problems){
51
- super(problems.summary);
51
+ super(`${problems}`);
52
52
  this.cause = problems;
53
53
  }
54
54
  }
@@ -116,10 +116,10 @@ class ProblemArray extends Array {
116
116
  this.count++;
117
117
  }
118
118
  get summary() {
119
- return this.join("\n");
119
+ return `${this}`;
120
120
  }
121
121
  toString() {
122
- return this.summary;
122
+ return this.join("\n");
123
123
  }
124
124
  throw() {
125
125
  throw new ArkTypeError(this);
@@ -44,6 +44,7 @@ import { checkDivisor } from "../nodes/rules/divisor.js";
44
44
  import { checkBound } from "../nodes/rules/range.js";
45
45
  import { checkRegex } from "../nodes/rules/regex.js";
46
46
  import { precedenceMap } from "../nodes/rules/rules.js";
47
+ import { isCheckResult } from "../scopes/type.js";
47
48
  import { domainOf, hasDomain } from "../utils/domains.js";
48
49
  import { throwInternalError } from "../utils/errors.js";
49
50
  import { hasKey, objectKeysOf } from "../utils/generics.js";
@@ -77,8 +78,8 @@ export class TraversalState {
77
78
  this.traversalConfig[entry[0]].unshift(entry[1]);
78
79
  }
79
80
  const isValid = traverse(node, this);
80
- for (const entry1 of configEntries){
81
- this.traversalConfig[entry1[0]].shift();
81
+ for (const entry of configEntries){
82
+ this.traversalConfig[entry[0]].shift();
82
83
  }
83
84
  return isValid;
84
85
  }
@@ -265,7 +266,14 @@ const entryCheckers = {
265
266
  },
266
267
  alias: (name, state)=>state.traverseResolution(name),
267
268
  class: checkClass,
268
- narrow: (narrow, state)=>narrow(state.data, state.problems),
269
+ narrow: (narrow, state)=>{
270
+ const lastProblemsCount = state.problems.count;
271
+ const result = narrow(state.data, state.problems);
272
+ if (!result && state.problems.count === lastProblemsCount) {
273
+ state.problems.mustBe(narrow.name ? `valid according to ${narrow.name}` : "valid");
274
+ }
275
+ return result;
276
+ },
269
277
  config: ({ config , node }, state)=>state.traverseConfig(config, node),
270
278
  value: (value, state)=>state.data === value || !state.problems.add("value", value),
271
279
  morph: (morph, state)=>{
@@ -278,6 +286,16 @@ const entryCheckers = {
278
286
  state.problems.addProblem(out);
279
287
  return false;
280
288
  }
289
+ if (isCheckResult(out)) {
290
+ if (out.problems) {
291
+ for (const problem of out.problems){
292
+ state.problems.addProblem(problem);
293
+ }
294
+ return false;
295
+ }
296
+ state.data = out.data;
297
+ return true;
298
+ }
281
299
  state.data = out;
282
300
  return true;
283
301
  },
@@ -1,7 +1,7 @@
1
1
  import { domainOf } from "./domains.js";
2
2
  import { stringify } from "./serialize.js";
3
3
  export const sizeOf = (data)=>typeof data === "string" || Array.isArray(data) ? data.length : typeof data === "number" ? data : 0;
4
- export const unitsOf = (data)=>typeof data === "string" ? "characters" : Array.isArray(data) ? "items" : "";
4
+ export const unitsOf = (data)=>typeof data === "string" ? "characters" : Array.isArray(data) ? "items long" : "";
5
5
  export class DataWrapper {
6
6
  toString() {
7
7
  return stringify(this.value);
@@ -24,8 +24,19 @@ export const hasKey = (o, k)=>{
24
24
  const valueAtKey = o?.[k];
25
25
  return valueAtKey !== undefined && valueAtKey !== null;
26
26
  };
27
+ export const hasSingleKey = (o, k)=>k in o && Object.keys(o).length === 1;
27
28
  export const keyCount = (o)=>Object.keys(o).length;
28
29
  export const hasKeys = (value)=>hasDomain(value, "object") ? Object.keys(value).length !== 0 : false;
30
+ const id = Symbol("id");
31
+ export const nominal = (o, name)=>Object.assign(o, {
32
+ [id]: name
33
+ });
34
+ export const composeNamed = (f, name)=>// define within a key to dynamically assign a name to the function
35
+ ({
36
+ [name]: (...args)=>nominal(f(...args), name)
37
+ })[name];
38
+ export const getNominalId = (data)=>hasDomain(data, "object") && id in data ? data[id] : undefined;
39
+ export const hasNominalId = (data, name)=>getNominalId(data) === name;
29
40
  export const listFrom = (data)=>Array.isArray(data) ? data : [
30
41
  data
31
42
  ];
@@ -1,74 +1,51 @@
1
1
  import { domainOf } from "./domains.js";
2
2
  import { isKeyOf } from "./generics.js";
3
3
  import { tryParseWellFormedBigint, tryParseWellFormedNumber } from "./numericLiterals.js";
4
- export const snapshot = (data, opts = {})=>snapshotRecurse(data, opts, []);
5
- const snapshotRecurse = (v, context, seen)=>{
6
- switch(domainOf(v)){
4
+ export const snapshot = (data, opts = {})=>serializeRecurse(data, opts, []);
5
+ export const stringify = (data, indent)=>{
6
+ switch(domainOf(data)){
7
+ case "object":
8
+ return JSON.stringify(serializeRecurse(data, stringifyOpts, []), null, indent);
9
+ case "symbol":
10
+ return stringifyOpts.onSymbol(data);
11
+ default:
12
+ return serializePrimitive(data);
13
+ }
14
+ };
15
+ const stringifyOpts = {
16
+ onCycle: ()=>"(cycle)",
17
+ onSymbol: (v)=>`(symbol${v.description && ` ${v.description}`})`,
18
+ onFunction: (v)=>`(function${v.name && ` ${v.name}`})`
19
+ };
20
+ const serializeRecurse = (data, context, seen)=>{
21
+ switch(domainOf(data)){
7
22
  case "object":
8
- if (typeof v === "function") {
9
- return stringifyOpts.onFunction(v);
23
+ if (typeof data === "function") {
24
+ return stringifyOpts.onFunction(data);
10
25
  }
11
- if (seen.includes(v)) {
26
+ if (seen.includes(data)) {
12
27
  return "(cycle)";
13
28
  }
14
29
  const nextSeen = [
15
30
  ...seen,
16
- v
31
+ data
17
32
  ];
18
- if (Array.isArray(v)) {
19
- return v.map((item)=>snapshotRecurse(item, context, nextSeen));
33
+ if (Array.isArray(data)) {
34
+ return data.map((item)=>serializeRecurse(item, context, nextSeen));
20
35
  }
21
36
  const result = {};
22
- for(const k in v){
23
- result[k] = snapshotRecurse(v[k], context, nextSeen);
37
+ for(const k in data){
38
+ result[k] = serializeRecurse(data[k], context, nextSeen);
24
39
  }
25
40
  return result;
26
41
  case "symbol":
27
- return stringifyOpts.onSymbol(v);
42
+ return stringifyOpts.onSymbol(data);
28
43
  case "bigint":
29
- return `${v}n`;
44
+ return `${data}n`;
30
45
  case "undefined":
31
46
  return "undefined";
32
47
  default:
33
- return v;
34
- }
35
- };
36
- export const serialize = (data, opts = {}, indent)=>{
37
- const seen = [];
38
- return JSON.stringify(data, (k, v)=>{
39
- switch(domainOf(v)){
40
- case "object":
41
- if (seen.includes(v)) {
42
- return opts.onCycle?.(v);
43
- }
44
- if (typeof v === "function") {
45
- return opts.onFunction?.(v);
46
- }
47
- return v;
48
- case "undefined":
49
- return "undefined";
50
- case "symbol":
51
- return opts.onSymbol?.(v);
52
- case "bigint":
53
- return `${v}n`;
54
- default:
55
- return v;
56
- }
57
- }, indent);
58
- };
59
- const stringifyOpts = {
60
- onCycle: ()=>"(cycle)",
61
- onSymbol: (v)=>`(symbol${v.description && ` ${v.description}`})`,
62
- onFunction: (v)=>`(function${v.name && ` ${v.name}`})`
63
- };
64
- export const stringify = (data, indent)=>{
65
- switch(domainOf(data)){
66
- case "object":
67
- return serialize(data, stringifyOpts, indent);
68
- case "symbol":
69
- return stringifyOpts.onSymbol(data);
70
- default:
71
- return serializePrimitive(data);
48
+ return data;
72
49
  }
73
50
  };
74
51
  export const serializePrimitive = (value)=>typeof value === "string" ? `'${value}'` : typeof value === "bigint" ? `${value}n` : `${value}`;