@altopelago/sansa 0.14.2 → 0.15.0-rc.2
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.
- package/CHANGELOG.md +118 -1
- package/README.md +96 -1
- package/conformance/README.md +8 -0
- package/conformance/aeonic-anchor-claims.json +133 -0
- package/conformance/aeonic-arithmetic-claims.json +60 -0
- package/conformance/aeonic-clock-claims.json +123 -0
- package/conformance/aeonic-comparison-claims.json +37 -0
- package/conformance/aeonic-datetime-claims.json +110 -0
- package/conformance/aeonic-rational-arithmetic-claims.json +72 -0
- package/conformance/aeonic-temporal-claims.json +105 -0
- package/conformance/cts-claims.json +17 -3
- package/conformance/results/aeonic-anchor-capacity.json +452 -0
- package/conformance/results/aeonic-anchor-snapshot-0.1.json +39 -0
- package/conformance/results/aeonic-arithmetic-snapshot-0.1.json +28 -0
- package/conformance/results/aeonic-clock-all-snapshot-0.1.json +49 -0
- package/conformance/results/aeonic-clock-arithmetic-snapshot-0.1.json +48 -0
- package/conformance/results/aeonic-clock-capacity.json +326 -0
- package/conformance/results/aeonic-clock-relations-snapshot-0.1.json +48 -0
- package/conformance/results/aeonic-comparison-snapshot-0.1.json +19 -0
- package/conformance/results/aeonic-datetime-all-snapshot-0.1.json +47 -0
- package/conformance/results/aeonic-datetime-arithmetic-snapshot-0.1.json +46 -0
- package/conformance/results/aeonic-datetime-capacity.json +302 -0
- package/conformance/results/aeonic-datetime-relations-snapshot-0.1.json +46 -0
- package/conformance/results/aeonic-rational-arithmetic-capacity.json +100 -0
- package/conformance/results/aeonic-rational-arithmetic-snapshot-0.2.json +30 -0
- package/conformance/results/aeonic-temporal-all-property-addressing-2026-11-16.json +39 -0
- package/conformance/results/aeonic-temporal-all-snapshot-0.1.json +39 -0
- package/conformance/results/aeonic-temporal-calendar-property-addressing-2026-11-16.json +38 -0
- package/conformance/results/aeonic-temporal-calendar-snapshot-0.1.json +38 -0
- package/conformance/results/aeonic-temporal-capacity-property-addressing-2026-11-16.json +136 -0
- package/conformance/results/aeonic-temporal-capacity.json +136 -0
- package/conformance/results/aeonic-temporal-relations-property-addressing-2026-11-16.json +38 -0
- package/conformance/results/aeonic-temporal-relations-snapshot-0.1.json +38 -0
- package/docs/aeonic-arithmetic.md +126 -0
- package/docs/aeonic-comparison.md +123 -0
- package/docs/aeonic-rational-arithmetic.md +167 -0
- package/docs/aeonic-temporal-civil-anchor.md +89 -0
- package/docs/aeonic-temporal-civil-clock.md +100 -0
- package/docs/aeonic-temporal-civil-date.md +124 -0
- package/docs/aeonic-temporal-civil-datetime.md +122 -0
- package/docs/api-contract.md +130 -3
- package/docs/capabilities.json +106 -2
- package/docs/child-identity-activation.md +93 -0
- package/docs/child-identity-candidate.md +60 -0
- package/docs/child-identity-tooling.md +31 -0
- package/docs/child-identity-workflows.md +102 -0
- package/docs/empty-keys-candidate.md +29 -0
- package/docs/migration-0.15.0.md +75 -0
- package/docs/property-addressing-implementation.md +118 -0
- package/docs/property-resolve-implementation.md +105 -0
- package/docs/property-selector-support.md +65 -0
- package/docs/property-selectors-api.d.ts +43 -0
- package/docs/property-selectors-api.pyi +27 -0
- package/docs/property-selectors-api.rs +48 -0
- package/docs/property-selectors-contract.md +168 -0
- package/docs/query-tool.md +32 -1
- package/docs/selector-cursor.md +45 -0
- package/docs/unicode-hardening.md +41 -0
- package/fixtures/address-v1.json +4 -3
- package/fixtures/child-identity-workflows/README.md +9 -0
- package/fixtures/child-identity-workflows/moved.aeon +10 -0
- package/fixtures/child-identity-workflows/original.aeon +10 -0
- package/fixtures/child-identity-workflows/reordered.aeon +10 -0
- package/fixtures/child-identity-workflows/replacement.aeon +10 -0
- package/fixtures/child-identity-workflows/workflows.json +89 -0
- package/fixtures/property-namespace-candidate-v1.json +336 -0
- package/fixtures/property-parser-candidate-v1.json +705 -0
- package/fixtures/property-query-candidate-v1.json +398 -0
- package/fixtures/property-resolve-candidate-v1.json +2702 -0
- package/fixtures/unicode-hardening-v1.json +401 -0
- package/package.json +30 -3
- package/scripts/calibrate-aeonic-anchor-capacity.py +294 -0
- package/scripts/calibrate-aeonic-clock-capacity.py +62 -0
- package/scripts/calibrate-aeonic-datetime-capacity.py +76 -0
- package/scripts/calibrate-aeonic-rational-capacity.py +85 -0
- package/scripts/calibrate-aeonic-temporal-capacity.py +95 -0
- package/scripts/cts-address.mjs +6 -2
- package/scripts/cts-aeonic-anchor.mjs +21 -0
- package/scripts/cts-aeonic-arithmetic-adapter.mjs +25 -0
- package/scripts/cts-aeonic-arithmetic.mjs +24 -0
- package/scripts/cts-aeonic-clock.mjs +24 -0
- package/scripts/cts-aeonic-comparison-adapter.mjs +30 -0
- package/scripts/cts-aeonic-comparison.mjs +25 -0
- package/scripts/cts-aeonic-datetime.mjs +24 -0
- package/scripts/cts-aeonic-rational-arithmetic-adapter.mjs +25 -0
- package/scripts/cts-aeonic-rational-arithmetic.mjs +24 -0
- package/scripts/cts-aeonic-temporal-civil-anchor-adapter.mjs +26 -0
- package/scripts/cts-aeonic-temporal-civil-clock-adapter.mjs +28 -0
- package/scripts/cts-aeonic-temporal-civil-date-adapter.mjs +28 -0
- package/scripts/cts-aeonic-temporal-civil-datetime-adapter.mjs +28 -0
- package/scripts/cts-aeonic-temporal.mjs +24 -0
- package/scripts/cts-instruction.mjs +4 -2
- package/scripts/cts-mutate.mjs +3 -2
- package/scripts/cts-resolve.mjs +17 -2
- package/scripts/playground.mjs +110 -0
- package/src/aeonic-arithmetic-binding.js +61 -0
- package/src/aeonic-arithmetic.d.ts +84 -0
- package/src/aeonic-arithmetic.js +276 -0
- package/src/aeonic-comparison.d.ts +86 -0
- package/src/aeonic-comparison.js +274 -0
- package/src/aeonic-convenience.d.ts +30 -0
- package/src/aeonic-convenience.js +45 -0
- package/src/aeonic-exact-number.js +34 -0
- package/src/aeonic-json.js +45 -0
- package/src/aeonic-rational-arithmetic.d.ts +86 -0
- package/src/aeonic-rational-arithmetic.js +417 -0
- package/src/aeonic-rational-json.js +51 -0
- package/src/aeonic-temporal-civil-anchor.d.ts +54 -0
- package/src/aeonic-temporal-civil-anchor.js +316 -0
- package/src/aeonic-temporal-civil-clock.d.ts +124 -0
- package/src/aeonic-temporal-civil-clock.js +388 -0
- package/src/aeonic-temporal-civil-date.d.ts +123 -0
- package/src/aeonic-temporal-civil-date.js +310 -0
- package/src/aeonic-temporal-civil-datetime.d.ts +138 -0
- package/src/aeonic-temporal-civil-datetime.js +501 -0
- package/src/index.d.ts +84 -1
- package/src/index.js +828 -183
- package/src/property-address.js +196 -0
- package/src/property-resolve.js +132 -0
- package/src/query-metadata.d.ts +16 -0
- package/src/query-metadata.js +25 -0
- package/src/selector-cursor.d.ts +19 -0
- package/src/selector-cursor.js +79 -0
- package/stress-tests/address/invalid.sansa-cases +0 -2
- package/stress-tests/address/valid.sansa-cases +3 -0
- package/tools/mutate-web/examples.mjs +1 -1
- package/tools/mutate-web/runtime.mjs +0 -2
- package/tools/playground/README.md +165 -0
- package/tools/playground/accessibility.js +91 -0
- package/tools/playground/aeon-highlight.js +77 -0
- package/tools/playground/aeon-source-composer.js +1077 -0
- package/tools/playground/anchor-examples.mjs +16 -0
- package/tools/playground/arithmetic-evaluator.mjs +28 -0
- package/tools/playground/arithmetic-model.mjs +187 -0
- package/tools/playground/arithmetic-worker.mjs +14 -0
- package/tools/playground/arithmetic.css +1 -0
- package/tools/playground/arithmetic.html +29 -0
- package/tools/playground/arithmetic.mjs +110 -0
- package/tools/playground/clock-examples.mjs +16 -0
- package/tools/playground/datetime-examples.mjs +22 -0
- package/tools/playground/examples.mjs +46 -0
- package/tools/playground/index.html +174 -0
- package/tools/playground/local.css +25 -0
- package/tools/playground/namespace.mjs +39 -0
- package/tools/playground/sansa-playground.js +1565 -0
- package/tools/playground/site.css +3914 -0
- package/tools/playground/temporal-examples.mjs +20 -0
- package/tools/playground/walkthrough.js +90 -0
- package/tools/playground/website-origin.json +16 -0
- package/tools/query-web/IDENTITY_SELECTORS.md +44 -0
- package/tools/query-web/app.js +4 -0
- package/tools/query-web/index.html +4 -0
- package/tools/query-web/runtime.mjs +70 -19
- package/tools/workflows/property-playground-assertions.mjs +33 -0
- package/tools/workflows/verify-child-identities.mjs +137 -0
- package/tools/workflows/verify-property-playground.mjs +48 -0
|
@@ -0,0 +1,501 @@
|
|
|
1
|
+
// Adapted from AltoPelago/aeonic at a4b3391dc678d2cc441fe661cfa669bc969086b9.
|
|
2
|
+
// Copyright (c) 2026 Patrik. MIT; see LICENSE and docs/aeonic-temporal-civil-datetime.md.
|
|
3
|
+
// Bounded UTF-8 counting keeps native/text APIs usable in browser workers.
|
|
4
|
+
function utf8Bytes(text, allowance) {
|
|
5
|
+
let bytes = 0;
|
|
6
|
+
for (const character of text) {
|
|
7
|
+
const point = character.codePointAt(0);
|
|
8
|
+
bytes += point <= 0x7f ? 1 : point <= 0x7ff ? 2 : point <= 0xffff ? 3 : 4;
|
|
9
|
+
if (bytes > allowance) break;
|
|
10
|
+
}
|
|
11
|
+
return bytes;
|
|
12
|
+
}
|
|
13
|
+
import { exceedsJsonDepth, parseStrictJson } from './aeonic-json.js';
|
|
14
|
+
import { RationalJsonNumber } from './aeonic-rational-json.js';
|
|
15
|
+
|
|
16
|
+
export const AEONIC_TEMPORAL_CIVIL_DATETIME_PROFILE = 'aeonic.operations.temporal.civil-datetime.v1';
|
|
17
|
+
export const AEONIC_TEMPORAL_CIVIL_DATETIME_DEFAULT_RESOURCE_LIMITS = Object.freeze({ maxRequestBytes: 65536, maxRequestDepth: 32,
|
|
18
|
+
maxTemporalCharacters: 1024, maxInputPieces: 512, maxIntermediatePieces: 4096, maxOutputPieces: 512,
|
|
19
|
+
maxWork: 16384, maxFractionDigits: 256, maxCountCharacters: 32, maxNumericCharacters: 4096,
|
|
20
|
+
maxCoefficientDigits: 1024, maxExponentMagnitude: 1000000, maxWorkspaceDigits: 4096,
|
|
21
|
+
maxOutputCharacters: 1024, maxResultBytes: 131072 });
|
|
22
|
+
const OPERATIONS = { relations: ['equal', 'compare', 'relate'], arithmetic: ['shift', 'shiftClock', 'step', 'materialize'] };
|
|
23
|
+
const TAGS = new Set(['civilDateTime', 'civilDateTimeSet', 'civilDate', 'civilDateSet', 'finiteNumber', 'exactNumber', 'exactRational',
|
|
24
|
+
'string', 'boolean', 'symbol', 'positiveInfinity', 'negativeInfinity', 'nan', 'explicitNull', 'explicitAbsence', 'toggle',
|
|
25
|
+
'hex', 'radix', 'encoding', 'separator', 'sansaAddress', 'referenceForm', 'temporal', 'container']);
|
|
26
|
+
const GRAINS = ['day', 'month', 'year'], CLOCKS = ['hour', 'minute', 'second'];
|
|
27
|
+
const NONE = 'none-declared', CLAMPED = 'clamping-declared', APPROX = 'approximation-declared';
|
|
28
|
+
const record = v => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
29
|
+
const scalar = v => typeof v === 'string' && !/[\uD800-\uDFFF]/u.test(v);
|
|
30
|
+
const identifier = v => scalar(v) && v.length > 0;
|
|
31
|
+
const pointer = (p, k) => scalar(k) ? p + '/' + k.replaceAll('~', '~0').replaceAll('/', '~1') : null;
|
|
32
|
+
function scalarOrder(a, b) {
|
|
33
|
+
const x = a[Symbol.iterator](), y = b[Symbol.iterator]();
|
|
34
|
+
for (;;) { const p = x.next(), q = y.next();
|
|
35
|
+
if (p.done || q.done) return p.done === q.done ? 0 : p.done ? -1 : 1;
|
|
36
|
+
if (p.value !== q.value) return p.value.codePointAt(0) - q.value.codePointAt(0);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
class Failure extends Error {
|
|
40
|
+
constructor(reason, stage, path) { super(reason); this.result = { outcome: 'diagnostic', reason, context: { stage, path } }; }
|
|
41
|
+
}
|
|
42
|
+
function stop(reason, stage, path) { throw new Failure(reason, stage, path); }
|
|
43
|
+
function guarded(action) { try { return action(); } catch (e) { if (e instanceof Failure) return e.result; throw e; } }
|
|
44
|
+
function required(v, fields, path, reason, stage) {
|
|
45
|
+
for (const k of fields) if (!Object.hasOwn(v, k)) stop(reason, stage, pointer(path, k));
|
|
46
|
+
}
|
|
47
|
+
function closed(v, fields, path, reason, stage) {
|
|
48
|
+
for (const k of Object.keys(v).sort(scalarOrder)) if (!fields.includes(k)) stop(reason, stage, pointer(path, k));
|
|
49
|
+
}
|
|
50
|
+
function configured(options) {
|
|
51
|
+
if (!record(options) || Object.keys(options).some(k => !['resourceLimits', 'capabilities'].includes(k))) throw new TypeError('Invalid trusted options');
|
|
52
|
+
const supplied = Object.hasOwn(options, 'resourceLimits') ? options.resourceLimits : {};
|
|
53
|
+
if (!record(supplied)) throw new TypeError('resourceLimits must be an object');
|
|
54
|
+
for (const [k, v] of Object.entries(supplied)) {
|
|
55
|
+
if (!Object.hasOwn(AEONIC_TEMPORAL_CIVIL_DATETIME_DEFAULT_RESOURCE_LIMITS, k) || !Number.isSafeInteger(v) || v < 0) throw new TypeError('Invalid resource limit: ' + k);
|
|
56
|
+
}
|
|
57
|
+
const capabilities = Object.hasOwn(options, 'capabilities') ? options.capabilities : ['relations', 'arithmetic'];
|
|
58
|
+
if (!Array.isArray(capabilities) || !capabilities.length || capabilities.some(k => typeof k !== 'string' || !Object.hasOwn(OPERATIONS, k)) || new Set(capabilities).size !== capabilities.length) throw new TypeError('Invalid trusted capabilities');
|
|
59
|
+
return { limits: { ...AEONIC_TEMPORAL_CIVIL_DATETIME_DEFAULT_RESOURCE_LIMITS, ...supplied }, available: new Set(capabilities.flatMap(k => OPERATIONS[k])) };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Pure civil calendar: no host Date, timezone or floating-point epoch conversion.
|
|
63
|
+
const leap = y => y % 4 === 0 && (y % 100 !== 0 || y % 400 === 0);
|
|
64
|
+
const monthLength = (y, m) => m === 2 ? leap(y) ? 29 : 28 : [4, 6, 9, 11].includes(m) ? 30 : 31;
|
|
65
|
+
const yearStart = y => 365 * (y - 1) + Math.floor((y - 1) / 4) - Math.floor((y - 1) / 100) + Math.floor((y - 1) / 400) + 1;
|
|
66
|
+
function ordinal(y, m, d) { let n = yearStart(y) + d - 1; for (let k = 1; k < m; k++) n += monthLength(y, k); return n; }
|
|
67
|
+
const LAST = yearStart(10000) - 1;
|
|
68
|
+
function date(n) {
|
|
69
|
+
let lo = 1, hi = 9999;
|
|
70
|
+
while (lo < hi) { const mid = Math.ceil((lo + hi) / 2); if (yearStart(mid) <= n) lo = mid; else hi = mid - 1; }
|
|
71
|
+
let m = 1, d = n - yearStart(lo) + 1;
|
|
72
|
+
while (d > monthLength(lo, m)) { d -= monthLength(lo, m); m++; }
|
|
73
|
+
return { y: lo, m, d };
|
|
74
|
+
}
|
|
75
|
+
const monthIndex = d => 12 * (d.y - 1) + d.m - 1;
|
|
76
|
+
const monthAt = n => ({ y: Math.floor(n / 12) + 1, m: n % 12 + 1 });
|
|
77
|
+
const fullText = n => { const d = date(n); return `${String(d.y).padStart(4, '0')}-${String(d.m).padStart(2, '0')}-${String(d.d).padStart(2, '0')}`; };
|
|
78
|
+
|
|
79
|
+
// Whole civil seconds are bounded integers below 2^53; fractions remain text.
|
|
80
|
+
const B = LAST * 86400, C = (s, f = '') => ({ s, f });
|
|
81
|
+
const cmp = (a, b) => a.s !== b.s ? Math.sign(a.s - b.s) : a.f === b.f ? 0 : a.f < b.f ? -1 : 1;
|
|
82
|
+
const same = (a, b) => cmp(a, b) === 0;
|
|
83
|
+
const piece = (lo, hi = lo, il = true, ih = true) => ({ lo, hi, il, ih });
|
|
84
|
+
const empty = p => cmp(p.lo, p.hi) > 0 || same(p.lo, p.hi) && !(p.il && p.ih);
|
|
85
|
+
function fields(text, path, limits, authored = false) {
|
|
86
|
+
if (typeof text !== 'string') stop('invalid_operand', 4, path);
|
|
87
|
+
characters([text], limits.maxTemporalCharacters, path);
|
|
88
|
+
const pattern = authored ? /^([0-9]{4}-(?:[0-9]{2}(?:-[0-9]{2})?)?)T([0-9]{2})(?::([0-9]{2})(?::([0-9]{2})(?:\.([0-9]+))?)?)?$(?![\s\S])/u
|
|
89
|
+
: /^([0-9]{4}-[0-9]{2}-[0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.([0-9]+))?$(?![\s\S])/u;
|
|
90
|
+
const m = pattern.exec(text); if (!m) stop('invalid_operand', 4, path);
|
|
91
|
+
const [_, ds, hh, mm, ss, raw = ''] = m;
|
|
92
|
+
if (raw.length > limits.maxFractionDigits) stop('resource_limit', 4, path);
|
|
93
|
+
const f = raw.replace(/0+$/u, '');
|
|
94
|
+
if (!authored && f !== raw) stop('invalid_operand', 4, path);
|
|
95
|
+
const y = Number(ds.slice(0, 4)), mo = ds.length > 5 ? Number(ds.slice(5, 7)) : 1, d = ds.length > 7 ? Number(ds.slice(8)) : 1;
|
|
96
|
+
if (y < 1 || mo < 1 || mo > 12 || d < 1 || d > monthLength(y, mo) || Number(hh) > 23 || Number(mm ?? 0) > 59 || Number(ss ?? 0) > 59) stop('invalid_operand', 4, path);
|
|
97
|
+
const grain = ds.length === 5 ? 'year' : ds.length === 7 ? 'month' : 'day', clock = ss !== undefined ? 'second' : mm !== undefined ? 'minute' : 'hour';
|
|
98
|
+
const start = ordinal(y, mo, d), count = grain === 'year' ? (leap(y) ? 366 : 365) : grain === 'month' ? monthLength(y, mo) : 1;
|
|
99
|
+
return { start, count, grain, clock, seconds: Number(hh) * 3600 + Number(mm ?? 0) * 60 + Number(ss ?? 0), f };
|
|
100
|
+
}
|
|
101
|
+
function coordinate(text, path, limits) {
|
|
102
|
+
const v = fields(text, path, limits); return C((v.start - 1) * 86400 + v.seconds, v.f);
|
|
103
|
+
}
|
|
104
|
+
function expand(form) {
|
|
105
|
+
const out = [], width = form.clock === 'hour' ? 3600 : form.clock === 'minute' ? 60 : 0;
|
|
106
|
+
for (let i = 0; i < form.count; i++) {
|
|
107
|
+
const lo = C((form.start - 1 + i) * 86400 + form.seconds, form.f);
|
|
108
|
+
out.push(piece(lo, width ? C(lo.s + width) : lo, true, !width));
|
|
109
|
+
}
|
|
110
|
+
return out;
|
|
111
|
+
}
|
|
112
|
+
function history(v, path) {
|
|
113
|
+
if (!record(v)) stop('invalid_operand', 4, path);
|
|
114
|
+
required(v, ['clamping', 'approximation'], path, 'invalid_operand', 4); closed(v, ['clamping', 'approximation'], path, 'invalid_operand', 4);
|
|
115
|
+
if (![NONE, CLAMPED].includes(v.clamping)) stop('invalid_operand', 4, path + '/clamping');
|
|
116
|
+
if (![NONE, APPROX].includes(v.approximation)) stop('invalid_operand', 4, path + '/approximation');
|
|
117
|
+
return { clamping: v.clamping, approximation: v.approximation };
|
|
118
|
+
}
|
|
119
|
+
function operand(v, limits, path) {
|
|
120
|
+
if (!record(v)) stop('invalid_operand', 4, path);
|
|
121
|
+
required(v, ['temporal'], path, 'invalid_operand', 4);
|
|
122
|
+
const t = v.temporal, at = path + '/temporal';
|
|
123
|
+
if (!record(t)) stop('invalid_operand', 4, at);
|
|
124
|
+
if (typeof t.category !== 'string' || !TAGS.has(t.category)) stop('invalid_operand', 4, at + '/category');
|
|
125
|
+
if (t.category === 'civilDateTimeSet') required(v, ['originDateGranularity', 'originClockForm', 'history'], path, 'invalid_operand', 4);
|
|
126
|
+
closed(v, ['temporal', 'originDateGranularity', 'originClockForm', 'history'], path, 'invalid_operand', 4);
|
|
127
|
+
const h = Object.hasOwn(v, 'history') ? history(v.history, path + '/history') : { clamping: NONE, approximation: NONE };
|
|
128
|
+
for (const [key, allowed] of [['originDateGranularity', [...GRAINS, 'undeclared']], ['originClockForm', [...CLOCKS, 'undeclared']]]) {
|
|
129
|
+
if (Object.hasOwn(v, key) && !allowed.includes(v[key])) stop('invalid_operand', 4, path + '/' + key);
|
|
130
|
+
}
|
|
131
|
+
if (!['civilDateTime', 'civilDateTimeSet'].includes(t.category)) return { deferred: true };
|
|
132
|
+
let pieces, form;
|
|
133
|
+
if (t.category === 'civilDateTime') {
|
|
134
|
+
required(t, ['value'], at, 'invalid_operand', 4); closed(t, ['category', 'value'], at, 'invalid_operand', 4);
|
|
135
|
+
form = fields(t.value, at + '/value', limits, true);
|
|
136
|
+
if (form.count > limits.maxInputPieces) stop('resource_limit', 4, at);
|
|
137
|
+
pieces = expand(form);
|
|
138
|
+
} else {
|
|
139
|
+
required(t, ['pieces'], at, 'invalid_operand', 4); closed(t, ['category', 'pieces'], at, 'invalid_operand', 4);
|
|
140
|
+
if (!Array.isArray(t.pieces) || !t.pieces.length) stop('invalid_operand', 4, at + '/pieces');
|
|
141
|
+
if (t.pieces.length > limits.maxInputPieces) stop('resource_limit', 4, at + '/pieces');
|
|
142
|
+
pieces = [];
|
|
143
|
+
for (let i = 0; i < t.pieces.length; i++) {
|
|
144
|
+
const p = t.pieces[i], where = at + '/pieces/' + i;
|
|
145
|
+
if (!record(p)) stop('invalid_operand', 4, where);
|
|
146
|
+
required(p, ['kind'], where, 'invalid_operand', 4);
|
|
147
|
+
if (!['point', 'interval'].includes(p.kind)) stop('invalid_operand', 4, where + '/kind');
|
|
148
|
+
const keys = p.kind === 'point' ? ['at'] : ['start', 'end', 'includeStart', 'includeEnd'];
|
|
149
|
+
required(p, keys, where, 'invalid_operand', 4); closed(p, ['kind', ...keys], where, 'invalid_operand', 4);
|
|
150
|
+
const lowerPath = where + (p.kind === 'point' ? '/at' : '/start');
|
|
151
|
+
const lo = coordinate(p.kind === 'point' ? p.at : p.start, lowerPath, limits); let q;
|
|
152
|
+
if (p.kind === 'point') q = piece(lo);
|
|
153
|
+
else {
|
|
154
|
+
let hi, boundary = false;
|
|
155
|
+
if (record(p.end)) {
|
|
156
|
+
required(p.end, ['boundary'], where + '/end', 'invalid_operand', 4); closed(p.end, ['boundary'], where + '/end', 'invalid_operand', 4);
|
|
157
|
+
if (p.end.boundary !== 'endOfDomain') stop('invalid_operand', 4, where + '/end/boundary');
|
|
158
|
+
hi = C(B); boundary = true;
|
|
159
|
+
} else hi = coordinate(p.end, where + '/end', limits);
|
|
160
|
+
for (const key of ['includeStart', 'includeEnd']) if (typeof p[key] !== 'boolean') stop('invalid_operand', 4, where + '/' + key);
|
|
161
|
+
if (boundary && p.includeEnd) stop('invalid_operand', 4, where + '/includeEnd');
|
|
162
|
+
if (cmp(lo, hi) >= 0) stop('invalid_operand', 4, where + '/end');
|
|
163
|
+
q = piece(lo, hi, p.includeStart, p.includeEnd);
|
|
164
|
+
}
|
|
165
|
+
const previous = pieces.at(-1);
|
|
166
|
+
if (previous && (cmp(previous.hi, q.lo) > 0 || same(previous.hi, q.lo) && (previous.ih || q.il))) stop('invalid_operand', 4, lowerPath);
|
|
167
|
+
pieces.push(q);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return { pieces, history: h, origin: { dateGranularity: v.originDateGranularity ?? form?.grain ?? 'undeclared', clockForm: v.originClockForm ?? form?.clock ?? 'undeclared' } };
|
|
171
|
+
}
|
|
172
|
+
function characters(values, limit, path) {
|
|
173
|
+
let n = 0; for (const value of values) for (const ch of value) if (++n > limit) stop('resource_limit', 4, path);
|
|
174
|
+
}
|
|
175
|
+
function exponent(text, limits, path) {
|
|
176
|
+
const abs = text.replace(/^[+-]/u, '').replace(/^0+/u, '') || '0', cap = String(limits.maxExponentMagnitude);
|
|
177
|
+
if (abs.length > cap.length || abs.length === cap.length && abs > cap) stop('resource_limit', 4, path);
|
|
178
|
+
return (text.startsWith('-') ? -1n : 1n) * BigInt(abs);
|
|
179
|
+
}
|
|
180
|
+
function amount(v, limits, path) {
|
|
181
|
+
if (!record(v)) stop('invalid_operand', 4, path);
|
|
182
|
+
required(v, ['number'], path, 'invalid_operand', 4);
|
|
183
|
+
const t = v.number, at = path + '/number';
|
|
184
|
+
if (!record(t)) stop('invalid_operand', 4, at);
|
|
185
|
+
if (typeof t.category !== 'string' || !TAGS.has(t.category)) stop('invalid_operand', 4, at + '/category');
|
|
186
|
+
if (t.category === 'exactNumber') required(v, ['history'], path, 'invalid_operand', 4);
|
|
187
|
+
closed(v, ['number', 'history'], path, 'invalid_operand', 4);
|
|
188
|
+
const h = v.history ?? NONE; if (![NONE, APPROX].includes(h) || Object.hasOwn(v, 'history') && v.history === null) stop('invalid_operand', 4, path + '/history');
|
|
189
|
+
if (!['finiteNumber', 'exactNumber'].includes(t.category)) return { deferred: true };
|
|
190
|
+
let c, e;
|
|
191
|
+
if (t.category === 'finiteNumber') {
|
|
192
|
+
required(t, ['value'], at, 'invalid_operand', 4); closed(t, ['category', 'value'], at, 'invalid_operand', 4);
|
|
193
|
+
if (typeof t.value !== 'string') stop('invalid_operand', 4, at + '/value');
|
|
194
|
+
characters([t.value], limits.maxNumericCharacters, at + '/value');
|
|
195
|
+
if (!/^[+-]?(?:(?:0|[1-9][0-9]*)(?:\.[0-9]+)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$(?![\s\S])/u.test(t.value)) stop('invalid_operand', 4, at + '/value');
|
|
196
|
+
const [m, x = '0'] = t.value.toLowerCase().split('e'); e = exponent(x, limits, at + '/value');
|
|
197
|
+
const [whole, f = ''] = m.replace(/^[+-]/u, '').split('.'); c = (whole + f).replace(/^0+/u, '') || '0';
|
|
198
|
+
if (c === '0') e = 0n;
|
|
199
|
+
else { const trim = c.replace(/0+$/u, ''); e += BigInt(c.length - trim.length - f.length); c = (m.startsWith('-') ? '-' : '') + trim; }
|
|
200
|
+
if (c.replace(/^-/, '').length > limits.maxCoefficientDigits || (e < 0n ? -e : e) > BigInt(limits.maxExponentMagnitude)) stop('resource_limit', 4, at + '/value');
|
|
201
|
+
} else {
|
|
202
|
+
required(t, ['coefficient', 'exponent'], at, 'invalid_operand', 4); closed(t, ['category', 'coefficient', 'exponent'], at, 'invalid_operand', 4);
|
|
203
|
+
for (const key of ['coefficient', 'exponent']) if (typeof t[key] !== 'string') stop('invalid_operand', 4, at + '/' + key);
|
|
204
|
+
characters([t.coefficient, t.exponent], limits.maxNumericCharacters, at);
|
|
205
|
+
if (!/^(?:0|-?[1-9](?:[0-9]*[1-9])?)$(?![\s\S])/u.test(t.coefficient)) stop('invalid_operand', 4, at + '/coefficient');
|
|
206
|
+
if (!/^(?:0|-?[1-9][0-9]*)$(?![\s\S])/u.test(t.exponent) || t.coefficient === '0' && t.exponent !== '0') stop('invalid_operand', 4, at + '/exponent');
|
|
207
|
+
c = t.coefficient; e = exponent(t.exponent, limits, at + '/exponent');
|
|
208
|
+
if (c.replace(/^-/, '').length > limits.maxCoefficientDigits) stop('resource_limit', 4, at + '/coefficient');
|
|
209
|
+
}
|
|
210
|
+
return { c, e, history: h };
|
|
211
|
+
}
|
|
212
|
+
function selection(input, op, limits) {
|
|
213
|
+
const extras = op === 'shift' ? ['unit', 'count'] : op === 'step' ? ['dateGranularity', 'clockForm', 'count'] : op === 'materialize' ? ['dateGranularity', 'clockForm'] : [];
|
|
214
|
+
for (const key of ['context', 'policy']) {
|
|
215
|
+
const at = '/input/' + key;
|
|
216
|
+
if (!Object.hasOwn(input, key)) { if (key === 'policy' && extras.length) stop('invalid_policy', 3, at); continue; }
|
|
217
|
+
if (!record(input[key])) stop('invalid_policy', 3, at);
|
|
218
|
+
if (key === 'policy') required(input[key], extras, at, 'invalid_policy', 3);
|
|
219
|
+
closed(input[key], ['profile', ...(key === 'policy' ? extras : [])], at, 'invalid_policy', 3);
|
|
220
|
+
}
|
|
221
|
+
for (const key of ['context', 'policy']) if (Object.hasOwn(input[key] ?? {}, 'profile') && !identifier(input[key].profile)) stop('invalid_policy', 3, '/input/' + key + '/profile');
|
|
222
|
+
const p = input.policy ?? {};
|
|
223
|
+
if (op === 'shift' && !['day', 'month', 'year', 'eom', 'eoy'].includes(p.unit)) stop('invalid_policy', 3, '/input/policy/unit');
|
|
224
|
+
if (['step', 'materialize'].includes(op)) for (const [k, allowed] of [['dateGranularity', GRAINS], ['clockForm', CLOCKS]]) if (!allowed.includes(p[k])) stop('invalid_policy', 3, '/input/policy/' + k);
|
|
225
|
+
if (['shift', 'step'].includes(op)) {
|
|
226
|
+
if (typeof p.count !== 'string') stop('invalid_policy', 3, '/input/policy/count');
|
|
227
|
+
let n = 0; for (const ch of p.count) if (++n > limits.maxCountCharacters) stop('resource_limit', 3, '/input/policy/count');
|
|
228
|
+
if (!/^(?:0|-?[1-9][0-9]*)$(?![\s\S])/u.test(p.count)) stop('invalid_policy', 3, '/input/policy/count');
|
|
229
|
+
}
|
|
230
|
+
const owner = Object.hasOwn(p, 'profile') ? 'policy' : Object.hasOwn(input.context ?? {}, 'profile') ? 'context' : null;
|
|
231
|
+
if (!owner) stop('invalid_policy', 3, '/input/policy/profile');
|
|
232
|
+
if (input[owner].profile !== AEONIC_TEMPORAL_CIVIL_DATETIME_PROFILE) stop('unsupported_profile', 3, '/input/' + owner + '/profile');
|
|
233
|
+
return { profile: AEONIC_TEMPORAL_CIVIL_DATETIME_PROFILE, ...Object.fromEntries(extras.map(k => [k, p[k]])) };
|
|
234
|
+
}
|
|
235
|
+
function guard(n, cap) { if (n > cap) stop('resource_limit', 6, null); }
|
|
236
|
+
function checkDomain(pieces) {
|
|
237
|
+
if (cmp(pieces[0].lo, C(0)) < 0 || cmp(pieces.at(-1).hi, C(B)) > 0 || same(pieces.at(-1).hi, C(B)) && pieces.at(-1).ih) stop('unrepresentable_result', 6, null);
|
|
238
|
+
}
|
|
239
|
+
function countValue(text, unit) {
|
|
240
|
+
const abs = text.replace(/^-/, ''), cap = String(unit === 'day' ? LAST : ['month', 'eom'].includes(unit) ? 119988 : 9999);
|
|
241
|
+
if (abs.length > cap.length || abs.length === cap.length && abs > cap) stop('unrepresentable_result', 6, null);
|
|
242
|
+
return Number(text);
|
|
243
|
+
}
|
|
244
|
+
function daySpan(p) {
|
|
245
|
+
const first = Math.floor(p.lo.s / 86400); let last = Math.floor(p.hi.s / 86400);
|
|
246
|
+
if (p.hi.s % 86400 === 0 && !p.hi.f && !p.ih) last--;
|
|
247
|
+
return [first, last];
|
|
248
|
+
}
|
|
249
|
+
function intersection(a, b) {
|
|
250
|
+
const low = cmp(a.lo, b.lo), high = cmp(a.hi, b.hi);
|
|
251
|
+
return piece(low >= 0 ? a.lo : b.lo, high <= 0 ? a.hi : b.hi, low === 0 ? a.il && b.il : low > 0 ? a.il : b.il, high === 0 ? a.ih && b.ih : high < 0 ? a.ih : b.ih);
|
|
252
|
+
}
|
|
253
|
+
function normalize(values) {
|
|
254
|
+
values.sort((a, b) => cmp(a.lo, b.lo) || Number(b.il) - Number(a.il) || -cmp(a.hi, b.hi) || Number(b.ih) - Number(a.ih));
|
|
255
|
+
const out = [];
|
|
256
|
+
for (const p of values) {
|
|
257
|
+
const last = out.at(-1);
|
|
258
|
+
if (!last || cmp(last.hi, p.lo) < 0 || same(last.hi, p.lo) && !(last.ih || p.il)) out.push({ ...p });
|
|
259
|
+
else {
|
|
260
|
+
if (same(last.lo, p.lo)) last.il ||= p.il;
|
|
261
|
+
if (cmp(p.hi, last.hi) > 0) { last.hi = p.hi; last.ih = p.ih; }
|
|
262
|
+
else if (same(last.hi, p.hi)) last.ih ||= p.ih;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
return out;
|
|
266
|
+
}
|
|
267
|
+
function mappedDay(n, unit, count) {
|
|
268
|
+
const d = date(n); let target, day, clamped;
|
|
269
|
+
if (unit === 'eoy') {
|
|
270
|
+
const y = d.y + count; if (y < 1 || y > 9999) stop('unrepresentable_result', 6, null);
|
|
271
|
+
const k = n - yearStart(d.y) + (leap(y) ? 366 : 365) - (leap(d.y) ? 366 : 365);
|
|
272
|
+
return { n: yearStart(y) + Math.max(0, k), clamped: k < 0 };
|
|
273
|
+
}
|
|
274
|
+
const index = monthIndex(d) + (unit === 'year' ? count * 12 : count);
|
|
275
|
+
if (index < 0 || index > 119987) stop('unrepresentable_result', 6, null);
|
|
276
|
+
target = monthAt(index); const size = monthLength(target.y, target.m);
|
|
277
|
+
if (unit === 'eom') { day = size - (monthLength(d.y, d.m) - d.d); clamped = day < 1; day = Math.max(1, day); }
|
|
278
|
+
else { clamped = d.d > size; day = Math.min(d.d, size); }
|
|
279
|
+
return { n: ordinal(target.y, target.m, day), clamped };
|
|
280
|
+
}
|
|
281
|
+
function calendarImage(pieces, policy, limits) {
|
|
282
|
+
const direct = policy.count === '0' || policy.unit === 'day'; let work = 0;
|
|
283
|
+
for (const p of pieces) { const [a, b] = daySpan(p); work += direct ? 1 : b - a + 1; if (work > limits.maxWork) stop('resource_limit', 6, null); }
|
|
284
|
+
guard(work, limits.maxIntermediatePieces);
|
|
285
|
+
const count = countValue(policy.count, policy.unit);
|
|
286
|
+
if (direct) {
|
|
287
|
+
const delta = policy.unit === 'day' ? count * 86400 : 0;
|
|
288
|
+
const out = pieces.map(p => piece(C(p.lo.s + delta, p.lo.f), C(p.hi.s + delta, p.hi.f), p.il, p.ih)); checkDomain(out); return { pieces: out, clamped: false };
|
|
289
|
+
}
|
|
290
|
+
const candidates = []; let clamped = false;
|
|
291
|
+
for (const p of pieces) {
|
|
292
|
+
const [first, last] = daySpan(p);
|
|
293
|
+
for (let day = first; day <= last; day++) {
|
|
294
|
+
const fragment = intersection(p, piece(C(day * 86400), C((day + 1) * 86400), true, false));
|
|
295
|
+
if (empty(fragment)) throw new Error('Calendar fragment accounting mismatch');
|
|
296
|
+
const mapped = mappedDay(day + 1, policy.unit, count); clamped ||= mapped.clamped;
|
|
297
|
+
const delta = (mapped.n - 1 - day) * 86400;
|
|
298
|
+
candidates.push(piece(C(fragment.lo.s + delta, fragment.lo.f), C(fragment.hi.s + delta, fragment.hi.f), fragment.il, fragment.ih));
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
const out = normalize(candidates); checkDomain(out); return { pieces: out, clamped };
|
|
302
|
+
}
|
|
303
|
+
function contains(a, b) {
|
|
304
|
+
let j = 0;
|
|
305
|
+
for (const p of a) {
|
|
306
|
+
while (j < b.length && (cmp(b[j].hi, p.lo) < 0 || same(b[j].hi, p.lo) && (!same(p.lo, p.hi) || !b[j].ih))) j++;
|
|
307
|
+
if (j === b.length) return false;
|
|
308
|
+
const q = b[j];
|
|
309
|
+
if (cmp(q.lo, p.lo) > 0 || cmp(q.hi, p.hi) < 0 || same(q.lo, p.lo) && p.il && !q.il || same(q.hi, p.hi) && p.ih && !q.ih) return false;
|
|
310
|
+
}
|
|
311
|
+
return true;
|
|
312
|
+
}
|
|
313
|
+
const identical = (a, b) => a.length === b.length && a.every((p, i) => same(p.lo, b[i].lo) && same(p.hi, b[i].hi) && p.il === b[i].il && p.ih === b[i].ih);
|
|
314
|
+
function label(a, b, op) {
|
|
315
|
+
const eq = identical(a, b);
|
|
316
|
+
if (op === 'equal') return eq ? 'equal' : 'notEqual';
|
|
317
|
+
const before = (x, y) => cmp(x.at(-1).hi, y[0].lo) < 0 || same(x.at(-1).hi, y[0].lo) && !(x.at(-1).ih && y[0].il);
|
|
318
|
+
if (op === 'compare') return eq ? 'equal' : before(a, b) ? 'before' : before(b, a) ? 'after' : 'indeterminate';
|
|
319
|
+
if (eq) return 'equal'; if (contains(a, b)) return 'containedBy'; if (contains(b, a)) return 'contains';
|
|
320
|
+
let i = 0, j = 0;
|
|
321
|
+
while (i < a.length && j < b.length) {
|
|
322
|
+
if (!empty(intersection(a[i], b[j]))) return 'overlaps';
|
|
323
|
+
const c = cmp(a[i].hi, b[j].hi); if (c <= 0) i++; if (c >= 0) j++;
|
|
324
|
+
}
|
|
325
|
+
return 'disjoint';
|
|
326
|
+
}
|
|
327
|
+
function compact(c) {
|
|
328
|
+
let text = (String(c.s) + c.f).replace(/^0+/u, '') || '0', e = -BigInt(c.f.length);
|
|
329
|
+
if (text === '0') return { c: '0', e: 0n };
|
|
330
|
+
const trim = text.replace(/0+$/u, ''); e += BigInt(text.length - trim.length); return { c: trim, e };
|
|
331
|
+
}
|
|
332
|
+
function complement(f) {
|
|
333
|
+
const chars = Array.from(f, ch => String(9 - Number(ch))); let carry = 1;
|
|
334
|
+
for (let i = chars.length - 1; i >= 0 && carry; i--) { const n = Number(chars[i]) + carry; chars[i] = String(n % 10); carry = n === 10 ? 1 : 0; }
|
|
335
|
+
return chars.join('').replace(/0+$/u, '');
|
|
336
|
+
}
|
|
337
|
+
function compareDecimal(a, b) {
|
|
338
|
+
const sa = a.c === '0' ? 0 : a.c.startsWith('-') ? -1 : 1, sb = b.c === '0' ? 0 : b.c.startsWith('-') ? -1 : 1;
|
|
339
|
+
if (sa !== sb) return sa < sb ? -1 : 1; if (!sa) return 0;
|
|
340
|
+
const x = a.c.replace(/^-/, ''), y = b.c.replace(/^-/, ''), dx = BigInt(x.length) + a.e, dy = BigInt(y.length) + b.e;
|
|
341
|
+
if (dx !== dy) return (dx < dy ? -1 : 1) * sa;
|
|
342
|
+
for (let i = 0; i < Math.max(x.length, y.length); i++) if ((x[i] ?? '0') !== (y[i] ?? '0')) return ((x[i] ?? '0') < (y[i] ?? '0') ? -1 : 1) * sa;
|
|
343
|
+
return 0;
|
|
344
|
+
}
|
|
345
|
+
function clockImage(pieces, amount, limits) {
|
|
346
|
+
const lower = compact(pieces[0].lo); if (lower.c !== '0') lower.c = '-' + lower.c;
|
|
347
|
+
const end = pieces.at(-1), upper = compact(C(B - end.hi.s - (end.hi.f ? 1 : 0), end.hi.f ? complement(end.hi.f) : ''));
|
|
348
|
+
const top = compareDecimal(amount, upper);
|
|
349
|
+
if (compareDecimal(amount, lower) < 0 || top > 0 || top === 0 && end.ih) stop('unrepresentable_result', 6, null);
|
|
350
|
+
let precision = 0; for (const p of pieces) precision = Math.max(precision, p.lo.f.length, p.hi.f.length);
|
|
351
|
+
const a = amount.e < 0n ? -amount.e : 0n, q = a > BigInt(precision) ? a : BigInt(precision);
|
|
352
|
+
if (amount.c !== '0') {
|
|
353
|
+
if (13n + q > BigInt(limits.maxWorkspaceDigits)) stop('resource_limit', 6, null);
|
|
354
|
+
if (a > BigInt(limits.maxFractionDigits)) stop('resource_limit', 6, null);
|
|
355
|
+
}
|
|
356
|
+
guard(pieces.length, limits.maxWork); guard(pieces.length, limits.maxIntermediatePieces);
|
|
357
|
+
if (amount.c === '0') return pieces;
|
|
358
|
+
// If a finer amount cannot cancel, even one coordinate alone exceeds the envelope.
|
|
359
|
+
if (a > BigInt(precision) && a + 22n > BigInt(limits.maxResultBytes)) stop('resource_limit', 7, null);
|
|
360
|
+
const digits = Number(q), scale = 10n ** q, delta = BigInt(amount.c) * 10n ** (amount.e + q);
|
|
361
|
+
const move = c => {
|
|
362
|
+
const n = BigInt(c.s) * scale + BigInt(c.f || '0') * 10n ** (q - BigInt(c.f.length)) + delta;
|
|
363
|
+
const s = Number(n / scale), f = (n % scale).toString().padStart(digits, '0').replace(/0+$/u, '');
|
|
364
|
+
return C(s, f === '0' ? '' : f);
|
|
365
|
+
};
|
|
366
|
+
return pieces.map(p => piece(move(p.lo), move(p.hi), p.il, p.ih));
|
|
367
|
+
}
|
|
368
|
+
function formFor(pieces, policy) {
|
|
369
|
+
const x = pieces[0].lo, d = date(Math.floor(x.s / 86400) + 1), grain = policy.dateGranularity;
|
|
370
|
+
const start = grain === 'year' ? yearStart(d.y) : grain === 'month' ? ordinal(d.y, d.m, 1) : ordinal(d.y, d.m, d.d);
|
|
371
|
+
const clock = policy.clockForm, time = x.s % 86400, seconds = clock === 'hour' ? Math.floor(time / 3600) * 3600 : clock === 'minute' ? Math.floor(time / 60) * 60 : time;
|
|
372
|
+
return { start, count: grain === 'year' ? (leap(d.y) ? 366 : 365) : grain === 'month' ? monthLength(d.y, d.m) : 1, grain, clock, seconds, f: clock === 'second' ? x.f : '' };
|
|
373
|
+
}
|
|
374
|
+
function stepped(form, text) {
|
|
375
|
+
const n = countValue(text, form.grain), d = date(form.start); let start;
|
|
376
|
+
if (form.grain === 'day') { start = form.start + n; if (start < 1 || start > LAST) stop('unrepresentable_result', 6, null); }
|
|
377
|
+
else if (form.grain === 'year') { if (d.y + n < 1 || d.y + n > 9999) stop('unrepresentable_result', 6, null); start = yearStart(d.y + n); }
|
|
378
|
+
else { const index = monthIndex(d) + n; if (index < 0 || index > 119987) stop('unrepresentable_result', 6, null); const t = monthAt(index); start = ordinal(t.y, t.m, 1); }
|
|
379
|
+
const t = date(start), count = form.grain === 'year' ? (leap(t.y) ? 366 : 365) : form.grain === 'month' ? monthLength(t.y, t.m) : 1;
|
|
380
|
+
return { ...form, start, count };
|
|
381
|
+
}
|
|
382
|
+
class PlannedText { constructor(length, render) { this.length = length; this.render = render; } }
|
|
383
|
+
function coordinatePlan(c) {
|
|
384
|
+
return new PlannedText(19 + (c.f ? c.f.length + 1 : 0), () => {
|
|
385
|
+
const text = fullText(Math.floor(c.s / 86400) + 1), time = c.s % 86400;
|
|
386
|
+
return `${text}T${String(Math.floor(time / 3600)).padStart(2, '0')}:${String(Math.floor(time / 60) % 60).padStart(2, '0')}:${String(time % 60).padStart(2, '0')}${c.f ? '.' + c.f : ''}`;
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
function descriptor(pieces) {
|
|
390
|
+
return { category: 'civilDateTimeSet', pieces: pieces.map(p => same(p.lo, p.hi)
|
|
391
|
+
? { kind: 'point', at: coordinatePlan(p.lo) }
|
|
392
|
+
: { kind: 'interval', start: coordinatePlan(p.lo), end: p.hi.s === B && !p.hi.f ? { boundary: 'endOfDomain' } : coordinatePlan(p.hi), includeStart: p.il, includeEnd: p.ih }) };
|
|
393
|
+
}
|
|
394
|
+
function materialPlan(form) {
|
|
395
|
+
const length = (form.grain === 'year' ? 5 : form.grain === 'month' ? 7 : 10) + 1 + (form.clock === 'hour' ? 2 : form.clock === 'minute' ? 5 : 8 + (form.f ? 1 + form.f.length : 0));
|
|
396
|
+
return new PlannedText(length, () => {
|
|
397
|
+
const d = fullText(form.start), t = coordinatePlan(C((form.start - 1) * 86400 + form.seconds, form.f)).render().split('T')[1];
|
|
398
|
+
return (form.grain === 'year' ? d.slice(0, 5) : form.grain === 'month' ? d.slice(0, 7) : d) + 'T' + (form.clock === 'hour' ? t.slice(0, 2) : form.clock === 'minute' ? t.slice(0, 5) : t);
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
function finish(planned, limits) {
|
|
402
|
+
let size = 0; const stack = [planned];
|
|
403
|
+
while (stack.length) {
|
|
404
|
+
const v = stack.pop();
|
|
405
|
+
if (v instanceof PlannedText) size += v.length + 2;
|
|
406
|
+
else if (typeof v === 'string') size += v.length + 2;
|
|
407
|
+
else if (typeof v === 'boolean') size += v ? 4 : 5;
|
|
408
|
+
else if (Array.isArray(v)) { size += 2 + Math.max(0, v.length - 1); for (const x of v) stack.push(x); }
|
|
409
|
+
else { const keys = Object.keys(v); size += 2 + Math.max(0, keys.length - 1); for (const k of keys) { size += k.length + 3; stack.push(v[k]); } }
|
|
410
|
+
if (size > limits.maxResultBytes) stop('resource_limit', 7, null);
|
|
411
|
+
}
|
|
412
|
+
const render = v => v instanceof PlannedText ? v.render() : Array.isArray(v) ? v.map(render) : record(v) ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, render(x)])) : v;
|
|
413
|
+
return render(planned);
|
|
414
|
+
}
|
|
415
|
+
function evaluate(request, limits, available) {
|
|
416
|
+
if (!record(request)) stop('invalid_operand', 2, null);
|
|
417
|
+
required(request, ['operation', 'input'], '', 'invalid_operand', 2);
|
|
418
|
+
if (!identifier(request.operation)) stop('invalid_operand', 2, '/operation');
|
|
419
|
+
if (!record(request.input)) stop('invalid_operand', 2, '/input');
|
|
420
|
+
closed(request, ['operation', 'input'], '', 'invalid_operand', 2);
|
|
421
|
+
const op = request.operation, input = request.input;
|
|
422
|
+
closed(input, ['left', 'right', 'value', 'amount', 'context', 'policy'], '/input', 'invalid_operand', 2);
|
|
423
|
+
if (!available.has(op)) stop('unsupported_operation', 2, '/operation');
|
|
424
|
+
const binary = OPERATIONS.relations.includes(op), keys = binary ? ['left', 'right'] : op === 'shiftClock' ? ['value', 'amount'] : ['value'];
|
|
425
|
+
required(input, keys, '/input', 'invalid_operand', 2); closed(input, [...keys, 'context', 'policy'], '/input', 'invalid_operand', 2);
|
|
426
|
+
const policy = selection(input, op, limits), values = keys.map(k => k === 'amount' ? amount(input[k], limits, '/input/amount') : operand(input[k], limits, '/input/' + k));
|
|
427
|
+
for (let i = 0; i < values.length; i++) if (values[i].deferred) stop('unsupported_domain', 5, '/input/' + keys[i] + (keys[i] === 'amount' ? '/number/category' : '/temporal/category'));
|
|
428
|
+
const [a, b] = values; let td, clamped = false, outputCount = 0;
|
|
429
|
+
if (binary) { guard(a.pieces.length + b.pieces.length, limits.maxWork); td = { category: 'symbol', value: label(a.pieces, b.pieces, op) }; }
|
|
430
|
+
else if (op === 'shift' || op === 'shiftClock') {
|
|
431
|
+
let pieces;
|
|
432
|
+
if (op === 'shift') { const r = calendarImage(a.pieces, policy, limits); pieces = r.pieces; clamped = r.clamped; }
|
|
433
|
+
else pieces = clockImage(a.pieces, b, limits);
|
|
434
|
+
outputCount = pieces.length; td = descriptor(pieces);
|
|
435
|
+
} else {
|
|
436
|
+
const source = formFor(a.pieces, policy), P = a.pieces.length, S = source.count;
|
|
437
|
+
guard(P + S, limits.maxWork); guard(S, limits.maxIntermediatePieces);
|
|
438
|
+
const matches = identical(a.pieces, expand(source));
|
|
439
|
+
if (!matches) stop(op === 'step' ? 'incompatible_operand' : 'unrepresentable_result', op === 'step' ? 6 : 7, op === 'step' ? '/input/value/temporal' : null);
|
|
440
|
+
if (op === 'step') {
|
|
441
|
+
const target = stepped(source, policy.count); guard(P + S + target.count, limits.maxWork); guard(S + target.count, limits.maxIntermediatePieces);
|
|
442
|
+
outputCount = target.count; td = descriptor(expand(target));
|
|
443
|
+
} else {
|
|
444
|
+
outputCount = S;
|
|
445
|
+
if (outputCount > limits.maxOutputPieces) stop('resource_limit', 7, null);
|
|
446
|
+
const value = materialPlan(source); if (value.length > limits.maxOutputCharacters) stop('resource_limit', 7, null);
|
|
447
|
+
td = { category: 'civilDateTime', value };
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
if (outputCount > limits.maxOutputPieces) stop('resource_limit', 7, null);
|
|
451
|
+
const metadata = { evaluation: 'exact-for-policy', clamping: clamped ? 'applied' : 'not-applied', effectivePolicy: policy }; let value;
|
|
452
|
+
if (binary) { value = td; metadata.operandHistory = { left: a.history, right: b.history }; metadata.operandOrigin = { left: a.origin, right: b.origin }; }
|
|
453
|
+
else value = { temporal: td, originDateGranularity: a.origin.dateGranularity, originClockForm: a.origin.clockForm,
|
|
454
|
+
history: { clamping: clamped ? CLAMPED : a.history.clamping, approximation: op === 'shiftClock' && b.history === APPROX ? APPROX : a.history.approximation } };
|
|
455
|
+
return finish({ outcome: 'value', value, metadata }, limits);
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function structuredText(value, limits) {
|
|
459
|
+
const stack = [{ value, depth: 1 }], active = new Set(), pieces = []; let bytes = 0;
|
|
460
|
+
function append(text) { bytes += utf8Bytes(text, limits.maxRequestBytes - bytes); if (bytes > limits.maxRequestBytes) stop('resource_limit', 1, null); pieces.push(text); }
|
|
461
|
+
while (stack.length) {
|
|
462
|
+
const task = stack.pop();
|
|
463
|
+
if (task.frame) {
|
|
464
|
+
const { item, array, keys, index, depth } = task, length = array ? item.length : keys.length;
|
|
465
|
+
if (index === length) { append(array ? ']' : '}'); active.delete(item); continue; }
|
|
466
|
+
if (index) append(','); const key = array ? index : keys[index];
|
|
467
|
+
if (!array) { if (key.length > limits.maxRequestBytes) stop('resource_limit', 1, null); append(JSON.stringify(key)); append(':'); }
|
|
468
|
+
stack.push({ ...task, index: index + 1 }, { value: item[key], depth: depth + 1 }); continue;
|
|
469
|
+
}
|
|
470
|
+
const item = task.value;
|
|
471
|
+
if (item instanceof RationalJsonNumber) { if (item.text.length > limits.maxRequestBytes) stop('resource_limit', 1, null); append(item.text); }
|
|
472
|
+
else if (item !== null && typeof item === 'object') {
|
|
473
|
+
if (task.depth > limits.maxRequestDepth) stop('resource_limit', 1, null);
|
|
474
|
+
if (active.has(item)) stop('invalid_operand', 2, null);
|
|
475
|
+
const array = Array.isArray(item);
|
|
476
|
+
if (!array && ![Object.prototype, null].includes(Object.getPrototypeOf(item))) throw new TypeError('Structured ingress requires JSON values');
|
|
477
|
+
append(array ? '[' : '{'); active.add(item);
|
|
478
|
+
stack.push({ frame: true, item, array, keys: array ? null : Object.keys(item), index: 0, depth: task.depth });
|
|
479
|
+
} else {
|
|
480
|
+
if (typeof item === 'string' && item.length > limits.maxRequestBytes) stop('resource_limit', 1, null);
|
|
481
|
+
if (typeof item === 'number' && !Number.isFinite(item)) throw new TypeError('Structured ingress requires JSON values');
|
|
482
|
+
const text = JSON.stringify(item); if (text === undefined) throw new TypeError('Structured ingress requires JSON values'); append(text);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
return pieces.join('');
|
|
486
|
+
}
|
|
487
|
+
export function evaluateAeonicCivilDateTimeText(text, options = {}) {
|
|
488
|
+
const { limits, available } = configured(options);
|
|
489
|
+
if (typeof text !== 'string') throw new TypeError('requestText must be text');
|
|
490
|
+
return guarded(() => {
|
|
491
|
+
if (!scalar(text)) stop('invalid_operand', 1, null);
|
|
492
|
+
if (text.length > limits.maxRequestBytes || utf8Bytes(text, limits.maxRequestBytes) > limits.maxRequestBytes || exceedsJsonDepth(text, limits.maxRequestDepth)) stop('resource_limit', 1, null);
|
|
493
|
+
let request; try { request = parseStrictJson(text); } catch (e) { if (e instanceof SyntaxError) stop('invalid_operand', 2, null); throw e; }
|
|
494
|
+
return evaluate(request, limits, available);
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
export function evaluateAeonicCivilDateTimeStructuredJson(request, options = {}) {
|
|
498
|
+
const { limits } = configured(options);
|
|
499
|
+
return guarded(() => evaluateAeonicCivilDateTimeText(structuredText(request, limits), options));
|
|
500
|
+
}
|
|
501
|
+
export const evaluateAeonicCivilDateTime = evaluateAeonicCivilDateTimeStructuredJson;
|