@cratis/chronicle 6.67.7 → 6.68.1

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 (53) hide show
  1. package/ChronicleClient.ts +14 -1
  2. package/ChronicleOptions.ts +12 -0
  3. package/EventStoreNamespaceResolver.ts +19 -0
  4. package/dist/ChronicleClient.d.ts +1 -0
  5. package/dist/ChronicleClient.d.ts.map +1 -1
  6. package/dist/ChronicleClient.js +14 -1
  7. package/dist/ChronicleClient.js.map +1 -1
  8. package/dist/ChronicleOptions.d.ts +8 -0
  9. package/dist/ChronicleOptions.d.ts.map +1 -1
  10. package/dist/ChronicleOptions.js +8 -0
  11. package/dist/ChronicleOptions.js.map +1 -1
  12. package/dist/EventStoreNamespaceResolver.d.ts +16 -0
  13. package/dist/EventStoreNamespaceResolver.d.ts.map +1 -0
  14. package/dist/EventStoreNamespaceResolver.js +4 -0
  15. package/dist/EventStoreNamespaceResolver.js.map +1 -0
  16. package/dist/index.d.ts +1 -0
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js.map +1 -1
  19. package/dist/testing/ConstraintKey.d.ts.map +1 -1
  20. package/dist/testing/ConstraintKey.js +32 -17
  21. package/dist/testing/ConstraintKey.js.map +1 -1
  22. package/dist/testing/EventScenario.d.ts.map +1 -1
  23. package/dist/testing/EventScenario.js +100 -67
  24. package/dist/testing/EventScenario.js.map +1 -1
  25. package/dist/testing/EventTypeConstraintClaims.d.ts +15 -0
  26. package/dist/testing/EventTypeConstraintClaims.d.ts.map +1 -0
  27. package/dist/testing/EventTypeConstraintClaims.js +66 -0
  28. package/dist/testing/EventTypeConstraintClaims.js.map +1 -0
  29. package/dist/testing/InProcessConstraints.d.ts.map +1 -1
  30. package/dist/testing/InProcessConstraints.js +8 -91
  31. package/dist/testing/InProcessConstraints.js.map +1 -1
  32. package/dist/testing/MeasuredCaseFolding.d.ts +14 -0
  33. package/dist/testing/MeasuredCaseFolding.d.ts.map +1 -0
  34. package/dist/testing/MeasuredCaseFolding.js +17 -0
  35. package/dist/testing/MeasuredCaseFolding.js.map +1 -0
  36. package/dist/testing/PropertyConstraintClaims.d.ts +17 -0
  37. package/dist/testing/PropertyConstraintClaims.d.ts.map +1 -0
  38. package/dist/testing/PropertyConstraintClaims.js +69 -0
  39. package/dist/testing/PropertyConstraintClaims.js.map +1 -0
  40. package/dist/tsconfig.tsbuildinfo +1 -1
  41. package/for_ChronicleClient/when_resolving_a_namespace.spec.ts +198 -0
  42. package/index.ts +1 -0
  43. package/package.json +1 -1
  44. package/testing/ConstraintKey.ts +34 -15
  45. package/testing/EventScenario.fixtures.spec.ts +1 -1
  46. package/testing/EventScenario.ts +120 -66
  47. package/testing/EventTypeConstraintClaims.ts +68 -0
  48. package/testing/InProcessConstraints.ts +7 -86
  49. package/testing/MeasuredCaseFolding.ts +22 -0
  50. package/testing/PropertyConstraintClaims.ts +75 -0
  51. package/testing/for_EventScenario/when_appending_case_folded_text/case_folded_text.fixture.ts +160 -0
  52. package/testing/for_EventScenario/when_appending_case_folded_text/with_case_folded_text.legacy.spec.ts +14 -0
  53. package/testing/for_EventScenario/when_appending_case_folded_text/with_case_folded_text.standard.spec.ts +13 -0
@@ -7,18 +7,23 @@ import type { ConstraintCapture } from '../events/constraints/ConstraintBuilder.
7
7
  import type { JsonSchema } from '../schemas/JsonSchema.js';
8
8
  import { UnsupportedEventSequenceOperation } from './UnsupportedEventSequenceOperation.js';
9
9
  import { isMeasuredNumericFormat, isMeasuredText, measuredNumericKey } from './MeasuredConstraintKeys.js';
10
+ import { isMeasuredCasingShape, isMeasuredCasingText, measuredLowerInvariant } from './MeasuredCaseFolding.js';
10
11
 
11
- type KeyContext = { name: string; fractions: boolean; measured: boolean };
12
+ type KeyContext = { name: string; fractions: boolean; measured: boolean; casing: boolean };
12
13
  type Claim = { key: string; parts: Array<{ property: string; raw: string }> };
13
14
 
14
15
  // Only characters captured by the packaged oracle, not every valid event-content character.
15
16
  const provenString = /^[A-Za-z0-9 .@_:\-|{}$\u00e9]*$/;
16
17
 
17
18
  function guidKey(value: unknown, name: string): string {
18
- if (typeof value === 'string' && /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(value)) return value.toLowerCase();
19
+ if (isDashedGuid(value)) return value.toLowerCase();
19
20
  throw new UnsupportedEventSequenceOperation('artifacts.constraints', name, 'Only dashed Guid keys are fixture-backed.');
20
21
  }
21
22
 
