@sublang/spex 4.2.0 → 5.0.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.
Files changed (100) hide show
  1. package/README.md +433 -89
  2. package/dist/cli.js +80 -42
  3. package/dist/commands/add.d.ts +12 -0
  4. package/dist/commands/add.js +138 -0
  5. package/dist/commands/auth-target.d.ts +11 -0
  6. package/dist/commands/auth-target.js +50 -0
  7. package/dist/commands/environment.d.ts +123 -0
  8. package/dist/commands/environment.js +411 -0
  9. package/dist/commands/export.d.ts +21 -0
  10. package/dist/commands/export.js +663 -0
  11. package/dist/commands/home.d.ts +56 -0
  12. package/dist/commands/home.js +215 -0
  13. package/dist/commands/install.d.ts +2 -0
  14. package/dist/commands/install.js +48 -0
  15. package/dist/commands/list.d.ts +2 -0
  16. package/dist/commands/list.js +87 -0
  17. package/dist/commands/login.d.ts +2 -0
  18. package/dist/commands/login.js +211 -0
  19. package/dist/commands/logout.d.ts +2 -0
  20. package/dist/commands/logout.js +74 -0
  21. package/dist/commands/publish.d.ts +2 -0
  22. package/dist/commands/publish.js +120 -0
  23. package/dist/commands/remove.d.ts +2 -0
  24. package/dist/commands/remove.js +34 -0
  25. package/dist/commands/run.d.ts +50 -0
  26. package/dist/commands/run.js +309 -0
  27. package/dist/commands/search.d.ts +2 -0
  28. package/dist/commands/search.js +34 -0
  29. package/dist/commands/settle.d.ts +124 -0
  30. package/dist/commands/settle.js +475 -0
  31. package/dist/commands/update.d.ts +2 -0
  32. package/dist/commands/update.js +37 -0
  33. package/dist/commands/whoami.d.ts +2 -0
  34. package/dist/commands/whoami.js +75 -0
  35. package/dist/lib/environment/agent-folders.d.ts +14 -0
  36. package/dist/lib/environment/agent-folders.js +11 -0
  37. package/dist/lib/environment/archive.d.ts +26 -0
  38. package/dist/lib/environment/archive.js +91 -0
  39. package/dist/lib/environment/builtins.d.ts +112 -0
  40. package/dist/lib/environment/builtins.js +539 -0
  41. package/dist/lib/environment/citations.d.ts +75 -0
  42. package/dist/lib/environment/citations.js +267 -0
  43. package/dist/lib/environment/exports.d.ts +190 -0
  44. package/dist/lib/environment/exports.js +1029 -0
  45. package/dist/lib/environment/format.d.ts +133 -0
  46. package/dist/lib/environment/format.js +651 -0
  47. package/dist/lib/environment/git-source.d.ts +41 -0
  48. package/dist/lib/environment/git-source.js +159 -0
  49. package/dist/lib/environment/index.d.ts +20 -0
  50. package/dist/lib/environment/index.js +27 -0
  51. package/dist/lib/environment/install.d.ts +140 -0
  52. package/dist/lib/environment/install.js +694 -0
  53. package/dist/lib/environment/layout.d.ts +15 -0
  54. package/dist/lib/environment/layout.js +50 -0
  55. package/dist/lib/environment/lock.d.ts +87 -0
  56. package/dist/lib/environment/lock.js +305 -0
  57. package/dist/lib/environment/marker.d.ts +15 -0
  58. package/dist/lib/environment/marker.js +31 -0
  59. package/dist/lib/environment/own-paths.d.ts +59 -0
  60. package/dist/lib/environment/own-paths.js +174 -0
  61. package/dist/lib/environment/placed-record.d.ts +32 -0
  62. package/dist/lib/environment/placed-record.js +72 -0
  63. package/dist/lib/environment/registries.d.ts +25 -0
  64. package/dist/lib/environment/registries.js +75 -0
  65. package/dist/lib/environment/registry.d.ts +173 -0
  66. package/dist/lib/environment/registry.js +390 -0
  67. package/dist/lib/environment/requests.d.ts +108 -0
  68. package/dist/lib/environment/requests.js +403 -0
  69. package/dist/lib/environment/resolve.d.ts +70 -0
  70. package/dist/lib/environment/resolve.js +451 -0
  71. package/dist/lib/environment/semver.d.ts +30 -0
  72. package/dist/lib/environment/semver.js +130 -0
  73. package/dist/lib/environment/store.d.ts +23 -0
  74. package/dist/lib/environment/store.js +123 -0
  75. package/dist/lib/environment/tar.d.ts +27 -0
  76. package/dist/lib/environment/tar.js +219 -0
  77. package/dist/lib/files.d.ts +66 -0
  78. package/dist/lib/files.js +233 -0
  79. package/dist/lib/git-host.d.ts +579 -0
  80. package/dist/lib/git-host.js +1363 -0
  81. package/dist/lib/home-file.d.ts +124 -0
  82. package/dist/lib/home-file.js +288 -0
  83. package/dist/lib/instance.d.ts +63 -0
  84. package/dist/lib/instance.js +130 -0
  85. package/dist/lib/words.d.ts +32 -0
  86. package/dist/lib/words.js +27 -0
  87. package/dist/lint.js +8 -0
  88. package/dist/testing/index.d.ts +1 -0
  89. package/dist/testing/index.js +7 -0
  90. package/dist/testing/standin-registry.d.ts +94 -0
  91. package/dist/testing/standin-registry.js +449 -0
  92. package/package.json +37 -3
  93. package/dist/attached-cli.d.ts +0 -13
  94. package/dist/attached-cli.js +0 -249
  95. package/dist/attached-client.d.ts +0 -53
  96. package/dist/attached-client.js +0 -237
  97. package/dist/generated-protocol.d.ts +0 -2
  98. package/dist/generated-protocol.js +0 -6
  99. package/dist/package-init.d.ts +0 -21
  100. package/dist/package-init.js +0 -442
