@astrale-os/kernel-dsl 1.0.0-beta.23 → 1.0.0-beta.25

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 (106) hide show
  1. package/dist/v1/builder/lowering/policy.js +4 -24
  2. package/dist/v1/builder/lowering/schema/context.js +0 -3
  3. package/dist/v1/builder/lowering/value/compile.js +24 -21
  4. package/dist/v1/builder/lowering/value/zod.js +10 -4
  5. package/dist/v1/builder/schema/diagnostic.d.ts +1 -1
  6. package/dist/v1/bundle/codec.js +50 -67
  7. package/dist/v1/bundle/diagnostic.d.ts +1 -1
  8. package/dist/v1/bundle/structure.js +2 -2
  9. package/dist/v1/compiled/admission/accept.js +6 -6
  10. package/dist/v1/compiled/admission/closure.js +16 -33
  11. package/dist/v1/compiled/admission/diagnostic.d.ts +8 -0
  12. package/dist/v1/compiled/admission/diagnostic.js +33 -0
  13. package/dist/v1/compiled/admission/semantics/class.js +11 -7
  14. package/dist/v1/compiled/admission/semantics/policy/admit.js +4 -19
  15. package/dist/v1/compiled/admission/wire/callable.d.ts +5 -2
  16. package/dist/v1/compiled/admission/wire/callable.js +13 -19
  17. package/dist/v1/compiled/admission/wire/class.js +6 -9
  18. package/dist/v1/compiled/admission/wire/entry.d.ts +1 -1
  19. package/dist/v1/compiled/admission/wire/entry.js +8 -13
  20. package/dist/v1/compiled/admission/wire/policy.js +4 -3
  21. package/dist/v1/compiled/admission/wire/program.d.ts +13 -3
  22. package/dist/v1/compiled/admission/wire/program.js +39 -44
  23. package/dist/v1/compiled/admission/wire/property.d.ts +4 -1
  24. package/dist/v1/compiled/admission/wire/property.js +8 -5
  25. package/dist/v1/compiled/admission/wire/value.d.ts +0 -2
  26. package/dist/v1/compiled/admission/wire/value.js +0 -7
  27. package/dist/v1/compiled/codec/json.js +4 -3
  28. package/dist/v1/compiled/compiler/compile.js +6 -17
  29. package/dist/v1/compiled/diagnostic.d.ts +1 -1
  30. package/dist/v1/compiled/loader/load.js +2 -7
  31. package/dist/v1/domain/model/input.d.ts +2 -2
  32. package/dist/v1/domain/validation/create.d.ts +3 -1
  33. package/dist/v1/domain/validation/create.js +13 -8
  34. package/dist/v1/language/callable/resolved.d.ts +3 -3
  35. package/dist/v1/language/chain.d.ts +7 -0
  36. package/dist/v1/language/chain.js +24 -0
  37. package/dist/v1/language/cycle.d.ts +10 -0
  38. package/dist/v1/language/cycle.js +30 -0
  39. package/dist/v1/language/limits.d.ts +19 -0
  40. package/dist/v1/language/limits.js +17 -0
  41. package/dist/v1/language/policy/analysis/budgets.js +17 -13
  42. package/dist/v1/language/policy/analysis/composition.d.ts +4 -0
  43. package/dist/v1/language/policy/analysis/composition.js +11 -0
  44. package/dist/v1/language/suspended.d.ts +7 -0
  45. package/dist/v1/language/suspended.js +23 -0
  46. package/dist/v1/language/value/compile/fields.js +12 -8
  47. package/dist/v1/language/value/compile/load.d.ts +5 -0
  48. package/dist/v1/language/value/compile/load.js +13 -0
  49. package/dist/v1/language/value/evaluate/assertions.d.ts +5 -1
  50. package/dist/v1/language/value/evaluate/assertions.js +49 -8
  51. package/dist/v1/language/value/evaluate/evaluator.js +107 -105
  52. package/dist/v1/language/value/evaluate/preparation.d.ts +16 -0
  53. package/dist/v1/language/value/evaluate/preparation.js +100 -47
  54. package/dist/v1/language/value/evaluate/program.d.ts +2 -2
  55. package/dist/v1/language/value/evaluate/program.js +5 -5
  56. package/dist/v1/language/value/evaluate/validate.d.ts +3 -3
  57. package/dist/v1/language/value/evaluate/validate.js +9 -9
  58. package/dist/v1/language/value/evaluate/validity.optimization.js +4 -3
  59. package/dist/v1/language/value/inclusion/equivalence.js +4 -2
  60. package/dist/v1/language/value/inclusion/evidence.js +2 -2
  61. package/dist/v1/language/value/inclusion/includes.d.ts +13 -4
  62. package/dist/v1/language/value/inclusion/includes.js +34 -5
  63. package/dist/v1/language/value/inclusion/location.js +10 -7
  64. package/dist/v1/language/value/ordering.js +62 -70
  65. package/dist/v1/language/value/profile/canonicalize.d.ts +6 -1
  66. package/dist/v1/language/value/profile/canonicalize.js +64 -83
  67. package/dist/v1/language/value/profile/json.validate.d.ts +13 -3
  68. package/dist/v1/language/value/profile/json.validate.js +18 -6
  69. package/dist/v1/language/value/reference/closure.js +3 -2
  70. package/dist/v1/language/value/reference/recursion.js +7 -26
  71. package/dist/v1/language/value/reference/references.d.ts +3 -1
  72. package/dist/v1/language/value/reference/references.js +7 -7
  73. package/dist/v1/language/value/syntax/walk.d.ts +5 -0
  74. package/dist/v1/language/value/syntax/walk.js +14 -0
  75. package/dist/v1/schema/.spec/schemas/domain-schema.schema.json +1 -1
  76. package/dist/v1/schema/admission/accept.d.ts +3 -1
  77. package/dist/v1/schema/admission/accept.js +4 -1
  78. package/dist/v1/schema/analysis/class.d.ts +4 -0
  79. package/dist/v1/schema/analysis/class.js +24 -2
  80. package/dist/v1/schema/canonical/revision.d.ts +4 -1
  81. package/dist/v1/schema/canonical/revision.js +4 -1
  82. package/dist/v1/schema/compatibility/context.d.ts +5 -2
  83. package/dist/v1/schema/compatibility/context.js +8 -6
  84. package/dist/v1/schema/compatibility/model.d.ts +1 -1
  85. package/dist/v1/schema/compatibility/structure/requirements.js +2 -2
  86. package/dist/v1/schema/compatibility/walk.js +2 -2
  87. package/dist/v1/schema/diagnostic.d.ts +1 -1
  88. package/dist/v1/schema/normalization/domain.js +8 -4
  89. package/dist/v1/schema/resolution/context.js +6 -7
  90. package/dist/v1/schema/resolution/domain.js +3 -11
  91. package/dist/v1/schema/rule.js +10 -3
  92. package/dist/v1/schema/validation/class.js +1 -1
  93. package/dist/v1/schema/validation/core.js +16 -8
  94. package/dist/v1/schema/validation/domain.js +20 -3
  95. package/dist/v1/schema/validation/policy/budgets.d.ts +5 -1
  96. package/dist/v1/schema/validation/policy/budgets.js +8 -1
  97. package/dist/v1/schema/validation/policy/references.js +5 -25
  98. package/dist/value/accept.d.ts +3 -3
  99. package/dist/value/canonical.js +2 -2
  100. package/dist/value/equal.d.ts +9 -1
  101. package/dist/value/equal.js +37 -3
  102. package/dist/value/index.d.ts +1 -1
  103. package/dist/value/limits.d.ts +11 -0
  104. package/package.json +2 -2
  105. package/dist/v1/compiled/admission/wire/pattern.d.ts +0 -12
  106. package/dist/v1/compiled/admission/wire/pattern.js +0 -111