23
+ function isDashedGuid(value: unknown): value is string {
24
+ return typeof value === 'string' && /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(value);
25
+ }
26
+
22
27
  function isDecimalFraction(value: number): boolean {
23
28
  // constraints-fractional-field-types.json: below 0.0001 .NET uses exponent strings, unlike JS.
24
29
  // The rounding/boundary vectors match JS below 1e15; keep larger fractions conservatively rejected.
@@ -26,16 +31,18 @@ function isDecimalFraction(value: number): boolean {
26
31
  }
27
32
 
28
33
  function numericKey(value: unknown, context: KeyContext): string {
29
- if (typeof value === 'number') {
30
- if (Number.isSafeInteger(value)) return String(value);
31
- if (context.fractions && isDecimalFraction(value)) return String(value);
32
- }
34
+ if (isSupportedNumber(value, context.fractions)) return String(value);
33
35
  const reason = context.fractions
34
36
  ? 'Only safe-integer or fractional numeric keys with magnitude at least 0.0001 and below 1e15 are fixture-backed; other values require a kernel-backed test.'
35
37
  : 'Only safe-integer numeric keys are fixture-backed; fractional, exponential and unsafe-integer comparisons require a kernel-backed test.';
36
38
  throw new UnsupportedEventSequenceOperation('artifacts.constraints', context.name, reason);
37
39
  }
38
40
 
41
+ function isSupportedNumber(value: unknown, fractions: boolean): value is number {
42
+ if (typeof value !== 'number') return false;
43
+ return Number.isSafeInteger(value) || fractions && isDecimalFraction(value);
44
+ }
45
+
39
46
  function kernelKeyString(value: unknown, context: KeyContext, schema?: JsonSchema): string {
40
47
  if (schema?.format === 'guid') return guidKey(value, context.name);
41
48
  if (schema?.type === 'number') return schemaNumericKey(value, context, schema.format);
@@ -48,24 +55,35 @@ function schemaNumericKey(value: unknown, context: KeyContext, format: string |
48
55
  }
49
56
 
50
57
  function scalarKey(value: unknown, context: KeyContext): string {
51
- if (typeof value === 'string') {
52
- const accepted = provenString.test(value) || context.measured && isMeasuredText(value);
53
- if (accepted) return value;
54
- }
58
+ if (typeof value === 'string' && isSupportedString(value, context)) return value;
55
59
  if (typeof value === 'boolean') return value ? 'True' : 'False';
56
60
  throw new UnsupportedEventSequenceOperation('artifacts.constraints', context.name,
57
61
  'Only fixture-backed scalar string and boolean keys are supported.');
58
62
  }
59
63
 
64
+ function isSupportedString(value: string, context: KeyContext): boolean {
65
+ return provenString.test(value) || context.measured && isMeasuredText(value) || context.casing && isMeasuredCasingText(value);
66
+ }
67
+
60
68
  function supportsFractions(capture: ConstraintCapture): boolean {
61
69
  const unique = capture.uniqueConstraint!;
62
- return !Object.values(capture.scope).some(Boolean) && !unique.ignoreCasing &&
63
- unique.removedWithEventTypeId === undefined && !unique.removedWithEventTypeIds?.length &&
70
+ return isUnscopedCaseSensitive(capture) && !hasPropertyRemovals(capture) &&
64
71
  unique.eventDefinitions.every(entry => entry.properties.length === 1);
65
72
  }
66
73
 
67
- function normalizedKey(joined: string, ignoreCasing: boolean, name: string): string {
74
+ function isUnscopedCaseSensitive(capture: ConstraintCapture): boolean {
75
+ return !Object.values(capture.scope).some(Boolean) && !capture.uniqueConstraint!.ignoreCasing;
76
+ }
77
+
78
+ function hasPropertyRemovals(capture: ConstraintCapture): boolean {
79
+ const unique = capture.uniqueConstraint!;
80
+ return unique.removedWithEventTypeId !== undefined || !!unique.removedWithEventTypeIds?.length;
81
+ }
82
+
83
+ function normalizedKey(joined: string, ignoreCasing: boolean, name: string, casing: boolean): string {
68
84
  if (!ignoreCasing) return joined;
85
+ // Scalars were admitted by isMeasuredCasingText, so the measured mapping is total for this text.
86
+ if (casing) return measuredLowerInvariant(joined);
69
87
  // The pinned kernel's ToLowerInvariant is proven only for the existing ASCII domain.
70
88
  if (!/^[\x20-\x7e]*$/.test(joined)) {
71
89
  throw new UnsupportedEventSequenceOperation('artifacts.constraints', name,
@@ -81,9 +99,10 @@ export function claimOf(name: string, capture: ConstraintCapture, event: Appende
81
99
  const properties = unique.eventDefinitions.find(entry => entry.eventTypeId === event.eventType.id.value)?.properties;
82
100
  if (properties === undefined) return undefined;
83
101
  const fractions = options.isolated && supportsFractions(capture);
84
- const context = { name, fractions, measured: fractions && unique.eventDefinitions.length === 1 };
102
+ const casing = options.isolated && isMeasuredCasingShape(unique, Object.values(capture.scope).some(Boolean), hasPropertyRemovals(capture));
103
+ const context = { name, fractions, measured: fractions && unique.eventDefinitions.length === 1, casing };
85
104
  const parts = properties.map(property => ({ property,
86
105
  raw: kernelKeyString(event.content[property], context, options.schema?.properties?.[property]) }));
87
106
  const joined = parts.map(part => part.raw).join('-');
88
- return { key: createHash('sha256').update(normalizedKey(joined, unique.ignoreCasing, name)).digest('hex'), parts };
107
+ return { key: createHash('sha256').update(normalizedKey(joined, unique.ignoreCasing, name, casing)).digest('hex'), parts };
89
108
  }
@@ -61,7 +61,7 @@ const fixtures = readdirSync(directory).filter(name => name.endsWith('.json') &&
61
61
  'constraints-event-type-siblings.json', 'constraints-composite.json',
62
62
  'constraints-ignore-casing.json', 'constraints-scopes.json', 'constraints-field-types.json', 'constraints-event-sequences.json',
63
63
  'constraints-field-combinations.json', 'constraints-removal-combinations.json', 'constraints-overlapping-definitions.json',
64
- 'constraints-fractional-field-types.json', 'constraints-fractional-collisions.json', 'constraints-field-key-measurements.json'].includes(name)).map(name => ({
64
+ 'constraints-fractional-field-types.json', 'constraints-fractional-collisions.json', 'constraints-field-key-measurements.json', 'constraints-ignore-casing-measurements.json'].includes(name)).map(name => ({
65
65
  name, fixture: JSON.parse(readFileSync(new URL(name, directory), 'utf8')) as Fixture
66
66
  }));
67
67
  const artifacts = { eventTypes: [OracleEventRecorded, AlternateRecorded, BoundaryRecorded], constraints: [] };
@@ -1,6 +1,7 @@
1
1
  // Copyright (c) Cratis. All rights reserved.
2
2
  // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
3
 
4
+ import type { Constructor } from '@cratis/fundamentals';
4
5
  import { DefaultClientArtifactsProvider } from '../artifacts/DefaultClientArtifactsProvider.js';
5
6
  import { TypeDiscoverer } from '../types/TypeDiscoverer.js';
6
7
  import { TypeIntrospector } from '../types/TypeIntrospector.js';
@@ -44,8 +45,7 @@ function isGuidOrNumericKey(schema: { type?: string; format?: string } | undefin
44
45
  function validateExtendedDefinition(name: string, unique: UniqueConstraintCapture | undefined,
45
46
  constructors: ReadonlyMap<string, Function>): void {
46
47
  if (!unique) return;
47
- const schemas = unique.eventDefinitions.flatMap(entry => entry.properties.map(property =>
48
- getEventTypeMetadata(constructors.get(entry.eventTypeId)!)?.schema.properties?.[property]));
48
+ const schemas = unique.eventDefinitions.flatMap(entry => propertySchemas(entry, constructors));
49
49
  if (!schemas.some(isGuidOrNumericKey)) return;
50
50
  if (schemas.some(schema => schema?.type === 'boolean')) {
51
51
  throw new UnsupportedEventSequenceOperation('artifacts.constraints', name,
@@ -56,8 +56,7 @@ function validateExtendedDefinition(name: string, unique: UniqueConstraintCaptur
56
56
  throw new UnsupportedEventSequenceOperation('artifacts.constraints', name,
57
57
  'Guid and numeric keys with covered-and-removal events are not fixture-backed.');
58
58
  }
59
- if (!supportsFieldlessPropertyRemoval(unique, constructors) &&
60
- removers.some(id => isFieldless(id, constructors))) {
59
+ if (hasUnsupportedFieldlessRemoval(unique, constructors, removers)) {
61
60
  throw new UnsupportedEventSequenceOperation('artifacts.constraints', name,
62
61
  'Guid and numeric keys with fieldless removal events are not fixture-backed.');
63
62
  }
@@ -66,30 +65,59 @@ function validateExtendedDefinition(name: string, unique: UniqueConstraintCaptur
66
65
  function validateKeySchemas(name: string, schemas: ReadonlyArray<{ type?: string; format?: string } | undefined>,
67
66
  options: { scoped: boolean; isolated: boolean; definitions: number; ignoreCasing: boolean }): void {
68
67
  const fail = (reason: string) => { throw new UnsupportedEventSequenceOperation('artifacts.constraints', name, reason); };
69
- const plainStrings = schemas.every(schema => schema?.type === 'string' && schema.format === undefined);
70
- if (options.scoped && !hasPlainScalarSchemas(schemas) && !hasCombinedKeySchemas(schemas)) {
68
+ if (options.scoped && !hasSupportedScopeSchemas(schemas)) {
71
69
  fail('Scoped property keys must be schema-backed strings, booleans, Guids or unformatted numbers.');
72
70
  }
73
- for (const schema of schemas) {
74
- const supported = supportsMeasuredKeySchema(schema, options, schemas.length);
75
- if (!supported) fail(`Unique keys with schema ${schema?.type ?? 'missing'}/${schema?.format ?? 'unformatted'} are not fixture-backed; date, object and other numeric formats require a kernel-backed test.`);
76
- }
77
- if (schemas.some(isGuidOrNumericKey) &&
78
- (options.definitions !== 1 || !options.isolated && !hasCombinedKeySchemas(schemas))) {
71
+ validateIndividualKeySchemas(name, schemas, options);
72
+ if (schemas.some(isGuidOrNumericKey) && !supportsGuidNumericDefinition(schemas, options)) {
79
73
  fail('Guid and numeric keys require one definition; combined keys require unformatted numbers or Guids.');
80
74
  }
81
- if (options.ignoreCasing && !plainStrings) fail('Case-insensitive keys must be schema-backed strings.');
75
+ if (options.ignoreCasing && !hasPlainStringSchemas(schemas)) fail('Case-insensitive keys must be schema-backed strings.');
82
76
  if (schemas.length > 1 && !hasCombinedKeySchemas(schemas)) {
83
77
  fail('Every property of a composite key must be a schema-backed string, Guid or unformatted number.');
84
78
  }
85
79
  }
86
80
 
81
+ function propertySchemas(entry: UniqueConstraintCapture['eventDefinitions'][number], constructors: ReadonlyMap<string, Function>) {
82
+ return entry.properties.map(property => getEventTypeMetadata(constructors.get(entry.eventTypeId)!)?.schema.properties?.[property]);
83
+ }
84
+
85
+ function validateIndividualKeySchemas(name: string, schemas: ReadonlyArray<{ type?: string; format?: string } | undefined>,
86
+ options: { scoped: boolean; isolated: boolean; definitions: number; ignoreCasing: boolean }): void {
87
+ for (const schema of schemas) {
88
+ if (!supportsMeasuredKeySchema(schema, options, schemas.length)) {
89
+ throw new UnsupportedEventSequenceOperation('artifacts.constraints', name,
90
+ `Unique keys with schema ${schema?.type ?? 'missing'}/${schema?.format ?? 'unformatted'} are not fixture-backed; date, object and other numeric formats require a kernel-backed test.`);
91
+ }
92
+ }
93
+ }
94
+
95
+ function hasSupportedScopeSchemas(schemas: ReadonlyArray<{ type?: string; format?: string } | undefined>): boolean {
96
+ return hasPlainScalarSchemas(schemas) || hasCombinedKeySchemas(schemas);
97
+ }
98
+
99
+ function supportsGuidNumericDefinition(schemas: ReadonlyArray<{ type?: string; format?: string } | undefined>,
100
+ options: { definitions: number; isolated: boolean }): boolean {
101
+ return options.definitions === 1 && (options.isolated || hasCombinedKeySchemas(schemas));
102
+ }
103
+
104
+ function hasPlainStringSchemas(schemas: ReadonlyArray<{ type?: string; format?: string } | undefined>): boolean {
105
+ return schemas.every(schema => schema?.type === 'string' && schema.format === undefined);
106
+ }
107
+
87
108
  function supportsFieldlessPropertyRemoval(unique: UniqueConstraintCapture | undefined, constructors: ReadonlyMap<string, Function>): boolean {
88
- return !!unique && !unique.ignoreCasing && unique.eventDefinitions.every(entry => {
89
- if (entry.properties.length !== 1) return false;
90
- const field = getEventTypeMetadata(constructors.get(entry.eventTypeId)!)?.schema.properties?.[entry.properties[0]];
91
- return field?.type === 'string' || field?.type === 'number';
92
- });
109
+ return !!unique && !unique.ignoreCasing && unique.eventDefinitions.every(entry => supportsFieldlessProperty(entry, constructors));
110
+ }
111
+
112
+ function supportsFieldlessProperty(entry: UniqueConstraintCapture['eventDefinitions'][number], constructors: ReadonlyMap<string, Function>): boolean {
113
+ if (entry.properties.length !== 1) return false;
114
+ const field = propertySchemas(entry, constructors)[0];
115
+ return field?.type === 'string' || field?.type === 'number';
116
+ }
117
+
118
+ function hasUnsupportedFieldlessRemoval(unique: UniqueConstraintCapture | undefined, constructors: ReadonlyMap<string, Function>,
119
+ removedWith: readonly (string | undefined)[]): boolean {
120
+ return !supportsFieldlessPropertyRemoval(unique, constructors) && removedWith.some(id => isFieldless(id, constructors));
93
121
  }
94
122
 
95
123
  function isFieldless(id: string | undefined, constructors: ReadonlyMap<string, Function>): boolean {
@@ -110,24 +138,32 @@ function validateScenarioDefinition(name: string, capture: ConstraintCapture,
110
138
  options: { selectedIds: ReadonlySet<string>; constructors: ReadonlyMap<string, Function>; definitions: number }): void {
111
139
  const { selectedIds, constructors, definitions } = options;
112
140
  const { ids, removedWith } = constraintReferences(capture);
113
- if ([...ids, ...removedWith].some(id => id !== undefined && !selectedIds.has(id))) {
141
+ if (hasUnselectedReferences([...ids, ...removedWith], selectedIds)) {
114
142
  throw new UnsupportedEventSequenceOperation('artifacts.constraints', name,
115
143
  'Every constrained event type must be in the selected catalog. Claiming and removal references must be complete.');
116
144
  }
117
145
  const scoped = Object.values(capture.scope).some(Boolean);
118
- if (scoped && !supportsFieldlessPropertyRemoval(capture.uniqueConstraint, constructors) && removedWith.some(id => isFieldless(id, constructors))) {
146
+ if (scoped && hasUnsupportedFieldlessRemoval(capture.uniqueConstraint, constructors, removedWith)) {
119
147
  throw new UnsupportedEventSequenceOperation('artifacts.constraints', name,
120
148
  'Scoped fieldless removers require a case-sensitive single-property unique constraint with string, Guid or numeric keys; other combinations are not fixture-backed.');
121
149
  }
122
150
  validateExtendedDefinition(name, capture.uniqueConstraint, constructors);
123
151
  for (const entry of capture.uniqueConstraint?.eventDefinitions ?? []) {
124
- const schemas = entry.properties.map(property => getEventTypeMetadata(constructors.get(entry.eventTypeId)!)?.schema.properties?.[property]);
152
+ const schemas = propertySchemas(entry, constructors);
125
153
  validateKeySchemas(name, schemas, { scoped, definitions,
126
- isolated: !scoped && capture.uniqueConstraint!.eventDefinitions.length === 1 && !removedWith.some(id => id !== undefined),
154
+ isolated: isIsolatedPropertyDefinition(capture.uniqueConstraint!, scoped, removedWith),
127
155
  ignoreCasing: capture.uniqueConstraint!.ignoreCasing });
128
156
  }
129
157
  }
130
158
 
159
+ function hasUnselectedReferences(ids: readonly (string | undefined)[], selectedIds: ReadonlySet<string>): boolean {
160
+ return ids.some(id => id !== undefined && !selectedIds.has(id));
161
+ }
162
+
163
+ function isIsolatedPropertyDefinition(unique: UniqueConstraintCapture, scoped: boolean, removedWith: readonly (string | undefined)[]): boolean {
164
+ return !scoped && unique.eventDefinitions.length === 1 && !removedWith.some(id => id !== undefined);
165
+ }
166
+
131
167
  function scenarioConstraints(definitions: ReadonlyMap<string, ConstraintCapture>, selectedIds: ReadonlySet<string>,
132
168
  constructors: ReadonlyMap<string, Function>): InProcessConstraints {
133
169
  // Other-sequence definitions neither validate nor index this scenario's event log.
@@ -150,6 +186,66 @@ function hasConstraintDecorators(type: Function): boolean {
150
186
  TypeIntrospector.getTrackedProperties(type).some(property => getUniquePropertyMetadata(type, property) !== undefined);
151
187
  }
152
188
 
189
+ function compileScenarioConstraints(eventTypes: Constructor[], discoveredArtifacts: DefaultClientArtifactsProvider | undefined,
190
+ discovered: Constructor[] | undefined): InProcessConstraints {
191
+ validateConstraintMetadata(discovered ?? []);
192
+ try {
193
+ // Keep global decorator contributions. A shadowed ID is accepted only when neither
194
+ // constructor has constraint decorators, so either one compiles to the same constraints.
195
+ const compiledEventTypes = [...new Set([...(discoveredArtifacts?.eventTypes ?? []), ...eventTypes])];
196
+ const constructorsById = constraintConstructors(compiledEventTypes);
197
+ const compiled = compileConstraints({ eventTypes: [...constructorsById.values()], constraints: discovered ?? [] });
198
+ const selectedIds = new Set(eventTypes.map(type => getEventTypeFor(type).id.value));
199
+ const definitions = discoveredArtifacts ? new Map([...compiled].filter(([, capture]) => referencesSelectedType(capture, selectedIds))) : compiled;
200
+ validateRemovalReferences(eventTypes, definitions);
201
+ return scenarioConstraints(definitions, selectedIds, constructorsById);
202
+ } catch (error) {
203
+ if (error instanceof UnsupportedEventSequenceOperation) throw error;
204
+ throw new UnsupportedEventSequenceOperation('artifacts.constraints', 'compiler', `Invalid constraint definition: ${String(error)}.`);
205
+ }
206
+ }
207
+
208
+ function validateConstraintMetadata(discovered: Constructor[]): void {
209
+ for (const type of discovered) {
210
+ if (!getConstraintMetadata(type)) throw new UnsupportedEventSequenceOperation('artifacts.constraints', type.name,
211
+ 'Every selected constraint must have @constraint metadata.');
212
+ }
213
+ }
214
+
215
+ function constraintConstructors(eventTypes: Constructor[]): Map<string, Constructor> {
216
+ const constructors = new Map<string, Constructor>();
217
+ for (const type of eventTypes) {
218
+ const id = getEventTypeFor(type).id.value;
219
+ const previous = constructors.get(id);
220
+ if (hasConflictingConstraintDecorators(previous, type)) {
221
+ throw new UnsupportedEventSequenceOperation('artifacts.eventTypes', id,
222
+ 'Conflicting constructors share an event type ID; constraint discovery cannot choose one.');
223
+ }
224
+ constructors.set(id, type);
225
+ }
226
+ return constructors;
227
+ }
228
+
229
+ function hasConflictingConstraintDecorators(previous: Function | undefined, type: Function): boolean {
230
+ return previous !== undefined && previous !== type && (hasConstraintDecorators(previous) || hasConstraintDecorators(type));
231
+ }
232
+
233
+ function referencesSelectedType(capture: ConstraintCapture, selectedIds: ReadonlySet<string>): boolean {
234
+ const { ids, removedWith } = constraintReferences(capture);
235
+ return [...ids, ...removedWith].some(id => id !== undefined && selectedIds.has(id));
236
+ }
237
+
238
+ function validateRemovalReferences(eventTypes: Constructor[], definitions: ReadonlyMap<string, ConstraintCapture>): void {
239
+ for (const type of eventTypes) {
240
+ for (const name of getRemovedConstraintNames(type)) {
241
+ if (!definitions.has(name)) {
242
+ throw new UnsupportedEventSequenceOperation('artifacts.constraints', name,
243
+ 'Unresolved removal constraint name in the selected catalog.');
244
+ }
245
+ }
246
+ }
247
+ }
248
+
153
249
  /** A kernel-free, fixture-bounded append scenario. No observer runs automatically. */
154
250
  export class EventScenario {
155
251
  readonly eventSequence: IEventSequence;
@@ -168,50 +264,8 @@ export class EventScenario {
168
264
  const discoveredArtifacts = selectedArtifacts && selectedConstraints === undefined
169
265
  ? new DefaultClientArtifactsProvider(TypeDiscoverer.default) : undefined;
170
266
  const discovered = selectedConstraints ?? discoveredArtifacts?.constraints ?? artifacts.constraints;
171
- let constraints: InProcessConstraints | undefined;
172
- if (options.constraints !== 'disabled') {
173
- for (const type of discovered ?? []) {
174
- if (!getConstraintMetadata(type)) throw new UnsupportedEventSequenceOperation('artifacts.constraints', type.name,
175
- 'Every selected constraint must have @constraint metadata.');
176
- }
177
- try {
178
- // Keep global decorator contributions. A shadowed ID is accepted only when neither
179
- // constructor has constraint decorators, so either one compiles to the same constraints.
180
- const compiledEventTypes = [...new Set([...(discoveredArtifacts?.eventTypes ?? []), ...eventTypes])];
181
- const constructorsById = new Map<string, (typeof eventTypes)[number]>();
182
- for (const type of compiledEventTypes) {
183
- const id = getEventTypeFor(type).id.value;
184
- const previous = constructorsById.get(id);
185
- if (previous && previous !== type && (hasConstraintDecorators(previous) || hasConstraintDecorators(type))) {
186
- throw new UnsupportedEventSequenceOperation('artifacts.eventTypes', id,
187
- 'Conflicting constructors share an event type ID; constraint discovery cannot choose one.');
188
- }
189
- constructorsById.set(id, type);
190
- }
191
- const compiled = compileConstraints({ eventTypes: [...constructorsById.values()], constraints: discovered ?? [] });
192
- const selectedIds = new Set(eventTypes.map(type => getEventTypeFor(type).id.value));
193
- const definitions = discoveredArtifacts ? new Map([...compiled].filter(([, capture]) => {
194
- const constrained = capture.uniqueConstraint?.eventDefinitions.map(entry => entry.eventTypeId) ??
195
- capture.uniqueEventType?.eventTypeIds ?? [capture.uniqueEventType?.eventTypeId];
196
- const removedWith = [...(capture.uniqueConstraint?.removedWithEventTypeIds ?? []),
197
- capture.uniqueConstraint?.removedWithEventTypeId,
198
- ...(capture.uniqueEventType?.removedWithEventTypeIds ?? [])];
199
- return [...constrained, ...removedWith].some(id => id !== undefined && selectedIds.has(id));
200
- })) : compiled;
201
- for (const type of eventTypes) {
202
- for (const name of getRemovedConstraintNames(type)) {
203
- if (!definitions.has(name)) {
204
- throw new UnsupportedEventSequenceOperation('artifacts.constraints', name,
205
- 'Unresolved removal constraint name in the selected catalog.');
206
- }
207
- }
208
- }
209
- constraints = scenarioConstraints(definitions, selectedIds, constructorsById);
210
- } catch (error) {
211
- if (error instanceof UnsupportedEventSequenceOperation) throw error;
212
- throw new UnsupportedEventSequenceOperation('artifacts.constraints', 'compiler', `Invalid constraint definition: ${String(error)}.`);
213
- }
214
- }
267
+ const constraints = options.constraints === 'disabled' ? undefined
268
+ : compileScenarioConstraints(eventTypes, discoveredArtifacts, discovered);
215
269
  if (artifacts.eventTypeMigrations?.length) {
216
270
  throw new UnsupportedEventSequenceOperation('artifacts.eventTypeMigrations', artifacts.eventTypeMigrations.map(type => type.name).join(', '),
217
271
  'Migrations are not fixture-backed.');
@@ -0,0 +1,68 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import type { ConstraintViolation } from '@cratis/chronicle.contracts';
5
+ import type { AppendedEvent } from '../events/AppendedEvent.js';
6
+ import type { ConstraintCapture } from '../events/constraints/ConstraintBuilder.js';
7
+ import { eventTypeScopeKey, scopeIndex } from './ConstraintScope.js';
8
+
9
+ const unavailable = '18446744073709551615';
10
+
11
+ /** Tracks unique event type cycles within one append over committed history. */
12
+ export class EventTypeConstraintClaims {
13
+ private readonly _stagedCycles = new Map<string, Map<string, Map<string, 'open' | 'released'>>>();
14
+
15
+ constructor(private readonly _definitions: ReadonlyMap<string, ConstraintCapture>,
16
+ private readonly _history: readonly AppendedEvent[]) { }
17
+
18
+ validate(name: string, definition: ConstraintCapture, event: AppendedEvent): ConstraintViolation[] {
19
+ const uniqueType = definition.uniqueEventType;
20
+ if (!uniqueType) return [];
21
+ const type = event.eventType.id.value;
22
+ if (!(uniqueType.eventTypeIds ?? [uniqueType.eventTypeId]).includes(type)) return [];
23
+ const source = event.context.eventSourceId;
24
+ const scope = eventTypeScopeKey(definition.scope, event.context);
25
+ const first = this.firstCoveredEvent(definition, source, scope);
26
+ const cycles = scopeIndex(this._stagedCycles, name, scope, () => new Map<string, 'open' | 'released'>());
27
+ // A cycle state recorded earlier in this append overrides durable history.
28
+ if (this.isClaimed(cycles.get(source), first)) {
29
+ // Durable storage supplies the sequence even when a staged claim causes rejection.
30
+ const sequence = first?.context.sequenceNumber.toString() ?? unavailable;
31
+ return [{ EventTypeId: type, SequenceNumber: BigInt(sequence), ConstraintType: 2,
32
+ ConstraintName: name,
33
+ Message: `Event '${type}' violated a unique event type constraint on sequence number ${sequence}`,
34
+ Details: {} }];
35
+ }
36
+ cycles.set(source, 'open');
37
+ return [];
38
+ }
39
+
40
+ release(event: AppendedEvent): void {
41
+ for (const [name, definition] of this._definitions) {
42
+ if (definition.uniqueEventType?.removedWithEventTypeIds?.includes(event.eventType.id.value)) {
43
+ const cycles = scopeIndex(this._stagedCycles, name, eventTypeScopeKey(definition.scope, event.context),
44
+ () => new Map<string, 'open' | 'released'>());
45
+ cycles.set(event.context.eventSourceId, 'released');
46
+ }
47
+ }
48
+ }
49
+
50
+ private firstCoveredEvent(definition: ConstraintCapture, source: string, scope: string): AppendedEvent | undefined {
51
+ const uniqueType = definition.uniqueEventType!;
52
+ const covered = uniqueType.eventTypeIds ?? [uniqueType.eventTypeId];
53
+ const removals = uniqueType.removedWithEventTypeIds ?? [];
54
+ // Durable answer: the earliest covered event after the latest removal for this source.
55
+ let first: AppendedEvent | undefined;
56
+ for (const prior of this._history) {
57
+ if (prior.context.eventSourceId !== source || eventTypeScopeKey(definition.scope, prior.context) !== scope) continue;
58
+ const priorType = prior.eventType.id.value;
59
+ if (removals.includes(priorType)) first = undefined;
60
+ else if (!first && covered.includes(priorType)) first = prior;
61
+ }
62
+ return first;
63
+ }
64
+
65
+ private isClaimed(state: 'open' | 'released' | undefined, first: AppendedEvent | undefined): boolean {
66
+ return state === 'open' || state === undefined && first !== undefined;
67
+ }
68
+ }
@@ -8,13 +8,12 @@ import { resolveConstraintMessage } from '../events/constraints/Constraints.js';
8
8
  import type { ConstraintViolation } from '../eventSequences/ConstraintViolation.js';
9
9
  import type { JsonSchema } from '../schemas/JsonSchema.js';
10
10
  import { UnsupportedEventSequenceOperation } from './UnsupportedEventSequenceOperation.js';
11
- import { eventTypeScopeKey, propertyScopeKey, scopeIndex } from './ConstraintScope.js';
12
11
  import { supportsPropertyOverlap } from './PropertyDefinitionSupport.js';
13
- import { claimOf } from './ConstraintKey.js';
12
+ import { PropertyConstraintClaims } from './PropertyConstraintClaims.js';
13
+ import { EventTypeConstraintClaims } from './EventTypeConstraintClaims.js';
14
14
 
15
15
  export type WireConstraintViolation = ContractsConstraintViolation;
16
16
 
17
- const unavailable = '18446744073709551615';
18
17
  /** Narrow, fixture-backed constraint validation over serialized event snapshots. */
19
18
  export class InProcessConstraints {
20
19
  private readonly _constrainedProperties = new Map<string, Set<string>>();
@@ -124,95 +123,17 @@ export class InProcessConstraints {
124
123
  /** Validate against committed history and all earlier entries of this append, without changing state. */
125
124
  validate(history: readonly AppendedEvent[], incoming: readonly AppendedEvent[]): WireConstraintViolation[] {
126
125
  const violations: WireConstraintViolation[] = [];
127
- // Durable ownership is one claim per source, not one entry per historical value.
128
- // Rebuild it from committed history; batch claims below remain independent and are never released.
129
- const owners = new Map<string, Map<string, Map<string, { key: string; sequence: string }>>>();
130
- for (const [name, definition] of this._definitions) {
131
- if (!definition.uniqueConstraint) continue;
132
- const unique = definition.uniqueConstraint;
133
- const removals = new Set([unique.removedWithEventTypeId, ...(unique.removedWithEventTypeIds ?? [])]);
134
- for (const prior of history) {
135
- const type = prior.eventType.id.value;
136
- const source = prior.context.eventSourceId;
137
- const claims = scopeIndex(owners, name, propertyScopeKey(definition.scope, prior.context),
138
- () => new Map<string, { key: string; sequence: string }>());
139
- if (removals.has(type)) {
140
- claims.delete(source);
141
- continue;
142
- }
143
- const properties = unique.eventDefinitions.find(entry => entry.eventTypeId === type)?.properties;
144
- if (properties === undefined) continue;
145
- claims.set(source, { key: claimOf(name, definition, prior, { schema: this._schemas.get(type), isolated: this._definitions.size === 1 })!.key,
146
- sequence: prior.context.sequenceNumber.toString() });
147
- }
148
- }
149
- const stagedKeys = new Map<string, Map<string, Map<string, string>>>();
150
- const stagedCycles = new Map<string, Map<string, Map<string, 'open' | 'released'>>>();
126
+ const propertyClaims = new PropertyConstraintClaims(this._definitions, this._schemas, history);
127
+ const eventTypeClaims = new EventTypeConstraintClaims(this._definitions, history);
151
128
  for (const event of incoming) {
152
- const type = event.eventType.id.value;
153
- const source = event.context.eventSourceId;
154
129
  const violationCount = violations.length;
155
130
  for (const [name, definition] of this._definitions) {
156
- const claim = definition.uniqueConstraint && claimOf(name, definition, event, { schema: this._schemas.get(type), isolated: this._definitions.size === 1 });
157
- if (claim) {
158
- const key = claim.key;
159
- const scope = propertyScopeKey(definition.scope, event.context);
160
- const durableClaims = owners.get(name)?.get(scope);
161
- const existing = [...(durableClaims?.entries() ?? [])].find(([, claim]) => claim.key === key);
162
- const batchClaims = scopeIndex(stagedKeys, name, scope, () => new Map<string, string>());
163
- const batchOwner = batchClaims.get(key);
164
- if (existing && existing[0] !== source || batchOwner !== undefined && batchOwner !== source) {
165
- // One violation per declared property, in declared order, each with its own original value.
166
- const sequence = existing?.[1].sequence ?? unavailable;
167
- for (const { property, raw } of claim.parts) {
168
- violations.push({ EventTypeId: type, SequenceNumber: BigInt(sequence), ConstraintType: 1,
169
- ConstraintName: name,
170
- Message: `Event '${type}' on member '${property}' violated a unique constraint on sequence number ${sequence}`,
171
- Details: { PropertyName: property, PropertyValue: raw } });
172
- }
173
- } else {
174
- batchClaims.set(key, source);
175
- }
176
- }
177
- const uniqueType = definition.uniqueEventType;
178
- if (uniqueType && (uniqueType.eventTypeIds ?? [uniqueType.eventTypeId]).includes(type)) {
179
- const covered = uniqueType.eventTypeIds ?? [uniqueType.eventTypeId];
180
- const removals = uniqueType.removedWithEventTypeIds ?? [];
181
- // Durable answer: the earliest covered event after the latest removal for this source.
182
- const scope = eventTypeScopeKey(definition.scope, event.context);
183
- let first: AppendedEvent | undefined;
184
- for (const prior of history) {
185
- if (prior.context.eventSourceId !== source || eventTypeScopeKey(definition.scope, prior.context) !== scope) continue;
186
- const priorType = prior.eventType.id.value;
187
- if (removals.includes(priorType)) first = undefined;
188
- else if (!first && covered.includes(priorType)) first = prior;
189
- }
190
- const cycles = scopeIndex(stagedCycles, name, scope, () => new Map<string, 'open' | 'released'>());
191
- const state = cycles.get(source);
192
- // A cycle state recorded earlier in this append overrides durable history.
193
- if (state === 'open' || state === undefined && first) {
194
- // Durable storage supplies the sequence even when a staged claim causes rejection.
195
- const sequence = first?.context.sequenceNumber.toString() ?? unavailable;
196
- violations.push({ EventTypeId: type, SequenceNumber: BigInt(sequence), ConstraintType: 2,
197
- ConstraintName: name,
198
- Message: `Event '${type}' violated a unique event type constraint on sequence number ${sequence}`,
199
- Details: {} });
200
- } else {
201
- cycles.set(source, 'open');
202
- }
203
- }
131
+ violations.push(...propertyClaims.validate(name, definition, event));
132
+ violations.push(...eventTypeClaims.validate(name, definition, event));
204
133
  }
205
134
  // Kernel batch observers release a cycle only after the entire event validates.
206
135
  // A covered-and-removal event first attempts its claim, then releases it.
207
- if (violations.length === violationCount) {
208
- for (const [name, definition] of this._definitions) {
209
- if (definition.uniqueEventType?.removedWithEventTypeIds?.includes(type)) {
210
- const cycles = scopeIndex(stagedCycles, name, eventTypeScopeKey(definition.scope, event.context),
211
- () => new Map<string, 'open' | 'released'>());
212
- cycles.set(source, 'released');
213
- }
214
- }
215
- }
136
+ if (violations.length === violationCount) eventTypeClaims.release(event);
216
137
  }
217
138
  return violations;
218
139
  }
@@ -0,0 +1,22 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ // constraints-ignore-casing-measurements.json: the kernel applies string.ToLowerInvariant to the joined key text.
5
+ // Only these five non-ASCII scalars are measured; neighbours such as Ø, È or U+0302 are not admitted by resemblance.
6
+ // The unicode flag matches whole scalars, so a lone or reversed surrogate never matches.
7
+ const measuredCasingText = /^[A-Za-z0-9 .@_:\-|{}$\u00c9\u00df\u00e9\u00f8\u0301]*$/u;
8
+
9
+ /** Text whose .NET lower-invariant mapping was captured by the packaged oracle; no normalization or full folding. */
10
+ export function isMeasuredCasingText(value: string): boolean { return measuredCasingText.test(value); }
11
+
12
+ /** Applies the measured lower-invariant mapping: ASCII letters and U+00C9 only; ß, ø and U+0301 map to themselves. */
13
+ export function measuredLowerInvariant(value: string): string {
14
+ return value.replace(/[A-Z\u00c9]/g, letter => letter === '\u00c9' ? '\u00e9' : String.fromCharCode(letter.charCodeAt(0) + 32));
15
+ }
16
+
17
+ type CasingDefinition = { ignoreCasing: boolean; eventDefinitions: ReadonlyArray<{ properties: readonly unknown[] }> };
18
+
19
+ /** The isolated, unscoped, single-property, removal-free ignoreCasing definition measured for non-ASCII text. */
20
+ export function isMeasuredCasingShape(unique: CasingDefinition, scoped: boolean, removable: boolean): boolean {
21
+ return unique.ignoreCasing && !scoped && !removable && unique.eventDefinitions.length === 1 && unique.eventDefinitions[0].properties.length === 1;
22
+ }