@astrale-os/kernel-dsl 1.0.0-beta.27 → 1.0.0-beta.28

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 (78) hide show
  1. package/dist/v1/addressing/ordering.d.ts +2 -2
  2. package/dist/v1/addressing/ordering.js +2 -4
  3. package/dist/v1/builder/index.d.ts +2 -0
  4. package/dist/v1/builder/index.js +1 -0
  5. package/dist/v1/builder/schema/rule.d.ts +316 -0
  6. package/dist/v1/builder/schema/rule.js +192 -0
  7. package/dist/v1/bundle/index.d.ts +2 -0
  8. package/dist/v1/bundle/index.js +1 -0
  9. package/dist/v1/bundle/rule.d.ts +14 -0
  10. package/dist/v1/bundle/rule.js +41 -0
  11. package/dist/v1/compiled/admission/diagnostic.d.ts +14 -0
  12. package/dist/v1/compiled/admission/diagnostic.js +6 -0
  13. package/dist/v1/compiled/admission/semantics/policy/callable.js +2 -3
  14. package/dist/v1/compiled/admission/semantics/policy/parity.js +8 -13
  15. package/dist/v1/compiled/admission/semantics/policy/pattern.js +3 -5
  16. package/dist/v1/compiled/admission/wire/policy.js +16 -11
  17. package/dist/v1/compiled/index.d.ts +2 -0
  18. package/dist/v1/compiled/index.js +1 -0
  19. package/dist/v1/compiled/rule.d.ts +49 -0
  20. package/dist/v1/compiled/rule.js +169 -0
  21. package/dist/v1/language/callable/admission.js +2 -1
  22. package/dist/v1/language/policy/analysis/branches.js +6 -7
  23. package/dist/v1/language/policy/analysis/budgets.js +8 -6
  24. package/dist/v1/language/policy/analysis/checks.js +5 -4
  25. package/dist/v1/language/policy/analysis/composition.js +2 -2
  26. package/dist/v1/language/policy/analysis/typing.js +3 -2
  27. package/dist/v1/language/policy/model/policy.d.ts +22 -0
  28. package/dist/v1/language/policy/model/policy.js +28 -4
  29. package/dist/v1/language/policy/normalization/normalize.js +33 -56
  30. package/dist/v1/language/value/evaluate/assertions.d.ts +2 -2
  31. package/dist/v1/language/value/evaluate/assertions.js +4 -34
  32. package/dist/v1/language/value/evaluate/evaluator.js +10 -15
  33. package/dist/v1/language/value/evaluate/validity.optimization.js +9 -14
  34. package/dist/v1/language/value/files.js +2 -1
  35. package/dist/v1/language/value/ordering.js +1 -3
  36. package/dist/v1/language/value/profile/canonicalize.js +1 -3
  37. package/dist/v1/language/value/syntax/walk.d.ts +2 -0
  38. package/dist/v1/language/value/syntax/walk.js +4 -0
  39. package/dist/v1/schema/compatibility/api.d.ts +2 -0
  40. package/dist/v1/schema/compatibility/api.js +1 -0
  41. package/dist/v1/schema/compatibility/rule.d.ts +13 -0
  42. package/dist/v1/schema/compatibility/rule.js +23 -0
  43. package/dist/v1/schema/enforcement/changes.d.ts +590 -0
  44. package/dist/v1/schema/enforcement/changes.js +566 -0
  45. package/dist/v1/schema/enforcement/derived.d.ts +236 -0
  46. package/dist/v1/schema/enforcement/derived.js +243 -0
  47. package/dist/v1/schema/enforcement/dispose.d.ts +308 -0
  48. package/dist/v1/schema/enforcement/dispose.js +275 -0
  49. package/dist/v1/schema/enforcement/facts.d.ts +89 -0
  50. package/dist/v1/schema/enforcement/facts.js +70 -0
  51. package/dist/v1/schema/enforcement/fields.d.ts +65 -0
  52. package/dist/v1/schema/enforcement/fields.js +36 -0
  53. package/dist/v1/schema/enforcement/index.d.ts +39 -0
  54. package/dist/v1/schema/enforcement/index.js +10 -0
  55. package/dist/v1/schema/enforcement/install.d.ts +1634 -0
  56. package/dist/v1/schema/enforcement/install.js +1223 -0
  57. package/dist/v1/schema/enforcement/lifecycle.d.ts +87 -0
  58. package/dist/v1/schema/enforcement/lifecycle.js +91 -0
  59. package/dist/v1/schema/enforcement/model.d.ts +253 -0
  60. package/dist/v1/schema/enforcement/model.js +1 -0
  61. package/dist/v1/schema/enforcement/obligations.d.ts +248 -0
  62. package/dist/v1/schema/enforcement/obligations.js +240 -0
  63. package/dist/v1/schema/enforcement/write.d.ts +1314 -0
  64. package/dist/v1/schema/enforcement/write.js +1017 -0
  65. package/dist/v1/schema/index.d.ts +1 -0
  66. package/dist/v1/schema/index.js +1 -0
  67. package/dist/v1/schema/resolution/origins.js +4 -7
  68. package/dist/v1/schema/rule.d.ts +4 -5
  69. package/dist/v1/schema/rule.js +19 -13
  70. package/dist/v1/schema/validation/policy/references.js +5 -11
  71. package/dist/v1/schema/validation/policy/uses.js +3 -8
  72. package/dist/value/canonical.d.ts +16 -1
  73. package/dist/value/canonical.js +90 -33
  74. package/dist/value/index.d.ts +2 -0
  75. package/dist/value/index.js +1 -0
  76. package/dist/value/rule.d.ts +12 -0
  77. package/dist/value/rule.js +50 -0
  78. package/package.json +5 -1
