@altopelago/sansa 0.10.0 → 0.11.0

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.
@@ -0,0 +1,486 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { constants as fsConstants } from 'node:fs';
4
+ import {
5
+ copyFile,
6
+ lstat,
7
+ mkdir,
8
+ open,
9
+ readFile,
10
+ readdir,
11
+ rename,
12
+ rmdir,
13
+ unlink,
14
+ writeFile,
15
+ } from 'node:fs/promises';
16
+ import path from 'node:path';
17
+ import { fileURLToPath } from 'node:url';
18
+
19
+ const repositoryRoot = path.resolve(
20
+ path.dirname(fileURLToPath(import.meta.url)),
21
+ '..',
22
+ );
23
+ const expectedPackageName = '@altopelago/sansa';
24
+ const packagePath = path.join(repositoryRoot, 'package.json');
25
+ const capabilitiesPath = path.join(repositoryRoot, 'docs', 'capabilities.json');
26
+ const changelogPath = path.join(repositoryRoot, 'CHANGELOG.md');
27
+ const transactionPath = path.join(repositoryRoot, '.sansa-version-transaction');
28
+ const journalPath = path.join(transactionPath, 'journal.json');
29
+ const journalNextPath = path.join(transactionPath, 'journal.next');
30
+ const semverPattern = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
31
+ const transactionStates = new Set(['staging', 'prepared', 'committed']);
32
+
33
+ const transactionTargets = [
34
+ {
35
+ label: 'package.json',
36
+ path: packagePath,
37
+ next: path.join(transactionPath, 'package.next'),
38
+ backup: path.join(transactionPath, 'package.backup'),
39
+ restore: path.join(transactionPath, 'package.restore'),
40
+ },
41
+ {
42
+ label: 'docs/capabilities.json',
43
+ path: capabilitiesPath,
44
+ next: path.join(transactionPath, 'capabilities.next'),
45
+ backup: path.join(transactionPath, 'capabilities.backup'),
46
+ restore: path.join(transactionPath, 'capabilities.restore'),
47
+ },
48
+ ];
49
+
50
+ function fail(message) {
51
+ console.error(`Version validation failed: ${message}`);
52
+ process.exitCode = 1;
53
+ }
54
+
55
+ function errorMessage(error) {
56
+ return error instanceof Error ? error.message : String(error);
57
+ }
58
+
59
+ function escapeRegExp(value) {
60
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
61
+ }
62
+
63
+ function semverParts(version) {
64
+ const withoutBuild = version.split('+', 1)[0];
65
+ const separator = withoutBuild.indexOf('-');
66
+ const core = (separator === -1 ? withoutBuild : withoutBuild.slice(0, separator))
67
+ .split('.')
68
+ .map((part) => BigInt(part));
69
+ const prerelease = separator === -1
70
+ ? null
71
+ : withoutBuild.slice(separator + 1).split('.');
72
+ return { core, prerelease };
73
+ }
74
+
75
+ function compareSemver(left, right) {
76
+ const a = semverParts(left);
77
+ const b = semverParts(right);
78
+ for (let index = 0; index < 3; index += 1) {
79
+ if (a.core[index] < b.core[index]) return -1;
80
+ if (a.core[index] > b.core[index]) return 1;
81
+ }
82
+ if (a.prerelease === null && b.prerelease === null) return 0;
83
+ if (a.prerelease === null) return 1;
84
+ if (b.prerelease === null) return -1;
85
+ const length = Math.max(a.prerelease.length, b.prerelease.length);
86
+ for (let index = 0; index < length; index += 1) {
87
+ const leftPart = a.prerelease[index];
88
+ const rightPart = b.prerelease[index];
89
+ if (leftPart === undefined) return -1;
90
+ if (rightPart === undefined) return 1;
91
+ if (leftPart === rightPart) continue;
92
+ const leftNumeric = /^\d+$/.test(leftPart);
93
+ const rightNumeric = /^\d+$/.test(rightPart);
94
+ if (leftNumeric && rightNumeric) {
95
+ return BigInt(leftPart) < BigInt(rightPart) ? -1 : 1;
96
+ }
97
+ if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1;
98
+ return leftPart < rightPart ? -1 : 1;
99
+ }
100
+ return 0;
101
+ }
102
+
103
+ async function exists(file) {
104
+ try {
105
+ await lstat(file);
106
+ return true;
107
+ } catch (error) {
108
+ if (error?.code === 'ENOENT') return false;
109
+ throw error;
110
+ }
111
+ }
112
+
113
+ async function unlinkIfPresent(file) {
114
+ try {
115
+ await unlink(file);
116
+ } catch (error) {
117
+ if (error?.code !== 'ENOENT') throw error;
118
+ }
119
+ }
120
+
121
+ async function assertRegularFile(file, label) {
122
+ const metadata = await lstat(file);
123
+ if (!metadata.isFile() || metadata.isSymbolicLink()) {
124
+ throw new Error(`${label} must be a regular file and must not be a symbolic link`);
125
+ }
126
+ return metadata;
127
+ }
128
+
129
+ async function assertTransactionDirectory() {
130
+ const metadata = await lstat(transactionPath);
131
+ if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
132
+ throw new Error(
133
+ `${path.relative(repositoryRoot, transactionPath)} must be a directory and must not be a symbolic link`,
134
+ );
135
+ }
136
+ }
137
+
138
+ async function assertKnownTransactionArtifacts() {
139
+ const knownArtifacts = new Set([
140
+ path.basename(journalPath),
141
+ path.basename(journalNextPath),
142
+ ...transactionTargets.flatMap((target) => [
143
+ path.basename(target.next),
144
+ path.basename(target.backup),
145
+ path.basename(target.restore),
146
+ ]),
147
+ ]);
148
+ const unknown = (await readdir(transactionPath))
149
+ .filter((artifact) => !knownArtifacts.has(artifact));
150
+ if (unknown.length > 0) {
151
+ throw new Error(
152
+ `Unknown recovery artifacts are present (${unknown.join(', ')}); preserve ${path.relative(repositoryRoot, transactionPath)} for manual inspection`,
153
+ );
154
+ }
155
+ }
156
+
157
+ async function readJson(file, label) {
158
+ await assertRegularFile(file, label);
159
+ try {
160
+ return JSON.parse(await readFile(file, 'utf8'));
161
+ } catch (error) {
162
+ throw new Error(`${label} is not valid JSON: ${errorMessage(error)}`);
163
+ }
164
+ }
165
+
166
+ async function writeDurableNew(file, source, mode) {
167
+ const handle = await open(file, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY, mode);
168
+ try {
169
+ await handle.writeFile(source);
170
+ await handle.sync();
171
+ } finally {
172
+ await handle.close();
173
+ }
174
+ }
175
+
176
+ async function syncFile(file) {
177
+ const handle = await open(file, 'r');
178
+ try {
179
+ await handle.sync();
180
+ } finally {
181
+ await handle.close();
182
+ }
183
+ }
184
+
185
+ async function writeJournal(state) {
186
+ await unlinkIfPresent(journalNextPath);
187
+ await writeDurableNew(
188
+ journalNextPath,
189
+ `${JSON.stringify({ schemaVersion: 1, state })}\n`,
190
+ 0o600,
191
+ );
192
+ await rename(journalNextPath, journalPath);
193
+ }
194
+
195
+ async function readJournal() {
196
+ if (!await exists(journalPath)) return null;
197
+ let journal;
198
+ try {
199
+ await assertRegularFile(journalPath, 'Version recovery journal');
200
+ journal = JSON.parse(await readFile(journalPath, 'utf8'));
201
+ } catch (error) {
202
+ throw new Error(
203
+ `Recovery journal is unreadable; preserve ${path.relative(repositoryRoot, transactionPath)} for manual inspection: ${errorMessage(error)}`,
204
+ );
205
+ }
206
+ if (journal?.schemaVersion !== 1 || !transactionStates.has(journal.state)) {
207
+ throw new Error(
208
+ `Recovery journal has an unsupported shape; preserve ${path.relative(repositoryRoot, transactionPath)} for manual inspection`,
209
+ );
210
+ }
211
+ return journal;
212
+ }
213
+
214
+ async function cleanupTransaction() {
215
+ for (const target of transactionTargets) {
216
+ await unlinkIfPresent(target.next);
217
+ await unlinkIfPresent(target.restore);
218
+ await unlinkIfPresent(target.backup);
219
+ }
220
+ await unlinkIfPresent(journalNextPath);
221
+ await unlinkIfPresent(journalPath);
222
+ try {
223
+ await rmdir(transactionPath);
224
+ } catch (error) {
225
+ if (error?.code !== 'ENOENT') throw error;
226
+ }
227
+ }
228
+
229
+ async function restorePreparedTransaction() {
230
+ for (const target of transactionTargets) {
231
+ if (!await exists(target.backup)) {
232
+ throw new Error(`Recovery backup is missing for ${target.label}`);
233
+ }
234
+ await assertRegularFile(target.backup, `Recovery backup for ${target.label}`);
235
+ const backup = await readFile(target.backup);
236
+ const current = await readFile(target.path).catch((error) => {
237
+ if (error?.code === 'ENOENT') return null;
238
+ throw error;
239
+ });
240
+ if (current !== null && current.equals(backup)) continue;
241
+ await unlinkIfPresent(target.restore);
242
+ const metadata = await lstat(target.backup);
243
+ await writeDurableNew(target.restore, backup, metadata.mode);
244
+ await rename(target.restore, target.path);
245
+ }
246
+ }
247
+
248
+ async function recoverVersionTransaction() {
249
+ if (!await exists(transactionPath)) return null;
250
+ await assertTransactionDirectory();
251
+ await assertKnownTransactionArtifacts();
252
+
253
+ const journal = await readJournal();
254
+ if (journal === null) {
255
+ const artifacts = await readdir(transactionPath);
256
+ await cleanupTransaction();
257
+ return artifacts.length === 0 ? 'empty' : 'staging';
258
+ }
259
+
260
+ if (journal.state === 'prepared') {
261
+ await restorePreparedTransaction();
262
+ }
263
+ if (journal.state === 'committed') {
264
+ for (const target of transactionTargets) {
265
+ await assertRegularFile(target.path, target.label);
266
+ }
267
+ }
268
+ await cleanupTransaction();
269
+ return journal.state;
270
+ }
271
+
272
+ async function assertNoPendingTransaction() {
273
+ if (await exists(transactionPath)) {
274
+ throw new Error(
275
+ 'An interrupted version transaction is present; ensure no other version command is running, then run `npm run version:recover`',
276
+ );
277
+ }
278
+ }
279
+
280
+ async function jsonWithReplacedVersion(file, label, currentVersion, nextVersion) {
281
+ const source = await readFile(file, 'utf8');
282
+ const current = JSON.stringify(currentVersion);
283
+ const matches = source.match(
284
+ new RegExp(`^ "version"\\s*:\\s*${escapeRegExp(current)}`, 'gm'),
285
+ ) ?? [];
286
+ if (matches.length !== 1) {
287
+ throw new Error(
288
+ `${label} must contain exactly one top-level version matching ${current}`,
289
+ );
290
+ }
291
+ return source.replace(
292
+ new RegExp(`^( "version"\\s*:\\s*)${escapeRegExp(current)}`, 'm'),
293
+ `$1${JSON.stringify(nextVersion)}`,
294
+ );
295
+ }
296
+
297
+ function releaseHeadingProblem(changelog, version) {
298
+ const releaseHeading = new RegExp(
299
+ `^## ${escapeRegExp(version)} - \\d{4}-\\d{2}-\\d{2}$`,
300
+ 'gm',
301
+ );
302
+ const matches = changelog.match(releaseHeading) ?? [];
303
+ return matches.length === 1
304
+ ? null
305
+ : `CHANGELOG.md must have exactly one dated release heading for ${version}`;
306
+ }
307
+
308
+ function metadataProblems(packageManifest, capabilities, changelog = null) {
309
+ const problems = [];
310
+ const version = packageManifest.version;
311
+ if (packageManifest.name !== expectedPackageName) {
312
+ problems.push(`package.json name must be ${JSON.stringify(expectedPackageName)}`);
313
+ }
314
+ if (typeof version !== 'string' || !semverPattern.test(version)) {
315
+ problems.push(`package.json has invalid SemVer version ${JSON.stringify(version)}`);
316
+ }
317
+ if (capabilities.implementation !== expectedPackageName) {
318
+ problems.push(
319
+ `docs/capabilities.json implementation must be ${JSON.stringify(expectedPackageName)}`,
320
+ );
321
+ }
322
+ if (capabilities.version !== version) {
323
+ problems.push(
324
+ `docs/capabilities.json version ${JSON.stringify(capabilities.version)} does not match package version ${JSON.stringify(version)}`,
325
+ );
326
+ }
327
+ if (changelog !== null && typeof version === 'string') {
328
+ const problem = releaseHeadingProblem(changelog, version);
329
+ if (problem !== null) problems.push(problem);
330
+ }
331
+ return problems;
332
+ }
333
+
334
+ async function loadMetadata({ includeChangelog }) {
335
+ const [packageManifest, capabilities, changelog] = await Promise.all([
336
+ readJson(packagePath, 'package.json'),
337
+ readJson(capabilitiesPath, 'docs/capabilities.json'),
338
+ includeChangelog
339
+ ? assertRegularFile(changelogPath, 'CHANGELOG.md').then(() => readFile(changelogPath, 'utf8'))
340
+ : Promise.resolve(null),
341
+ ]);
342
+ return { packageManifest, capabilities, changelog };
343
+ }
344
+
345
+ async function checkVersion() {
346
+ await assertNoPendingTransaction();
347
+ const metadata = await loadMetadata({ includeChangelog: true });
348
+ const problems = metadataProblems(
349
+ metadata.packageManifest,
350
+ metadata.capabilities,
351
+ metadata.changelog,
352
+ );
353
+ await Promise.all([
354
+ jsonWithReplacedVersion(
355
+ packagePath,
356
+ 'package.json',
357
+ metadata.packageManifest.version,
358
+ metadata.packageManifest.version,
359
+ ),
360
+ jsonWithReplacedVersion(
361
+ capabilitiesPath,
362
+ 'docs/capabilities.json',
363
+ metadata.capabilities.version,
364
+ metadata.capabilities.version,
365
+ ),
366
+ ]).catch((error) => problems.push(errorMessage(error)));
367
+ if (problems.length > 0) throw new Error(problems.join('; '));
368
+ console.log(
369
+ `Version consistency passed: ${metadata.packageManifest.name}@${metadata.packageManifest.version}`,
370
+ );
371
+ }
372
+
373
+ async function writeVersionTransaction(updates) {
374
+ try {
375
+ await mkdir(transactionPath, { mode: 0o700 });
376
+ } catch (error) {
377
+ if (error?.code === 'EEXIST') {
378
+ throw new Error(
379
+ 'A version transaction is already present; ensure no other version command is running, then run `npm run version:recover`',
380
+ );
381
+ }
382
+ throw error;
383
+ }
384
+
385
+ try {
386
+ await writeJournal('staging');
387
+ for (const [index, target] of transactionTargets.entries()) {
388
+ const metadata = await assertRegularFile(target.path, target.label);
389
+ await writeDurableNew(target.next, updates[index], metadata.mode);
390
+ await copyFile(target.path, target.backup, fsConstants.COPYFILE_EXCL);
391
+ await syncFile(target.backup);
392
+ }
393
+ await writeJournal('prepared');
394
+ for (const target of transactionTargets) {
395
+ await rename(target.next, target.path);
396
+ }
397
+ await writeJournal('committed');
398
+ await cleanupTransaction();
399
+ } catch (error) {
400
+ let recoveredState;
401
+ try {
402
+ recoveredState = await recoverVersionTransaction();
403
+ } catch (recoveryError) {
404
+ throw new Error(
405
+ `${errorMessage(error)}; automatic recovery failed: ${errorMessage(recoveryError)}`,
406
+ );
407
+ }
408
+ if (recoveredState === 'committed') return;
409
+ throw new Error(`${errorMessage(error)}; original version files were restored`);
410
+ }
411
+ }
412
+
413
+ async function setVersion(version) {
414
+ if (!semverPattern.test(version)) {
415
+ throw new Error(
416
+ `Expected a SemVer version without a leading "v", received ${JSON.stringify(version)}`,
417
+ );
418
+ }
419
+ await assertNoPendingTransaction();
420
+ const metadata = await loadMetadata({ includeChangelog: true });
421
+ const problems = metadataProblems(
422
+ metadata.packageManifest,
423
+ metadata.capabilities,
424
+ metadata.changelog,
425
+ );
426
+ if (problems.length > 0) {
427
+ throw new Error(`Refusing to update inconsistent release metadata: ${problems.join('; ')}`);
428
+ }
429
+ if (metadata.packageManifest.version === version) {
430
+ console.log(`${expectedPackageName} release metadata is already ${version}.`);
431
+ return;
432
+ }
433
+ if (compareSemver(version, metadata.packageManifest.version) <= 0) {
434
+ throw new Error(
435
+ `New version ${version} must have higher SemVer precedence than current version ${metadata.packageManifest.version}`,
436
+ );
437
+ }
438
+
439
+ const updates = await Promise.all([
440
+ jsonWithReplacedVersion(
441
+ packagePath,
442
+ 'package.json',
443
+ metadata.packageManifest.version,
444
+ version,
445
+ ),
446
+ jsonWithReplacedVersion(
447
+ capabilitiesPath,
448
+ 'docs/capabilities.json',
449
+ metadata.capabilities.version,
450
+ version,
451
+ ),
452
+ ]);
453
+ await writeVersionTransaction(updates);
454
+ console.log(`Set ${expectedPackageName} release metadata to ${version}.`);
455
+ console.log('Add the dated CHANGELOG.md heading, then run `npm run version:check`.');
456
+ }
457
+
458
+ async function recoverVersion() {
459
+ const state = await recoverVersionTransaction();
460
+ if (state === null) {
461
+ console.log('No interrupted version transaction was found.');
462
+ return;
463
+ }
464
+ const outcome = state === 'committed'
465
+ ? 'kept the committed version files'
466
+ : 'restored the pre-transaction version files';
467
+ console.log(`Recovered version transaction (${state}); ${outcome}.`);
468
+ }
469
+
470
+ const [command, ...args] = process.argv.slice(2);
471
+
472
+ try {
473
+ if (command === 'check' && args.length === 0) {
474
+ await checkVersion();
475
+ } else if (command === 'set' && args.length === 1) {
476
+ await setVersion(args[0]);
477
+ } else if (command === 'recover' && args.length === 0) {
478
+ await recoverVersion();
479
+ } else {
480
+ throw new Error(
481
+ 'Usage: node scripts/version.mjs check | set <version> | recover',
482
+ );
483
+ }
484
+ } catch (error) {
485
+ fail(errorMessage(error));
486
+ }
package/src/index.d.ts CHANGED
@@ -262,11 +262,15 @@ export interface SansaMutateDiagnostic {
262
262
 
263
263
  export interface SansaResolveBinding {
264
264
  readonly address?: string;
265
+ /** Opaque structural occurrence identity supplied by the host namespace. */
266
+ readonly identity?: string;
265
267
  readonly name?: string;
266
268
  readonly key?: string;
267
269
  readonly index?: number;
268
270
  readonly semanticType?: string;
269
271
  readonly datatype?: string;
272
+ readonly generics?: readonly SansaDatatypeGenericComponent[];
273
+ readonly clarifiers?: readonly SansaDatatypeClarifierComponent[];
270
274
  readonly representationKind?: string;
271
275
  readonly kind?: string;
272
276
  readonly type?: string;
@@ -276,12 +280,33 @@ export interface SansaResolveBinding {
276
280
  readonly nullReason?: string;
277
281
  readonly value?: unknown;
278
282
  readonly scalar?: unknown;
283
+ readonly origin?: string;
284
+ readonly span?: string;
279
285
  readonly children?: readonly SansaResolveBinding[];
280
286
  readonly parent?: SansaResolveBinding | null;
281
287
  readonly attributeSpace?: SansaResolveBinding;
282
288
  readonly attributes?: SansaResolveBinding;
283
289
  }
284
290
 
291
+ export interface SansaDatatypeDescriptor {
292
+ readonly datatype: string;
293
+ readonly generics: readonly SansaDatatypeGenericComponent[];
294
+ readonly clarifiers: readonly SansaDatatypeClarifierComponent[];
295
+ }
296
+
297
+ export interface SansaDatatypeStringComponent {
298
+ readonly kind: 'StringLiteral';
299
+ readonly value: string;
300
+ }
301
+
302
+ export interface SansaDatatypeNumberComponent {
303
+ readonly kind: 'NumberLiteral';
304
+ readonly value: string;
305
+ }
306
+
307
+ export type SansaDatatypeGenericComponent = SansaDatatypeDescriptor | SansaDatatypeNumberComponent;
308
+ export type SansaDatatypeClarifierComponent = SansaDatatypeStringComponent | SansaDatatypeNumberComponent;
309
+
285
310
  export interface SansaResolveNamespace<TBinding extends object = SansaResolveBinding> {
286
311
  readonly root: TBinding | (() => TBinding | undefined);
287
312
  readonly contextualRoot?: TBinding;
@@ -630,6 +655,8 @@ export type SansaMutationTargetSurfaceInput<TBinding extends object = SansaResol
630
655
  | 'aeon'
631
656
  | 'json'
632
657
  | 'json-compatible'
658
+ | 'telex'
659
+ | 'telex.aes'
633
660
  | SansaMutationTargetSurface<TBinding>;
634
661
 
635
662
  export interface SansaMutationTargetSurface<TBinding extends object = SansaResolveBinding> {