dreamteamer 0.44.1 → 0.45.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.
- package/package.json +3 -2
- package/scripts/migrate-stubs.mjs +98 -0
- package/skills/using-dreamteamer/SKILL.md +2 -2
- package/skills/using-dreamteamer/references/collections.md +17 -23
- package/src/check.js +56 -75
- package/src/cli.js +18 -13
- package/src/collections-cli.js +19 -48
- package/src/commit.js +1 -1
- package/src/compile-collections.js +8 -2
- package/src/compile.js +12 -1
- package/src/exports-cli.js +91 -0
- package/src/exports.js +162 -0
- package/src/fields.js +2 -7
- package/src/records-api.d.ts +3 -0
- package/src/records.js +0 -35
- package/src/runtime.js +8 -0
- package/src/store.js +35 -91
package/src/collections-cli.js
CHANGED
|
@@ -28,7 +28,7 @@ import { sortRows } from './temporal.js';
|
|
|
28
28
|
import { keyBetween, placementKey } from './fractional-index.js';
|
|
29
29
|
import { ensureRepo, ensureAllRepos } from './init.js';
|
|
30
30
|
import { expectedMirrors, ownersReadIn } from './relations.js';
|
|
31
|
-
import { parseRecord
|
|
31
|
+
import { parseRecord } from './records.js';
|
|
32
32
|
|
|
33
33
|
import { storageOf, jsonSchemaOf, recordTitleOf, positionFieldOf, fieldsOf, displayOf, storedFieldsOf, targetsOf } from './descriptor.js';
|
|
34
34
|
/**
|
|
@@ -141,39 +141,21 @@ export function collectionCommand(ws, collection, verb, args) {
|
|
|
141
141
|
}
|
|
142
142
|
case 'get': {
|
|
143
143
|
const id = need(pos, 0, 'id');
|
|
144
|
+
// an id no root holds that an exports manifest vouches for (cr-dt-004): named, and still exit 1
|
|
145
|
+
const ext = store.external(collection, id, { referrer: flags.referrer });
|
|
146
|
+
if (ext) {
|
|
147
|
+
if (flags.json) emit(JSON.stringify({ $external: { collection, id, ...ext } }, null, 2));
|
|
148
|
+
console.error(`${collection}/${id} is not held here — external: "${ext.label}", held by ${ext.from ?? 'a workspace the manifest does not name'} (${ext.manifest})`);
|
|
149
|
+
return 1;
|
|
150
|
+
}
|
|
144
151
|
const { fields, file } = store.read(collection, id);
|
|
145
152
|
// descriptor v2: a record older than the `created` stamp still answers it — read, never written
|
|
146
153
|
const created = store.createdOf(collection, id, fields, file);
|
|
147
154
|
if (created !== undefined && fields.created === undefined) fields.created = created;
|
|
148
|
-
|
|
149
|
-
const shadows = store.shadowedStubs(collection, id).map((f) => store.locationOf(d, f).file);
|
|
150
|
-
if (flags.json) { emit(JSON.stringify({ ...fields, id, ...whereKeys(store.locationOf(d, file)), ...(fields.stub === true ? { $stub: true } : {}), ...(shadows.length ? { $shadows: shadows } : {}) }, null, 2)); return 0; }
|
|
155
|
+
if (flags.json) { emit(JSON.stringify({ ...fields, id, ...whereKeys(store.locationOf(d, file)) }, null, 2)); return 0; }
|
|
151
156
|
console.log(dump(fields).trimEnd());
|
|
152
157
|
return 0;
|
|
153
158
|
}
|
|
154
|
-
case 'stub': {
|
|
155
|
-
// A placeholder of a record only another root holds (cr-dt-003): what its schema requires and
|
|
156
|
-
// nothing more, written through add — which yields it to that record and gives it its mirrors.
|
|
157
|
-
const id = need(pos, 0, 'id');
|
|
158
|
-
const ref = `${collection}/${id}`;
|
|
159
|
-
if (storageOf(d).format === 'binary') throw new Error(`${collection} is format: binary — a file record cannot be a stub (no frontmatter to carry stub: true). Clear or repoint the referring field in this workspace (dt set <referrer> <field>=), hold the file here instead of in the layer, or make the field soft: true — nothing was written.`);
|
|
160
|
-
if (!fieldsOf(d).stub) throw new Error(`${collection} cannot carry a stub — it is never read as a layer (runtime, module-owned, placed or env-pointed) — nothing was written.`);
|
|
161
|
-
if (!store.layered(d)) throw new Error(`${collection} reads no record layer — a stub has nothing to yield to; nothing was written.`);
|
|
162
|
-
const claims = store.ids(collection).has(id) ? [store.ids(collection).get(id), ...store.shadowedStubs(collection, id)] : [];
|
|
163
|
-
const own = claims.find((f) => !store.layerOfFile(d, f));
|
|
164
|
-
if (own) throw new Error(`${ref} is already held by this workspace (${rel(ws.root, own)}) — nothing was written.`);
|
|
165
|
-
if (!claims.length) throw new Error(`no layer holds ${ref} — nothing to copy.`);
|
|
166
|
-
const { fields: answer, file: from } = store.read(collection, id);
|
|
167
|
-
const engineOwned = (k) => k === 'stub' || fieldsOf(d)[k]?.mirror_of !== undefined || d.compiled?.fields?.[k]?.derived || d.compiled?.fields?.[k]?.virtual;
|
|
168
|
-
const candidate = Object.fromEntries(Object.entries(answer).filter(([k]) => !engineOwned(k)));
|
|
169
|
-
const copied = stubFields(jsonSchemaOf(d), candidate, (s) => store.ajv.compile(s)(structuredClone(candidate)));
|
|
170
|
-
const { file } = store.add(collection, { ...Object.fromEntries(copied.map((k) => [k, answer[k]])), ...coerceArrays(d, stripMeta(flags)), stub: true }, { id });
|
|
171
|
-
const stubOf = store.locationOf(d, from).file;
|
|
172
|
-
flags.json
|
|
173
|
-
? emit(JSON.stringify({ id, path: rel(ws.root, file), $stubOf: stubOf, copied }))
|
|
174
|
-
: console.log(`✔ ${at}${rel(ws.root, file)} — stub of ${ref} (layer ${store.layerOfFile(d, from)?.layer} answers it here); copied: ${copied.join(', ')}`);
|
|
175
|
-
return 0;
|
|
176
|
-
}
|
|
177
159
|
case 'add': {
|
|
178
160
|
// An opaque collection is written by IMPORTING a file: the id is positional (nothing can
|
|
179
161
|
// generate it from fields that do not exist) and the bytes come from --from.
|
|
@@ -196,13 +178,11 @@ export function collectionCommand(ws, collection, verb, args) {
|
|
|
196
178
|
flags[titleField] = pos[0];
|
|
197
179
|
}
|
|
198
180
|
const fields = coerceArrays(d, stripMeta(flags));
|
|
199
|
-
const { id, file, idFallback, deprecated
|
|
181
|
+
const { id, file, idFallback, deprecated } = store.add(collection, fields, { id: flags.id });
|
|
200
182
|
for (const k of deprecated ?? []) console.warn(`⚠ ${k} is deprecated on ${collection} — it still validates, and nothing draws it. Check the collection's description for what replaced it.`);
|
|
201
|
-
// promoting a stub is a choice the operator should see made: name every placeholder it now covers
|
|
202
|
-
const covers = (shadows ?? []).map((f) => store.layerOfFile(d, f)?.layer ?? 'this workspace');
|
|
203
183
|
flags.json
|
|
204
|
-
? emit(JSON.stringify({ id, path: rel(ws.root, file), ...(idFallback ? { idFallback } : {})
|
|
205
|
-
: console.log(`✔ ${at}${rel(ws.root, file)}
|
|
184
|
+
? emit(JSON.stringify({ id, path: rel(ws.root, file), ...(idFallback ? { idFallback } : {}) }))
|
|
185
|
+
: console.log(`✔ ${at}${rel(ws.root, file)}`);
|
|
206
186
|
// ⚠ SAY IT, EVERY TIME. The id was derived from a hash because the value it is generated
|
|
207
187
|
// from carries no a-z0-9 — the write succeeded and the record is fine, but the id is
|
|
208
188
|
// unreadable and unguessable, and nobody finds that out until they try to type it. By
|
|
@@ -263,12 +243,8 @@ export function collectionCommand(ws, collection, verb, args) {
|
|
|
263
243
|
const id = need(pos, 0, 'id');
|
|
264
244
|
if (flags['dry-run']) return dryRunPlan(`rm ${collection}/${id}`, { records: store.ids(collection).has(id) ? 1 : 0, refs: store.findInboundRefs(`${collection}/${id}`).length });
|
|
265
245
|
const where = store.ids(collection).has(id) ? store.locate(collection, id) : null; // a missing id is store.rm's to refuse
|
|
266
|
-
const { inboundIgnored
|
|
267
|
-
|
|
268
|
-
const next = store.ids(collection).get(id);
|
|
269
|
-
const showing = next ? store.layerOfFile(d, next) : null;
|
|
270
|
-
const nowShows = next ? `${inboundResolveToStub ? ` — ${inboundResolveToStub} inbound reference(s) now resolve to the stub` : ''}; stub ${showing ? `in layer ${showing.layer}` : 'in this workspace'} now shows (${store.locationOf(d, next).file})` : '';
|
|
271
|
-
flags.json ? emit(JSON.stringify({ id, removed: true, inboundIgnored, ...(next ? { $now: store.locationOf(d, next).file } : {}) })) : console.log(`✔ ${at}removed${landedIn(where)}${inboundIgnored ? ` (${inboundIgnored} inbound reference(s) left dangling — run \`dreamteamer check\`)` : ''}${nowShows}`);
|
|
246
|
+
const { inboundIgnored } = store.rm(collection, id, { force: !!flags.force });
|
|
247
|
+
flags.json ? emit(JSON.stringify({ id, removed: true, inboundIgnored })) : console.log(`✔ ${at}removed${landedIn(where)}${inboundIgnored ? ` (${inboundIgnored} inbound reference(s) left dangling — run \`dreamteamer check\`)` : ''}`);
|
|
272
248
|
return 0;
|
|
273
249
|
}
|
|
274
250
|
case 'rename': {
|
|
@@ -1060,7 +1036,7 @@ function relationsRebuild(store, flags, pos) {
|
|
|
1060
1036
|
// workspace against a module-owned target) implies no mirror on a target it cannot be committed with
|
|
1061
1037
|
const perRepo = (r) => {
|
|
1062
1038
|
const groups = new Map();
|
|
1063
|
-
for (const o of parseEach(store, r.owner, (f) => unreadableOwners.push(rel(store.root, f))
|
|
1039
|
+
for (const o of parseEach(store, r.owner, (f) => unreadableOwners.push(rel(store.root, f)))) {
|
|
1064
1040
|
const repo = store.repoOfFile(store.descriptor(r.owner), o.file);
|
|
1065
1041
|
if (!groups.has(repo)) groups.set(repo, []);
|
|
1066
1042
|
groups.get(repo).push(o);
|
|
@@ -1081,9 +1057,7 @@ function relationsRebuild(store, flags, pos) {
|
|
|
1081
1057
|
// The write lock, like every other write verb: several agents work in one tree, and a concurrent
|
|
1082
1058
|
// `dt set` landing mid-sweep would be clobbered back to the pre-set mirror value.
|
|
1083
1059
|
store.withWriteLock(() => {
|
|
1084
|
-
|
|
1085
|
-
for (const { id, file, fields } of parseEach(store, collection, (f) => console.warn(`⚠ ${rel(store.root, f)}: parse error, skipped — \`dreamteamer check\` reports it`), { withStubs: true })) {
|
|
1086
|
-
if (store.layerOfFile(d, file) && store.ids(collection).get(id) !== file) continue; // a layer's stub is its own repo's
|
|
1060
|
+
for (const { id, file, fields } of parseEach(store, collection, (f) => console.warn(`⚠ ${rel(store.root, f)}: parse error, skipped — \`dreamteamer check\` reports it`))) {
|
|
1087
1061
|
let changed = false;
|
|
1088
1062
|
const repo = store.repoOfFile(d, file);
|
|
1089
1063
|
for (const { r, exp } of expected) {
|
|
@@ -1126,13 +1100,10 @@ function relationsRebuild(store, flags, pos) {
|
|
|
1126
1100
|
* mid-walk cannot be resumed past — and rebuild is the one reader that has already written by the
|
|
1127
1101
|
* time a later record blows up, so an abort leaves a partial sweep behind an error naming no file
|
|
1128
1102
|
* at all. Here the bad record is handed to `onError` and skipped, and the walk finishes. */
|
|
1129
|
-
function* parseEach(store, collection, onError
|
|
1103
|
+
function* parseEach(store, collection, onError) {
|
|
1130
1104
|
const d = store.descriptor(collection);
|
|
1131
1105
|
const bf = bodyField(d);
|
|
1132
|
-
// `withStubs`: a shadowed stub still OWNS references in its own repo, and the mirrors it justifies
|
|
1133
|
-
// there are not this workspace's to delete
|
|
1134
1106
|
const rows = [...store.ids(collection)].map(([id, file]) => ({ id, file }));
|
|
1135
|
-
if (withStubs) rows.push(...store.shadowedStubRecords(collection));
|
|
1136
1107
|
for (const { id, file } of rows) {
|
|
1137
1108
|
let fields;
|
|
1138
1109
|
try {
|
|
@@ -1340,7 +1311,7 @@ const FORCE_RM = ['json', 'force', 'dry-run'];
|
|
|
1340
1311
|
const NAV_MOVE = ['json', 'after', 'before', 'top', 'bottom'];
|
|
1341
1312
|
|
|
1342
1313
|
export const VERB_FLAGS = {
|
|
1343
|
-
list: ['json', 'filter', 'where', 'sort'], get:
|
|
1314
|
+
list: ['json', 'filter', 'where', 'sort'], get: ['json', 'referrer'], add: ['json', 'id', 'from', 'force'], set: JSON_ONLY,
|
|
1344
1315
|
rm: FORCE_RM, rename: JSON_ONLY, reorder: [...NAV_MOVE, 'init'], values: ['json', 'limit'],
|
|
1345
1316
|
history: JSON_ONLY, diff: ['json', 'hash'], revert: ['json', 'hash'],
|
|
1346
1317
|
ensure: ['json', 'all'], for: ['json', 'ids'], relations: JSON_ONLY, rebuild: ['json', 'drop'],
|
|
@@ -1388,7 +1359,7 @@ export function refuseUnknownFlags(store, collection, verb, flags) {
|
|
|
1388
1359
|
// ⚠ NO DESCRIPTOR MEANS NO OPEN HALF — offering "plus any field of X" for a thing with no fields
|
|
1389
1360
|
// would read as though the refused flag were merely misspelled.
|
|
1390
1361
|
const openOf = !d ? null
|
|
1391
|
-
: !system ? (['list', 'add', 'set'
|
|
1362
|
+
: !system ? (['list', 'add', 'set'].includes(verb) ? `field of ${collection}` : null)
|
|
1392
1363
|
: (collection === 'ui-views' && verb !== 'rm') || (isEntityKind(store, collection) && verb === 'set') ? `declared key of ${collection}` : null;
|
|
1393
1364
|
const open = openOf ? Object.keys(storedFieldsOf(d)) : [];
|
|
1394
1365
|
const allowed = new Set([...known, ...open]);
|
package/src/commit.js
CHANGED
|
@@ -356,7 +356,7 @@ function scopeByRepo(descriptors, only) {
|
|
|
356
356
|
|
|
357
357
|
/** In-progress merge/rebase/cherry-pick makes a commit's meaning ambiguous. Ordinary dirtiness
|
|
358
358
|
* is NOT a refusal condition — committing dirty records is this verb's entire job. */
|
|
359
|
-
function inProgress(cwd) {
|
|
359
|
+
export function inProgress(cwd) {
|
|
360
360
|
let gitDir;
|
|
361
361
|
try { gitDir = execFileSync('git', ['rev-parse', '--absolute-git-dir'], { cwd, stdio: QUIET }).toString().trim(); }
|
|
362
362
|
catch { return 'not a git repository'; }
|
|
@@ -88,6 +88,7 @@ export function compileCollections(ctx) {
|
|
|
88
88
|
const allPeers = new Set([...modulePeers.values()].flat());
|
|
89
89
|
const out = new Map();
|
|
90
90
|
const layerClaims = new Map(); // layer name -> clone folders some collection here accounts for
|
|
91
|
+
const layerReads = new Map(); // layer name -> clone folders some collection here READS (cr-dt-004); compiled sources never sit in a layer's data
|
|
91
92
|
const inert = [];
|
|
92
93
|
const moduleColls = new Map();
|
|
93
94
|
const owners = new Map(); // collection -> owning module name
|
|
@@ -212,6 +213,7 @@ export function compileCollections(ctx) {
|
|
|
212
213
|
const why = runtime ? 'is a compiled source' : owner === 'module' ? `is \`storage.owner: module\` — one shared list read from the module's clone, which a layer would duplicate` : a.under ? 'is stored under another collection (storage.under) — a placed collection is not layered' : pointed ? 'is env-pointed (its storage.path is a template) — its records are per machine, not a clone\'s' : null;
|
|
213
214
|
if (why && l.records) fail(`git_modules.${l.name}.records names "${name}", which ${why}`);
|
|
214
215
|
if (why) {
|
|
216
|
+
if (!runtime) l.skipsSome = true; // a reader that skips one of the layer's collections never reads it completely (cr-dt-004); compiled sources never sit in a layer's data
|
|
215
217
|
// an INHERENT layer reads every collection both have, so one that cannot layer is skipped —
|
|
216
218
|
// said only when the clone actually holds records there, so a quiet compile stays quiet
|
|
217
219
|
const n = fileCount(path.join(root, at));
|
|
@@ -219,6 +221,7 @@ export function compileCollections(ctx) {
|
|
|
219
221
|
continue;
|
|
220
222
|
}
|
|
221
223
|
collLayers.push({ name: l.name, path: at, repo: l.root });
|
|
224
|
+
(layerReads.get(l.name) ?? layerReads.set(l.name, []).get(l.name)).push(at);
|
|
222
225
|
}
|
|
223
226
|
|
|
224
227
|
// an opaque record's fields are the ones derived from the file itself
|
|
@@ -229,7 +232,9 @@ export function compileCollections(ctx) {
|
|
|
229
232
|
fields.ext ??= { type: 'string', virtual: true, description: "The file's extension, lowercase and without the dot. Read from the file." };
|
|
230
233
|
fields.bytes ??= { type: 'integer', virtual: true, description: "The file's size in bytes. Read from the file." };
|
|
231
234
|
}
|
|
232
|
-
const { fields: resolved, errors, warnings, defaults: fieldDefaults } = resolveFields(fields, { name, collections: typeNames, peers: allPeers, runtime
|
|
235
|
+
const { fields: resolved, errors, warnings, defaults: fieldDefaults } = resolveFields(fields, { name, collections: typeNames, peers: allPeers, runtime });
|
|
236
|
+
// a collection a reader can read from a layer: what `check` counts a referrer by (cr-dt-004); compiled sources never sit in a layer's data
|
|
237
|
+
const layerable = !runtime && owner !== 'module' && !a.under && !pointed;
|
|
233
238
|
if (errors.length) fail(`collection "${name}" (${where}):\n ${errors.join('\n ')}`);
|
|
234
239
|
for (const w of warnings) warn(`⚠ collection ${name}: ${w}`);
|
|
235
240
|
const constraints = authored.constraints ?? [];
|
|
@@ -326,6 +331,7 @@ export function compileCollections(ctx) {
|
|
|
326
331
|
fields: resolved,
|
|
327
332
|
json_schema: jsonSchema,
|
|
328
333
|
...(collLayers.length ? { layers: collLayers } : {}),
|
|
334
|
+
...(layerable ? { layerable: true } : {}),
|
|
329
335
|
...(external ? { external: true } : {}),
|
|
330
336
|
...(unavailable ? { unavailable } : {}),
|
|
331
337
|
},
|
|
@@ -358,7 +364,7 @@ export function compileCollections(ctx) {
|
|
|
358
364
|
placement(out, fail);
|
|
359
365
|
|
|
360
366
|
for (const [, c] of out) c.doc = { ...c.doc, compiled: c.compiled };
|
|
361
|
-
return { compiled: out, inert, moduleColls };
|
|
367
|
+
return { compiled: out, inert, moduleColls, layerReads };
|
|
362
368
|
}
|
|
363
369
|
|
|
364
370
|
/**
|
package/src/compile.js
CHANGED
|
@@ -328,6 +328,11 @@ export function shadowWarning({ name, winner, loser }) {
|
|
|
328
328
|
return `⚠ module ${name}: ${CHANNEL_LABEL[winner]} copy shadows ${CHANNEL_LABEL[loser]} copy`;
|
|
329
329
|
}
|
|
330
330
|
|
|
331
|
+
/** The `name` in a folder's package.json, or null — an absent clone or an unreadable file is unknown. */
|
|
332
|
+
function pkgNameAt(dir) {
|
|
333
|
+
try { return JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).name ?? null; } catch { return null; }
|
|
334
|
+
}
|
|
335
|
+
|
|
331
336
|
export function compile(ws) {
|
|
332
337
|
const { root, pkg } = ws;
|
|
333
338
|
const extensions = ws.extensions ?? [];
|
|
@@ -935,7 +940,7 @@ export function compile(ws) {
|
|
|
935
940
|
const collectionsFail = (msg) => fail(uninstalled.length
|
|
936
941
|
? `${msg}\n run \`dreamteamer install\` first — dreamteamer.git_modules declares ${uninstalled.join(', ')}, and no clone of ${uninstalled.length === 1 ? 'it' : 'them'} is on disk yet`
|
|
937
942
|
: msg);
|
|
938
|
-
const { compiled: compiledColls, inert: inertSources, moduleColls } = compileCollections({
|
|
943
|
+
const { compiled: compiledColls, inert: inertSources, moduleColls, layerReads } = compileCollections({
|
|
939
944
|
groups: descriptorGroups, mixins: mixinDocs, namespaces, nsOwners,
|
|
940
945
|
runtimeKinds: new Set([...kinds, ...DERIVED_KINDS]), core: CORE_COLLECTIONS,
|
|
941
946
|
moduleDeps, modulePeers, channelOf, wsModuleName, engineName, dataOwners,
|
|
@@ -1221,6 +1226,12 @@ export function compile(ws) {
|
|
|
1221
1226
|
// `storage.base` is a field instead of a path test. An older runtime has no key here, which
|
|
1222
1227
|
// reads as "no namespaces", which is exactly right for a workspace that never declared any.
|
|
1223
1228
|
namespaces,
|
|
1229
|
+
// What the record layer needs to judge an exports manifest (cr-dt-004) without reading package.json:
|
|
1230
|
+
// this workspace's package name, and per layer its package name, data folder, the folders read from
|
|
1231
|
+
// it and whether `records:` narrows it — completeness itself is judged at run time, on the disk.
|
|
1232
|
+
package: pkg.name ?? null,
|
|
1233
|
+
data_path: config.data_path ?? 'data',
|
|
1234
|
+
layers: layers.map((l) => ({ name: l.name, root: l.root, data: path.posix.join(l.root, l.dataPath), package: pkgNameAt(path.join(root, l.root)), reads: layerReads.get(l.name) ?? [], narrowed: !!l.records || !!l.skipsSome })),
|
|
1224
1235
|
// The extensions this runtime was compiled WITH, and the source kinds they staged — so the next
|
|
1225
1236
|
// compile can prune a kind whose extension is gone, and `staleness` can walk a contributed kind
|
|
1226
1237
|
// without loading any extension code.
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// dt exports [--layer <name> …] [--dry-run] [--json] — write a repo's exports manifest from this
|
|
2
|
+
// context (cr-dt-004). Bare: this workspace's own; --layer: that layer's, written into its clone — how a
|
|
3
|
+
// reader records the ids a layer names in the reader, which the layer alone cannot see. The rules are
|
|
4
|
+
// src/exports.js `regenerate`, shared with `check`, so `check` names a manifest stale exactly when this
|
|
5
|
+
// would change or drop one of its entries. Writes and commits ONE path, `dreamteamer-exports.json`.
|
|
6
|
+
import { execFileSync } from 'node:child_process';
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { parseRecord } from './records.js';
|
|
10
|
+
import { inProgress } from './commit.js';
|
|
11
|
+
import { exportsFacts } from './runtime.js';
|
|
12
|
+
import { storageOf, bodyFieldOf, recordTitleOf } from './descriptor.js';
|
|
13
|
+
import { EXPORTS_FILE, readExports, serializeExports, exportsContext, outsideRefs, regenerate } from './exports.js';
|
|
14
|
+
|
|
15
|
+
/** The manifest `dt exports` would write for `repo` (null: this workspace) and what changes. */
|
|
16
|
+
export function planExports(store, repo) {
|
|
17
|
+
const facts = exportsFacts(store.root);
|
|
18
|
+
const ctx = exportsContext({ root: store.root, descriptors: store.descriptors, own: facts.own, layers: facts.layers, dataPath: facts.data });
|
|
19
|
+
const readableD = (d) => d && !storageOf(d).runtime && !storageOf(d).unavailable;
|
|
20
|
+
const readable = [...store.descriptors.values()].filter(readableD);
|
|
21
|
+
// an unparseable record (a conflict mid-merge) is check's to report — skipped here, never fatal; while
|
|
22
|
+
// one is unread, nothing it might name is dropped as unreferenced (the repo is not read completely)
|
|
23
|
+
let unparsed = false;
|
|
24
|
+
const fieldsAt = (d, file) => { try { return parseRecord(file, d, bodyFieldOf(d)); } catch { unparsed = true; return null; } };
|
|
25
|
+
const repoOf = (c, id) => {
|
|
26
|
+
const d = store.descriptors.get(c);
|
|
27
|
+
const f = readableD(d) ? store.ids(c).get(id) : undefined;
|
|
28
|
+
return f ? store.layerOfFile(d, f)?.layer ?? null : undefined;
|
|
29
|
+
};
|
|
30
|
+
const titled = (d, id, file) => {
|
|
31
|
+
if (storageOf(d).format === 'binary') return id;
|
|
32
|
+
const t = /\{\{\s*([A-Za-z_][\w]*)/.exec(recordTitleOf(d))?.[1];
|
|
33
|
+
return String(fieldsAt(d, file)?.[t] ?? id);
|
|
34
|
+
};
|
|
35
|
+
const records = readable.flatMap((d) => [...store.ids(d.name)]
|
|
36
|
+
.filter(([id]) => repoOf(d.name, id) === repo && storageOf(d).format !== 'binary')
|
|
37
|
+
.map(([id, file]) => ({ collection: d.name, id, descriptor: d, fields: fieldsAt(d, file) })).filter((r) => r.fields));
|
|
38
|
+
const resolve = (c, id) => (repoOf(c, id) === undefined ? null : { label: titled(store.descriptors.get(c), id, store.ids(c).get(id)), from: ctx.packageOf(repoOf(c, id)) });
|
|
39
|
+
const held = (c, id) => repoOf(c, id) === repo;
|
|
40
|
+
const dir = ctx.rootOf(repo);
|
|
41
|
+
const current = readExports(dir); // throws on an unparseable file, naming it — never overwritten
|
|
42
|
+
const outside = outsideRefs({ records, held, resolve, namespaces: store.namespaces });
|
|
43
|
+
const { next, changes } = regenerate({ current: current ?? {}, outside, ctx: unparsed ? { ...ctx, complete: () => false } : ctx, repo, held });
|
|
44
|
+
return { dir, file: path.join(dir, EXPORTS_FILE), text: serializeExports(next), changes, entries: Object.values(next).reduce((n, m) => n + Object.keys(m).length, 0) };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Write (and commit) each named repo's manifest; returns the exit code. */
|
|
48
|
+
export function runExports(store, { layers = [], dryRun = false, json = false } = {}) {
|
|
49
|
+
const known = new Set((exportsFacts(store.root).layers ?? []).map((l) => l.name));
|
|
50
|
+
for (const l of layers) if (!known.has(l)) throw new Error(`--layer ${l}: not a record layer of this workspace (have: ${[...known].join(', ') || 'none'})`);
|
|
51
|
+
const out = [];
|
|
52
|
+
for (const repo of layers.length ? layers : [null]) {
|
|
53
|
+
const plan = planExports(store, repo);
|
|
54
|
+
const before = fs.existsSync(plan.file) ? fs.readFileSync(plan.file, 'utf8') : null;
|
|
55
|
+
const where = path.relative(store.root, plan.file);
|
|
56
|
+
let committed = null;
|
|
57
|
+
let note = null;
|
|
58
|
+
if (!dryRun && before !== plan.text) {
|
|
59
|
+
if (plan.text === null) fs.rmSync(plan.file); else fs.writeFileSync(plan.file, plan.text);
|
|
60
|
+
// a merge, rebase, cherry-pick or revert refuses a one-path commit: write, and say how to finish
|
|
61
|
+
const busy = inProgress(plan.dir);
|
|
62
|
+
if (busy) note = `${busy} — the manifest is written; git add it and conclude it`;
|
|
63
|
+
else {
|
|
64
|
+
const git = (args) => {
|
|
65
|
+
try { return execFileSync('git', args, { cwd: plan.dir, stdio: ['ignore', 'pipe', 'pipe'] }).toString().trim(); }
|
|
66
|
+
catch (e) { throw new Error(`git ${args[0]} in ${path.relative(store.root, plan.dir) || '.'} failed: ${String(e.stderr || e.message).trim()}`); }
|
|
67
|
+
};
|
|
68
|
+
// an emptied manifest git never tracked: nothing to add, nothing to commit
|
|
69
|
+
// an emptied manifest is un-staged with --ignore-unmatch: one git never tracked leaves nothing to commit
|
|
70
|
+
git(plan.text === null ? ['rm', '--cached', '-q', '--ignore-unmatch', '--', EXPORTS_FILE] : ['add', '--', EXPORTS_FILE]);
|
|
71
|
+
// back to what HEAD already holds (a hand edit undone), or never tracked: nothing to commit
|
|
72
|
+
let same = false;
|
|
73
|
+
try { execFileSync('git', ['diff', '--cached', '--quiet', 'HEAD', '--', EXPORTS_FILE], { cwd: plan.dir, stdio: 'ignore' }); same = true; } catch { /* differs, or no HEAD yet */ }
|
|
74
|
+
if (!same) {
|
|
75
|
+
git(['commit', '--only', '-q', '-m', `dreamteamer: exports — ${plan.entries} entr${plan.entries === 1 ? 'y' : 'ies'}`, '--', EXPORTS_FILE]);
|
|
76
|
+
committed = git(['rev-parse', '--short', 'HEAD']);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
const count = (k) => plan.changes.filter((c) => c.kind === k).length;
|
|
81
|
+
out.push({ repo, path: where, changed: before !== plan.text, changes: plan.changes, entries: plan.entries, committed, note });
|
|
82
|
+
if (json) continue;
|
|
83
|
+
console.log(before === plan.text
|
|
84
|
+
? `✔ ${repo ?? 'this workspace'} · ${where} — exports manifest current (${plan.entries} entr${plan.entries === 1 ? 'y' : 'ies'})`
|
|
85
|
+
: `${dryRun ? '·' : '✔'} ${repo ?? 'this workspace'} · ${where} — ${count('add')} added, ${count('refresh') + count('fill')} changed, ${count('drop')} dropped (${plan.entries} entr${plan.entries === 1 ? 'y' : 'ies'})${dryRun ? ' — dry run, nothing written' : committed ? ` · committed ${committed}` : ''}`);
|
|
86
|
+
for (const c of plan.changes) console.log(` ${c.kind} ${c.ref} — ${c.why}`);
|
|
87
|
+
if (note) console.log(`⚠ ${note}`);
|
|
88
|
+
}
|
|
89
|
+
if (json) console.log(JSON.stringify({ dryRun, manifests: out }, null, 2));
|
|
90
|
+
return 0;
|
|
91
|
+
}
|
package/src/exports.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// The exports manifest (cr-dt-004) — `dreamteamer-exports.json` at a repo root: per id that repo's own
|
|
2
|
+
// records name and no file of the repo holds, a display label and the package name of the workspace that
|
|
3
|
+
// held it when the entry was written. A reader reads a layer WITHOUT that layer's own layers, so this is
|
|
4
|
+
// the repo's proof that such an id exists elsewhere. Written only by `dt exports`; `check` reads it.
|
|
5
|
+
//
|
|
6
|
+
// Record layer: pure over the roots, descriptors and the facts compile recorded in the runtime — it never
|
|
7
|
+
// reads package.json. One walk of a repo's references (`outsideRefs`) and one judgement (`regenerate`)
|
|
8
|
+
// serve `check`, `dt exports` and the migration script, so the three cannot disagree.
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { walk } from './records.js';
|
|
12
|
+
import { parseRef } from './namespace.js';
|
|
13
|
+
import { storageOf, fieldsOf, targetsOf, isSoft } from './descriptor.js';
|
|
14
|
+
|
|
15
|
+
export const EXPORTS_FILE = 'dreamteamer-exports.json';
|
|
16
|
+
|
|
17
|
+
/** The manifest of the repo rooted at `dir` — `{ <collection>: { <id>: { label, from? } } }` — or null
|
|
18
|
+
* when it has none. An unparseable file throws, naming its path: it is never read as empty. */
|
|
19
|
+
export function readExports(dir) {
|
|
20
|
+
const file = path.join(dir, EXPORTS_FILE);
|
|
21
|
+
if (!fs.existsSync(file)) return null;
|
|
22
|
+
try { return JSON.parse(fs.readFileSync(file, 'utf8')).references ?? {}; } catch (e) {
|
|
23
|
+
throw new Error(`${EXPORTS_FILE} does not parse (${e.message}) — resolve it by hand: keep every entry line of both sides, then run dt exports`);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The file's bytes: tab-indented, collections and ids sorted, one line per entry, nothing time- or
|
|
28
|
+
* version-dependent — so an unchanged manifest regenerates byte for byte. `null` for an empty one. */
|
|
29
|
+
export function serializeExports(refs) {
|
|
30
|
+
const colls = Object.keys(refs).filter((c) => Object.keys(refs[c]).length).sort();
|
|
31
|
+
if (!colls.length) return null;
|
|
32
|
+
const entry = (e) => `{ "label": ${JSON.stringify(e.label)}${e.from ? `, "from": ${JSON.stringify(e.from)}` : ''} }`;
|
|
33
|
+
const blocks = colls.map((c) => `\t\t${JSON.stringify(c)}: {\n${Object.keys(refs[c]).sort().map((id) => `\t\t\t${JSON.stringify(id)}: ${entry(refs[c][id])}`).join(',\n')}\n\t\t}`);
|
|
34
|
+
return `{\n\t"dreamteamer_exports": 1,\n\t"references": {\n${blocks.join(',\n')}\n\t}\n}\n`;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Every hard-reference field of a descriptor's fields, nested ones included: `[path, targets, soft]`. */
|
|
38
|
+
export function collectRefFields(fields, prefix = []) {
|
|
39
|
+
const out = [];
|
|
40
|
+
for (const [key, f] of Object.entries(fields ?? {})) {
|
|
41
|
+
if (!f || typeof f !== 'object') continue;
|
|
42
|
+
const p = [...prefix, key];
|
|
43
|
+
const targets = targetsOf(f);
|
|
44
|
+
if (targets) out.push([p, targets, isSoft(f)]);
|
|
45
|
+
if (f.type === 'object' && f.fields) out.push(...collectRefFields(f.fields, p));
|
|
46
|
+
}
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Every leaf value at a field path, arrays flattened. */
|
|
51
|
+
export function* valuesAt(obj, fieldPath) {
|
|
52
|
+
let vals = [obj];
|
|
53
|
+
for (const key of fieldPath) vals = vals.flatMap((v) => (Array.isArray(v) ? v : [v])).flatMap((v) => (v && typeof v === 'object' ? [v[key]] : []));
|
|
54
|
+
for (const v of vals.flat(Infinity)) if (v != null) yield v;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Is every file under `dataDir` inside one of the `reads` folders (paths relative to `root`)? Judged on
|
|
58
|
+
* the disk NOW, so a folder a pull added after compile makes the repo incomplete without a recompile. */
|
|
59
|
+
function readsAll(root, dataDir, reads) {
|
|
60
|
+
const abs = path.join(root, dataDir);
|
|
61
|
+
if (!fs.existsSync(abs)) return true;
|
|
62
|
+
const prefixes = reads.map((r) => path.join(root, r) + path.sep);
|
|
63
|
+
for (const f of walk(abs)) if (!prefixes.some((p) => f.startsWith(p))) return false;
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The one context every judgement uses. `layers` are the runtime's layer facts (null: an older runtime —
|
|
69
|
+
* nothing is known, so no layer is complete and no layer holder is seen); `own` this workspace's package
|
|
70
|
+
* name. A repo is named by its layer name, the write root by null.
|
|
71
|
+
*/
|
|
72
|
+
export function exportsContext({ root, descriptors, own, layers, dataPath = 'data' }) {
|
|
73
|
+
const facts = new Map((layers ?? []).map((l) => [l.name, l]));
|
|
74
|
+
const rootsOf = (coll) => {
|
|
75
|
+
const d = descriptors.get(coll);
|
|
76
|
+
if (!d) return [];
|
|
77
|
+
return storageOf(d).roots.map((r) => {
|
|
78
|
+
const fact = r.layer ? facts.get(r.layer) : null;
|
|
79
|
+
return { layer: r.layer ?? null, package: r.layer ? fact?.package ?? null : own, present: !r.layer || (!!fact && fs.existsSync(path.join(root, r.repo))) };
|
|
80
|
+
});
|
|
81
|
+
};
|
|
82
|
+
const complete = (layer) => {
|
|
83
|
+
if (layer) { const l = facts.get(layer); return !!l && !l.narrowed && readsAll(root, l.data, l.reads); }
|
|
84
|
+
const reads = [];
|
|
85
|
+
for (const d of descriptors.values()) {
|
|
86
|
+
if (storageOf(d).unavailable) return false;
|
|
87
|
+
if (storageOf(d).base !== 'runtime' && !path.isAbsolute(storageOf(d).path) && !storageOf(d).path.includes('${')) reads.push(storageOf(d).path);
|
|
88
|
+
}
|
|
89
|
+
return readsAll(root, dataPath, reads);
|
|
90
|
+
};
|
|
91
|
+
return { own, rootsOf, complete, packageOf: (layer) => (layer ? facts.get(layer)?.package ?? null : own), rootOf: (layer) => (layer ? path.join(root, facts.get(layer)?.root ?? path.join('git_modules', layer)) : root) };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Does this context read the entry's holder for its collection — a root of that collection, on disk,
|
|
95
|
+
* whose package is the entry's `from`? An entry with no holder is seen by no context. */
|
|
96
|
+
export function sees(entry, coll, ctx) {
|
|
97
|
+
return !!entry?.from && ctx.rootsOf(coll).some((r) => r.present && r.package === entry.from);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* A repo's outside references: every value of a hard, non-mirror reference field on one of its records
|
|
102
|
+
* that names an id the repo does not hold. `records` yields `{ collection, id, fields, descriptor }`;
|
|
103
|
+
* `held(coll, id)` says the repo holds it; `resolve(coll, id)` answers `{ label, from }` or null.
|
|
104
|
+
* @returns {Map<string, { collection, id, resolved, referrers: string[] }>} keyed `<collection>/<id>`
|
|
105
|
+
*/
|
|
106
|
+
export function outsideRefs({ records, held, resolve, namespaces }) {
|
|
107
|
+
const out = new Map();
|
|
108
|
+
for (const { collection, id, fields, descriptor } of records) {
|
|
109
|
+
for (const [fieldPath, targets, soft] of collectRefFields(fieldsOf(descriptor))) {
|
|
110
|
+
if (soft || (fieldPath.length === 1 && fieldsOf(descriptor)[fieldPath[0]]?.mirror_of !== undefined)) continue;
|
|
111
|
+
for (const value of valuesAt(fields, fieldPath)) {
|
|
112
|
+
const ref = typeof value === 'string' && !value.startsWith('@') ? parseRef(value, namespaces) : null;
|
|
113
|
+
if (!ref || (targets !== '*' && !targets.includes(ref.collection)) || held(ref.collection, ref.id)) continue;
|
|
114
|
+
const key = `${ref.collection}/${ref.id}`;
|
|
115
|
+
if (!out.has(key)) out.set(key, { collection: ref.collection, id: ref.id, resolved: resolve(ref.collection, ref.id), referrers: [] });
|
|
116
|
+
out.get(key).referrers.push(`${collection}/${id}`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return out;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The manifest `dt exports` would write for `repo` in this context, and why — design §3's rules:
|
|
125
|
+
* add an outside reference that resolves here; refresh a label only where the entry's holder is seen
|
|
126
|
+
* and still has the id (its `from` never changes); fill a holder-less entry whose id resolves here;
|
|
127
|
+
* drop an entry for an id the repo now holds, one whose seen holder lost the id, and — only where this
|
|
128
|
+
* context reads every record of the repo — one nothing references; keep everything else as written.
|
|
129
|
+
*/
|
|
130
|
+
export function regenerate({ current, outside, ctx, repo, held }) {
|
|
131
|
+
const next = {};
|
|
132
|
+
const changes = [];
|
|
133
|
+
const put = (c, id, e) => { (next[c] ??= {})[id] = e; };
|
|
134
|
+
const complete = ctx.complete(repo);
|
|
135
|
+
for (const [c, ids] of Object.entries(current ?? {})) {
|
|
136
|
+
for (const [id, e] of Object.entries(ids)) {
|
|
137
|
+
const ref = `${c}/${id}`;
|
|
138
|
+
const o = outside.get(ref);
|
|
139
|
+
const why = held(c, id) ? 'held by the repo itself'
|
|
140
|
+
: !o && complete ? 'no record references it'
|
|
141
|
+
: o && !o.resolved && sees(e, c, ctx) ? `its holder ${e.from} no longer has it`
|
|
142
|
+
: null;
|
|
143
|
+
if (why) { changes.push({ ref, kind: 'drop', why }); continue; }
|
|
144
|
+
if (o?.resolved && !e.from) { put(c, id, o.resolved); changes.push({ ref, kind: 'fill', why: `held by ${o.resolved.from}` }); continue; }
|
|
145
|
+
if (o?.resolved && o.resolved.from === e.from && sees(e, c, ctx) && o.resolved.label !== e.label) {
|
|
146
|
+
put(c, id, { label: o.resolved.label, from: e.from });
|
|
147
|
+
changes.push({ ref, kind: 'refresh', why: `label "${e.label}" is now "${o.resolved.label}"` });
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
put(c, id, e);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
for (const [ref, o] of outside) {
|
|
154
|
+
if (!o.resolved || current?.[o.collection]?.[o.id]) continue;
|
|
155
|
+
put(o.collection, o.id, o.resolved);
|
|
156
|
+
changes.push({ ref, kind: 'add', why: `named by ${o.referrers[0]}${o.referrers.length > 1 ? ` +${o.referrers.length - 1}` : ''}` });
|
|
157
|
+
}
|
|
158
|
+
return { next, changes };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** A manifest is stale exactly when `regenerate` would change or drop one of its existing entries. */
|
|
162
|
+
export const isStale = (changes) => changes.some((c) => c.kind !== 'add');
|
package/src/fields.js
CHANGED
|
@@ -29,13 +29,11 @@ export const DISPLAY_KEYS = new Set(['editable', 'hidden', 'form_section', 'plac
|
|
|
29
29
|
const PASS_THROUGH = ['default', 'examples', 'pattern', 'minimum', 'maximum', 'minItems', 'maxItems', 'minLength', 'maxLength', 'const'];
|
|
30
30
|
|
|
31
31
|
/** The fields every collection has. `created` is stored (engine-written); `id` and `last_modified` are
|
|
32
|
-
* computed on read
|
|
33
|
-
* of several roots answers an id (records.js `resolveClaims`). */
|
|
32
|
+
* computed on read. */
|
|
34
33
|
export const INJECTED_FIELDS = {
|
|
35
34
|
id: { type: 'string', title: 'Id', virtual: true, description: 'The record\'s path inside its collection.' },
|
|
36
35
|
created: { type: 'datetime', title: 'Created', derived: true, description: 'When the record was first written. Stamped by the engine at add; read from the id\'s date or the first commit for a record written before it existed.' },
|
|
37
36
|
last_modified: { type: 'datetime', title: 'Last modified', virtual: true, description: 'When the record was last committed, from git.' },
|
|
38
|
-
stub: { type: 'boolean', title: 'Stub', display: { hidden: ['list', 'form'] }, description: 'A placeholder: it yields to a real record of the same id in any other root (a record layer, or the workspace reading this one), and answers only where none exists.' },
|
|
39
37
|
};
|
|
40
38
|
|
|
41
39
|
/** Is `type` a reference to one or more collections, given the names that exist? */
|
|
@@ -61,12 +59,9 @@ export function resolveFields(authored, ctx) {
|
|
|
61
59
|
const defaults = {};
|
|
62
60
|
const known = new Set(Object.keys(authored ?? {}));
|
|
63
61
|
const fields = {};
|
|
64
|
-
// `created` is STAMPED by the store, which a kind whose records compile writes never goes through
|
|
65
|
-
// `stub` exists only where a record can yield — a collection that can never be a layer root (a
|
|
66
|
-
// compiled source, module-owned, placed, env-pointed: ctx.unlayerable) has nothing to yield to
|
|
62
|
+
// `created` is STAMPED by the store, which a kind whose records compile writes never goes through
|
|
67
63
|
for (const [k, v] of Object.entries(INJECTED_FIELDS)) {
|
|
68
64
|
if (k === 'created' && ctx.runtime) continue;
|
|
69
|
-
if (k === 'stub' && (ctx.runtime || ctx.unlayerable)) continue;
|
|
70
65
|
if (known.has(k)) errors.push(`field "${k}" is injected by the engine and cannot be authored`);
|
|
71
66
|
fields[k] = { ...v };
|
|
72
67
|
}
|
package/src/records-api.d.ts
CHANGED
|
@@ -60,6 +60,9 @@ export class Store {
|
|
|
60
60
|
recordDirs(d: Descriptor): string[];
|
|
61
61
|
/** id → record file, across every folder the collection's records sit in */
|
|
62
62
|
ids(collection: string): Map<string, string>;
|
|
63
|
+
/** An id no root here holds that an exports manifest vouches for — the referring record's repo's when
|
|
64
|
+
* `referrer` names it, else this workspace's — answered only where `check` says external (cr-dt-004). */
|
|
65
|
+
external(collection: string, id: string, opts?: { referrer?: string }): { label: string; from?: string; manifest: string } | null;
|
|
63
66
|
read(collection: string, id: string): { fields: Fields; file: string };
|
|
64
67
|
/** Where a record is read from: `file` workspace-relative (absolute for a root outside every repo
|
|
65
68
|
* here) and `repo`, the workspace-relative repo root that commits it — null when none does. */
|
package/src/records.js
CHANGED
|
@@ -29,41 +29,6 @@ export function parseRecordText(text, d, bodyField) {
|
|
|
29
29
|
return fields;
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
-
// ---- stubs: a record that yields its id (0.41.0) --------------------------------------
|
|
33
|
-
// A record carrying `stub: true` is a placeholder — a thin copy a workspace keeps so its own references
|
|
34
|
-
// resolve standalone — and it YIELDS to any non-stub of the same id in any other root. The store and
|
|
35
|
-
// `check` both decide which file answers an id through `resolveClaims`, so they cannot disagree.
|
|
36
|
-
|
|
37
|
-
/** Does a record file carry `stub: true`? Read only for an id more than one root claims — never for the
|
|
38
|
-
* whole index. A file record (`format: binary`) has no fields and is never a stub; one that will not
|
|
39
|
-
* parse is not a stub either, and `check` reports the parse error on its own. */
|
|
40
|
-
export function isStubRecord(file, d) {
|
|
41
|
-
if (storageOf(d).format === 'binary') return false;
|
|
42
|
-
try { return parseRecordText(fs.readFileSync(file, 'utf8'), d).stub === true; } catch { return false; }
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/** Which of an id's claimants answers, in root order. One non-stub wins wherever it sits and every stub
|
|
46
|
-
* is `shadowed`; two or more non-stubs are `conflicts` (the first answers, exactly as before stubs
|
|
47
|
-
* existed); stubs only — the first root answers and the rest are shadowed. A stub only ever weakens
|
|
48
|
-
* its own claim, so nothing a layer writes can displace a non-stub. */
|
|
49
|
-
export function resolveClaims(claims, isStub) {
|
|
50
|
-
if (claims.length < 2) return { winner: claims[0], conflicts: [], shadowed: [] };
|
|
51
|
-
const stub = claims.map(isStub);
|
|
52
|
-
const real = claims.filter((_, i) => !stub[i]);
|
|
53
|
-
if (!real.length) return { winner: claims[0], conflicts: [], shadowed: claims.slice(1) };
|
|
54
|
-
return { winner: real[0], conflicts: real.length > 1 ? real : [], shadowed: claims.filter((_, i) => stub[i]) };
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/** The fields a stub of a record must carry to validate on its own (cr-dt-003): the schema's root
|
|
58
|
-
* `required`, plus each `allOf` branch's `then.required` whose `if` holds for this record (`holds`
|
|
59
|
-
* evaluates a subschema against it), kept to the keys the record carries. Nothing optional and nothing
|
|
60
|
-
* a branch that does not apply requires — a stub is read by every workspace that reads this one. */
|
|
61
|
-
export function stubFields(schema, fields, holds) {
|
|
62
|
-
const keys = new Set(schema?.required ?? []);
|
|
63
|
-
for (const b of schema?.allOf ?? []) if (b?.then?.required && (b.if === undefined || holds(b.if))) for (const k of b.then.required) keys.add(k);
|
|
64
|
-
return [...keys].filter((k) => fields[k] !== undefined);
|
|
65
|
-
}
|
|
66
|
-
|
|
67
32
|
// id patterns may use unicode property escapes — compile with the u flag
|
|
68
33
|
export function patternRe(pattern) {
|
|
69
34
|
try { return new RegExp(pattern, 'u'); } catch { return new RegExp(pattern); }
|
package/src/runtime.js
CHANGED
|
@@ -119,6 +119,14 @@ function walkDescriptors(dir, out = []) {
|
|
|
119
119
|
return out;
|
|
120
120
|
}
|
|
121
121
|
|
|
122
|
+
/** What compile recorded for the exports manifest (cr-dt-004): this workspace's package name and data
|
|
123
|
+
* folder, and per layer `{ name, root, data, package, reads, narrowed }` — `layers: null` from a runtime
|
|
124
|
+
* older than them, which a caller reads as "nothing is known". */
|
|
125
|
+
export function exportsFacts(root) {
|
|
126
|
+
const m = readManifest(root);
|
|
127
|
+
return { own: m?.package ?? null, data: m?.data_path ?? 'data', layers: m?.layers ?? null };
|
|
128
|
+
}
|
|
129
|
+
|
|
122
130
|
/**
|
|
123
131
|
* The workspace's declared namespaces, longest-first — the closed set every reference is split
|
|
124
132
|
* against. Read off the MANIFEST rather than package.json so the record layer keeps its single
|