@@ -24,6 +24,7 @@ export { SchemaError as Error } from './diagnostic.js';
24
24
  export type { SchemaDiagnostic as Diagnostic } from './diagnostic.js';
25
25
  export { RULES } from './rule.js';
26
26
  export type { SchemaRule as Rule, SchemaRuleStage as RuleStage } from './rule.js';
27
+ export * as enforcement from './enforcement/index.js';
27
28
  export { limits } from '../language/limits.js';
28
29
  export type { LimitKey } from '../language/limits.js';
29
30
  export { measurePolicies } from './validation/policy/budgets.js';
@@ -12,6 +12,7 @@ export { DOMAIN_FORMAT as FORMAT, DOMAIN_VERSION as VERSION } from './model/form
12
12
  export { compile, load } from '../compiled/index.js';
13
13
  export { SchemaError as Error } from './diagnostic.js';
14
14
  export { RULES } from './rule.js';
15
+ export * as enforcement from './enforcement/index.js';
15
16
  export { limits } from '../language/limits.js';
16
17
  export { measurePolicies } from './validation/policy/budgets.js';
17
18
  /** The versioned value-schema grammar embedded in declarations. */
@@ -1,6 +1,6 @@
1
1
  import { compareDefinitionRefs, definitionRefIndex } from '../../addressing/ordering.js';
2
2
  import { isBinaryInput } from '../../language/callable/model/callable.js';
3
- import { CLASS_OPERATIONS, isClassRuleChecks, policyVariableClass, } from '../../language/policy/model/policy.js';
3
+ import { CLASS_OPERATIONS, isClassRuleChecks, PolicyComposition, policyVariableClass, } from '../../language/policy/model/policy.js';
4
4
  import { isValueObject as isJsonObject } from '../../language/value/model/object.js';
5
5
  import { walkSchema } from '../../language/value/syntax/walk.js';
6
6
  /** Collect only semantic refs, never strings or objects embedded as JSON data. */
@@ -95,8 +95,7 @@ function collectPolicyExpressionRefs(expression, add) {
95
95
  collectPolicyPatternRefs(expression.match, add);
96
96
  return;
97
97
  }
98
- const refs = 'allOf' in expression ? expression.allOf : expression.anyOf;
99
- refs.forEach((ref) => add(ref, 'policy'));
98
+ PolicyComposition.of(expression).operands.forEach((ref) => add(ref, 'policy'));
100
99
  }