@@ -4,7 +4,6 @@ import { isBinaryInput } from '../../language/callable/model/callable.js';
4
4
  import { compareEdgeUniqueFields, compareEdgeUniqueTuples, compareNodeUniqueTuples, } from '../../language/class/unique.js';
5
5
  import { CLASS_OPERATIONS } from '../../language/policy/model/policy.js';
6
6
  import { normalizeClassRule, normalizePolicyChecks, normalizePolicyExpression, } from '../../language/policy/normalization/normalize.js';
7
- import { admitStateTopology } from '../../language/state/topology.js';
8
7
  import { canonicalizeValueSchema } from '../../language/value/profile/canonicalize.js';
9
8
  export function normalizeDomainSchema(schema) {
10
9
  const classes = mapRecord(schema.classes, canonicalizeClass);
@@ -180,9 +179,14 @@ function canonicalizeProperty(value) {
180
179
  }),
181
180
  ...(value.immutable === undefined ? {} : { immutable: value.immutable }),
182
181
  ...(value.description === undefined ? {} : { description: value.description }),
183
- ...(value.state === undefined
184
- ? {}
185
- : { state: admitStateTopology(value.state) }),
182
+ ...(value.state === undefined ? {} : { state: canonicalizeStateTopology(value.state) }),
183
+ };
184
+ }
185
+ /** Orders a topology the structure shaped; only validation judges what it declares. */
186
+ function canonicalizeStateTopology(value) {
187
+ return {
188
+ initial: value.initial,
189
+ transitions: mapRecord(value.transitions, (events) => mapRecord(events, (target) => target)),
186
190
  };
187
191
  }