@@ -0,0 +1,539 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
+ // The built-in spec package (environments-11, DR-104): the playbooks
4
+ // Playbook ships, staged at build as `sublang/playbooks` at Playbook's
5
+ // version under `assets/builtins/<version>/`, seeded into the store at
6
+ // start with a release index under `cache/builtins/`, and served as a
7
+ // registry source that needs no network. Several seeded versions stand
8
+ // side by side, so a lock pinning an older one keeps installing it.
9
+ import { existsSync, lstatSync, readdirSync, readFileSync } from "node:fs";
10
+ import { mkdir, readFile } from "node:fs/promises";
11
+ import { dirname, join } from "node:path";
12
+ import { Document, isMap, parseDocument } from "yaml";
13
+ import { readVersioned, VersionConflictError, writeApplicationBytes, writeVersionedBytes } from "../files.js";
14
+ import { packFiles } from "./archive.js";
15
+ import { BUILTIN_PACKAGE_NAME, specExportName } from "./exports.js";
16
+ import { artifactLanguages, inArtifact, parseManifestText, providedArtifacts, readRelease, ROOT_FILES, sha256Hex } from "./format.js";
17
+ import { isRegistrySource, parseLock, serializeLock } from "./lock.js";
18
+ import { RegistryError } from "./registry.js";
19
+ import { parseRequests, PUBLIC_REGISTRY_ORIGIN, setRegistryIn, requestsDigest, setSpaceIn } from "./requests.js";
20
+ import { compareVersions, isVersion } from "./semver.js";
21
+ export { BUILTIN_PACKAGE_NAME };
22
+ /** The built-in spec package staged under `root`, where the app's build
23
+ * stages it: the highest version staged. */
24
+ export function stagedBuiltinPackage(root) {
25
+ const versions = existsSync(root) ? readdirSync(root).filter((name) => isVersion(name) && existsSync(join(root, name, "meta.yaml"))) : [];
26
+ if (versions.length === 0)
27
+ throw new Error(`no built-in spec package is staged under ${root}: run the core's build`);
28
+ const version = versions.sort(compareVersions).at(-1);
29
+ return { name: BUILTIN_PACKAGE_NAME, version, dir: join(root, version) };
30
+ }
31
+ function recordFile(cacheDir, version) {
32
+ return join(cacheDir, "builtins", `${version}.json`);
33
+ }
34
+ /** Seed a built-in release into the store and record its index
35
+ * (environments-11). Idempotent; an older seeded release stays. */
36
+ export async function seedBuiltinPackage(store, cacheDir, pkg) {
37
+ // Seeded already, its files whole in the store: nothing to do.
38
+ const seeded = readRecord(recordFile(cacheDir, pkg.version));
39
+ if (seeded && seeded.files.every((file) => store.has(file.sha256, file.executable)))
40
+ return seeded;
41
+ const release = await shippedRecord(pkg);
42
+ if (`${release.manifest.org}/${release.manifest.name}` !== BUILTIN_PACKAGE_NAME || release.manifest.version !== pkg.version) {
43
+ throw new Error(`${pkg.dir} holds ${release.manifest.org}/${release.manifest.name} ${release.manifest.version}, not ${BUILTIN_PACKAGE_NAME} ${pkg.version}`);
44
+ }
45
+ for (const file of release.files) {
46
+ if (store.has(file.sha256, file.executable))
47
+ continue;
48
+ const bytes = await readFile(join(pkg.dir, ...file.path.split("/")));
49
+ store.put(bytes, file.sha256, file.executable, `${BUILTIN_PACKAGE_NAME} ${file.path}`);
50
+ }
51
+ const file = recordFile(cacheDir, pkg.version);
52
+ await mkdir(dirname(file), { recursive: true });
53
+ writeApplicationBytes(file, JSON.stringify(release));
54
+ return release;
55
+ }
56
+ /** A shipped release read, checked and packed once per process: the
57
+ * same for every home this process serves. */
58
+ const shippedRecords = new Map();
59
+ function shippedRecord(pkg) {
60
+ const key = `${pkg.dir}\u0000${pkg.version}`;
61
+ let record = shippedRecords.get(key);
62
+ if (!record) {
63
+ record = (async () => {
64
+ const { manifest, files } = await readRelease(pkg.dir);
65
+ const archive = packFiles(manifest.name, files.map((file) => ({ path: file.path, executable: file.executable, data: readFileSync(join(pkg.dir, ...file.path.split("/"))) })));
66
+ return { format: 1, name: BUILTIN_PACKAGE_NAME, version: pkg.version, manifest, files, checksum: sha256Hex(archive), size: archive.length };
67
+ })();
68
+ record.catch(() => shippedRecords.delete(key));
69
+ shippedRecords.set(key, record);
70
+ }
71
+ return record;
72
+ }
73
+ function readRecord(file) {
74
+ try {
75
+ const value = JSON.parse(readFileSync(file, "utf8"));
76
+ return value.format === 1 && value.name === BUILTIN_PACKAGE_NAME && isVersion(value.version) && Array.isArray(value.files) ? value : null;
77
+ }
78
+ catch {
79
+ return null;
80
+ }
81
+ }
82
+ const PUBLISHED_AT = "1970-01-01T00:00:00.000Z";
83
+ /** The seeded built-in releases as a registry source (environments-11):
84
+ * no network, `sublang/playbooks` only. */
85
+ export function builtinRegistrySource(options) {
86
+ const { store, cacheDir } = options;
87
+ let shippedCache;
88
+ function shippedRelease() {
89
+ const pkg = options.shipped ?? null;
90
+ if (!pkg)
91
+ return undefined;
92
+ if (shippedCache?.pkg.dir !== pkg.dir)
93
+ shippedCache = { pkg, release: shippedRecord(pkg) };
94
+ return shippedCache.release;
95
+ }
96
+ async function releases() {
97
+ const out = new Map();
98
+ const dir = join(cacheDir, "builtins");
99
+ if (existsSync(dir)) {
100
+ for (const name of readdirSync(dir)) {
101
+ if (!name.endsWith(".json"))
102
+ continue;
103
+ const record = readRecord(join(dir, name));
104
+ // A seeded release serves only while the store holds its files.
105
+ if (record && record.files.every((file) => store.has(file.sha256, file.executable)))
106
+ out.set(record.version, record);
107
+ }
108
+ }
109
+ const shipped = shippedRelease();
110
+ if (shipped) {
111
+ const release = await shipped;
112
+ out.set(release.version, release);
113
+ }
114
+ return [...out.values()].sort((a, b) => compareVersions(a.version, b.version));
115
+ }
116
+ async function releaseOf(name, version) {
117
+ if (name !== BUILTIN_PACKAGE_NAME)
118
+ throw new RegistryError("not_found", name, `${name} is not the built-in spec package`);
119
+ const release = (await releases()).find((item) => item.version === version);
120
+ if (!release)
121
+ throw new RegistryError("not_found", name, `${name} ${version} is not on this computer yet`);
122
+ return release;
123
+ }
124
+ function artifactsOf(release) {
125
+ const languages = artifactLanguages(release.manifest, release.files);
126
+ const out = {};
127
+ for (const [id, artifact] of Object.entries(release.manifest.artifacts)) {
128
+ out[id] = { kind: artifact.kind, ...(artifact.language ? { language: artifact.language } : {}), languages: languages[id] ?? [] };
129
+ }
130
+ return out;
131
+ }
132
+ async function bytesOf(release, path) {
133
+ const file = release.files.find((item) => item.path === path);
134
+ if (!file)
135
+ throw new RegistryError("not_found", BUILTIN_PACKAGE_NAME, `${BUILTIN_PACKAGE_NAME} ${release.version} has no file ${path}`);
136
+ if (store.has(file.sha256, file.executable))
137
+ return new Uint8Array(await readFile(store.pathOf(file.sha256, file.executable)));
138
+ const shipped = options.shipped ?? null;
139
+ if (shipped && shipped.version === release.version)
140
+ return new Uint8Array(await readFile(join(shipped.dir, ...path.split("/"))));
141
+ throw new RegistryError("not_found", BUILTIN_PACKAGE_NAME, `${BUILTIN_PACKAGE_NAME} ${release.version}: ${path} is not in the store`);
142
+ }
143
+ return {
144
+ url: options.url ?? "builtin:",
145
+ async index(name) {
146
+ if (name !== BUILTIN_PACKAGE_NAME)
147
+ throw new RegistryError("not_found", name, `${name} is not the built-in spec package`);
148
+ const versions = (await releases()).map((release) => ({
149
+ version: release.version,
150
+ format: 2,
151
+ published_at: PUBLISHED_AT,
152
+ checksum: release.checksum,
153
+ yanked: false,
154
+ suppressed: false,
155
+ dependencies: { ...release.manifest.dependencies },
156
+ artifacts: artifactsOf(release),
157
+ }));
158
+ return { org: "sublang", name: "playbooks", latest: versions.at(-1)?.version ?? null, versions };
159
+ },
160
+ async version(name, version) {
161
+ const release = await releaseOf(name, version);
162
+ const artifacts = {};
163
+ const indexArtifacts = artifactsOf(release);
164
+ for (const [id, artifact] of Object.entries(release.manifest.artifacts)) {
165
+ artifacts[id] = { ...indexArtifacts[id], ...(artifact.from ? { from: artifact.from } : {}), requires: [...artifact.requires] };
166
+ }
167
+ return {
168
+ org: "sublang",
169
+ name: "playbooks",
170
+ version,
171
+ format: 2,
172
+ ...(release.manifest.description ? { description: release.manifest.description } : {}),
173
+ ...(release.manifest.license ? { license: release.manifest.license } : {}),
174
+ ...(release.manifest.repository ? { repository: release.manifest.repository } : {}),
175
+ languages: [...new Set(Object.values(indexArtifacts).flatMap((artifact) => artifact.languages))].sort(),
176
+ artifacts,
177
+ dependencies: { ...release.manifest.dependencies },
178
+ checksum: release.checksum,
179
+ size: release.size,
180
+ published_at: PUBLISHED_AT,
181
+ yanked: false,
182
+ suppressed: false,
183
+ files: release.files.map((file) => ({ ...file })),
184
+ dist: { tarball: `/api/v1/packages/sublang/playbooks/${version}/download`, sha256: release.checksum },
185
+ };
186
+ },
187
+ async file(name, version, path) {
188
+ return bytesOf(await releaseOf(name, version), path);
189
+ },
190
+ async archive(name, version) {
191
+ const release = await releaseOf(name, version);
192
+ const data = [];
193
+ for (const file of release.files)
194
+ data.push({ path: file.path, executable: file.executable, data: await bytesOf(release, file.path) });
195
+ return packFiles(release.manifest.name, data);
196
+ },
197
+ async publish(name) {
198
+ throw new RegistryError("forbidden", name, `${name} comes with Spex and is not published from here`);
199
+ },
200
+ async search(query) {
201
+ const all = await releases();
202
+ const latest = all.at(-1);
203
+ if (!latest)
204
+ return [];
205
+ const description = latest.manifest.description ?? "";
206
+ const q = query.toLowerCase();
207
+ if (!BUILTIN_PACKAGE_NAME.includes(q) && !description.toLowerCase().includes(q))
208
+ return [];
209
+ return [{ name: BUILTIN_PACKAGE_NAME, description, versions: all.map((release) => release.version) }];
210
+ },
211
+ };
212
+ }
213
+ /**
214
+ * Whether this device's seed serves a lock's release of the built-in spec
215
+ * package (environments-7, environments-11): it holds the locked version
216
+ * and each locked file at the digest the lock records for it. The
217
+ * archive's checksum is not compared: each device packs its own archive
218
+ * from its seed, so another device's lock of the same files may record
219
+ * another.
220
+ */
221
+ export async function seedServes(seed, version, files) {
222
+ let resource;
223
+ try {
224
+ resource = await seed.version(BUILTIN_PACKAGE_NAME, version);
225
+ }
226
+ catch (error) {
227
+ if (error instanceof RegistryError)
228
+ return false;
229
+ throw error;
230
+ }
231
+ const digests = new Map((resource.files ?? []).map((file) => [file.path, file.sha256]));
232
+ return files.every((file) => digests.get(file.path) === file.sha256);
233
+ }
234
+ /** A release folder's files, read synchronously as `readRelease` lists
235
+ * them: links refused, `.git` and `node_modules` folders skipped. */
236
+ function listFilesSync(dir) {
237
+ const files = [];
238
+ const walk = (relative) => {
239
+ const absolute = relative ? join(dir, ...relative.split("/")) : dir;
240
+ for (const name of readdirSync(absolute).sort()) {
241
+ const path = relative ? `${relative}/${name}` : name;
242
+ const stat = lstatSync(join(absolute, name));
243
+ if (stat.isDirectory()) {
244
+ if (name === ".git" || name === "node_modules")
245
+ continue;
246
+ walk(path);
247
+ }
248
+ else if (stat.isFile()) {
249
+ if (name === ".DS_Store")
250
+ continue;
251
+ const bytes = readFileSync(join(absolute, name));
252
+ files.push({ path, size: bytes.length, sha256: sha256Hex(bytes), executable: (stat.mode & 0o100) !== 0 });
253
+ }
254
+ else {
255
+ throw new Error(`${pkgPathOf(dir, path)} is not a file`);
256
+ }
257
+ }
258
+ };
259
+ walk("");
260
+ return files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
261
+ }
262
+ function pkgPathOf(dir, path) {
263
+ return join(dir, ...path.split("/"));
264
+ }
265
+ /**
266
+ * The lock an environment requesting only the built-in spec package
267
+ * resolves to, computed from the release this app ships without any
268
+ * source or network (environments-3, environments-6): every artifact in
269
+ * its original language, every file of theirs, each playbook it
270
+ * provides exported under its id. A clone the store makes holds it from
271
+ * its first commit.
272
+ */
273
+ export function builtinLock(pkg, registryUrl, requestsText) {
274
+ const key = `${pkg.dir}\u0000${pkg.version}\u0000${registryUrl}`;
275
+ let resolution = builtinResolutions.get(key);
276
+ if (!resolution) {
277
+ resolution = builtinResolution(pkg, registryUrl);
278
+ builtinResolutions.set(key, resolution);
279
+ }
280
+ return { format: 1, requests: requestsDigest(requestsText), packages: { [BUILTIN_PACKAGE_NAME]: structuredClone(resolution) } };
281
+ }
282
+ /** The built-in release's resolution, once per release and registry:
283
+ * reading and packing it is the slow part. */
284
+ const builtinResolutions = new Map();
285
+ function builtinResolution(pkg, registryUrl) {
286
+ const { manifest, issues } = parseManifestText(readFileSync(join(pkg.dir, "meta.yaml"), "utf8"));
287
+ if (!manifest)
288
+ throw new Error(issues.map((issue) => issue.message).join("; "));
289
+ const files = listFilesSync(pkg.dir);
290
+ const archive = packFiles(manifest.name, files.map((file) => ({ path: file.path, executable: file.executable, data: readFileSync(pkgPathOf(pkg.dir, file.path)) })));
291
+ const artifacts = {};
292
+ const exports = {};
293
+ const ids = Object.keys(manifest.artifacts).sort();
294
+ const provided = providedArtifacts(manifest);
295
+ for (const id of ids) {
296
+ const artifact = manifest.artifacts[id];
297
+ artifacts[id] = { language: artifact.kind === "applet" ? null : artifact.language ?? null, fallback: false };
298
+ if (!provided.has(id))
299
+ continue;
300
+ if (artifact.kind === "playbook" || artifact.kind === "skill")
301
+ exports[id] = id;
302
+ else if (artifact.kind === "spec")
303
+ exports[specExportName(BUILTIN_PACKAGE_NAME)] = id;
304
+ }
305
+ const selected = files.filter((file) => ROOT_FILES.includes(file.path)
306
+ || ids.some((id) => inArtifact(file.path, manifest.artifacts[id].kind, id, artifacts[id].language, manifest.name)));
307
+ return {
308
+ source: { registry: registryUrl.replace(/\/+$/, ""), version: manifest.version, checksum: sha256Hex(archive) },
309
+ requiredBy: [],
310
+ artifacts,
311
+ files: selected.map((file) => ({ path: file.path, sha256: file.sha256, executable: file.executable })),
312
+ exports,
313
+ };
314
+ }
315
+ /**
316
+ * A new environment at its root (environments-11, storage-6): your own
317
+ * group's clone, or a project's working folder at its pairing.
318
+ * `spex.yaml` requests the built-in spec package where it does not —
319
+ * with `space` naming the environment's instance where one is given, the
320
+ * caller giving the instance its spex repository is placed at wherever
321
+ * it has one — and, where that is all it requests and no lock stands,
322
+ * its lock, so the first commit holding either holds both. Returns
323
+ * whether `spex.yaml` was written.
324
+ */
325
+ export function prepareBuiltinEnvironment(root, pkg, registryUrl, space = null) {
326
+ const wrote = ensureBuiltinRequest(root, pkg.version, space);
327
+ const lockFile = join(root, "spex.lock");
328
+ if (existsSync(lockFile))
329
+ return wrote;
330
+ const { bytes } = readVersioned(join(root, "spex.yaml"));
331
+ if (bytes === null)
332
+ return wrote;
333
+ const text = bytes.toString("utf8");
334
+ let requested;
335
+ try {
336
+ requested = Object.keys(parseRequests(text).packages);
337
+ }
338
+ catch {
339
+ return wrote;
340
+ }
341
+ if (requested.length !== 1 || requested[0] !== BUILTIN_PACKAGE_NAME)
342
+ return wrote;
343
+ try {
344
+ // Written only where no lock stands yet (DR-111).
345
+ writeVersionedBytes(lockFile, serializeLock(builtinLock(pkg, parseRequests(text).registry ?? registryUrl, text)), null);
346
+ }
347
+ catch (error) {
348
+ // The first resolve writes it instead.
349
+ console.error(`spex: ${root} holds no lock yet: ${error instanceof Error ? error.message : String(error)}`);
350
+ }
351
+ return wrote;
352
+ }
353
+ /**
354
+ * Move an environment's built-in lock to `registryUrl` where it is
355
+ * still the one a pairing prepared (environments-11, DR-127): `spex.yaml`
356
+ * requesting the built-in spec package alone, and `spex.lock` exactly
357
+ * the built-in lock at the registry it records — another than
358
+ * `registryUrl`, or that one while `spex.yaml` does not name `space`.
359
+ * A lock holding anything else — another release, another package, a
360
+ * resolution of the reader's — is left as it is. Where `space` is given
361
+ * — the instance placed at — `spex.yaml` names it first, and the lock
362
+ * follows its bytes (DR-165).
363
+ * Written under the versions read, a file changed meanwhile left
364
+ * standing (DR-111). Returns whether it wrote.
365
+ */
366
+ export function rehomeBuiltinLock(root, pkg, registryUrl, space = null) {
367
+ const target = registryUrl.replace(/\/+$/, "");
368
+ const lockFile = join(root, "spex.lock");
369
+ const requests = readVersioned(join(root, "spex.yaml"));
370
+ const locked = readVersioned(lockFile);
371
+ if (requests.bytes === null || locked.bytes === null)
372
+ return false;
373
+ const text = requests.bytes.toString("utf8");
374
+ const current = locked.bytes.toString("utf8");
375
+ let lock;
376
+ try {
377
+ const parsed = parseRequests(text);
378
+ if (parsed.registry !== undefined)
379
+ return false;
380
+ const requested = Object.keys(parsed.packages);
381
+ if (requested.length !== 1 || requested[0] !== BUILTIN_PACKAGE_NAME)
382
+ return false;
383
+ lock = parseLock(current);
384
+ }
385
+ catch {
386
+ return false;
387
+ }
388
+ const source = lock.packages[BUILTIN_PACKAGE_NAME]?.source;
389
+ if (Object.keys(lock.packages).length !== 1 || !source || !isRegistrySource(source))
390
+ return false;
391
+ // Nothing to move where the lock records the target already and
392
+ // `spex.yaml` names the instance placed at, or none is given.
393
+ const naming = space !== null && parseRequests(text).space !== space;
394
+ if (source.registry === target && !naming)
395
+ return false;
396
+ if (current !== serializeLock(builtinLock(pkg, source.registry, text)))
397
+ return false;
398
+ let next = text;
399
+ if (naming) {
400
+ const doc = parseDocument(text);
401
+ setSpaceIn(doc, space);
402
+ next = doc.toString({ lineWidth: 0 });
403
+ parseRequests(next);
404
+ try {
405
+ writeVersionedBytes(join(root, "spex.yaml"), next, requests.version);
406
+ }
407
+ catch (error) {
408
+ if (error instanceof VersionConflictError)
409
+ return false;
410
+ throw error;
411
+ }
412
+ }
413
+ try {
414
+ writeVersionedBytes(lockFile, serializeLock(builtinLock(pkg, target, next)), locked.version);
415
+ }
416
+ catch (error) {
417
+ if (error instanceof VersionConflictError)
418
+ return false;
419
+ throw error;
420
+ }
421
+ return true;
422
+ }
423
+ /**
424
+ * Request the built-in spec package at a caret requirement in an
425
+ * environment's `spex.yaml` at its root where it is not requested
426
+ * (environments-11, storage-6): written synchronously, so a clone's
427
+ * first commit already holds it; comments and key order of an existing
428
+ * file are kept, and the file is written under the version read, so a
429
+ * file changed meanwhile is refused as a conflict (DR-111). Where `space` is given and the file
430
+ * names none, the request names it as the environment's instance
431
+ * (environments-2, DR-165). A file that does not read, or a root that
432
+ * does not exist — a working folder removed meanwhile — is left as it
433
+ * is, nothing created. Returns whether it wrote.
434
+ */
435
+ export function ensureBuiltinRequest(root, version, space = null) {
436
+ if (!existsSync(root))
437
+ return false;
438
+ const file = join(root, "spex.yaml");
439
+ const read = readVersioned(file);
440
+ const text = read.bytes === null ? "" : read.bytes.toString("utf8");
441
+ if (read.bytes !== null) {
442
+ try {
443
+ if (parseRequests(text).packages[BUILTIN_PACKAGE_NAME])
444
+ return false;
445
+ }
446
+ catch {
447
+ return false;
448
+ }
449
+ }
450
+ const doc = text.trim() === "" ? new Document({ format: 1, packages: {} }) : parseDocument(text);
451
+ if (read.bytes === null)
452
+ setRegistryIn(doc, PUBLIC_REGISTRY_ORIGIN);
453
+ if (space !== null && !doc.has("space"))
454
+ setSpaceIn(doc, space);
455
+ if (!isMap(doc.get("packages", true)))
456
+ doc.set("packages", doc.createNode({}));
457
+ doc.setIn(["packages", BUILTIN_PACKAGE_NAME], doc.createNode({ version: `^${version}` }));
458
+ const next = doc.toString({ lineWidth: 0 });
459
+ parseRequests(next);
460
+ writeVersionedBytes(file, next, read.version);
461
+ return true;
462
+ }
463
+ /**
464
+ * A new project's environment at its pairing (storage-6, DR-176): where
465
+ * the working folder holds no `spex.yaml`, one naming the public
466
+ * registry as every new file does (environments-38), `space` where the
467
+ * project's spex repository is placed at an instance (DR-170), and
468
+ * requesting nothing — the built-in spec package is a global package,
469
+ * never a project's request (environments-11). Created exclusively, so a
470
+ * file written meanwhile stands; a root that does not exist is left as
471
+ * it is. Returns whether it wrote.
472
+ */
473
+ export function prepareProjectEnvironment(root, space = null) {
474
+ if (!existsSync(root))
475
+ return false;
476
+ const doc = new Document({ format: 1, ...(space !== null ? { space } : {}), registry: PUBLIC_REGISTRY_ORIGIN, packages: {} });
477
+ const text = doc.toString({ lineWidth: 0 });
478
+ parseRequests(text);
479
+ try {
480
+ writeVersionedBytes(join(root, "spex.yaml"), text, null);
481
+ }
482
+ catch (error) {
483
+ if (error instanceof VersionConflictError)
484
+ return false;
485
+ throw error;
486
+ }
487
+ return true;
488
+ }
489
+ /** A registry that answers `sublang/playbooks` from the built-in source
490
+ * first — offline, from what this device seeded — and everything else
491
+ * from the remote registry, whose URL the lock records. */
492
+ export function compositeRegistry(builtin, remote) {
493
+ async function builtinHas(name, version) {
494
+ if (name !== BUILTIN_PACKAGE_NAME)
495
+ return false;
496
+ try {
497
+ return (await builtin.index(name)).versions.some((entry) => entry.version === version);
498
+ }
499
+ catch {
500
+ return false;
501
+ }
502
+ }
503
+ return {
504
+ url: remote.url,
505
+ async index(name) {
506
+ if (name === BUILTIN_PACKAGE_NAME) {
507
+ const index = await builtin.index(name).catch(() => null);
508
+ if (index && index.versions.length > 0)
509
+ return index;
510
+ }
511
+ return remote.index(name);
512
+ },
513
+ async version(name, version) {
514
+ return (await builtinHas(name, version)) ? builtin.version(name, version) : remote.version(name, version);
515
+ },
516
+ async file(name, version, path) {
517
+ return (await builtinHas(name, version)) ? builtin.file(name, version, path) : remote.file(name, version, path);
518
+ },
519
+ async archive(name, version) {
520
+ return (await builtinHas(name, version)) ? builtin.archive(name, version) : remote.archive(name, version);
521
+ },
522
+ publish: (name, version, tgz) => remote.publish(name, version, tgz),
523
+ async search(query) {
524
+ const local = await builtin.search(query).catch(() => []);
525
+ let far;
526
+ try {
527
+ far = await remote.search(query);
528
+ }
529
+ catch (error) {
530
+ // Offline, the built-in spec package still answers.
531
+ if (local.length > 0)
532
+ return local;
533
+ throw error;
534
+ }
535
+ return [...local, ...far.filter((result) => !local.some((item) => item.name === result.name))];
536
+ },
537
+ };
538
+ }
539
+ //# sourceMappingURL=builtins.js.map
@@ -0,0 +1,75 @@
1
+ /** A release's spec item cited by address: the package and the item's anchor. */
2
+ export type Address = {
3
+ name: string;
4
+ anchor: string;
5
+ };
6
+ /**
7
+ * What building a release's spec could not carry: a citation of a spec
8
+ * of no package, or of a file two packages claim, removed, or a decision
9
+ * record's link, reduced to its text — with the item citing it, or
10
+ * "intent" before any item.
11
+ */
12
+ export type CitationWarning = {
13
+ kind: "citation" | "record";
14
+ item: string;
15
+ /** The cited file's specs-relative path and anchor, or the record's id. */
16
+ target: string;
17
+ /** For a citation of a file two or more packages claim, those packages, in name order. */
18
+ claims?: string[];
19
+ };
20
+ export type ReleaseContext = {
21
+ /** The specs-relative path of the file being built, e.g. "packages/tools.md". */
22
+ selfPath: string;
23
+ /**
24
+ * The package `<org>/<pkg>` whose provided spec that specs-relative
25
+ * file is; the packages claiming it alike, where two or more do; or
26
+ * null.
27
+ */
28
+ packageOf: (specsRelativePath: string) => string | {
29
+ claims: string[];
30
+ } | null;
31
+ };
32
+ export type TreeContext = {
33
+ /** The specs-relative path of that package's placed spec, or null where none stands. */
34
+ placedPathOf: (name: string) => string | null;
35
+ /** The specs-relative path this file is placed at, e.g. "packages/tools.md". */
36
+ selfPath: string;
37
+ };
38
+ /** The package and anchor of a `spex:<org>/<pkg>#<anchor>` url, or null. */
39
+ export declare function parseAddress(url: string): Address | null;
40
+ /** The address citing `anchor` in the spec `name` provides. */
41
+ export declare function formatAddress(name: string, anchor: string): string;
42
+ /**
43
+ * A citation's url: `#<anchor>`, a relative `<path>#<anchor>`, or an
44
+ * address `spex:<org>/<pkg>#<anchor>`.
45
+ */
46
+ export declare function isCitationUrl(url: string): boolean;
47
+ /**
48
+ * Rewrite a project's spec file for a release (environments-42): a
49
+ * relative citation into `selfPath` becomes a same-file citation, one
50
+ * into a package's spec that package's address, and one into a spec of
51
+ * no package or into a file two packages claim is removed; a decision
52
+ * record's link keeps its text alone. A citation of `meta.md` at the
53
+ * specs root is kept as the link from `specs/packages/`, where the
54
+ * placed spec stands; a same-file citation, an address and every other
55
+ * link stay.
56
+ */
57
+ export declare function rewriteForRelease(text: string, ctx: ReleaseContext): {
58
+ text: string;
59
+ warnings: CitationWarning[];
60
+ };
61
+ /**
62
+ * Rewrite a release's spec for the tree it is placed in
63
+ * (environments-41): an address whose package's spec stands there
64
+ * becomes the relative link to that file's anchor, and one whose
65
+ * package's does not is removed, counted under that package in
66
+ * `waiting`. So `specs/` holds no address, a plain link to one is
67
+ * treated alike, keeping its text where it waits, and a `spex:` link
68
+ * that is no address, which resolves nowhere, is removed alike, counted
69
+ * under no package. A same-file citation, a relative one — `meta.md`'s
70
+ * among them — and every other link stay.
71
+ */
72
+ export declare function rewriteForTree(text: string, ctx: TreeContext): {
73
+ text: string;
74
+ waiting: Record<string, number>;
75
+ };