arktype 0.6.0 → 1.0.0-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 (64) hide show
  1. package/README.md +1 -1
  2. package/dist/api.cjs +2 -2
  3. package/dist/api.d.ts +1 -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 +27 -19
  8. package/dist/cjs/nodes/predicate.js +0 -1
  9. package/dist/cjs/parse/ast/config.js +4 -6
  10. package/dist/cjs/parse/ast/distributableFunction.js +2 -2
  11. package/dist/cjs/parse/ast/morph.js +2 -1
  12. package/dist/cjs/parse/ast/narrow.js +8 -1
  13. package/dist/cjs/parse/definition.js +2 -2
  14. package/dist/cjs/parse/string/reduce/dynamic.js +1 -1
  15. package/dist/cjs/parse/string/shift/operand/unenclosed.js +1 -1
  16. package/dist/cjs/parse/string/string.js +2 -2
  17. package/dist/cjs/scopes/ark.js +6 -6
  18. package/dist/cjs/scopes/scope.js +47 -59
  19. package/dist/cjs/scopes/type.js +19 -14
  20. package/dist/cjs/scopes/validation/validation.js +5 -0
  21. package/dist/cjs/traverse/problems.js +3 -3
  22. package/dist/cjs/traverse/traverse.js +19 -1
  23. package/dist/cjs/utils/generics.js +16 -0
  24. package/dist/cjs/utils/serialize.js +29 -53
  25. package/dist/mjs/nodes/compose.js +5 -5
  26. package/dist/mjs/nodes/discriminate.js +1 -1
  27. package/dist/mjs/nodes/node.js +25 -19
  28. package/dist/mjs/nodes/predicate.js +0 -1
  29. package/dist/mjs/parse/ast/config.js +4 -6
  30. package/dist/mjs/parse/ast/distributableFunction.js +2 -2
  31. package/dist/mjs/parse/ast/morph.js +2 -1
  32. package/dist/mjs/parse/ast/narrow.js +9 -2
  33. package/dist/mjs/parse/definition.js +2 -2
  34. package/dist/mjs/parse/string/reduce/dynamic.js +1 -1
  35. package/dist/mjs/parse/string/shift/operand/unenclosed.js +1 -1
  36. package/dist/mjs/parse/string/string.js +2 -2
  37. package/dist/mjs/scopes/ark.js +5 -5
  38. package/dist/mjs/scopes/scope.js +48 -60
  39. package/dist/mjs/scopes/type.js +16 -13
  40. package/dist/mjs/scopes/validation/validation.js +5 -0
  41. package/dist/mjs/traverse/problems.js +3 -3
  42. package/dist/mjs/traverse/traverse.js +19 -1
  43. package/dist/mjs/utils/generics.js +11 -0
  44. package/dist/mjs/utils/serialize.js +29 -52
  45. package/dist/tsconfig.temp.tsbuildinfo +1 -1
  46. package/dist/types/nodes/branch.d.ts +5 -3
  47. package/dist/types/nodes/node.d.ts +15 -8
  48. package/dist/types/nodes/predicate.d.ts +3 -3
  49. package/dist/types/nodes/rules/props.d.ts +8 -8
  50. package/dist/types/parse/ast/distributableFunction.d.ts +1 -1
  51. package/dist/types/parse/ast/morph.d.ts +2 -2
  52. package/dist/types/parse/ast/node.d.ts +6 -6
  53. package/dist/types/parse/ast/tuple.d.ts +4 -4
  54. package/dist/types/parse/definition.d.ts +2 -2
  55. package/dist/types/parse/string/reduce/dynamic.d.ts +5 -5
  56. package/dist/types/parse/string/string.d.ts +3 -3
  57. package/dist/types/scopes/ark.d.ts +8 -87
  58. package/dist/types/scopes/scope.d.ts +9 -8
  59. package/dist/types/scopes/type.d.ts +22 -13
  60. package/dist/types/scopes/validation/validation.d.ts +2 -0
  61. package/dist/types/traverse/traverse.d.ts +6 -1
  62. package/dist/types/utils/generics.d.ts +5 -0
  63. package/dist/types/utils/serialize.d.ts +0 -1
  64. package/package.json +2 -2