188
192
  function canonicalizeDirectedEndpoints(value) {
@@ -1,5 +1,6 @@
1
1
  import { definitionRefIndex } from '../../addressing/ordering.js';
2
2
  import { DOMAIN_REVISION_PATTERN } from '../../addressing/patterns.js';
3
+ import { chainDepths } from '../../language/chain.js';
3
4
  import { limits } from '../../language/limits.js';
4
5
  import { escapePointerToken } from '../../language/value/syntax/pointer.js';
5
6
  import { revisionOfDomainSchema } from '../canonical/revision.js';
@@ -79,7 +80,6 @@ function loadDependencyClosure(candidate, dependencies, lookup, diagnostics) {
79
80
  {
80
81
  schema: candidate,
81
82
  key: `${candidate.origin}\u0000candidate`,
82
- depth: 0,
83
83
  edges: Object.entries(candidate.dependencies),
84
84
  index: 0,
85
85
  },
@@ -128,11 +128,6 @@ function loadDependencyClosure(candidate, dependencies, lookup, diagnostics) {
128
128
  }
129
129
  continue;
130
130
  }
131
- const depth = frame.depth + 1;
132
- if (depth > limits.dependency.depth) {
133
- diagnostics.push(diagnostic('DV_DEPENDENCY_LIMITS', pointer, `Dependency depth ${depth} exceeds the maximum ${limits.dependency.depth}.`));
134
- continue;
135
- }
136
131
  const key = `${dependency.origin}\u0000${dependency.revision}`;
137
132
  if (visited.has(key))
138
133
  continue;
@@ -140,11 +135,15 @@ function loadDependencyClosure(candidate, dependencies, lookup, diagnostics) {
140
135
  frames.push({
141
136
  schema: nested,
142
137
  key,
143
- depth,
144
138
  edges: Object.entries(nested.dependencies),
145
139
  index: 0,
146
140
  });
147
141
  }
142
+ const depths = chainDepths([candidate], (schema) => Object.values(schema.dependencies).flatMap(({ origin }) => dependencies.get(origin) ?? []));
143
+ const depth = depths.get(candidate);
144
+ if (depth > limits.dependency.depth) {
145
+ diagnostics.push(diagnostic('DV_DEPENDENCY_LIMITS', '/dependencies', `Dependency depth ${depth} exceeds the maximum ${limits.dependency.depth}.`));
146
+ }
148
147
  }
