@burnsred/entity-sync 0.0.0-stage → 3.0.0-rc.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/.claude-plugin/marketplace.json +14 -0
- package/.claude-plugin/plugin.json +11 -0
- package/CHANGELOG.md +15 -0
- package/LICENSE +21 -0
- package/README.md +240 -2
- package/agents/entity-editor.md +16 -0
- package/bin/entity-sync.mjs +36 -0
- package/dist/cli.d.mts +20 -0
- package/dist/commands/asserts.d.mts +4 -0
- package/dist/commands/check.d.mts +6 -0
- package/dist/commands/inspect.d.mts +30 -0
- package/dist/commands/plan.d.mts +28 -0
- package/dist/commands/schema.d.mts +39 -0
- package/dist/config.d.mts +175 -0
- package/dist/index.d.mts +5 -0
- package/dist/lib/cache.d.mts +120 -0
- package/dist/lib/diff.d.mts +228 -0
- package/dist/lib/field-map.d.mts +93 -0
- package/dist/lib/gen-asserts.d.mts +70 -0
- package/dist/lib/graph.d.mts +90 -0
- package/dist/lib/parse-entities.d.mts +257 -0
- package/dist/lib/parse-schema.d.mts +98 -0
- package/dist/lib/resolve.d.mts +135 -0
- package/dist/project.d.mts +60 -0
- package/hooks/editor-guard.mjs +86 -0
- package/hooks/hooks.json +15 -0
- package/package.json +54 -4
- package/skills/entity/SKILL.md +105 -0
- package/skills/entity/reference/create.md +74 -0
- package/skills/entity/reference/editor.md +80 -0
- package/skills/entity/reference/enums.md +89 -0
- package/skills/entity/reference/fields.md +101 -0
- package/skills/entity/reference/sync.md +191 -0
- package/src/cli.mjs +110 -0
- package/src/commands/asserts.mjs +52 -0
- package/src/commands/check.mjs +88 -0
- package/src/commands/inspect.mjs +290 -0
- package/src/commands/plan.mjs +542 -0
- package/src/commands/schema.mjs +206 -0
- package/src/config.mjs +205 -0
- package/src/index.mjs +19 -0
- package/src/lib/cache.mjs +323 -0
- package/src/lib/diff.mjs +706 -0
- package/src/lib/field-map.mjs +438 -0
- package/src/lib/gen-asserts.mjs +478 -0
- package/src/lib/graph.mjs +284 -0
- package/src/lib/parse-entities.mjs +935 -0
- package/src/lib/parse-schema.mjs +667 -0
- package/src/lib/resolve.mjs +455 -0
- package/src/project.mjs +115 -0
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* Decide which schema component each entity models.
|
|
4
|
+
*
|
|
5
|
+
* This is the foundation everything downstream trusts: get it wrong and the diff
|
|
6
|
+
* confidently rewrites an entity to match the wrong serializer. So the rules are
|
|
7
|
+
* ordered by how much they can be trusted, and anything that cannot be decided
|
|
8
|
+
* on evidence is reported rather than guessed.
|
|
9
|
+
*
|
|
10
|
+
* ## Three sources, in priority order
|
|
11
|
+
*
|
|
12
|
+
* 1. **annotation** - a `@schema <Component>` JSDoc tag on the class. Decided
|
|
13
|
+
* once by a human, then never re-derived. Always wins.
|
|
14
|
+
*
|
|
15
|
+
* 2. **path** - `apiBase` looked up in the schema's paths index. A resource
|
|
16
|
+
* usually exposes two serializers, a list and a detail
|
|
17
|
+
* (`Application` / `ApplicationDetail`), and which one an entity models is
|
|
18
|
+
* genuinely ambiguous from the URL alone. Rather than guess by name - the
|
|
19
|
+
* thing that gets `ApplicationRow` wrong - candidates are scored by how well
|
|
20
|
+
* their field names overlap the entity's declared fields. The winner is
|
|
21
|
+
* reported *with* its score and runner-up, so a human can confirm it once and
|
|
22
|
+
* annotate.
|
|
23
|
+
*
|
|
24
|
+
* 3. **nested** - for the 23 entities with no endpoint of their own, the
|
|
25
|
+
* component is read off the parent that embeds them: find the parent's
|
|
26
|
+
* resolved component, find the field pointing at this entity, take its
|
|
27
|
+
* `$ref`. This runs to a fixpoint, because a child's parent may itself only
|
|
28
|
+
* be resolvable as a nested entity.
|
|
29
|
+
*
|
|
30
|
+
* Entities backed by a `DuckScreen` hold client-side screen state and have no
|
|
31
|
+
* schema counterpart at all; they are excluded rather than reported as failures.
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @typedef {import('./parse-entities.mjs').ParsedEntity} ParsedEntity
|
|
36
|
+
* @typedef {import('./parse-schema.mjs').ParsedSchema} ParsedSchema
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* @typedef {object} Candidate
|
|
41
|
+
* @property {string} component
|
|
42
|
+
* @property {number} score field-name overlap, 0..1
|
|
43
|
+
* @property {string} via how it was found, e.g. 'detail' or 'list'
|
|
44
|
+
*/
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @typedef {object} Resolution
|
|
48
|
+
* @property {string} className
|
|
49
|
+
* @property {string} file
|
|
50
|
+
* @property {string | null} component the chosen component, if any
|
|
51
|
+
* @property {'annotation' | 'path' | 'nested' | null} source
|
|
52
|
+
* @property {Candidate[]} candidates all considered, best first
|
|
53
|
+
* @property {boolean} ambiguous more than one plausible candidate
|
|
54
|
+
* @property {boolean} excluded no schema counterpart by design
|
|
55
|
+
* @property {string | null} note why it is unresolved or excluded
|
|
56
|
+
*/
|
|
57
|
+
|
|
58
|
+
/** Ducks that mean "client-side state", not "API resource". */
|
|
59
|
+
const SCREEN_DUCKS = new Set(['DuckScreen']);
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Jaccard overlap between two sets of field names.
|
|
63
|
+
*
|
|
64
|
+
* Used as the tiebreak between a list and detail serializer. It is a measurable
|
|
65
|
+
* criterion rather than a naming heuristic, which is what makes it trustworthy
|
|
66
|
+
* for the one case naming gets wrong: `ApplicationRow` (8 fields) scores higher
|
|
67
|
+
* against `Application` while `Application` (25 fields) scores higher against
|
|
68
|
+
* `ApplicationDetail`.
|
|
69
|
+
*
|
|
70
|
+
* @param {string[]} a
|
|
71
|
+
* @param {string[]} b
|
|
72
|
+
* @returns {number} 0..1, rounded to 3 places
|
|
73
|
+
*/
|
|
74
|
+
export function fieldOverlap(a, b) {
|
|
75
|
+
const setA = new Set(a);
|
|
76
|
+
const setB = new Set(b);
|
|
77
|
+
if (!setA.size && !setB.size) return 1;
|
|
78
|
+
|
|
79
|
+
let shared = 0;
|
|
80
|
+
for (const name of setA) if (setB.has(name)) shared += 1;
|
|
81
|
+
|
|
82
|
+
const union = setA.size + setB.size - shared;
|
|
83
|
+
return union === 0 ? 0 : Math.round((shared / union) * 1000) / 1000;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Names an entity declares, taking the union of its `static fields` keys and its
|
|
88
|
+
* `Fields` type members.
|
|
89
|
+
*
|
|
90
|
+
* Both are used because either can be the more complete picture when an entity is
|
|
91
|
+
* mid-edit, and for scoring purposes a superset is more informative than picking
|
|
92
|
+
* one arbitrarily.
|
|
93
|
+
*
|
|
94
|
+
* @param {ParsedEntity} entity
|
|
95
|
+
* @returns {string[]}
|
|
96
|
+
*/
|
|
97
|
+
function entityFieldNames(entity) {
|
|
98
|
+
return [
|
|
99
|
+
...new Set([
|
|
100
|
+
...entity.fields.map((f) => f.name),
|
|
101
|
+
...entity.fieldsTypeMembers.map((m) => m.name),
|
|
102
|
+
]),
|
|
103
|
+
];
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Candidate components for an entity with an `apiBase`.
|
|
108
|
+
*
|
|
109
|
+
* Looks at the collection path and its `{uuid}` detail sibling, since those are
|
|
110
|
+
* the two serializers DRF viewsets normally expose.
|
|
111
|
+
*
|
|
112
|
+
* @param {ParsedEntity} entity
|
|
113
|
+
* @param {ParsedSchema} schema
|
|
114
|
+
* @returns {Candidate[]}
|
|
115
|
+
*/
|
|
116
|
+
function pathCandidates(entity, schema) {
|
|
117
|
+
if (!entity.apiBase) return [];
|
|
118
|
+
|
|
119
|
+
const base = entity.apiBase.endsWith('/')
|
|
120
|
+
? entity.apiBase
|
|
121
|
+
: `${entity.apiBase}/`;
|
|
122
|
+
|
|
123
|
+
/** @type {Map<string, string>} component -> via */
|
|
124
|
+
const found = new Map();
|
|
125
|
+
|
|
126
|
+
const collection = schema.pathsIndex[base];
|
|
127
|
+
if (collection?.get) found.set(collection.get.component, 'list');
|
|
128
|
+
// A create-only endpoint still identifies the resource.
|
|
129
|
+
if (!found.size && collection?.post) {
|
|
130
|
+
found.set(collection.post.component, 'create');
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// DRF detail routes are `<base>{pk}/`; the parameter name varies (uuid, id).
|
|
134
|
+
for (const [urlPath, methods] of Object.entries(schema.pathsIndex)) {
|
|
135
|
+
if (!urlPath.startsWith(base)) continue;
|
|
136
|
+
const tail = urlPath.slice(base.length);
|
|
137
|
+
if (!/^\{[^}]+\}\/$/.test(tail)) continue;
|
|
138
|
+
if (methods.get) found.set(methods.get.component, 'detail');
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const names = entityFieldNames(entity);
|
|
142
|
+
|
|
143
|
+
return [...found.entries()]
|
|
144
|
+
.map(([component, via]) => ({
|
|
145
|
+
component,
|
|
146
|
+
via,
|
|
147
|
+
score: fieldOverlap(
|
|
148
|
+
names,
|
|
149
|
+
(schema.components[component]?.fields ?? []).map((f) => f.name),
|
|
150
|
+
),
|
|
151
|
+
}))
|
|
152
|
+
.sort((a, b) => b.score - a.score);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Build className -> [{ entity, fieldName }] for every `EntityField` reference,
|
|
157
|
+
* so a child can find the parents that embed it.
|
|
158
|
+
*
|
|
159
|
+
* @param {ParsedEntity[]} entities
|
|
160
|
+
* @returns {Map<string, { parent: ParsedEntity, fieldName: string }[]>}
|
|
161
|
+
*/
|
|
162
|
+
function buildParentIndex(entities) {
|
|
163
|
+
/** @type {Map<string, { parent: ParsedEntity, fieldName: string }[]>} */
|
|
164
|
+
const index = new Map();
|
|
165
|
+
|
|
166
|
+
for (const parent of entities) {
|
|
167
|
+
for (const field of parent.fields) {
|
|
168
|
+
if (!field.entityRef) continue;
|
|
169
|
+
const existing = index.get(field.entityRef) ?? [];
|
|
170
|
+
existing.push({ parent, fieldName: field.name });
|
|
171
|
+
index.set(field.entityRef, existing);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return index;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Resolve every entity to a component.
|
|
180
|
+
*
|
|
181
|
+
* @param {object} input
|
|
182
|
+
* @param {ParsedEntity[]} input.entities
|
|
183
|
+
* @param {ParsedSchema} input.schema
|
|
184
|
+
* @returns {Resolution[]} in the order entities were given
|
|
185
|
+
*/
|
|
186
|
+
export function resolveEntities({ entities, schema }) {
|
|
187
|
+
const parentIndex = buildParentIndex(entities);
|
|
188
|
+
|
|
189
|
+
/** @type {Map<string, Resolution>} */
|
|
190
|
+
const resolutions = new Map();
|
|
191
|
+
|
|
192
|
+
for (const entity of entities) {
|
|
193
|
+
resolutions.set(entity.className, {
|
|
194
|
+
className: entity.className,
|
|
195
|
+
file: entity.file,
|
|
196
|
+
component: null,
|
|
197
|
+
source: null,
|
|
198
|
+
candidates: [],
|
|
199
|
+
ambiguous: false,
|
|
200
|
+
excluded: false,
|
|
201
|
+
note: null,
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// ── Pass 1: annotations win outright ────────────────────────────────────────
|
|
206
|
+
for (const entity of entities) {
|
|
207
|
+
const resolution = /** @type {Resolution} */ (
|
|
208
|
+
resolutions.get(entity.className)
|
|
209
|
+
);
|
|
210
|
+
if (!entity.schemaAnnotation) continue;
|
|
211
|
+
|
|
212
|
+
if (!schema.components[entity.schemaAnnotation]) {
|
|
213
|
+
// A stale annotation is worse than none, so it is surfaced loudly rather
|
|
214
|
+
// than silently falling through to derivation.
|
|
215
|
+
resolution.note = `@schema ${entity.schemaAnnotation} is not a component in the schema`;
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
resolution.component = entity.schemaAnnotation;
|
|
220
|
+
resolution.source = 'annotation';
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// ── Exclusions: entities with no schema counterpart ─────────────────────────
|
|
224
|
+
for (const entity of entities) {
|
|
225
|
+
const resolution = /** @type {Resolution} */ (
|
|
226
|
+
resolutions.get(entity.className)
|
|
227
|
+
);
|
|
228
|
+
if (resolution.component) continue;
|
|
229
|
+
|
|
230
|
+
// An explicit `@noSchema` is a recorded decision, so it reads as excluded
|
|
231
|
+
// rather than reappearing as a failure on every run.
|
|
232
|
+
if (entity.noSchema !== null) {
|
|
233
|
+
resolution.excluded = true;
|
|
234
|
+
resolution.note = entity.noSchema || 'declared @noSchema';
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
if (entity.duck && SCREEN_DUCKS.has(entity.duck)) {
|
|
239
|
+
resolution.excluded = true;
|
|
240
|
+
resolution.note = `${entity.duck}: client-side screen state, not an API resource`;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// ── Pass 2: derive from apiBase via the paths index ─────────────────────────
|
|
245
|
+
for (const entity of entities) {
|
|
246
|
+
const resolution = /** @type {Resolution} */ (
|
|
247
|
+
resolutions.get(entity.className)
|
|
248
|
+
);
|
|
249
|
+
if (resolution.component || resolution.excluded) continue;
|
|
250
|
+
|
|
251
|
+
if (!entity.apiBase) {
|
|
252
|
+
if (entity.apiBaseNote) resolution.note = entity.apiBaseNote;
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const candidates = pathCandidates(entity, schema);
|
|
257
|
+
resolution.candidates = candidates;
|
|
258
|
+
|
|
259
|
+
if (!candidates.length) {
|
|
260
|
+
resolution.note = `no schema path matches apiBase ${entity.apiBase}`;
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
resolution.component = candidates[0].component;
|
|
265
|
+
resolution.source = 'path';
|
|
266
|
+
// Flag a near-tie: when two serializers fit about as well, the choice is a
|
|
267
|
+
// judgement call and deserves a human's confirmation, not a silent pick.
|
|
268
|
+
resolution.ambiguous =
|
|
269
|
+
candidates.length > 1 && candidates[0].score - candidates[1].score < 0.1;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// ── Pass 3: propagate into nested entities, to a fixpoint ───────────────────
|
|
273
|
+
// A child's component is whatever `$ref` its parent's field points at. This
|
|
274
|
+
// has to iterate, because a parent may itself only become resolvable in an
|
|
275
|
+
// earlier round of this same pass.
|
|
276
|
+
let changed = true;
|
|
277
|
+
while (changed) {
|
|
278
|
+
changed = false;
|
|
279
|
+
|
|
280
|
+
for (const entity of entities) {
|
|
281
|
+
const resolution = /** @type {Resolution} */ (
|
|
282
|
+
resolutions.get(entity.className)
|
|
283
|
+
);
|
|
284
|
+
if (resolution.component || resolution.excluded) continue;
|
|
285
|
+
|
|
286
|
+
/** @type {Map<string, string>} component -> "Parent.field" */
|
|
287
|
+
const viaParents = new Map();
|
|
288
|
+
|
|
289
|
+
for (const { parent, fieldName } of parentIndex.get(entity.className) ??
|
|
290
|
+
[]) {
|
|
291
|
+
const parentResolution = resolutions.get(parent.className);
|
|
292
|
+
if (!parentResolution?.component) continue;
|
|
293
|
+
|
|
294
|
+
const parentComponent = schema.components[parentResolution.component];
|
|
295
|
+
const schemaField = parentComponent?.fields.find(
|
|
296
|
+
(f) => f.name === fieldName,
|
|
297
|
+
);
|
|
298
|
+
// Only an unambiguous single ref identifies a component. A field with
|
|
299
|
+
// two refs is an enum union, and one with none is a scalar - in both
|
|
300
|
+
// cases the parent tells us nothing about a nested entity.
|
|
301
|
+
if (schemaField?.refs.length !== 1) continue;
|
|
302
|
+
|
|
303
|
+
const ref = schemaField.refs[0];
|
|
304
|
+
if (schema.components[ref]?.kind !== 'object') continue;
|
|
305
|
+
|
|
306
|
+
viaParents.set(ref, `${parent.className}.${fieldName}`);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
if (!viaParents.size) continue;
|
|
310
|
+
|
|
311
|
+
const [[component, via]] = [...viaParents.entries()];
|
|
312
|
+
|
|
313
|
+
if (viaParents.size > 1) {
|
|
314
|
+
// The same entity embedded by two parents under different serializers
|
|
315
|
+
// cannot satisfy both. Reporting beats picking one.
|
|
316
|
+
resolution.candidates = [...viaParents.entries()].map(
|
|
317
|
+
([name, from]) => ({
|
|
318
|
+
component: name,
|
|
319
|
+
score: fieldOverlap(
|
|
320
|
+
entityFieldNames(entity),
|
|
321
|
+
(schema.components[name]?.fields ?? []).map((f) => f.name),
|
|
322
|
+
),
|
|
323
|
+
via: from,
|
|
324
|
+
}),
|
|
325
|
+
);
|
|
326
|
+
resolution.candidates.sort((a, b) => b.score - a.score);
|
|
327
|
+
resolution.ambiguous = true;
|
|
328
|
+
resolution.component = resolution.candidates[0].component;
|
|
329
|
+
resolution.source = 'nested';
|
|
330
|
+
resolution.note = `embedded by multiple parents with differing components: ${[
|
|
331
|
+
...viaParents.values(),
|
|
332
|
+
].join(', ')}`;
|
|
333
|
+
} else {
|
|
334
|
+
resolution.component = component;
|
|
335
|
+
resolution.source = 'nested';
|
|
336
|
+
resolution.candidates = [
|
|
337
|
+
{
|
|
338
|
+
component,
|
|
339
|
+
via,
|
|
340
|
+
score: fieldOverlap(
|
|
341
|
+
entityFieldNames(entity),
|
|
342
|
+
(schema.components[component]?.fields ?? []).map((f) => f.name),
|
|
343
|
+
),
|
|
344
|
+
},
|
|
345
|
+
];
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
changed = true;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// ── Anything still unresolved gets a reason ─────────────────────────────────
|
|
353
|
+
for (const entity of entities) {
|
|
354
|
+
const resolution = /** @type {Resolution} */ (
|
|
355
|
+
resolutions.get(entity.className)
|
|
356
|
+
);
|
|
357
|
+
if (resolution.component || resolution.excluded || resolution.note)
|
|
358
|
+
continue;
|
|
359
|
+
|
|
360
|
+
resolution.note = parentIndex.has(entity.className)
|
|
361
|
+
? 'no endpoint, and no parent resolved to a component naming this field'
|
|
362
|
+
: 'no endpoint, and not embedded by any other entity';
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
return entities.map(
|
|
366
|
+
(entity) => /** @type {Resolution} */ (resolutions.get(entity.className)),
|
|
367
|
+
);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* @typedef {object} EnumResolution
|
|
372
|
+
* @property {string} name the dict's identifier
|
|
373
|
+
* @property {string} file
|
|
374
|
+
* @property {string | null} typeName the type alias to assert against
|
|
375
|
+
* @property {string | null} component the `*Enum` component it models, if any
|
|
376
|
+
* @property {string[]} values the dict's own values, for the report
|
|
377
|
+
* @property {boolean} local no `@schemaEnum` tag: a client-side enum
|
|
378
|
+
* @property {string | null} note why it is unresolved, when it is
|
|
379
|
+
*/
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* Resolve each choices dict to the schema component it models.
|
|
383
|
+
*
|
|
384
|
+
* Unlike entity resolution, this is a lookup rather than a derivation: only the
|
|
385
|
+
* `@schemaEnum` tag binds a dict to a component. Deriving `X` -> `XEnum` by name
|
|
386
|
+
* was rejected because more than half the dicts in `src/entities` have no broker
|
|
387
|
+
* counterpart at all - the policy-snapshot widget and rule enums are a
|
|
388
|
+
* client-side convention - and a name-based rule would report every one of them
|
|
389
|
+
* as unresolved on every run.
|
|
390
|
+
*
|
|
391
|
+
* So an untagged dict is `local`, not a failure. The gap in the other direction,
|
|
392
|
+
* a component no dict models, is found by walking entity fields in `diff.mjs`,
|
|
393
|
+
* which knows which components are actually referenced.
|
|
394
|
+
*
|
|
395
|
+
* @param {object} input
|
|
396
|
+
* @param {import('./parse-entities.mjs').ParsedEnum[]} input.enums
|
|
397
|
+
* @param {ParsedSchema} input.schema
|
|
398
|
+
* @returns {EnumResolution[]}
|
|
399
|
+
*/
|
|
400
|
+
export function resolveEnums({ enums, schema }) {
|
|
401
|
+
return enums.map((parsed) => {
|
|
402
|
+
/** @type {EnumResolution} */
|
|
403
|
+
const resolution = {
|
|
404
|
+
name: parsed.name,
|
|
405
|
+
file: parsed.file,
|
|
406
|
+
typeName: parsed.typeName,
|
|
407
|
+
component: null,
|
|
408
|
+
values: parsed.values,
|
|
409
|
+
local: parsed.schemaEnum === null,
|
|
410
|
+
note: null,
|
|
411
|
+
};
|
|
412
|
+
|
|
413
|
+
if (parsed.schemaEnum === null) return resolution;
|
|
414
|
+
|
|
415
|
+
const component = schema.components[parsed.schemaEnum];
|
|
416
|
+
|
|
417
|
+
if (!component) {
|
|
418
|
+
resolution.note = `no component named ${parsed.schemaEnum}`;
|
|
419
|
+
} else if (component.kind !== 'enum') {
|
|
420
|
+
resolution.note = `${parsed.schemaEnum} is a ${component.kind} component, not an enum`;
|
|
421
|
+
} else if (!parsed.typeName) {
|
|
422
|
+
resolution.component = parsed.schemaEnum;
|
|
423
|
+
resolution.note = `no exported type alias; expected \`export type ${parsed.name}\``;
|
|
424
|
+
} else {
|
|
425
|
+
resolution.component = parsed.schemaEnum;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
return resolution;
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Index resolved enums by the component they model.
|
|
434
|
+
*
|
|
435
|
+
* @param {EnumResolution[]} resolutions
|
|
436
|
+
* @returns {Record<string, { name: string, typeName: string, file: string }>}
|
|
437
|
+
*/
|
|
438
|
+
export function buildEnumByComponent(resolutions) {
|
|
439
|
+
/** @type {Record<string, { name: string, typeName: string, file: string }>} */
|
|
440
|
+
const index = {};
|
|
441
|
+
|
|
442
|
+
for (const resolution of resolutions) {
|
|
443
|
+
if (!resolution.component || !resolution.typeName) continue;
|
|
444
|
+
// First one wins, matching `buildEntityByComponent`. Two dicts claiming one
|
|
445
|
+
// component is a mistake, and the duplicate surfaces as enum drift on
|
|
446
|
+
// whichever one lost.
|
|
447
|
+
index[resolution.component] ??= {
|
|
448
|
+
name: resolution.name,
|
|
449
|
+
typeName: resolution.typeName,
|
|
450
|
+
file: resolution.file,
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
return index;
|
|
455
|
+
}
|
package/src/project.mjs
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* Shared loading for the commands: parse the schema and the entities once, the
|
|
4
|
+
* same way, from the paths in the resolved config.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { existsSync } from 'node:fs';
|
|
8
|
+
import { createRequire } from 'node:module';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { pathToFileURL } from 'node:url';
|
|
11
|
+
|
|
12
|
+
import { display } from './config.mjs';
|
|
13
|
+
import { buildEntityByComponent } from './lib/field-map.mjs';
|
|
14
|
+
import { parseEntitiesDir, parseEnumsDir } from './lib/parse-entities.mjs';
|
|
15
|
+
import { parseSchemaFile } from './lib/parse-schema.mjs';
|
|
16
|
+
import {
|
|
17
|
+
buildEnumByComponent,
|
|
18
|
+
resolveEnums,
|
|
19
|
+
resolveEntities,
|
|
20
|
+
} from './lib/resolve.mjs';
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @typedef {import('./config.mjs').ResolvedConfig} ResolvedConfig
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @param {ResolvedConfig} config
|
|
28
|
+
*/
|
|
29
|
+
export function readSchema(config) {
|
|
30
|
+
if (!existsSync(config.schema.dts)) {
|
|
31
|
+
throw new Error(
|
|
32
|
+
`${display(config, config.schema.dts)} does not exist yet - run \`entity-sync schema\` first.`,
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
return parseSchemaFile(config.schema.dts);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* @param {ResolvedConfig} config
|
|
40
|
+
*/
|
|
41
|
+
export function readEntities(config) {
|
|
42
|
+
return parseEntitiesDir(config.entitiesDir, config.root, {
|
|
43
|
+
prefixes: config.settingsPrefixes,
|
|
44
|
+
basePrefix: config.apiBasePrefix,
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* @param {ResolvedConfig} config
|
|
50
|
+
*/
|
|
51
|
+
export function readEnums(config) {
|
|
52
|
+
return parseEnumsDir(config.entitiesDir, config.root);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Everything `plan` and `asserts` both need.
|
|
57
|
+
*
|
|
58
|
+
* @param {ResolvedConfig} config
|
|
59
|
+
*/
|
|
60
|
+
export function loadProject(config) {
|
|
61
|
+
const schema = readSchema(config);
|
|
62
|
+
const entities = readEntities(config);
|
|
63
|
+
const resolutions = resolveEntities({ entities, schema });
|
|
64
|
+
const entityByComponent = buildEntityByComponent(resolutions, entities);
|
|
65
|
+
|
|
66
|
+
const enums = readEnums(config);
|
|
67
|
+
const enumResolutions = resolveEnums({ enums, schema });
|
|
68
|
+
const enumByComponent = buildEnumByComponent(enumResolutions);
|
|
69
|
+
|
|
70
|
+
return {
|
|
71
|
+
schema,
|
|
72
|
+
entities,
|
|
73
|
+
resolutions,
|
|
74
|
+
entityByComponent,
|
|
75
|
+
enums,
|
|
76
|
+
enumResolutions,
|
|
77
|
+
enumByComponent,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Import a peer dependency as the project resolves it, so the project's own
|
|
83
|
+
* version (and config) is used rather than whichever copy sits beside this
|
|
84
|
+
* package.
|
|
85
|
+
*
|
|
86
|
+
* @param {string} root
|
|
87
|
+
* @param {string} name
|
|
88
|
+
* @returns {Promise<any>}
|
|
89
|
+
*/
|
|
90
|
+
export async function importFromProject(root, name) {
|
|
91
|
+
try {
|
|
92
|
+
const require = createRequire(join(root, 'package.json'));
|
|
93
|
+
return await import(pathToFileURL(require.resolve(name)).href);
|
|
94
|
+
} catch {
|
|
95
|
+
return import(name);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Format generated source with the project's prettier and prettier config.
|
|
101
|
+
*
|
|
102
|
+
* Load-bearing, not cosmetic: unformatted output would produce a whole-file
|
|
103
|
+
* diff on every sync, burying the lines that actually changed.
|
|
104
|
+
*
|
|
105
|
+
* @param {ResolvedConfig} config
|
|
106
|
+
* @param {string} path absolute path the source will be written to
|
|
107
|
+
* @param {string} source
|
|
108
|
+
* @returns {Promise<string>}
|
|
109
|
+
*/
|
|
110
|
+
export async function formatForProject(config, path, source) {
|
|
111
|
+
const prettier = await importFromProject(config.root, 'prettier');
|
|
112
|
+
const api = prettier.default ?? prettier;
|
|
113
|
+
const options = (await api.resolveConfig(path)) ?? {};
|
|
114
|
+
return api.format(source, { ...options, filepath: path });
|
|
115
|
+
}
|