@@ -15,8 +15,13 @@ _export(exports, {
15
15
  objectKeysOf: ()=>objectKeysOf,
16
16
  prototypeKeysOf: ()=>prototypeKeysOf,
17
17
  hasKey: ()=>hasKey,
18
+ hasSingleKey: ()=>hasSingleKey,
18
19
  keyCount: ()=>keyCount,
19
20
  hasKeys: ()=>hasKeys,
21
+ nominal: ()=>nominal,
22
+ composeNamed: ()=>composeNamed,
23
+ getNominalId: ()=>getNominalId,
24
+ hasNominalId: ()=>hasNominalId,
20
25
  listFrom: ()=>listFrom
21
26
  });
22
27
  const _domainsTs = require("./domains.js");
@@ -45,8 +50,19 @@ const hasKey = (o, k)=>{
45
50
  const valueAtKey = o?.[k];
46
51
  return valueAtKey !== undefined && valueAtKey !== null;
47
52
  };
53
+ const hasSingleKey = (o, k)=>k in o && Object.keys(o).length === 1;
48
54
  const keyCount = (o)=>Object.keys(o).length;
49
55
  const hasKeys = (value)=>(0, _domainsTs.hasDomain)(value, "object") ? Object.keys(value).length !== 0 : false;
56
+ const id = Symbol("id");
57
+ const nominal = (o, name)=>Object.assign(o, {
58
+ [id]: name
59
+ });
60
+ const composeNamed = (f, name)=>// define within a key to dynamically assign a name to the function
61
+ ({
62
+ [name]: (...args)=>nominal(f(...args), name)
63
+ })[name];
64
+ const getNominalId = (data)=>(0, _domainsTs.hasDomain)(data, "object") && id in data ? data[id] : undefined;
65
+ const hasNominalId = (data, name)=>getNominalId(data) === name;
50
66
  const listFrom = (data)=>Array.isArray(data) ? data : [
51
67
  data
52
68
  ];
@@ -10,7 +10,6 @@ function _export(target, all) {
10
10
  }