149
148
  function validateDependencyUse(candidate, directOrigins, diagnostics) {
150
149
  // Each reference that cannot resolve is reported where it is written; the dependency it lacks
@@ -1,11 +1,10 @@
1
1
  import { Key, MethodKey, PropertyKey } from '../../addressing/index.js';
2
2
  import { compareUnicode } from '../../addressing/ordering.js';
3
3
  import { createDomain, createSourceDomain } from '../../domain/create.js';
4
- import { createDomainValidation, unknownInputField } from '../../domain/validation/create.js';
4
+ import { createDomainValidation, validateInputField } from '../../domain/validation/create.js';
5
5
  import { isBinaryInput } from '../../language/callable/model/callable.js';
6
6
  import { inputFieldNodes } from '../../language/value/compile/fields.js';
7
7
  import { prepareValueSchema } from '../../language/value/evaluate/preparation.js';
8
- import { validateValueProgram } from '../../language/value/evaluate/program.js';
9
8
  import { validateJsonInstance, validatePreparedInstance, } from '../../language/value/evaluate/validate.js';
10
9
  import { classifyPreparedOrdering } from '../../language/value/ordering.js';
11
10
  import { revisionOfDomainSchema } from '../canonical/revision.js';
@@ -98,15 +97,8 @@ export function callableValidation(input, output, registry, patterns) {
98
97
  return Object.freeze({
99
98
  ...(fields === undefined ? {} : { fields: Object.freeze(Object.keys(fields)) }),
100
99
  validateInput: (value, options) => validatePreparedInstance(prepared.value, value, options),
101
- validateInputField(field, value) {
102
- const nodes = fields?.[field];
103
- return nodes === undefined
104
- ? unknownInputField(field)
105
- : validateValueProgram(inputProgram, value, nodes);
106
- },
107
- validateOutput: (value) => output === undefined
108
- ? []
109
- : validateJsonInstance(output, value, registry, '', patterns),
100
+ validateInputField: (field, value) => validateInputField(inputProgram, fields, field, value),
101
+ validateOutput: (value) => output === undefined ? [] : validateJsonInstance(output, value, registry, '', patterns),
110
102
  });
111
103
  }
112
104
  function definitionsOf(schema) {
@@ -9,7 +9,7 @@ const CHECKS = [
9
9
  ];
10
10
  const DEPENDENCIES = ['/dependencies/{alias}', '/dependencies'];
11
11
  const count = (value) => value.toLocaleString('en-US');
12
- const { dependency, policy } = limits;
12
+ const { dependency, inheritance, policy } = limits;
13
13
  const at = (field) => [
14
14
  `/functions/{function}${field}`,
15
15
  `/classes/{class}/methods/{method}${field}`,
@@ -131,7 +131,7 @@ export const RULES = deepFreeze({
131
131
  DV_DEPENDENCY_LIMITS: {
132
132
  stage: 'context',
133
133
  positions: ['/dependencies', '/dependencies/{alias}'],
134
- statement: `A Domain has at most ${dependency.direct} direct dependencies, a closure of at most ${dependency.closure} Domains and a dependency depth of at most ${dependency.depth}.`,
134
+ statement: `A Domain has at most ${dependency.direct} direct dependencies, a closure of at most ${dependency.closure} Domains and a longest chain of at most ${dependency.depth} dependencies.`,
135
135
  limits: ['dependency.direct', 'dependency.closure', 'dependency.depth'],
136
136
  },
137
137
  DV_DEPENDENCY_REVISION_COHERENCE: {
@@ -182,10 +182,17 @@ export const RULES = deepFreeze({
182
182
  positions: ['/entrypoint'],
183
183
  statement: 'The entrypoint names a View its Domain declares.',
184
184
  },
185
+ DV_INHERITANCE_LIMITS: {
186
+ stage: 'context',
187
+ positions: ['/classes/{class}/extends'],
188
+ statement: `A Class has at most ${inheritance.depth} parents on its longest chain of parents, those of its dependencies included.`,
189
+ limits: ['inheritance.depth'],
190
+ },
185
191
  DV_JSON_VALUE: {
186
192
  stage: 'structure',
187
193
  positions: ANY,
188
- statement: `The document is portable JSON: as text, UTF-8 that parses, within ${count(defaultLimits.maxBytes)} bytes, with no byte-order mark and no repeated member name; as a value, null, booleans, finite numbers other than negative zero, strings, arrays and plain objects, with no string or member name that holds U+0000 or a lone surrogate or exceeds ${count(defaultLimits.maxStringBytes)} bytes of UTF-8, at most ${count(defaultLimits.maxDepth)} nested arrays and objects, and at most ${count(defaultLimits.maxMembers)} members and items in all.`,
194
+ statement: `The document is portable JSON: as text, UTF-8 that parses, within ${count(defaultLimits.maxBytes)} bytes, with no byte-order mark and no repeated member name; as a value, null, booleans, finite numbers other than negative zero, strings, arrays and plain objects, with no string or member name that holds U+0000 or a lone surrogate or exceeds ${count(defaultLimits.maxStringBytes)} bytes of UTF-8, at most ${count(defaultLimits.maxDepth)} nested arrays and objects, and at most ${count(defaultLimits.maxMembers)} members and items in all. A Bundle holds a closure whole, so as a whole it holds at most ${count(limits.closure.members)} members and items, and each Domain in it the limits above.`,
195
+ limits: ['closure.members'],
189
196
  conditions: ['#/$defs/portable-string/not'],
190
197
  },
191
198
  DV_METHOD_ABSTRACT: {
@@ -17,7 +17,7 @@ const formatDefinitionRef = Key.of;
17
17
  * registry; each dependency's is built at most once, so the Classes share them.
18
18
  */
19
19
  export function validateDefinitions(environment, analysis, registry) {
20
- const diagnostics = [...analysis.diagnostics];
20
+ const diagnostics = [];
21
21
  const schema = environment.candidate;
22
22
  let scope;
23
23
  const registries = new Map([[schema.origin, registry]]);
@@ -6,7 +6,7 @@ import { coveringEdgeUniqueTuples, coveringNodeUniqueTuples, edgeUniqueKeys, nod
6
6
  import { checkCoreEdgeSet, checkHeldKeys, coreEndpointsSatisfy, DOMAIN_ENDPOINT_CLASS, } from '../../language/core/facts.js';
7
7
  import { policyObjectKey, policyObjectOrigin, projectedMemberClass, } from '../../language/policy/model/policy.js';
8
8
  import { validateJsonInstance } from '../../language/value/evaluate/validate.js';
9
- import { escapePointerToken } from '../../language/value/syntax/pointer.js';
9
+ import { appendPointer, escapePointerToken } from '../../language/value/syntax/pointer.js';
10
10
  import { diagnostic, valueDiagnostic } from '../diagnostic.js';
11
11
  import { classSatisfies } from './class.js';
12
12
  const formatDefinitionRef = Key.of;
@@ -134,18 +134,26 @@ function endpointSatisfies(environment, endpoint, accepts) {
134
134
  return classSatisfies(environment, endpoint.classRef, accepts);
135
135
  }
136
136
  function validateCreationProperties(definition, properties, registry, code, pointer, diagnostics) {
137
- const schema = {
137
+ const fields = [...definition.properties].filter(([, field]) => field.auto === undefined);
138
+ // Which Properties the fact holds is judged apart from their values: a Property's schema is the
139
+ // root of its own local references, here as at a write, so it is never nested in another schema.
140
+ const held = {
138
141
  type: 'object',
139
- properties: Object.fromEntries([...definition.properties]
140
- .filter(([, field]) => field.auto === undefined)
141
- .map(([name, field]) => [name, field.schema])),
142
- required: [...definition.properties]
143
- .filter(([, field]) => field.required && field.auto === undefined)
142
+ properties: Object.fromEntries(fields.map(([name]) => [name, true])),
143
+ required: fields
144
+ .filter(([, field]) => field.required)
144
145
  .map(([name]) => name)
145
146
  .sort(compareUnicode),
146
147
  additionalProperties: false,
147
148
  };
148
- for (const refusal of validateJsonInstance(schema, properties, registry, pointer)) {
149
+ const refusals = validateJsonInstance(held, properties, registry, pointer);
150
+ for (const [name, field] of fields) {
151
+ if (!Object.hasOwn(properties, name))
152
+ continue;
153
+ const at = appendPointer(pointer, name);
154
+ refusals.push(...validateJsonInstance(field.schema, properties[name], registry, at));
155
+ }
156
+ for (const refusal of refusals) {
149
157
  diagnostics.push(valueDiagnostic(code, refusal));
150
158
  }
151
159
  }
@@ -11,15 +11,32 @@ import { validateViews } from './view.js';
11
11
  export function validateDomainSchemaSemantics(schema, lookup) {
12
12
  const context = buildDomainResolutionContext(schema, lookup);
13
13
  const analysis = analyzeDefinitions(context);
14
+ // Past the inheritance limit no Class is composed, and the rules below read the composition.
15
+ if (analysis.diagnostics.some(({ code }) => code === 'DV_INHERITANCE_LIMITS')) {
16
+ return Object.freeze({
17
+ context,
18
+ analysis,
19
+ diagnostics: Object.freeze(orderAndDeduplicate([...context.diagnostics, ...analysis.diagnostics])),
20
+ });
21
+ }
14
22
  const registry = createValueSchemaRegistry(context);
23
+ const valueRefusals = validateEmbeddedValueSchemas(schema, registry);
24
+ // The Class and Core rules read every Property value schema as admitted. A reference with no
25
+ // target is the one refusal they can read, and it may only mean a dependency this context lacks.
26
+ const readable = valueRefusals.every(({ valueCode }) => valueCode === 'VS_REFERENCE_RESOLUTION');
15
27
  const diagnostics = [
16
28
  ...context.diagnostics,
17
- ...validateEmbeddedValueSchemas(schema, registry),
18
- ...validateDefinitions(context, analysis, registry),
29
+ ...analysis.diagnostics,
30
+ ...valueRefusals,
19
31
  ...validateContracts(schema, registry),
20
32
  ...validatePolicies(context, analysis),
21
33
  ...validateViews(context),
22
- ...validateCore(context, analysis, registry),
34
+ ...(readable
35
+ ? [
36
+ ...validateDefinitions(context, analysis, registry),
37
+ ...validateCore(context, analysis, registry),
38
+ ]
39
+ : []),
23
40
  ];
24
41
  return Object.freeze({
25
42
  context,
@@ -26,7 +26,11 @@ export interface PolicyMeasures {
26
26
  export declare function measurePolicies(input: unknown): PolicyMeasures;
27
27
  /** The measures of one structured document, from its Policies once normalized. */
28
28
  export declare function measureDomainPolicies(schema: DomainSchemaIR, normalized?: ReadonlyMap<string, PolicyExpression>): PolicyMeasures;
29
- /** `PL_BUDGET`: every measure of the document within `limits.policy`. */
29
+ /**
30
+ * `PL_BUDGET`: every measure of the document within `limits.policy`. Typing expands what stays in
31
+ * `normalized`, and a Policy without a measure within them has no bound on its expansion, so it
32
+ * leaves: it is refused here or by `PL_REF` or `PL_COMPOSITION`, and whatever composes it with it.
33
+ */
30
34
  export declare function validatePolicyBudgets(context: PolicyValidationContext): void;
31
35
  /**
32
36
  * `PL_BUDGET` for one check tree at `pointer`, from its measure: the document's trees, and the
@@ -35,11 +35,18 @@ export function measureDomainPolicies(schema, normalized = normalizedPolicies(sc
35
35
  }
36
36
  return deepFreeze({ policies, unmeasured, checks });
37
37
  }
38
- /** `PL_BUDGET`: every measure of the document within `limits.policy`. */
38
+ /**
39
+ * `PL_BUDGET`: every measure of the document within `limits.policy`. Typing expands what stays in
40
+ * `normalized`, and a Policy without a measure within them has no bound on its expansion, so it
41
+ * leaves: it is refused here or by `PL_REF` or `PL_COMPOSITION`, and whatever composes it with it.
42
+ */
39
43
  export function validatePolicyBudgets(context) {
40
44
  const measures = measureDomainPolicies(context.environment.candidate, context.normalized);
45
+ for (const name of measures.unmeasured)
46
+ context.normalized.delete(name);
41
47
  for (const [name, measure] of Object.entries(measures.policies)) {
42
48
  for (const limit of exceededLimits(measure)) {
49
+ context.normalized.delete(name);
43
50
  context.add('PL_BUDGET', `/policies/${escapePointerToken(name)}`, REFUSAL[limit](measure));
44
51
  }
45
52
  }
@@ -1,5 +1,6 @@
1
1
  import { equalDefinitionRefs } from '../../../addressing/definition-ref.js';
2
2
  import { branchesOf, isConnected, targetMode } from '../../../language/policy/analysis/branches.js';
3
+ import { compositionCycles } from '../../../language/policy/analysis/composition.js';
3
4
  import { policyVariableClass } from '../../../language/policy/model/policy.js';
4
5
  import { normalizePolicyExpression, normalizePolicyPattern, } from '../../../language/policy/normalization/normalize.js';
5
6
  import { escapePointerToken } from '../../../language/value/syntax/pointer.js';
@@ -103,31 +104,10 @@ function validateComposition(context, declaration, pointer) {
103
104
  refs.forEach((ref, index) => context.resolvePolicy(ref, `${pointer}/${key}/${index}`));
104
105
  }
105
106
  function validateCycles(context) {
106
- const visiting = new Set();
107
- const visited = new Set();
108
- const visit = (name, stack) => {
109
- if (visiting.has(name)) {
110
- context.add('PL_COMPOSITION', `/policies/${escapePointerToken(name)}`, `Named Policy composition cycle: ${[...stack, name].join(' -> ')}.`);
111
- return;
112
- }
113
- if (visited.has(name))
114
- return;
115
- visiting.add(name);
116
- const declaration = context.environment.candidate.policies[name];
117
- const expression = declaration?.expression;
118
- if (expression !== undefined && !('match' in expression)) {
119
- const refs = 'allOf' in expression ? expression.allOf : expression.anyOf;
120
- for (const ref of refs) {
121
- if (ref.origin === context.environment.candidate.origin && ref.kind === 'policy') {
122
- visit(ref.name, [...stack, name]);
123
- }
124
- }
125
- }
126
- visiting.delete(name);
127
- visited.add(name);
128
- };
129
- for (const name of Object.keys(context.environment.candidate.policies))
130
- visit(name, []);
107
+ const { candidate } = context.environment;
108
+ for (const { path, target } of compositionCycles(Object.keys(candidate.policies), (name) => candidate.policies[name]?.expression, candidate.origin)) {
109
+ context.add('PL_COMPOSITION', `/policies/${escapePointerToken(target)}`, `Named Policy composition cycle: ${[...path, target].join(' -> ')}.`);
110
+ }
131
111
  }
132
112
  function patternOperands(value) {
133
113
  return 'allOf' in value
@@ -1,15 +1,15 @@
1
1
  import type { Value } from './types.js';
2
- import { type Options } from './limits.js';
2
+ import { type Options, type StructuralOptions } from './limits.js';
3
3
  /**
4
4
  * Admit an unknown host value and return a detached portable snapshot.
5
5
  *
6
6
  * Every source property is obtained from one descriptor snapshot. Accessors are never invoked.
7
7
  */
8
- export declare function accept(input: unknown, options?: Options): Value;
8
+ export declare function accept(input: unknown, options?: StructuralOptions): Value;
9
9
  /** Admit a canonically byte-bounded immutable snapshot; owned subtrees may be shared. */
10
10
  export declare function acceptImmutable(input: unknown, options?: Options): Value;
11
11
  /** Admit a read-only snapshot, sharing owned immutable subtrees without freezing new wrappers. */
12
- export declare function acceptForRead(input: unknown, options?: Options): Value;
12
+ export declare function acceptForRead(input: unknown, options?: StructuralOptions): Value;
13
13
  /**
14
14
  * Private PropertyValues owner seam. Retain immediate recursive values, not the enclosing
15
15
  * dictionary: its canonical coordinates are re-admitted by the Property owner on every use.
@@ -6,8 +6,8 @@ import { canonicalPrimitiveBytes, utf8Length } from './unicode.js';
6
6
  const encoder = new TextEncoder();
7
7
  /** RFC 8785 canonical JSON for one admitted portable snapshot. */
8
8
  export function serialize(input, options) {
9
- const limits = limitsFor(options);
10
- return serializeSnapshot(acceptForRead(input, options), limits.maxBytes);
9
+ const { maxBytes, ...structure } = limitsFor(options);
10
+ return serializeSnapshot(acceptForRead(input, { limits: structure }), maxBytes);
11
11
  }
12
12
  /** Serialize a trusted portable value whose default structural admission proof is still valid. */
13
13
  export function serializeAdmitted(input) {
@@ -1,3 +1,11 @@
1
1
  import type { Value } from './types.js';
2
- /** Compare two portable Values by their canonical JSON meaning. */
2
+ /**
3
+ * Whether two admitted Values are the same JSON value: the same scalar, Arrays item by item, Objects
4
+ * with the same names whose values are the same, in any member order. This is exactly when their
5
+ * canonical JSON texts are equal (`proofs/Canonical.lean`).
6
+ *
7
+ * It reads what admission let through and answers for all of it: it admits nothing, so no limit of
8
+ * its own can refuse a value other limits admitted, and it holds neither a text nor a stack frame
9
+ * per level.
10
+ */
3
11
  export declare function equal(left: Value, right: Value): boolean;
@@ -1,5 +1,39 @@
1
- import { serialize } from './json.js';
2
- /** Compare two portable Values by their canonical JSON meaning. */
1
+ /**
2
+ * Whether two admitted Values are the same JSON value: the same scalar, Arrays item by item, Objects
3
+ * with the same names whose values are the same, in any member order. This is exactly when their
4
+ * canonical JSON texts are equal (`proofs/Canonical.lean`).
5
+ *
6
+ * It reads what admission let through and answers for all of it: it admits nothing, so no limit of
7
+ * its own can refuse a value other limits admitted, and it holds neither a text nor a stack frame
8
+ * per level.
9
+ */
3
10
  export function equal(left, right) {
4
- return left === right || serialize(left) === serialize(right);
11
+ const pending = [left, right];
12
+ while (pending.length > 0) {
13
+ const second = pending.pop();
14
+ const first = pending.pop();
15
+ if (first === second)
16
+ continue;
17
+ if (first === null || second === null)
18
+ return false;
19
+ if (typeof first !== 'object' || typeof second !== 'object')
20
+ return false;
21
+ if (Array.isArray(first) !== Array.isArray(second))
22
+ return false;
23
+ if (Array.isArray(first)) {
24
+ if (first.length !== second.length)
25
+ return false;
26
+ first.forEach((item, index) => pending.push(item, second[index]));
27
+ continue;
28
+ }
29
+ const names = Object.keys(first);
30
+ if (names.length !== Object.keys(second).length)
31
+ return false;
32
+ for (const name of names) {
33
+ if (!Object.hasOwn(second, name))
34
+ return false;
35
+ pending.push(first[name], second[name]);
36
+ }
37
+ }
38
+ return true;
5
39
  }
@@ -4,6 +4,6 @@ export { equal } from './equal.js';
4
4
  export { BoundaryError, DecodeError } from './error.js';
5
5
  export type { BoundaryErrorCode, DecodeErrorCode } from './error.js';
6
6
  export { defaultLimits } from './limits.js';
7
- export type { LimitOverrides, Limits, Options } from './limits.js';
7
+ export type { LimitOverrides, Limits, Options, StructuralLimitOverrides, StructuralOptions, } from './limits.js';
8
8
  export * as json from './json.js';
9
9
  export type { Array, Object, Primitive, Value, ValueKind } from './types.js';
@@ -17,5 +17,16 @@ export interface LimitOverrides {
17
17
  export interface Options {
18
18
  readonly limits?: LimitOverrides;
19
19
  }
20
+ /**
21
+ * The limits of a capture that never measures canonical bytes. Holding a value to `maxBytes` takes
22
+ * `acceptImmutable`, or a JSON route, which measure them. `never` rather than absent, so that a shared
23
+ * constant naming bytes is refused as a literal is.
24
+ */
25
+ export interface StructuralLimitOverrides extends Omit<LimitOverrides, 'maxBytes'> {
26
+ readonly maxBytes?: never;
27
+ }
28
+ export interface StructuralOptions {
29
+ readonly limits?: StructuralLimitOverrides;
30
+ }
20
31
  export declare const defaultLimits: Readonly<Limits>;
21
32
  export declare function limitsFor(options: Options | undefined): Limits;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrale-os/kernel-dsl",
3
- "version": "1.0.0-beta.23",
3
+ "version": "1.0.0-beta.25",
4
4
  "description": "Astrale Kernel DSL - Schema authoring, inference, and IR serialization",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -110,7 +110,7 @@
110
110
  "ajv": "^8.20.0",
111
111
  "re2js": "2.8.7",
112
112
  "typescript": "~6.0.3",
113
- "vitest": "^5.0.1",
113
+ "vitest": "^5.0.5",
114
114
  "yaml": "2.9.0"
115
115
  },
116
116
  "scripts": {
@@ -1,12 +0,0 @@
1
- import { type Value as JsonValue } from '@astrale-os/kernel-dsl/value';
2
- import { type Pattern, type RunPattern } from '../../model/schema.js';
3
- /** The machine compiled from each admitted I-Regexp source, shared by its occurrences. */
4
- export type Machines = Map<string, Pattern | RunPattern>;
5
- /**
6
- * Admit one received pattern as data and return the machine compiled from its source. A received
7
- * machine never decides membership: it may come from another compiler, from a host with other
8
- * Unicode data, or from a forger, and the artifact carries no compiler version that could tell a
9
- * current machine from those, so it is ignored rather than compared. Its source decides, through
10
- * the same bounded `isIRegexp` and `compilePattern` that source resolution uses.
11
- */
12
- export declare function pattern(input: JsonValue, patternIndex: number, path: string, machines: Machines): Pattern | RunPattern;
@@ -1,111 +0,0 @@
1
- import {} from '@astrale-os/kernel-dsl/value';
2
- import { compilePattern } from '../../../language/value/regexp/compile.js';
3
- import { isIRegexp } from '../../../language/value/regexp/syntax.js';
4
- import {} from '../../model/schema.js';
5
- import { invalid } from '../diagnostic.js';
6
- import { object, exact, array, integer, scalar, index, boundedInteger } from './value.js';
7
- /**
8
- * Admit one received pattern as data and return the machine compiled from its source. A received
9
- * machine never decides membership: it may come from another compiler, from a host with other
10
- * Unicode data, or from a forger, and the artifact carries no compiler version that could tell a
11
- * current machine from those, so it is ignored rather than compared. Its source decides, through
12
- * the same bounded `isIRegexp` and `compilePattern` that source resolution uses.
13
- */
14
- export function pattern(input, patternIndex, path, machines) {
15
- const value = object(input, `patterns[${patternIndex}]`, path);
16
- const { source } = Object.hasOwn(value, 'runs')
17
- ? runPattern(value, path)
18
- : nfaPattern(value, path);
19
- let machine = machines.get(source);
20
- if (machine === undefined) {
21
- if (!isIRegexp(source))
22
- invalid('Pattern source', 'COMPILED_SOURCE_INVALID', `${path}/source`);
23
- machine = compilePattern(source);
24
- machines.set(source, machine);
25
- }
26
- return machine;
27
- }
28
- function nfaPattern(value, path) {
29
- exact(value, ['source', 'start', 'states'], 'Pattern', path);
30
- if (typeof value.source !== 'string')
31
- invalid('Pattern source', undefined, `${path}/source`);
32
- const statesPath = `${path}/states`;
33
- const states = array(value.states, 'Pattern states', statesPath).map((item, stateIndex) => {
34
- const statePath = `${statesPath}/${stateIndex}`;
35
- const state = object(item, 'Pattern state', statePath);
36
- exact(state, ['epsilon', 'transitions'], 'Pattern state', statePath, ['accepting']);
37
- if (state.accepting !== undefined && state.accepting !== true)
38
- invalid('accepting', undefined, `${statePath}/accepting`);
39
- const epsilonPath = `${statePath}/epsilon`;
40
- const transitionsPath = `${statePath}/transitions`;
41
- return {
42
- epsilon: array(state.epsilon, 'epsilon', epsilonPath).map((target, index) => integer(target, 'epsilon', `${epsilonPath}/${index}`)),
43
- transitions: array(state.transitions, 'transitions', transitionsPath).map((transitionValue, transitionIndex) => {
44
- const transitionPath = `${transitionsPath}/${transitionIndex}`;
45
- const transition = object(transitionValue, 'transition', transitionPath);
46
- exact(transition, ['to', 'ranges'], 'transition', transitionPath);
47
- const rangesPath = `${transitionPath}/ranges`;
48
- return {
49
- to: integer(transition.to, 'transition target', `${transitionPath}/to`),
50
- ranges: array(transition.ranges, 'ranges', rangesPath).map((rangeValue, rangeIndex) => {
51
- const rangePath = `${rangesPath}/${rangeIndex}`;
52
- const range = array(rangeValue, 'range', rangePath);
53
- if (range.length !== 2)
54
- invalid('range', undefined, rangePath);
55
- const minimum = scalar(range[0], 'range minimum', `${rangePath}/0`);
56
- const maximum = scalar(range[1], 'range maximum', `${rangePath}/1`);
57
- if (minimum > maximum)
58
- invalid('range order', undefined, rangePath);
59
- return [minimum, maximum];
60
- }),
61
- };
62
- }),
63
- ...(state.accepting === true ? { accepting: true } : {}),
64
- };
65
- });
66
- const start = index(value.start, states.length, 'Pattern start', `${path}/start`);
67
- for (const [stateIndex, state] of states.entries()) {
68
- state.epsilon.forEach((target, indexValue) => index(target, states.length, 'epsilon', `${statesPath}/${stateIndex}/epsilon/${indexValue}`));
69
- state.transitions.forEach(({ to }, transitionIndex) => index(to, states.length, 'transition', `${statesPath}/${stateIndex}/transitions/${transitionIndex}/to`));
70
- }
71
- return { source: value.source, start, states };
72
- }
73
- function runPattern(value, path) {
74
- exact(value, ['source', 'runs'], 'RunPattern', path);
75
- if (typeof value.source !== 'string')
76
- invalid('Pattern source', undefined, `${path}/source`);
77
- const entries = array(value.runs, 'scalar runs', `${path}/runs`);
78
- if (entries.length === 0 || entries.length > 4096) {
79
- invalid('scalar run count', undefined, `${path}/runs`);
80
- }
81
- const runs = entries.map((entry, position) => {
82
- const runPath = `${path}/runs/${position}`;
83
- const run = object(entry, 'scalar run', runPath);
84
- exact(run, ['ranges', 'minimum'], 'scalar run', runPath, ['maximum']);
85
- const minimum = boundedInteger(run.minimum, 0, 1000, 'run minimum', `${runPath}/minimum`);
86
- const maximum = run.maximum === undefined
87
- ? undefined
88
- : boundedInteger(run.maximum, minimum, 1000, 'run maximum', `${runPath}/maximum`);
89
- if (position !== entries.length - 1 && minimum !== maximum) {
90
- invalid('exact scalar prefix', undefined, `${runPath}/maximum`);
91
- }
92
- let previous = -1;
93
- const ranges = array(run.ranges, 'scalar ranges', `${runPath}/ranges`).map((entry, index) => {
94
- const rangePath = `${runPath}/ranges/${index}`;
95
- const range = array(entry, 'scalar range', rangePath);
96
- if (range.length !== 2)
97
- invalid('scalar range', undefined, rangePath);
98
- const minimum = scalar(range[0], 'range minimum', `${rangePath}/0`);
99
- const maximum = scalar(range[1], 'range maximum', `${rangePath}/1`);
100
- if (minimum > maximum ||
101
- minimum <= previous ||
102
- (minimum >= 0xd800 && minimum <= 0xdfff) ||
103
- (maximum >= 0xd800 && maximum <= 0xdfff))
104
- invalid('ordered scalar range', undefined, rangePath);
105
- previous = maximum;
106
- return [minimum, maximum];
107
- });
108
- return { ranges, minimum, ...(maximum === undefined ? {} : { maximum }) };
109
- });
110
- return { source: value.source, runs };
111
- }