@aintela/chat 0.3.7 → 0.4.1

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.
@@ -30,11 +30,191 @@ function primitiveOf(schema) {
30
30
  }
31
31
 
32
32
  const opts = { bannerComment: '', additionalProperties: false, format: false };
33
- const interfaces = new Map(); // declaration name -> its TS block (deduped ACROSS compiles)
33
+ const interfaces = new Map(); // declaration name -> { text, from } (deduped ACROSS compiles)
34
34
 
35
- // One compile() output holds the requested type PLUS every nested sub-schema hoisted into its own
36
- // named declaration. Split it so identical hoisted names from different tools (deep contracts share
37
- // sub-types) dedupe instead of colliding as duplicate identifiers in the generated file.
35
+ // ---- one declaration per named type -------------------------------------------
36
+ // json-schema-to-typescript gives a sub-schema its own declaration when something $refs it, and names
37
+ // that declaration after the LAST SEGMENT of the pointer — which for an array element is always the
38
+ // keyword `items`. So every repeated nested list, in every tool, emitted as one interface called
39
+ // `Items`, and the second shape to claim that name was dropped in favour of the first: a
40
+ // reschedule-quote flight typechecked as an expense-report line, and the only sign was a warning.
41
+ //
42
+ // The fix has two halves. The manifest now carries the C# type name as `title` on every object node
43
+ // (server side: UiToolsManifest.StampTitles) — the only record of that name a JSON Schema can keep.
44
+ // Here we act on it: every titled object is lifted into `$defs/<TypeName>` and referenced from each
45
+ // place it appears, so ONE C# contract is ONE exported interface under its real name, however many
46
+ // payloads embed it. Two DIFFERENT shapes claiming one name is then a genuine clash and stops the run
47
+ // (`reportCollisions`) instead of silently mistyping a payload.
48
+ const POINTER_SEGMENT_ALIAS = { items: 'item', additionalProperties: 'value', prefixItems: 'item' };
49
+ const POINTER_SEGMENT_SKIP = new Set(['properties', '$defs', 'definitions', 'allOf', 'anyOf', 'oneOf']);
50
+ const DEFS = '#/$defs/';
51
+
52
+ const pascal = (segment) => segment
53
+ .replace(/[^A-Za-z0-9]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''))
54
+ .replace(/^(.)/, (c) => c.toUpperCase());
55
+
56
+ // '#/properties/replacing/items' -> ['properties', 'replacing', 'items'] (JSON-pointer unescaped)
57
+ const pointerSegments = (pointer) => pointer.slice(1).split('/').filter(Boolean)
58
+ .map((s) => s.replace(/~1/g, '/').replace(/~0/g, '~'));
59
+
60
+ const pointerOf = (segments) => '#' + segments
61
+ .map((s) => '/' + s.replace(/~/g, '~0').replace(/\//g, '~1')).join('');
62
+
63
+ const resolvePointer = (root, pointer) =>
64
+ pointerSegments(pointer).reduce((node, s) => (node == null ? node : node[s]), root);
65
+
66
+ // `null` is expressed as a member of `type`, and `"default": null` alongside it — both are facts about
67
+ // the SLOT a value sits in, not about the type, and a type is the same type in a nullable slot.
68
+ const withoutNullability = (node) => {
69
+ const type = Array.isArray(node.type) ? node.type.filter((t) => t !== 'null') : node.type;
70
+ const body = { ...node, ...(type === undefined ? {} : { type: type.length === 1 ? type[0] : type }) };
71
+ delete body.default;
72
+ return body;
73
+ };
74
+ const isNullable = (node) => Array.isArray(node.type) && node.type.includes('null');
75
+
76
+ // `{ anyOf: [X, { type: 'null' }] }` — how a nullable slot reads once its type is a $ref (a `type`
77
+ // member cannot say it alongside one). Same slot fact, so it unwraps the same way.
78
+ const withoutNullUnion = (node) => {
79
+ for (const keyword of ['anyOf', 'oneOf']) {
80
+ const branches = node[keyword];
81
+ if (!Array.isArray(branches) || branches.length !== 2) continue;
82
+ const value = branches.find((b) => b && b.type !== 'null');
83
+ if (value && branches.some((b) => b && b.type === 'null')) return value;
84
+ }
85
+ return node;
86
+ };
87
+
88
+ function eachRef(node, fn) {
89
+ if (Array.isArray(node)) { node.forEach((child) => eachRef(child, fn)); return; }
90
+ if (!node || typeof node !== 'object') return;
91
+ if (typeof node.$ref === 'string' && node.$ref.startsWith('#')) node.$ref = fn(node.$ref);
92
+ for (const [key, child] of Object.entries(node)) if (key !== '$ref') eachRef(child, fn);
93
+ }
94
+
95
+ function collectRefs(node, into = new Set()) {
96
+ eachRef(node, (ref) => { into.add(ref); return ref; });
97
+ return into;
98
+ }
99
+
100
+ // A manifest published by an OLDER server carries no titles. Name the sub-schemas that would be hoisted
101
+ // anyway (the $ref targets) after their owner rather than after their keyword, so `Items` can never
102
+ // recur: `#/properties/replacing/items` under RescheduleQuoteCardArgs becomes
103
+ // `RescheduleQuoteCardArgsReplacingItem`. Long and mechanical on purpose — a name like that reads as a
104
+ // prompt to republish the manifest from a current server, and it is never WRONG.
105
+ function nameUntitledRefTargets(schema, rootName) {
106
+ for (const pointer of collectRefs(schema)) {
107
+ const target = resolvePointer(schema, pointer);
108
+ if (!target || typeof target !== 'object' || target.title || !target.properties) continue;
109
+ target.title = rootName + pointerSegments(pointer)
110
+ .filter((s) => !POINTER_SEGMENT_SKIP.has(s))
111
+ .map((s) => pascal(POINTER_SEGMENT_ALIAS[s] ?? s))
112
+ .join('');
113
+ }
114
+ }
115
+
116
+ const collisions = [];
117
+
118
+ function hoistNamedTypes(schema, rootName, from) {
119
+ nameUntitledRefTargets(schema, rootName);
120
+
121
+ // A node carrying its own `description` is left where it is: a $ref's description migrates onto the
122
+ // DECLARATION, so lifting one would stamp a single parameter's prose on the shared type.
123
+ const nameable = (node) => !!node && typeof node === 'object' && typeof node.$ref !== 'string'
124
+ && !!node.title && !!node.properties && !node.description;
125
+
126
+ // Index every named node BEFORE anything moves, and repoint the schema builder's own $refs — it
127
+ // writes a type out once and points at that copy thereafter — at the `$defs` entry each target is
128
+ // about to become. Doing it up front is what makes the shape comparison below order-independent:
129
+ // the two spellings of one type reduce to the same key whichever is met first.
130
+ const named = new Map(); // original pointer -> title (the document root is never lifted)
131
+ (function index(node, segments) {
132
+ if (Array.isArray(node)) { node.forEach((c, i) => index(c, [...segments, String(i)])); return; }
133
+ if (!node || typeof node !== 'object' || typeof node.$ref === 'string') return;
134
+ if (segments.length > 0 && nameable(node)) named.set(pointerOf(segments), node.title);
135
+ for (const key of Object.keys(node)) if (key !== 'title') index(node[key], [...segments, key]);
136
+ })(schema, []);
137
+ eachRef(schema, (ref) => (named.has(ref) ? DEFS + named.get(ref) : ref));
138
+
139
+ // Every remaining pointer is written against the document AS PUBLISHED, so resolve against an
140
+ // untouched copy — lifting a type rewrites nodes out from under the pointers aimed at them.
141
+ const original = structuredClone(schema);
142
+
143
+ // A schema's identity, BY NAME: two nodes are the same type when they agree structurally and their
144
+ // named sub-types agree by name. Property order is an artefact of reflection and cannot count;
145
+ // a pointer counts as whatever it points at; a nullable slot holds the same type as a plain one.
146
+ const shapeOf = (raw, root = false, seen = new Set()) => {
147
+ if (Array.isArray(raw)) return `[${raw.map((n) => shapeOf(n, false, seen)).join(',')}]`;
148
+ if (!raw || typeof raw !== 'object') return JSON.stringify(raw);
149
+ const node = withoutNullUnion(raw);
150
+ if (node !== raw) return shapeOf(node, root, seen);
151
+ if (typeof node.$ref === 'string') {
152
+ if (node.$ref.startsWith(DEFS)) return `~named:${node.$ref.slice(DEFS.length)}`;
153
+ if (seen.has(node.$ref)) return '~cycle';
154
+ const target = resolvePointer(original, node.$ref);
155
+ return target ? shapeOf(target, false, new Set([...seen, node.$ref])) : `~dangling:${node.$ref}`;
156
+ }
157
+ if (!root && node.title) return `~named:${node.title}`;
158
+ const body = withoutNullability(node);
159
+ return `{${Object.keys(body).filter((k) => k !== 'title').sort()
160
+ .map((k) => `${JSON.stringify(k)}:${shapeOf(body[k], false, seen)}`).join(',')}}`;
161
+ };
162
+
163
+ // Rebuild a subtree so it stands on its own: every pointer at a named type becomes a `$defs`
164
+ // reference, and every other pointer is resolved and inlined. Without this a lifted body can end up
165
+ // pointing back at the place it was lifted from — which now IS the body — and dereferencing never
166
+ // terminates.
167
+ const materialize = (node, root = false, seen = new Set()) => {
168
+ if (Array.isArray(node)) return node.map((child) => materialize(child, false, seen));
169
+ if (!node || typeof node !== 'object') return node;
170
+ if (typeof node.$ref === 'string') {
171
+ if (node.$ref.startsWith(DEFS) || seen.has(node.$ref)) return { ...node };
172
+ const target = resolvePointer(original, node.$ref);
173
+ return target ? materialize(target, root, new Set([...seen, node.$ref])) : { ...node };
174
+ }
175
+ if (!root && nameable(node)) {
176
+ const ref = { $ref: DEFS + node.title };
177
+ return isNullable(node) ? { anyOf: [ref, { type: 'null' }] } : ref;
178
+ }
179
+ return Object.fromEntries(Object.entries(node)
180
+ .map(([key, child]) => [key, materialize(child, false, seen)]));
181
+ };
182
+
183
+ // Post-order, so a type nested inside another is already a reference by the time its owner is lifted.
184
+ const defs = new Map(); // title -> { body, shape, from }
185
+ const visit = (node, root) => {
186
+ if (Array.isArray(node)) return node.map((child) => visit(child, false));
187
+ if (!node || typeof node !== 'object' || typeof node.$ref === 'string') return node;
188
+
189
+ for (const key of Object.keys(node)) if (key !== 'title') node[key] = visit(node[key], false);
190
+ if (root || !nameable(node)) return node;
191
+
192
+ const body = withoutNullability(node);
193
+ const shape = shapeOf(body, true);
194
+ const existing = defs.get(node.title);
195
+ if (existing && existing.shape !== shape) {
196
+ collisions.push({ name: node.title, first: existing, second: { body, from } });
197
+ return node; // reported at the end of the run; nothing is written
198
+ }
199
+ if (!existing) defs.set(node.title, { body: materialize(body, true), shape, from });
200
+
201
+ const ref = { $ref: DEFS + node.title };
202
+ return isNullable(node) ? { anyOf: [ref, { type: 'null' }] } : ref;
203
+ };
204
+ visit(schema, true);
205
+ if (defs.size === 0) return schema;
206
+
207
+ // Whatever pointers are left aim INTO a subtree that has moved; materializing the document settles
208
+ // them the same way it settled the bodies, and leaves `$defs` as the only pointer target.
209
+ const hoisted = materialize(schema, true);
210
+ hoisted.$defs = { ...(schema.$defs ?? {}) };
211
+ for (const [title, def] of defs) hoisted.$defs[title] = def.body;
212
+ return hoisted;
213
+ }
214
+
215
+ // One compile() output holds the requested type PLUS every named sub-schema hoisted into its own
216
+ // declaration. Split it so the same type reached through two different tools (deep contracts share
217
+ // sub-types) dedupes instead of colliding as duplicate identifiers in the generated file.
38
218
  function splitDeclarations(ts) {
39
219
  const starts = [...ts.matchAll(/^export (?:interface|type) (\w+)/gm)]
40
220
  .map((m) => ({ name: m[1], start: m.index }));
@@ -46,32 +226,52 @@ function splitDeclarations(ts) {
46
226
 
47
227
  // Registers the schema's declarations (deduped by name) and returns the TS type to reference at
48
228
  // the use site; `fallback` is used when the tool has no schema for that leg.
49
- async function register(typeName, schema, fallback = 'void') {
229
+ async function register(typeName, schema, fallback = 'void', from = typeName) {
50
230
  if (!typeName || !schema) return fallback;
51
231
  const prim = primitiveOf(schema);
52
232
  if (prim) return prim;
53
- if (!interfaces.has(typeName)) {
54
- const ts = await compile(schema, typeName, opts);
55
- for (const block of splitDeclarations(ts)) {
56
- const existing = interfaces.get(block.name);
57
- if (existing === undefined) interfaces.set(block.name, block.text);
58
- else if (existing !== block.text)
59
- console.warn(`aia-gen-uitools: type name '${block.name}' appears with differing shapes; keeping the first.`);
60
- }
233
+ const ts = await compile(hoistNamedTypes(schema, typeName, from), typeName, opts);
234
+ // Compiled every time, not just the first: a second tool declaring the SAME name with a different
235
+ // shape is exactly the mistake worth catching, and skipping the compile is what used to hide it.
236
+ for (const block of splitDeclarations(ts)) {
237
+ const existing = interfaces.get(block.name);
238
+ if (existing === undefined) interfaces.set(block.name, { text: block.text, from });
239
+ else if (existing.text !== block.text)
240
+ collisions.push({ name: block.name, first: existing, second: { text: block.text, from } });
61
241
  }
62
242
  return typeName;
63
243
  }
64
244
 
245
+ const indent = (text) => text.split('\n').map((line) => ' ' + line).join('\n');
246
+ const show = (side) => indent(side.text ?? JSON.stringify(side.body, null, 2));
247
+
248
+ // Two contracts want one TypeScript name for two different shapes. Whichever we kept, the other payload
249
+ // would be typed as it — `tsc` would then accept the wrong fields and reject the right ones, which is
250
+ // not something to leave a caller to notice in a warning line.
251
+ function reportCollisions() {
252
+ if (collisions.length === 0) return;
253
+ for (const { name, first, second } of collisions)
254
+ console.error(
255
+ `aia-gen-uitools: '${name}' is claimed by two DIFFERENT shapes — one payload would be typed`
256
+ + ` as the other.\n from ${first.from}:\n${show(first)}\n from ${second.from}:\n${show(second)}`,
257
+ );
258
+ console.error('aia-gen-uitools: nothing written. Fix it at the source — give one of the C# contracts'
259
+ + " a distinct type name, or a distinct JSON-Schema 'title'.");
260
+ process.exit(1);
261
+ }
262
+
65
263
  const rows = [];
66
264
  for (const c of manifest.components) {
265
+ const where = (leg) => `${c.component} (${leg})`;
67
266
  rows.push({
68
267
  ...c,
69
- argsTs: await register(c.argsTypeName, c.args, 'UiToolArgs'),
70
- inputTs: await register(c.inputTypeName, c.input),
71
- answerTs: await register(c.answerTypeName, c.answer),
72
- resultTs: await register(c.resultTypeName, c.result),
268
+ argsTs: await register(c.argsTypeName, c.args, 'UiToolArgs', where('args')),
269
+ inputTs: await register(c.inputTypeName, c.input, 'void', where('input')),
270
+ answerTs: await register(c.answerTypeName, c.answer, 'void', where('answer')),
271
+ resultTs: await register(c.resultTypeName, c.result, 'void', where('result')),
73
272
  });
74
273
  }
274
+ reportCollisions();
75
275
 
76
276
  // ---- uiContracts.generated.ts -------------------------------------------------
77
277
  writeFileSync(
@@ -80,7 +280,7 @@ writeFileSync(
80
280
  '// AUTO-GENERATED by aia-gen-uitools — do not edit. Source: the server UiToolsManifest.',
81
281
  '/* eslint-disable */',
82
282
  '',
83
- ...[...interfaces.values()],
283
+ ...[...interfaces.values()].map((d) => d.text),
84
284
  '',
85
285
  ].join('\n'),
86
286
  );