11
11
  _export(exports, {
12
12
  snapshot: ()=>snapshot,
13
- serialize: ()=>serialize,
14
13
  stringify: ()=>stringify,
15
14
  serializePrimitive: ()=>serializePrimitive,
16
15
  deserializePrimitive: ()=>deserializePrimitive
@@ -18,74 +17,51 @@ _export(exports, {
18
17
  const _domainsTs = require("./domains.js");
19
18
  const _genericsTs = require("./generics.js");
20
19
  const _numericLiteralsTs = require("./numericLiterals.js");
21
- const snapshot = (data, opts = {})=>snapshotRecurse(data, opts, []);
22
- const snapshotRecurse = (v, context, seen)=>{
23
- switch((0, _domainsTs.domainOf)(v)){
20
+ const snapshot = (data, opts = {})=>serializeRecurse(data, opts, []);
21
+ const stringify = (data, indent)=>{
22
+ switch((0, _domainsTs.domainOf)(data)){
23
+ case "object":
24
+ return JSON.stringify(serializeRecurse(data, stringifyOpts, []), null, indent);
25
+ case "symbol":
26
+ return stringifyOpts.onSymbol(data);
27
+ default:
28
+ return serializePrimitive(data);
29
+ }
30
+ };
31
+ const stringifyOpts = {
32
+ onCycle: ()=>"(cycle)",
33
+ onSymbol: (v)=>`(symbol${v.description && ` ${v.description}`})`,
34
+ onFunction: (v)=>`(function${v.name && ` ${v.name}`})`
35
+ };
36
+ const serializeRecurse = (data, context, seen)=>{
37
+ switch((0, _domainsTs.domainOf)(data)){
24
38
  case "object":
25
- if (typeof v === "function") {
26
- return stringifyOpts.onFunction(v);
39
+ if (typeof data === "function") {
40
+ return stringifyOpts.onFunction(data);
27
41
  }
28
- if (seen.includes(v)) {
42
+ if (seen.includes(data)) {
29
43
  return "(cycle)";
30
44
  }
31
45
  const nextSeen = [
32
46
  ...seen,
33
- v
47
+ data
34
48
  ];
35
- if (Array.isArray(v)) {
36
- return v.map((item)=>snapshotRecurse(item, context, nextSeen));
49
+ if (Array.isArray(data)) {
50
+ return data.map((item)=>serializeRecurse(item, context, nextSeen));
37
51
  }
38
52
  const result = {};
39
- for(const k in v){
40
- result[k] = snapshotRecurse(v[k], context, nextSeen);
53
+ for(const k in data){
54
+ result[k] = serializeRecurse(data[k], context, nextSeen);
41
55
  }
42
56
  return result;
43
57
  case "symbol":
44
- return stringifyOpts.onSymbol(v);
58
+ return stringifyOpts.onSymbol(data);
45
59
  case "bigint":
46
- return `${v}n`;
60
+ return `${data}n`;
47
61
  case "undefined":
48
62
  return "undefined";
49
63
  default:
50
- return v;
51
- }
52
- };
53
- const serialize = (data, opts = {}, indent)=>{
54
- const seen = [];
55
- return JSON.stringify(data, (k, v)=>{
56
- switch((0, _domainsTs.domainOf)(v)){
57
- case "object":
58
- if (seen.includes(v)) {
59
- return opts.onCycle?.(v);
60
- }
61
- if (typeof v === "function") {
62
- return opts.onFunction?.(v);
63
- }
64
- return v;
65
- case "undefined":
66
- return "undefined";
67
- case "symbol":
68
- return opts.onSymbol?.(v);
69
- case "bigint":
70
- return `${v}n`;
71
- default:
72
- return v;
73
- }
74
- }, indent);
75
- };
76
- const stringifyOpts = {
77
- onCycle: ()=>"(cycle)",
78
- onSymbol: (v)=>`(symbol${v.description && ` ${v.description}`})`,
79
- onFunction: (v)=>`(function${v.name && ` ${v.name}`})`
80
- };
81
- const stringify = (data, indent)=>{
82
- switch((0, _domainsTs.domainOf)(data)){
83
- case "object":
84
- return serialize(data, stringifyOpts, indent);
85
- case "symbol":
86
- return stringifyOpts.onSymbol(data);
87
- default:
88
- return serializePrimitive(data);
64
+ return data;
89
65
  }
90
66
  };
91
67
  const serializePrimitive = (value)=>typeof value === "string" ? `'${value}'` : typeof value === "bigint" ? `${value}n` : `${value}`;
@@ -41,7 +41,7 @@ function _classPrivateFieldSet(receiver, privateMap, value) {
41
41
  import { throwInternalError } from "../utils/errors.js";
42
42
  import { objectKeysOf } from "../utils/generics.js";
43
43
  import { Path } from "../utils/paths.js";
44
- import { serialize } from "../utils/serialize.js";
44
+ import { stringify } from "../utils/serialize.js";
45
45
  export const composeIntersection = (reducer)=>(l, r, state)=>l === undefined ? r === undefined ? throwUndefinedOperandsError() : r : r === undefined ? l : reducer(l, r, state);
46
46
  export const throwUndefinedOperandsError = ()=>throwInternalError(`Unexpected operation two undefined operands`);
47
47
  export const disjointDescriptionWriters = {
@@ -49,10 +49,10 @@ export const disjointDescriptionWriters = {
49
49
  range: ({ l , r })=>`${stringifyRange(l)} and ${stringifyRange(r)}`,
50
50
  class: ({ l , r })=>`classes ${typeof l === "string" ? l : l.name} and ${typeof r === "string" ? r : r.name}`,
51
51
  tupleLength: ({ l , r })=>`tuples of length ${l} and ${r}`,
52
- value: ({ l , r })=>`literal values ${serialize(l)} and ${serialize(r)}`,
53
- leftAssignability: ({ l , r })=>`literal value ${serialize(l.value)} and ${serialize(r)}`,
54
- rightAssignability: ({ l , r })=>`literal value ${serialize(r.value)} and ${serialize(l)}`,
55
- union: ({ l , r })=>`branches ${serialize(l)} and branches ${serialize(r)}`
52
+ value: ({ l , r })=>`literal values ${stringify(l)} and ${stringify(r)}`,
53
+ leftAssignability: ({ l , r })=>`literal value ${stringify(l.value)} and ${stringify(r)}`,
54
+ rightAssignability: ({ l , r })=>`literal value ${stringify(r.value)} and ${stringify(l)}`,
55
+ union: ({ l , r })=>`branches ${stringify(l)} and branches ${stringify(r)}`
56
56
  };
57
57
  export const stringifyRange = (range)=>"limit" in range ? `the range of exactly ${range.limit}` : range.min ? range.max ? `the range bounded by ${range.min.comparator}${range.min.limit} and ${range.max.comparator}${range.max.limit}` : `${range.min.comparator}${range.min.limit}` : range.max ? `${range.max.comparator}${range.max.limit}` : "the unbounded range";
58
58
  var _disjoints = /*#__PURE__*/ new WeakMap();
@@ -244,4 +244,4 @@ const serializeData = {
244
244
  };
245
245
  export const serializeCase = (kind, data)=>serializeData[kind](data);
246
246
  const branchIncludesMorph = (branch, $)=>"morph" in branch ? true : "props" in branch ? Object.values(branch.props).some((prop)=>nodeIncludesMorph(propToNode(prop), $)) : false;
247
- const nodeIncludesMorph = (node, $)=>typeof node === "string" ? $.resolve(node).includesMorph : Object.values(node).some((predicate)=>predicate === true ? false : isArray(predicate) ? predicate.some((branch)=>branchIncludesMorph(branch, $)) : branchIncludesMorph(predicate, $));
247
+ const nodeIncludesMorph = (node, $)=>typeof node === "string" ? $.resolve(node).includesMorph : Object.values($.resolveTypeNode(node)).some((predicate)=>predicate === true ? false : isArray(predicate) ? predicate.some((branch)=>branchIncludesMorph(branch, $)) : branchIncludesMorph(predicate, $));
@@ -5,17 +5,18 @@ import { Path } from "../utils/paths.js";
5
5
  import { anonymousDisjoint, composeKeyedIntersection, IntersectionState, isDisjoint, isEquality, throwUndefinedOperandsError } from "./compose.js";
6
6
  import { flattenPredicate, isLiteralCondition, predicateIntersection, predicateUnion } from "./predicate.js";
7
7
  import { mappedKeys } from "./rules/props.js";
8
+ export const isConfigNode = (node)=>"config" in node;
8
9
  export const nodeIntersection = (l, r, state)=>{
9
10
  state.domain = undefined;
10
- const lResolution = state.type.scope.resolveNode(l);
11
- const rResolution = state.type.scope.resolveNode(r);
12
- const result = resolutionIntersection(lResolution, rResolution, state);
11
+ const lDomains = state.type.scope.resolveTypeNode(l);
12
+ const rDomains = state.type.scope.resolveTypeNode(r);
13
+ const result = typeNodeIntersection(lDomains, rDomains, state);
13
14
  if (typeof result === "object" && !hasKeys(result)) {
14
- return hasKeys(state.disjoints) ? anonymousDisjoint() : state.addDisjoint("domain", objectKeysOf(lResolution), objectKeysOf(rResolution));
15
+ return hasKeys(state.disjoints) ? anonymousDisjoint() : state.addDisjoint("domain", objectKeysOf(lDomains), objectKeysOf(rDomains));
15
16
  }
16
- return result === lResolution ? l : result === rResolution ? r : result;
17
+ return result === lDomains ? l : result === rDomains ? r : result;
17
18
  };
18
- const resolutionIntersection = composeKeyedIntersection((domain, l, r, context)=>{
19
+ const typeNodeIntersection = composeKeyedIntersection((domain, l, r, context)=>{
19
20
  if (l === undefined) {
20
21
  return r === undefined ? throwUndefinedOperandsError() : undefined;
21
22
  }
@@ -32,15 +33,15 @@ export const rootIntersection = (l, r, type)=>{
32
33
  return isDisjoint(result) ? throwParseError(compileDisjointReasonsMessage(state.disjoints)) : isEquality(result) ? l : result;
33
34
  };
34
35
  export const rootUnion = (l, r, type)=>{
35
- const lResolution = type.scope.resolveNode(l);
36
- const rResolution = type.scope.resolveNode(r);
36
+ const lDomains = type.scope.resolveTypeNode(l);
37
+ const rDomains = type.scope.resolveTypeNode(r);
37
38
  const result = {};
38
39
  const domains = objectKeysOf({
39
- ...lResolution,
40
- ...rResolution
40
+ ...lDomains,
41
+ ...rDomains
41
42
  });
42
43
  for (const domain of domains){
43
- result[domain] = hasKey(lResolution, domain) ? hasKey(rResolution, domain) ? predicateUnion(domain, lResolution[domain], rResolution[domain], type) : lResolution[domain] : hasKey(rResolution, domain) ? rResolution[domain] : throwUndefinedOperandsError();
44
+ result[domain] = hasKey(lDomains, domain) ? hasKey(rDomains, domain) ? predicateUnion(domain, lDomains[domain], rDomains[domain], type) : lDomains[domain] : hasKey(rDomains, domain) ? rDomains[domain] : throwUndefinedOperandsError();
44
45
  }
45
46
  return result;
46
47
  };
@@ -51,20 +52,25 @@ export const flattenType = (type)=>{
51
52
  path: new Path(),
52
53
  lastDomain: "undefined"
53
54
  };
54
- return type.config ? [
55
+ return flattenNode(type.node, ctx);
56
+ };
57
+ export const flattenNode = (node, ctx)=>{
58
+ if (typeof node === "string") {
59
+ return ctx.type.scope.resolve(node).flat;
60
+ }
61
+ const hasConfig = isConfigNode(node);
62
+ const flattenedTypeNode = flattenTypeNode(hasConfig ? node.node : node, ctx);
63
+ return hasConfig ? [
55
64
  [
56
65
  "config",
57
66
  {
58
- config: entriesOf(type.config),
59
- node: flattenNode(type.node, ctx)
67
+ config: entriesOf(node.config),
68
+ node: flattenedTypeNode
60
69
  }
61
70
  ]
62
- ] : flattenNode(type.node, ctx);
71
+ ] : flattenedTypeNode;
63
72
  };
64
- export const flattenNode = (node, ctx)=>{
65
- if (typeof node === "string") {
66
- return ctx.type.scope.resolve(node).flat;
67
- }
73
+ export const flattenTypeNode = (node, ctx)=>{
68
74
  const domains = objectKeysOf(node);
69
75
  if (domains.length === 1) {
70
76
  const domain = domains[0];
@@ -3,7 +3,6 @@ import { isArray } from "../utils/objectKinds.js";
3
3
  import { branchIntersection, compareBranches, flattenBranch, isBranchComparison } from "./branch.js";
4
4
  import { equality, IntersectionState, isEquality } from "./compose.js";
5
5
  import { flattenBranches } from "./discriminate.js";
6
- import "./rules/rules.js";
7
6
  const emptyRulesIfTrue = (predicate)=>predicate === true ? {} : predicate;
8
7
  export const comparePredicates = (l, r, context)=>{
9
8
  if (l === true && r === true) {
@@ -1,7 +1,5 @@
1
- export const parseConfigTuple = (def, ctx)=>{
2
- const anonymousType = ctx.type.scope.type(def[0], {
3
- name: ctx.type.scope.getAnonymousTypeName(ctx),
4
- ...def[2]
1
+ import { parseDefinition } from "../definition.js";
2
+ export const parseConfigTuple = (def, ctx)=>({
3
+ node: ctx.type.scope.resolveTypeNode(parseDefinition(def[0], ctx)),
4
+ config: def[2]
5
5
  });
6
- return anonymousType.name;
7
- };
@@ -3,8 +3,8 @@ import { throwParseError } from "../../utils/errors.js";
3
3
  import { objectKeysOf } from "../../utils/generics.js";
4
4
  import { stringify } from "../../utils/serialize.js";
5
5
  export const writeMalformedDistributableFunctionMessage = (def)=>`Expected a Function or Record<Domain, Function> operand (${stringify(def)} was invalid)`;
6
- export const distributeFunctionToNode = (distributableFunction, inputNode, ctx, ruleKey)=>{
7
- const domains = objectKeysOf(ctx.type.scope.resolveNode(inputNode));
6
+ export const distributeFunctionToNode = (distributableFunction, node, ctx, ruleKey)=>{
7
+ const domains = objectKeysOf(node);
8
8
  if (!hasDomain(distributableFunction, "object")) {
9
9
  return throwParseError(writeMalformedDistributableFunctionMessage(distributableFunction));
10
10
  }
@@ -7,7 +7,8 @@ export const parseMorphTuple = (def, ctx)=>{
7
7
  if (typeof def[2] !== "function") {
8
8
  return throwParseError(writeMalformedMorphExpressionMessage(def[2]));
9
9
  }
10
- const resolution = ctx.type.scope.resolveNode(parseDefinition(def[0], ctx));
10
+ const node = parseDefinition(def[0], ctx);
11
+ const resolution = ctx.type.scope.resolveTypeNode(node);
11
12
  const morph = def[2];
12
13
  ctx.type.includesMorph = true;
13
14
  let domain;
@@ -1,7 +1,14 @@
1
- import { rootIntersection } from "../../nodes/node.js";
1
+ import { isConfigNode, rootIntersection } from "../../nodes/node.js";
2
2
  import { parseDefinition } from "../definition.js";
3
3
  import { distributeFunctionToNode } from "./distributableFunction.js";
4
4
  export const parseNarrowTuple = (def, ctx)=>{
5
5
  const inputNode = parseDefinition(def[0], ctx);
6
- return rootIntersection(inputNode, distributeFunctionToNode(def[2], inputNode, ctx, "narrow"), ctx.type);
6
+ const resolution = ctx.type.scope.resolveNode(inputNode);
7
+ const hasConfig = isConfigNode(resolution);
8
+ const typeNode = hasConfig ? resolution.node : resolution;
9
+ const result = rootIntersection(inputNode, distributeFunctionToNode(def[2], typeNode, ctx, "narrow"), ctx.type);
10
+ return hasConfig ? {
11
+ config: resolution.config,
12
+ node: result
13
+ } : result;
7
14
  };
@@ -28,12 +28,12 @@ export const parseDefinition = (def, ctx)=>{
28
28
  };
29
29
  case "Function":
30
30
  if (isType(def)) {
31
- return ctx.type.scope.addAnonymous(def, ctx);
31
+ return ctx.type.scope.addAnonymousTypeReference(def, ctx);
32
32
  }
33
33
  if (isThunk(def)) {
34
34
  const returned = def();
35
35
  if (isType(returned)) {
36
- return ctx.type.scope.addAnonymous(returned, ctx);
36
+ return ctx.type.scope.addAnonymousTypeReference(returned, ctx);
37
37
  }
38
38
  }
39
39
  return throwParseError(writeBadDefinitionTypeMessage("Function"));
@@ -14,7 +14,7 @@ export class DynamicState {
14
14
  }
15
15
  resolveRoot() {
16
16
  this.assertHasRoot();
17
- return this.ctx.type.scope.resolveNode(this.root);
17
+ return this.ctx.type.scope.resolveTypeNode(this.root);
18
18
  }
19
19
  rootToString() {
20
20
  this.assertHasRoot();
@@ -4,7 +4,7 @@ export const parseUnenclosed = (s)=>{
4
4
  s.setRoot(unenclosedToNode(s, token));
5
5
  };
6
6
  const unenclosedToNode = (s, token)=>{
7
- if (s.ctx.type.scope.addReferenceIfResolvable(token, s.ctx)) {
7
+ if (s.ctx.type.scope.addParsedReferenceIfResolvable(token, s.ctx)) {
8
8
  return token;
9
9
  }
10
10
  return maybeParseUnenclosedLiteral(token) ?? s.error(token === "" ? writeMissingOperandMessage(s) : writeUnresolvableMessage(token));
@@ -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] === "λ";
@@ -25,6 +25,10 @@ const email = rootType(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/, {
25
25
  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
26
  mustBe: "a valid UUID"
27
27
  });
28
+ // https://semver.org/
29
+ 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-]+)*))?$/, {
30
+ mustBe: "a valid semantic version (see https://semver.org/)"
31
+ });
28
32
  export const validationScope = scope({
29
33
  // Character sets
30
34
  alpha: [
@@ -61,6 +65,7 @@ export const validationScope = scope({
61
65
  parsedNumber,
62
66
  parsedInteger,
63
67
  parsedDate,
68
+ semver,
64
69
  integer: [
65
70
  "node",
66
71
  {