101
100
  function collectPolicyPatternRefs(expression, add) {
102
101
  if ('sameNode' in expression) {
@@ -121,8 +120,7 @@ function collectPolicyPatternRefs(expression, add) {
121
120
  collectPolicyPatternRefs(expression.exists.where, add);
122
121
  return;
123
122
  }
124
- const children = 'allOf' in expression ? expression.allOf : expression.anyOf;
125
- children.forEach((child) => collectPolicyPatternRefs(child, add));
123
+ PolicyComposition.of(expression).operands.forEach((child) => collectPolicyPatternRefs(child, add));
126
124
  }
127
125
  function collectPolicyCheckRefs(expression, add) {
128
126
  if ('sameNode' in expression) {
@@ -137,8 +135,7 @@ function collectPolicyCheckRefs(expression, add) {
137
135
  add(expression.object.ref, 'policy');
138
136
  return;
139
137
  }
140
- const children = 'allOf' in expression ? expression.allOf : expression.anyOf;
141
- children.forEach((child) => collectPolicyCheckRefs(child, add));
138
+ PolicyComposition.of(expression).operands.forEach((child) => collectPolicyCheckRefs(child, add));
142
139
  }
143
140
  export function collectValueDefinitionRefs(schema, add) {
144
141
  walkSchema(schema, ({ schema: current }) => {
@@ -16,11 +16,10 @@ export type SchemaRuleStage = 'structure' | 'rule' | 'context';
16
16
  */
17
17
  export interface SchemaRule extends DiagnosticRule {
18
18
  readonly stage: SchemaRuleStage;
19
- /** What the feature the rule guards enforces on data or on calls, where it enforces something. */
19
+ /**
20
+ * What the feature the rule guards enforces, where it enforces something: on data, the statement of
21
+ * each row of `enforcement` which names the rule; on calls and reads, which no table holds, its own.
22
+ */
20
23
  readonly enforces?: string;
21
24
  }
22
- /**
23
- * Every Schema diagnostic code with the rule it reports. A code added to the DSL does not compile
24
- * until it is described here.
25
- */
26
25
  export declare const RULES: Readonly<Record<SchemaDiagnosticCode, SchemaRule>>;
@@ -2,6 +2,8 @@ import { defaultLimits } from '@astrale-os/kernel-dsl/value';
2
2
  import * as metadata from '../language/definition/metadata.js';
3
3
  import { deepFreeze } from '../language/freeze.js';
4
4
  import { limits } from '../language/limits.js';
5
+ import { DISPOSE } from './enforcement/dispose.js';
6
+ import { WRITE } from './enforcement/write.js';
5
7
  const ANY = ['{/path*}'];
6
8
  const CHECKS = [
7
9
  '/classes/{class}/policies/{operation}{/path*}',
@@ -19,7 +21,7 @@ const at = (field) => [
19
21
  * Every Schema diagnostic code with the rule it reports. A code added to the DSL does not compile
20
22
  * until it is described here.
21
23
  */
22
- export const RULES = deepFreeze({
24
+ const DECLARED = {
23
25
  DV_ACCEPTANCE_CONTEXT: {
24
26
  stage: 'context',
25
27
  positions: ['/dependencies'],
@@ -47,7 +49,6 @@ export const RULES = deepFreeze({
47
49
  stage: 'rule',
48
50
  positions: ['/classes/{class}/policies'],
49
51
  statement: 'An abstract Class declares no read or traverse Policy.',
50
- enforces: 'No Node or Edge is of an abstract Class exactly: only its concrete descendants are.',
51
52
  },
52
53
  DV_CLASS_ACYCLIC: {
53
54
  stage: 'rule',
@@ -82,7 +83,7 @@ export const RULES = deepFreeze({
82
83
  DV_CORE_EDGE_PROPERTIES: {
83
84
  stage: 'context',
84
85
  positions: ['/core/edges/{index}/properties{/path*}'],
85
- statement: 'The Properties of a Core Edge satisfy its Class: every required Property that no automatic program writes is present, every automatic one is absent, and each value fits its schema.',
86
+ statement: 'The Properties of a Core Edge satisfy its Class: every required Property that no automatic program writes is present, every automatic one is absent, and each value fits its schema. Each value is judged alone, against the schema of its Property, as the root of its local references.',
86
87
  },
87
88
  DV_CORE_EDGE_UNIQUE: {
88
89
  stage: 'context',
@@ -97,7 +98,7 @@ export const RULES = deepFreeze({
97
98
  DV_CORE_NODE_PROPERTIES: {
98
99
  stage: 'context',
99
100
  positions: ['/core/nodes/{slug}/properties{/path*}'],
100
- statement: 'The Properties of a Core Node satisfy its Class: every required Property that no automatic program writes is present, every automatic one is absent, and each value fits its schema.',
101
+ statement: 'The Properties of a Core Node satisfy its Class: every required Property that no automatic program writes is present, every automatic one is absent, and each value fits its schema. Each value is judged alone, against the schema of its Property, as the root of its local references.',
101
102
  },
102
103
  DV_CORE_NODE_UNIQUE: {
103
104
  stage: 'context',
@@ -164,13 +165,11 @@ export const RULES = deepFreeze({
164
165
  stage: 'rule',
165
166
  positions: ['/classes/{class}/endpoints/{endpoint}/{count}'],
166
167
  statement: 'An Edge endpoint that accepts a Class another Domain owns requires no minimum count: neither 1 nor 1..*.',
167
- enforces: 'Every Node an endpoint accepts holds a number of Edges of the Class within its count: at least one for 1 and 1..*, at most one for 0..1 and 1.',
168
168
  },
169
169
  DV_EDGE_LIFETIME: {
170
170
  stage: 'rule',
171
171
  positions: ['/classes/{class}/endpoints/{endpoint}/onDelete'],
172
172
  statement: 'An endpoint that can hold a Node of another Domain does not declare restrict, and no endpoint declares detach in an Edge Class with an endpoint that requires an Edge.',
173
- enforces: 'Deleting a Node at a restrict endpoint is refused unless the same transition deletes the Edge; at a detach endpoint the Edge is deleted with the Node.',
174
173
  },
175
174
  DV_EDGE_ROLE: {
176
175
  stage: 'rule',
@@ -181,7 +180,6 @@ export const RULES = deepFreeze({
181
180
  stage: 'context',
182
181
  positions: ['/classes/{class}/unique/{index}/{index}/property'],
183
182
  statement: 'Each Property a unique tuple of an Edge Class names is a Property of the Class, own or inherited, that is keyable: a string, number, boolean or instant that no automatic program writes.',
184
- enforces: 'No two Edges of the Class and of its concrete descendants share the values of a tuple’s fields while each of those fields is present.',
185
183
  },
186
184
  DV_ENTRYPOINT: {
187
185
  stage: 'rule',
@@ -218,7 +216,6 @@ export const RULES = deepFreeze({
218
216
  stage: 'context',
219
217
  positions: ['/classes/{class}/unique/{index}/{index}'],
220
218
  statement: 'Each Property a unique tuple of a Node Class names is a Property of the Class, own or inherited, that is keyable: a string, number, boolean or instant that no automatic program writes.',
221
- enforces: 'No two Nodes of the Class and of its concrete descendants share the values of a tuple while every Property of the tuple has a value; a Node missing one holds no key.',
222
219
  },
223
220
  DV_PROPERTY_AUTO: {
224
221
  stage: 'context',
@@ -227,19 +224,16 @@ export const RULES = deepFreeze({
227
224
  '/classes/{class}/properties/{property}/auto/set',
228
225
  ],
229
226
  statement: 'A required automatic Property is written on create, and the instant setter writes only a Property whose schema is an instant.',
230
- enforces: 'The Kernel sets the Property to the instant of each transition of its events, and refuses a transition that writes it.',
231
227
  },
232
228
  DV_PROPERTY_IMMUTABLE: {
233
229
  stage: 'rule',
234
230
  positions: ['/classes/{class}/properties/{property}/immutable'],
235
231
  statement: 'An immutable Property is neither automatic nor a State Property, and a required one is immutable from create, not once.',
236
- enforces: 'A create Property is written only when its Node or Edge is created; a once Property is written only while it is absent, and never unset.',
237
232
  },
238
233
  DV_PROPERTY_STATE: {
239
234
  stage: 'rule',
240
235
  positions: ['/classes/{class}/properties/{property}/state'],
241
236
  statement: 'A State Property is required and not automatic, has the string enumeration of exactly its states as schema, and a topology whose initial state and transition targets are its states.',
242
- enforces: 'Its value is always one of its states; the Kernel does not hold changes to its transitions.',
243
237
  },
244
238
  DV_REF_RESOLVES: {
245
239
  stage: 'context',
@@ -367,7 +361,6 @@ export const RULES = deepFreeze({
367
361
  '/classes/{class}/constraints/acyclic',
368
362
  ],
369
363
  statement: 'A directed Edge Class has source and target endpoints and an undirected one two incident endpoints, and only a directed one declares unique tuples or is acyclic.',
370
- enforces: 'No Edges of an acyclic Class form a directed cycle.',
371
364
  conditions: ['#/$defs/edge-class/if'],
372
365
  },
373
366
  STRUCTURE_FORMAT: {
@@ -450,4 +443,17 @@ export const RULES = deepFreeze({
450
443
  positions: ['/version'],
451
444
  statement: 'The document version is one this DSL reads: v1.',
452
445
  },
453
- });
446
+ };
447
+ const ROWS = [
448
+ ...Object.values(WRITE),
449
+ ...Object.values(DISPOSE),
450
+ ];
451
+ /**
452
+ * What a rule's feature enforces on data is the statement of each row which names the rule, so a
453
+ * rule restates none. A rule keeps its own sentence only for what no table holds: calls, reads.
454
+ */
455
+ function withItsRows([code, rule]) {
456
+ const statements = ROWS.filter((row) => row.accepted === code).map((row) => row.statement);
457
+ return [code, statements.length === 0 ? rule : { ...rule, enforces: statements.join(' ') }];
458
+ }
459
+ export const RULES = deepFreeze(Object.fromEntries(Object.entries(DECLARED).map(withItsRows)));
@@ -1,7 +1,7 @@
1
1
  import { equalDefinitionRefs } from '../../../addressing/definition-ref.js';
2
2
  import { branchesOf, isConnected, targetMode } from '../../../language/policy/analysis/branches.js';
3
3
  import { compositionCycles } from '../../../language/policy/analysis/composition.js';
4
- import { policyVariableClass } from '../../../language/policy/model/policy.js';
4
+ import { PolicyComposition, policyVariableClass } from '../../../language/policy/model/policy.js';
5
5
  import { normalizePolicyExpression, normalizePolicyPattern, } from '../../../language/policy/normalization/normalize.js';
6
6
  import { escapePointerToken } from '../../../language/value/syntax/pointer.js';
7
7
  import { referenceContracts } from './objects.js';
@@ -83,8 +83,8 @@ function validatePatternNode(context, pattern, pointer, scope, declarations, use
83
83
  validatePatternNode(context, pattern.exists.where, `${pointer}/exists/where`, nested, declarations, uses);
84
84
  return;
85
85
  }
86
- const { key, values } = patternOperands(pattern);
87
- values.forEach((child, index) => validatePatternNode(context, child, `${pointer}/${key}/${index}`, scope, declarations, uses));
86
+ const { operator, operands } = PolicyComposition.of(pattern);
87
+ operands.forEach((child, index) => validatePatternNode(context, child, `${pointer}/${operator}/${index}`, scope, declarations, uses));
88
88
  }
89
89
  function validateTerm(context, term, pointer, scope, uses) {
90
90
  if (term.kind === 'ref')
@@ -99,9 +99,8 @@ function validateTerm(context, term, pointer, scope, uses) {
99
99
  }
100
100
  }
101
101
  function validateComposition(context, declaration, pointer) {
102
- const key = 'allOf' in declaration ? 'allOf' : 'anyOf';
103
- const refs = 'allOf' in declaration ? declaration.allOf : declaration.anyOf;
104
- refs.forEach((ref, index) => context.resolvePolicy(ref, `${pointer}/${key}/${index}`));
102
+ const { operator, operands } = PolicyComposition.of(declaration);
103
+ operands.forEach((ref, index) => context.resolvePolicy(ref, `${pointer}/${operator}/${index}`));
105
104
  }
106
105
  function validateCycles(context) {
107
106
  const { candidate } = context.environment;
@@ -109,11 +108,6 @@ function validateCycles(context) {
109
108
  context.add('PL_COMPOSITION', `/policies/${escapePointerToken(target)}`, `Named Policy composition cycle: ${[...path, target].join(' -> ')}.`);
110
109
  }
111
110
  }
112
- function patternOperands(value) {
113
- return 'allOf' in value
114
- ? { key: 'allOf', values: value.allOf }
115
- : { key: 'anyOf', values: value.anyOf };
116
- }
117
111
  function isEdge(value) {
118
112
  return 'source' in value;
119
113
  }
@@ -2,7 +2,7 @@ import { Key } from '../../../addressing/index.js';
2
2
  import { definitionRefIndex } from '../../../addressing/ordering.js';
3
3
  import { isBinaryInput } from '../../../language/callable/model/callable.js';
4
4
  import { neverAdmittedClasses, } from '../../../language/policy/analysis/checks.js';
5
- import { CLASS_OPERATIONS, checksNameTheCaller, isClassRuleChecks, } from '../../../language/policy/model/policy.js';
5
+ import { CLASS_OPERATIONS, checksNameTheCaller, isClassRuleChecks, PolicyComposition, } from '../../../language/policy/model/policy.js';
6
6
  import { normalizePolicyChecks } from '../../../language/policy/normalization/normalize.js';
7
7
  import { GRAPH_NODE_PATH_SCHEMA_ID } from '../../../language/value/syntax/node-path/schema.js';
8
8
  import { escapePointerToken } from '../../../language/value/syntax/pointer.js';
@@ -139,8 +139,8 @@ function visitChecks(validation, typing, expression, context, pointer, leaves) {
139
139
  leaves.set(expression, classes);
140
140
  return;
141
141
  }
142
- const { key, values } = checkOperands(expression);
143
- values.forEach((child, index) => visitChecks(validation, typing, child, context, `${pointer}/${key}/${index}`, leaves));
142
+ const { operator, operands } = PolicyComposition.of(expression);
143
+ operands.forEach((child, index) => visitChecks(validation, typing, child, context, `${pointer}/${operator}/${index}`, leaves));
144
144
  }
145
145
  function selfContracts(validation, context, pointer) {
146
146
  if (context.receiver === undefined) {
@@ -202,8 +202,3 @@ function isDefinitionRef(value) {
202
202
  record.kind === 'class' &&
203
203
  typeof record.name === 'string');
204
204
  }
205
- function checkOperands(value) {
206
- return 'allOf' in value
207
- ? { key: 'allOf', values: value.allOf }
208
- : { key: 'anyOf', values: value.anyOf };
209
- }
@@ -1,4 +1,4 @@
1
- import type { Value } from './types.js';
1
+ import type { Primitive, Value } from './types.js';
2
2
  import { type Options } from './limits.js';
3
3
  /** RFC 8785 canonical JSON for one admitted portable snapshot. */
4
4
  export declare function serialize(input: unknown, options?: Options): string;
@@ -11,3 +11,18 @@ export declare function encode(input: unknown, options?: Options): Uint8Array;
11
11
  * other container is counted member by member.
12
12
  */
13
13
  export declare function byteLength(input: Value): number;
14
+ /** The order of member names in canonical JSON: by UTF-16 code unit, the order `<` gives strings. */
15
+ export declare function compareCodeUnits(left: string, right: string): number;
16
+ declare const ARRAY: unique symbol;
17
+ declare const OBJECT: unique symbol;
18
+ declare const END: unique symbol;
19
+ export type CanonicalToken = Primitive | typeof ARRAY | typeof OBJECT | typeof END;
20
+ /**
21
+ * A trusted Value as the tokens of its canonical JSON, in order: each scalar and member name, and
22
+ * where each container starts and ends, with member names in `compareCodeUnits` order. Two values
23
+ * have the same tokens exactly when they have the same canonical JSON text, and no value's tokens
24
+ * are a prefix of another's. Admission bounded the value, so the reading checks no limit of its own,
25
+ * and it holds neither the text, which may outgrow any string, nor a stack frame per level.
26
+ */
27
+ export declare function canonicalTokens(value: Value): Generator<CanonicalToken, void, undefined>;
28
+ export {};
@@ -50,44 +50,101 @@ export function byteLength(input) {
50
50
  }
51
51
  /** The canonical JSON bytes of a trusted Value, counted member by member, owned roots at once. */
52
52
  function measure(value) {
53
- if (value === null || typeof value !== 'object')
54
- return canonicalPrimitiveBytes(value);
55
- const owned = immutableSnapshotBytes(value);
56
- if (owned !== undefined)
57
- return owned;
58
- if (Array.isArray(value)) {
59
- let bytes = 2 + Math.max(0, value.length - 1);
60
- for (const item of value)
61
- bytes += measure(item);
62
- return bytes;
53
+ let bytes = 0;
54
+ const pending = [value];
55
+ while (pending.length > 0) {
56
+ const next = pending.pop();
57
+ if (next === null || typeof next !== 'object') {
58
+ bytes += canonicalPrimitiveBytes(next);
59
+ continue;
60
+ }
61
+ const owned = immutableSnapshotBytes(next);
62
+ if (owned !== undefined) {
63
+ bytes += owned;
64
+ }
65
+ else if (Array.isArray(next)) {
66
+ bytes += 2 + Math.max(0, next.length - 1);
67
+ for (const item of next)
68
+ pending.push(item);
69
+ }
70
+ else {
71
+ const names = Object.keys(next);
72
+ bytes += 2 + Math.max(0, names.length - 1) + names.length;
73
+ for (const name of names) {
74
+ bytes += canonicalPrimitiveBytes(name);
75
+ pending.push(next[name]);
76
+ }
77
+ }
63
78
  }
64
- const keys = Object.keys(value);
65
- let bytes = 2 + Math.max(0, keys.length - 1) + keys.length;
66
- for (const key of keys)
67
- bytes += canonicalPrimitiveBytes(key) + measure(value[key]);
68
79
  return bytes;
69
80
  }
70
81
  function serializeValue(value) {
71
- if (value === null)
72
- return 'null';
73
- switch (typeof value) {
74
- case 'boolean':
75
- return value ? 'true' : 'false';
76
- case 'number':
77
- case 'string':
78
- return JSON.stringify(value);
79
- case 'object':
80
- return Array.isArray(value)
81
- ? `[${value.map(serializeValue).join(',')}]`
82
- : serializeObject(value);
82
+ let output = '';
83
+ const closers = [];
84
+ // Whether the last token completed a value, so that the next entry follows a comma, and whether
85
+ // it was an Object member name, so that the next token is that member's value.
86
+ let complete = false;
87
+ let named = false;
88
+ for (const token of canonicalTokens(value)) {
89
+ if (token === END) {
90
+ output += closers.pop();
91
+ complete = true;
92
+ continue;
93
+ }
94
+ if (complete)
95
+ output += ',';
96
+ complete = false;
97
+ if (!named && closers.at(-1) === '}') {
98
+ output += `${JSON.stringify(token)}:`;
99
+ named = true;
100
+ continue;
101
+ }
102
+ named = false;
103
+ if (token === ARRAY || token === OBJECT) {
104
+ output += token === ARRAY ? '[' : '{';
105
+ closers.push(token === ARRAY ? ']' : '}');
106
+ }
107
+ else {
108
+ output += JSON.stringify(token);
109
+ complete = true;
110
+ }
83
111
  }
112
+ return output;
84
113
  }
85
- function serializeObject(value) {
86
- return `{${Object.keys(value)
87
- .sort(compareUtf16)
88
- .map((key) => `${JSON.stringify(key)}:${serializeValue(value[key])}`)
89
- .join(',')}}`;
90
- }
91
- function compareUtf16(left, right) {
114
+ /** The order of member names in canonical JSON: by UTF-16 code unit, the order `<` gives strings. */
115
+ export function compareCodeUnits(left, right) {
92
116
  return left < right ? -1 : left > right ? 1 : 0;
93
117
  }
118
+ const ARRAY = Symbol('array');
119
+ const OBJECT = Symbol('object');
120
+ const END = Symbol('end');
121
+ /**
122
+ * A trusted Value as the tokens of its canonical JSON, in order: each scalar and member name, and
123
+ * where each container starts and ends, with member names in `compareCodeUnits` order. Two values
124
+ * have the same tokens exactly when they have the same canonical JSON text, and no value's tokens
125
+ * are a prefix of another's. Admission bounded the value, so the reading checks no limit of its own,
126
+ * and it holds neither the text, which may outgrow any string, nor a stack frame per level.
127
+ */
128
+ export function* canonicalTokens(value) {
129
+ const pending = [value];
130
+ while (pending.length > 0) {
131
+ const next = pending.pop();
132
+ if (next === null || typeof next !== 'object') {
133
+ yield next;
134
+ }
135
+ else if (Array.isArray(next)) {
136
+ yield ARRAY;
137
+ pending.push(END);
138
+ for (let index = next.length - 1; index >= 0; index -= 1)
139
+ pending.push(next[index]);
140
+ }
141
+ else {
142
+ yield OBJECT;
143
+ pending.push(END);
144
+ const names = Object.keys(next).sort(compareCodeUnits);
145
+ for (let index = names.length - 1; index >= 0; index -= 1) {
146
+ pending.push(next[names[index]], names[index]);
147
+ }
148
+ }
149
+ }
150
+ }
@@ -6,4 +6,6 @@ export type { BoundaryErrorCode, DecodeErrorCode } from './error.js';
6
6
  export { defaultLimits } from './limits.js';
7
7
  export type { LimitOverrides, Limits, Options, StructuralLimitOverrides, StructuralOptions, } from './limits.js';
8
8
  export * as json from './json.js';
9
+ export { PORTABLE_VALUE_RULES } from './rule.js';
10
+ export type { PortableValueRule } from './rule.js';
9
11
  export type { Array, Object, Primitive, Value, ValueKind } from './types.js';
@@ -4,3 +4,4 @@ export { equal } from './equal.js';
4
4
  export { BoundaryError, DecodeError } from './error.js';
5
5
  export { defaultLimits } from './limits.js';
6
6
  export * as json from './json.js';
7
+ export { PORTABLE_VALUE_RULES } from './rule.js';
@@ -0,0 +1,12 @@
1
+ import type { BoundaryErrorCode, DecodeErrorCode } from './error.js';
2
+ import type { Limits } from './limits.js';
3
+ /** The rule one portable value code reports, stated once, and the limits it enforces. */
4
+ export interface PortableValueRule {
5
+ readonly statement: string;
6
+ readonly limits?: readonly [keyof Limits, ...(keyof Limits)[]];
7
+ }
8
+ /**
9
+ * Every code of a refused host value or JSON text with the rule it reports, frozen. A code added
10
+ * here does not compile until it is described.
11
+ */
12
+ export declare const PORTABLE_VALUE_RULES: Readonly<Record<BoundaryErrorCode | DecodeErrorCode, PortableValueRule>>;
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Every code of a refused host value or JSON text with the rule it reports, frozen. A code added
3
+ * here does not compile until it is described.
4
+ */
5
+ export const PORTABLE_VALUE_RULES = Object.freeze({
6
+ VALUE_TYPE: {
7
+ statement: 'A portable value is null, a boolean, a number, a string, an array or an object: a function, a bigint, a symbol or undefined is none, anywhere in it.',
8
+ },
9
+ VALUE_NUMBER: {
10
+ statement: 'A portable number is finite and is not negative zero.',
11
+ },
12
+ VALUE_STRING: {
13
+ statement: 'A portable string, a member name included, holds Unicode scalar values and no U+0000.',
14
+ },
15
+ VALUE_ARRAY: {
16
+ statement: 'A portable array has a valid length and no hole, no symbol or other member than its indexes, and each element an enumerable data property.',
17
+ },
18
+ VALUE_OBJECT: {
19
+ statement: 'A portable object has no prototype or one with none of its own, no symbol member, and each member an enumerable data property.',
20
+ },
21
+ VALUE_CYCLE: {
22
+ statement: 'A portable value does not contain itself.',
23
+ },
24
+ VALUE_LIMIT: {
25
+ statement: 'A portable value holds within the limits of its admission: its nesting, its total of members and elements, the bytes of one string, and the bytes of its canonical JSON where it is captured immutable, serialized or measured.',
26
+ limits: ['maxDepth', 'maxMembers', 'maxStringBytes', 'maxBytes'],
27
+ },
28
+ VALUE_REFLECTION: {
29
+ statement: 'A host value whose reflection throws is refused, with what it threw as the cause.',
30
+ },
31
+ JSON_SYNTAX: {
32
+ statement: 'JSON text is exactly one strict JSON value, without a byte order mark.',
33
+ },
34
+ JSON_UTF8: {
35
+ statement: 'JSON bytes are valid UTF-8.',
36
+ },
37
+ JSON_DUPLICATE_MEMBER: {
38
+ statement: 'A JSON object names each member once, compared after decoding.',
39
+ },
40
+ JSON_NUMBER: {
41
+ statement: 'A JSON number resolves to a finite binary64 and not to negative zero.',
42
+ },
43
+ JSON_STRING: {
44
+ statement: 'A JSON string, a member name included, holds Unicode scalar values and no U+0000.',
45
+ },
46
+ JSON_LIMIT: {
47
+ statement: 'JSON text holds within the limits of its decoding: its bytes, its nesting, its total of members and elements, and the bytes of one string.',
48
+ limits: ['maxBytes', 'maxDepth', 'maxMembers', 'maxStringBytes'],
49
+ },
50
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrale-os/kernel-dsl",
3
- "version": "1.0.0-beta.27",
3
+ "version": "1.0.0-beta.28",
4
4
  "description": "Astrale Kernel DSL - Schema authoring, inference, and IR serialization",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -71,6 +71,10 @@
71
71
  "types": "./dist/v1/schema/compatibility/api.d.ts",
72
72
  "import": "./dist/v1/schema/compatibility/api.js"
73
73
  },
74
+ "./v1/schema/enforcement": {
75
+ "types": "./dist/v1/schema/enforcement/index.d.ts",
76
+ "import": "./dist/v1/schema/enforcement/index.js"
77
+ },
74
78
  "./v1/schema/fingerprint": {
75
79
  "types": "./dist/v1/schema/fingerprint.d.ts",
76
80
  "import": "./dist/v1/schema/fingerprint.js"