@vectoriox/iox-ui 5.110.0 → 5.112.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/assist-core/index.d.ts +650 -0
- package/assist-core/package.json +3 -0
- package/fesm2022/vectoriox-iox-ui-assist-core.mjs +1144 -0
- package/fesm2022/vectoriox-iox-ui-assist-core.mjs.map +1 -0
- package/fesm2022/vectoriox-iox-ui-generation-core.mjs +307 -122
- package/fesm2022/vectoriox-iox-ui-generation-core.mjs.map +1 -1
- package/generation-core/index.d.ts +280 -45
- package/package.json +5 -1
- package/src/assist-core/assist-locale.ts +73 -0
- package/src/assist-core/assist-turn.ts +240 -0
- package/src/assist-core/brief.ts +98 -0
- package/src/assist-core/budget.ts +34 -0
- package/src/assist-core/content-fields.ts +256 -0
- package/src/assist-core/field-edits.ts +178 -0
- package/src/assist-core/field-values.ts +42 -0
- package/src/assist-core/fields-schema.ts +117 -0
- package/src/assist-core/public-api.ts +24 -0
- package/src/assist-core/rich-text.ts +32 -0
- package/src/assist-core/route-schema.ts +49 -0
- package/src/assist-core/summarize-item.ts +219 -0
- package/src/assist-core/surfaces.ts +235 -0
- package/src/generation-core/ai-run.ts +34 -0
- package/src/generation-core/check-list.ts +8 -7
- package/src/generation-core/compose-layout.ts +54 -10
- package/src/generation-core/layout-wire.ts +8 -15
- package/src/generation-core/list-table.ts +39 -0
- package/src/generation-core/plan-words.ts +12 -3
- package/src/generation-core/public-api.ts +1 -0
- package/src/generation-core/site-spec.generated.ts +160 -76
- package/styles/iox-design.css +103 -0
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import { AROUND_TEXT_CHARS, MEMORY_TURNS } from './budget';
|
|
2
|
+
import { AssistIssue, AssistIssueCode, Brief, HandleMap } from './brief';
|
|
3
|
+
import { FieldChange } from './field-edits';
|
|
4
|
+
import { FieldEdit } from './fields-schema';
|
|
5
|
+
import { ContentRecord, clipText } from './summarize-item';
|
|
6
|
+
import { AssistSurface, CommitKind, EditFamily, SURFACES, SurfaceStatus } from './surfaces';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The turn wire (plan §3d) — what cms-client posts and polls and iox-cms stores and answers, ONE definition both sides
|
|
10
|
+
* import (generation-core `ai-run.ts` is the precedent for generations). A turn is a document on the jobs runner:
|
|
11
|
+
* POST answers 202 `{ turnId }`, the client polls the turn every 750 ms until it is terminal.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export enum AssistTurnStatus {
|
|
15
|
+
Queued = 'queued',
|
|
16
|
+
Routing = 'routing',
|
|
17
|
+
Editing = 'editing',
|
|
18
|
+
Done = 'done',
|
|
19
|
+
Refused = 'refused',
|
|
20
|
+
Failed = 'failed',
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const TERMINAL: ReadonlySet<AssistTurnStatus> = new Set([AssistTurnStatus.Done, AssistTurnStatus.Refused, AssistTurnStatus.Failed]);
|
|
24
|
+
|
|
25
|
+
export const isTerminalTurn = (status: AssistTurnStatus): boolean => TERMINAL.has(status);
|
|
26
|
+
|
|
27
|
+
/** Auto = the step's model from Settings ▸ AI ▸ Models (A-D14). */
|
|
28
|
+
export const ASSIST_MODEL_AUTO = 'auto';
|
|
29
|
+
|
|
30
|
+
/** `'auto'` or a model id. */
|
|
31
|
+
export type AssistModelChoice = typeof ASSIST_MODEL_AUTO | string;
|
|
32
|
+
|
|
33
|
+
export const ASSIST_POLL_MS = 750;
|
|
34
|
+
|
|
35
|
+
export const MAX_SENTENCE_CHARS = 2000;
|
|
36
|
+
|
|
37
|
+
export interface AssistTurnRequest {
|
|
38
|
+
readonly surface: AssistSurface;
|
|
39
|
+
/** `assistSessionKey(surface, target)`; the server adds the user. */
|
|
40
|
+
readonly sessionKey: string;
|
|
41
|
+
readonly sentence: string;
|
|
42
|
+
readonly model: AssistModelChoice;
|
|
43
|
+
readonly contentType?: string;
|
|
44
|
+
readonly itemId?: string;
|
|
45
|
+
readonly brief: Brief;
|
|
46
|
+
readonly handles: HandleMap;
|
|
47
|
+
/** A form-fill surface: the form's current values (it may be unsaved) — the edits are checked against them. */
|
|
48
|
+
readonly values?: ContentRecord;
|
|
49
|
+
/** Field keys the owner changed since the last AI turn — kept unless the sentence names them (rule 9). */
|
|
50
|
+
readonly ownerEdited?: ReadonlyArray<string>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** POST's 202 answer. */
|
|
54
|
+
export interface AssistTurnAccepted {
|
|
55
|
+
readonly turnId: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** A turn's own refusals and failures, beside generation-core's `AiRefusalCode`s (credits, plan, key), which a turn returns as they are. */
|
|
59
|
+
export enum AssistRefusalCode {
|
|
60
|
+
/** The turn machinery runs, no model is connected yet. */
|
|
61
|
+
NotConnected = 'ai.assistNotConnected',
|
|
62
|
+
/** The turn spent its own credit cap (trap T8) before a call it still needed. */
|
|
63
|
+
TurnBudget = 'ai.assistTurnBudget',
|
|
64
|
+
/** The routed families need a permission the person who asked does not hold. */
|
|
65
|
+
Permission = 'ai.assistPermission',
|
|
66
|
+
/** A process died during this turn's call more often than one resume allows. */
|
|
67
|
+
Interrupted = 'ai.assistInterrupted',
|
|
68
|
+
/** The provider call threw — the turn ends; the owner may ask again. */
|
|
69
|
+
CallFailed = 'ai.assistCallFailed',
|
|
70
|
+
/** The model's answer broke the check twice (the first time it was re-asked with the issues). */
|
|
71
|
+
InvalidAnswer = 'ai.assistInvalidAnswer',
|
|
72
|
+
/** The chosen model is not on the vetted list for this step, and the turn runs on IOX credits. */
|
|
73
|
+
ModelNotOffered = 'ai.assistModelNotOffered',
|
|
74
|
+
/** The chosen model cannot do the step (on the studio's own key any model may be typed; this one lacks a need). */
|
|
75
|
+
ModelDeclined = 'ai.assistModelDeclined',
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface AssistTurnRefusal {
|
|
79
|
+
/** An `AssistRefusalCode` or an `AiRefusalCode` — a string, so both fit. */
|
|
80
|
+
readonly code: string;
|
|
81
|
+
readonly message: string;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface AssistTurn {
|
|
85
|
+
readonly id: string;
|
|
86
|
+
readonly surface: AssistSurface;
|
|
87
|
+
readonly sessionKey: string;
|
|
88
|
+
readonly status: AssistTurnStatus;
|
|
89
|
+
readonly sentence: string;
|
|
90
|
+
/** The model it ran on (Auto resolved) — the one the ledger row names (R-H11). */
|
|
91
|
+
readonly model?: string;
|
|
92
|
+
readonly families?: ReadonlyArray<EditFamily>;
|
|
93
|
+
readonly reply?: string;
|
|
94
|
+
readonly edits?: ReadonlyArray<FieldEdit>;
|
|
95
|
+
readonly changes?: ReadonlyArray<FieldChange>;
|
|
96
|
+
readonly kept?: ReadonlyArray<FieldChange>;
|
|
97
|
+
readonly issues?: ReadonlyArray<AssistIssue>;
|
|
98
|
+
readonly refusal?: AssistTurnRefusal;
|
|
99
|
+
readonly credits?: number;
|
|
100
|
+
/** ISO time. */
|
|
101
|
+
readonly createdAt: string;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export enum AssistRouteKey {
|
|
105
|
+
Turns = 'turns',
|
|
106
|
+
Turn = 'turn',
|
|
107
|
+
Session = 'session',
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The path templates, `:param` filled by `assistPath` — neither side hand-types a URL. */
|
|
111
|
+
export const ASSIST_ROUTES: Readonly<Record<AssistRouteKey, string>> = {
|
|
112
|
+
[AssistRouteKey.Turns]: 'admin/api/org/:orgId/ai/assist/turns',
|
|
113
|
+
[AssistRouteKey.Turn]: 'admin/api/org/:orgId/ai/assist/turns/:turnId',
|
|
114
|
+
[AssistRouteKey.Session]: 'admin/api/org/:orgId/ai/assist/sessions/:sessionKey',
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
export class AssistPathError extends Error {}
|
|
118
|
+
|
|
119
|
+
/** A route with its params filled, each URL-encoded; a missing param throws. */
|
|
120
|
+
export function assistPath(route: AssistRouteKey, params: Readonly<Record<string, string>>): string {
|
|
121
|
+
return ASSIST_ROUTES[route].replace(/:([A-Za-z]+)/g, (_, name: string) => {
|
|
122
|
+
const value = params[name];
|
|
123
|
+
if (!value) throw new AssistPathError(`${route}: no ${name}`);
|
|
124
|
+
return encodeURIComponent(value);
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** What a session is about, beside its surface (A-D9: per user × surface × target). */
|
|
129
|
+
export interface AssistTarget {
|
|
130
|
+
readonly contentType?: string;
|
|
131
|
+
readonly itemId?: string | null;
|
|
132
|
+
readonly pageId?: string;
|
|
133
|
+
readonly submissionId?: string;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const SESSION_TARGET_KEYS: Readonly<Record<AssistSurface, ReadonlyArray<keyof AssistTarget>>> = {
|
|
137
|
+
[AssistSurface.BuilderPage]: ['pageId'],
|
|
138
|
+
[AssistSurface.ContentItem]: ['contentType', 'itemId'],
|
|
139
|
+
[AssistSurface.ContentFromPhotos]: ['contentType'],
|
|
140
|
+
[AssistSurface.ContentList]: ['contentType'],
|
|
141
|
+
[AssistSurface.SchemaType]: ['contentType'],
|
|
142
|
+
[AssistSurface.ShopProduct]: ['itemId'],
|
|
143
|
+
[AssistSurface.Media]: [],
|
|
144
|
+
[AssistSurface.BuilderSite]: [],
|
|
145
|
+
[AssistSurface.FormInbox]: ['submissionId'],
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/** A target not saved yet. */
|
|
149
|
+
export const NEW_TARGET = 'new';
|
|
150
|
+
const SESSION_SEPARATOR = ':';
|
|
151
|
+
|
|
152
|
+
/** `contentItem:projects:<itemId|new>` — each part encoded, so a value never carries the separator. */
|
|
153
|
+
export function assistSessionKey(surface: AssistSurface, target: AssistTarget = {}): string {
|
|
154
|
+
const parts = SESSION_TARGET_KEYS[surface].map(k => encodeURIComponent(target[k] || NEW_TARGET));
|
|
155
|
+
return [surface, ...parts].join(SESSION_SEPARATOR);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export interface AssistMemoryLine {
|
|
159
|
+
readonly turnId: string;
|
|
160
|
+
readonly createdAt: string;
|
|
161
|
+
readonly line: string;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const SENTENCE_IN_MEMORY_CHARS = 80;
|
|
165
|
+
|
|
166
|
+
function outcome(turn: AssistTurn): string {
|
|
167
|
+
const named = (list: ReadonlyArray<FieldChange> | undefined) =>
|
|
168
|
+
(list ?? []).map(c => (c.locale ? `${c.label} (${c.locale})` : c.label)).join(', ');
|
|
169
|
+
switch (turn.status) {
|
|
170
|
+
case AssistTurnStatus.Refused: return `refused: ${turn.refusal?.message ?? ''}`.trim();
|
|
171
|
+
case AssistTurnStatus.Failed: return 'failed';
|
|
172
|
+
case AssistTurnStatus.Done: {
|
|
173
|
+
const changed = named(turn.changes);
|
|
174
|
+
const kept = named(turn.kept);
|
|
175
|
+
const head = changed ? `changed ${changed}` : `no change${turn.reply ? `: ${turn.reply}` : ''}`;
|
|
176
|
+
return kept ? `${head}; kept ${kept} (the owner edited it)` : head;
|
|
177
|
+
}
|
|
178
|
+
default: return turn.status;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** One line the next turn reads as memory — never a tree, a record or a value. */
|
|
183
|
+
export function memoryLine(turn: AssistTurn): AssistMemoryLine {
|
|
184
|
+
const asked = clipText(turn.sentence.replace(/\s+/g, ' ').trim(), SENTENCE_IN_MEMORY_CHARS);
|
|
185
|
+
return { turnId: turn.id, createdAt: turn.createdAt, line: clipText(`"${asked}" → ${outcome(turn)}`, AROUND_TEXT_CHARS) };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** `GET …/ai/assist/sessions/:sessionKey` — the memory the next turn is sent. */
|
|
189
|
+
export interface AssistSession {
|
|
190
|
+
readonly sessionKey: string;
|
|
191
|
+
readonly lines: ReadonlyArray<AssistMemoryLine>;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** A session's answer from its stored turns (those of another session are ignored). */
|
|
195
|
+
export function assistSession(sessionKey: string, turns: ReadonlyArray<AssistTurn>): AssistSession {
|
|
196
|
+
return { sessionKey, lines: sessionMemory(turns.filter(t => t.sessionKey === sessionKey)) };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** A session's memory: its last `MEMORY_TURNS` finished turns, oldest first. */
|
|
200
|
+
export function sessionMemory(turns: ReadonlyArray<AssistTurn>): AssistMemoryLine[] {
|
|
201
|
+
return turns
|
|
202
|
+
.filter(t => isTerminalTurn(t.status))
|
|
203
|
+
.slice()
|
|
204
|
+
.sort((a, b) => a.createdAt.localeCompare(b.createdAt))
|
|
205
|
+
.slice(-MEMORY_TURNS)
|
|
206
|
+
.map(memoryLine);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const isObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
210
|
+
const nonEmpty = (v: unknown): v is string => typeof v === 'string' && v.trim() !== '';
|
|
211
|
+
|
|
212
|
+
/** Absent, or a list of non-empty field keys. */
|
|
213
|
+
const isOwnerEdited = (v: unknown): boolean => v === undefined || (Array.isArray(v) && v.every(nonEmpty));
|
|
214
|
+
|
|
215
|
+
/** A key `assistSessionKey` made for this surface. */
|
|
216
|
+
export const isSessionOf = (key: unknown, surface: AssistSurface): boolean =>
|
|
217
|
+
nonEmpty(key) && (key === surface || key.startsWith(`${surface}${SESSION_SEPARATOR}`));
|
|
218
|
+
|
|
219
|
+
/** What the server refuses in a posted turn before anything runs. Empty = accepted. */
|
|
220
|
+
export function validateTurnRequest(req: unknown): AssistIssue[] {
|
|
221
|
+
const issue = (code: AssistIssueCode, message: string): AssistIssue => ({ code, message });
|
|
222
|
+
if (!isObject(req)) return [issue(AssistIssueCode.BadRequest, 'a turn is an object')];
|
|
223
|
+
const surface = req['surface'] as AssistSurface;
|
|
224
|
+
const spec = Object.prototype.hasOwnProperty.call(SURFACES, surface) ? SURFACES[surface] : undefined;
|
|
225
|
+
if (!spec) return [issue(AssistIssueCode.UnknownSurface, `"${String(surface)}" is not a surface`)];
|
|
226
|
+
const sentence = req['sentence'];
|
|
227
|
+
const brief = req['brief'];
|
|
228
|
+
return [
|
|
229
|
+
...(spec.status !== SurfaceStatus.Built ? [issue(AssistIssueCode.SurfaceNotBuilt, `${surface} is not built yet`)] : []),
|
|
230
|
+
...(!isSessionOf(req['sessionKey'], surface) ? [issue(AssistIssueCode.BadRequest, `the session key is not a ${surface} session`)] : []),
|
|
231
|
+
...(!nonEmpty(sentence) ? [issue(AssistIssueCode.EmptySentence, 'the sentence is empty')] : []),
|
|
232
|
+
...(nonEmpty(sentence) && sentence.length > MAX_SENTENCE_CHARS ? [issue(AssistIssueCode.SentenceTooLong, `the sentence is over ${MAX_SENTENCE_CHARS} characters`)] : []),
|
|
233
|
+
...(!nonEmpty(req['model']) ? [issue(AssistIssueCode.BadRequest, 'no model choice (auto or a model id)')] : []),
|
|
234
|
+
...(!isObject(brief) || brief['surface'] !== surface ? [issue(AssistIssueCode.BadRequest, `the brief is not a ${surface} brief`)] : []),
|
|
235
|
+
...(!isObject(req['handles']) || !Object.keys(req['handles']).length ? [issue(AssistIssueCode.MissingHandles, 'the brief\'s handles are missing')] : []),
|
|
236
|
+
...(spec.commit === CommitKind.FormFill && !isObject(req['values']) ? [issue(AssistIssueCode.MissingValues, 'a form-fill turn carries the form\'s values')] : []),
|
|
237
|
+
...(!isOwnerEdited(req['ownerEdited']) ? [issue(AssistIssueCode.BadRequest, 'ownerEdited is a list of field keys')] : []),
|
|
238
|
+
...(spec.perContentType && !nonEmpty(req['contentType']) ? [issue(AssistIssueCode.BadRequest, `${surface} names its content type`)] : []),
|
|
239
|
+
];
|
|
240
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { AssistScope, AssistSurface, EditFamily } from './surfaces';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The brief (plan §3c): what the model is told, built by CODE from what the screen holds, sized by distance from the
|
|
5
|
+
* focus. It names things by HANDLE (`f.summary`, `s2`), never by id (rule 3); the handle map that goes with it is
|
|
6
|
+
* kept by the caller and the server, never sent.
|
|
7
|
+
*/
|
|
8
|
+
export interface Brief<TFocus = unknown, TAround = unknown> {
|
|
9
|
+
readonly surface: AssistSurface;
|
|
10
|
+
/** The thing the sentence is about, in full. */
|
|
11
|
+
readonly focus: TFocus;
|
|
12
|
+
/** Its neighbourhood, summarised. */
|
|
13
|
+
readonly around: TAround;
|
|
14
|
+
/** The business reading (kind, voice, facts, languages) — the caller passes it; null when there is none. */
|
|
15
|
+
readonly owner: string | null;
|
|
16
|
+
readonly rules: BriefRules;
|
|
17
|
+
/** The session's last turns, one line each, oldest first. */
|
|
18
|
+
readonly memory: ReadonlyArray<string>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface BriefRules {
|
|
22
|
+
/** The families a turn on this focus may answer in. */
|
|
23
|
+
readonly families: ReadonlyArray<EditFamily>;
|
|
24
|
+
/** The locale words are written in (a multiLang field gets this one key). */
|
|
25
|
+
readonly locale: string;
|
|
26
|
+
/** What is never written here, each with why — the model leaves it and says it "needs you". */
|
|
27
|
+
readonly never: ReadonlyArray<NeverWrite>;
|
|
28
|
+
/** The focus rung and the rungs it can widen to. */
|
|
29
|
+
readonly scope: AssistScope;
|
|
30
|
+
readonly widensTo: ReadonlyArray<AssistScope>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface NeverWrite {
|
|
34
|
+
readonly handle: string;
|
|
35
|
+
readonly label: string;
|
|
36
|
+
readonly reason: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** What a handle stands for. `path` is the key path inside the target; `id` a record the handle names (never sent). */
|
|
40
|
+
export interface HandleTarget {
|
|
41
|
+
readonly key: string;
|
|
42
|
+
readonly path: ReadonlyArray<string>;
|
|
43
|
+
readonly id?: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export type HandleMap = Readonly<Record<string, HandleTarget>>;
|
|
47
|
+
|
|
48
|
+
export enum AssistIssueCode {
|
|
49
|
+
UnknownHandle = 'unknownHandle',
|
|
50
|
+
NeverWrite = 'neverWrite',
|
|
51
|
+
WrongType = 'wrongType',
|
|
52
|
+
NotAnOption = 'notAnOption',
|
|
53
|
+
Duplicate = 'duplicate',
|
|
54
|
+
WrongLocale = 'wrongLocale',
|
|
55
|
+
HtmlNotAllowed = 'htmlNotAllowed',
|
|
56
|
+
UnknownFamily = 'unknownFamily',
|
|
57
|
+
BadRequest = 'badRequest',
|
|
58
|
+
UnknownSurface = 'unknownSurface',
|
|
59
|
+
SurfaceNotBuilt = 'surfaceNotBuilt',
|
|
60
|
+
EmptySentence = 'emptySentence',
|
|
61
|
+
SentenceTooLong = 'sentenceTooLong',
|
|
62
|
+
MissingHandles = 'missingHandles',
|
|
63
|
+
MissingValues = 'missingValues',
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface AssistIssue {
|
|
67
|
+
readonly code: AssistIssueCode;
|
|
68
|
+
readonly handle?: string;
|
|
69
|
+
readonly message: string;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** A caller's mistake building a brief (a focus that is not on the screen) — never a model answer. */
|
|
73
|
+
export class AssistBriefError extends Error {
|
|
74
|
+
constructor(readonly code: AssistIssueCode, message: string) {
|
|
75
|
+
super(message);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export type HandleResolution = { ok: true; target: HandleTarget } | { ok: false; issue: AssistIssue };
|
|
80
|
+
|
|
81
|
+
/** The one way a handle becomes a key: an unknown handle is refused, never guessed (trap T1). */
|
|
82
|
+
export function resolveHandle(handles: HandleMap, handle: string): HandleResolution {
|
|
83
|
+
const target = Object.prototype.hasOwnProperty.call(handles, handle) ? handles[handle] : undefined;
|
|
84
|
+
if (target) return { ok: true, target };
|
|
85
|
+
return { ok: false, issue: { code: AssistIssueCode.UnknownHandle, handle, message: `"${handle}" is not a handle of this brief` } };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Every handle of the list that the brief does not know. */
|
|
89
|
+
export function unknownHandles(handles: HandleMap, list: ReadonlyArray<string>): AssistIssue[] {
|
|
90
|
+
return list.flatMap(h => {
|
|
91
|
+
const r = resolveHandle(handles, h);
|
|
92
|
+
return 'issue' in r ? [r.issue] : [];
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export const FIELD_HANDLE_PREFIX = 'f.';
|
|
97
|
+
export const SIBLING_HANDLE_PREFIX = 's';
|
|
98
|
+
export const fieldHandle = (key: string): string => `${FIELD_HANDLE_PREFIX}${key}`;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { JsonSchema, STRICT_SCHEMA_BUDGET, strictSchemaComplexity } from '@vectoriox/iox-ui/generation-core';
|
|
2
|
+
|
|
3
|
+
/** The house budget every Assist request is held to (plan F6, trap T7) — generation-core's, never a copy and never raised. */
|
|
4
|
+
export const MAX_ASSIST_PROPERTIES = STRICT_SCHEMA_BUDGET.properties;
|
|
5
|
+
|
|
6
|
+
/** The route request is small and fast (plan §3a). */
|
|
7
|
+
export const MAX_ROUTE_PROPERTIES = 12;
|
|
8
|
+
|
|
9
|
+
/** Around-layer text is a summary: at most this many characters per value (plan §3c). */
|
|
10
|
+
export const AROUND_TEXT_CHARS = 160;
|
|
11
|
+
|
|
12
|
+
/** Sibling items sent as examples of voice (plan §3c: 3–5). */
|
|
13
|
+
export const AROUND_ITEMS_MAX = 5;
|
|
14
|
+
|
|
15
|
+
/** The session memory sent with a turn: the last turns, one line each (plan §3c). */
|
|
16
|
+
export const MEMORY_TURNS = 6;
|
|
17
|
+
|
|
18
|
+
export class AssistBudgetError extends Error {}
|
|
19
|
+
|
|
20
|
+
/** What a request's strict schemas break of the house budget — empty when it fits. */
|
|
21
|
+
export function assistBudgetIssues(schemas: ReadonlyArray<JsonSchema>, maxProperties: number = MAX_ASSIST_PROPERTIES): string[] {
|
|
22
|
+
const c = strictSchemaComplexity(schemas);
|
|
23
|
+
return [
|
|
24
|
+
...c.unsupported,
|
|
25
|
+
...(c.properties > maxProperties ? [`${c.properties} properties (budget ${maxProperties})`] : []),
|
|
26
|
+
...(c.optional > STRICT_SCHEMA_BUDGET.optional ? [`${c.optional} optional (budget ${STRICT_SCHEMA_BUDGET.optional})`] : []),
|
|
27
|
+
...(c.unions > STRICT_SCHEMA_BUDGET.unions ? [`${c.unions} unions (budget ${STRICT_SCHEMA_BUDGET.unions})`] : []),
|
|
28
|
+
];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function assertAssistBudget(name: string, schemas: ReadonlyArray<JsonSchema>, maxProperties?: number): void {
|
|
32
|
+
const issues = assistBudgetIssues(schemas, maxProperties);
|
|
33
|
+
if (issues.length) throw new AssistBudgetError(`${name}: ${issues.join('; ')}`);
|
|
34
|
+
}
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import { fieldHandle } from './brief';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A content type's fields as Assist sees them, read from the REAL stored schema (iox-cms `schemas` row:
|
|
5
|
+
* `{ name, metaData, schemaObject: { properties } }`; each property `{ type, label, controller: { type, options } }` —
|
|
6
|
+
* cms-client `schema-doc/property-def.model.ts`). A multiLang field is `type: 'object'` + `controller.type: 'multiLang'`
|
|
7
|
+
* whose `properties` are its locales (`{ en: {…}, he: {…} }`), each with the inner control.
|
|
8
|
+
*
|
|
9
|
+
* Every field is either WRITABLE (one of the kinds below) or NEVER written, with a reason. Never written:
|
|
10
|
+
* - by what it is: relations, media (ids / URLs), secrets, dates, e-mail, nested structures, a select with no options;
|
|
11
|
+
* - by what it is about — a closed word list over the key and the label (English + Hebrew): money (price, cost, fee,
|
|
12
|
+
* currency, discount, VAT…), stock (quantity, inventory…), product codes (SKU, barcode…), contact facts (phone, e-mail,
|
|
13
|
+
* address, location, hours…), dates and web addresses (slug, URL, link). A field whose controller or type is `money`
|
|
14
|
+
* / `price` / `currency` is money, ready for "money as a field type" (AI plan) the day it exists.
|
|
15
|
+
* The model never sees the value of a never-written field, only whether it is filled; the owner fills it ("needs you").
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
export interface ContentControllerDef {
|
|
19
|
+
readonly type?: string;
|
|
20
|
+
readonly options?: unknown;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface ContentPropertyDef {
|
|
24
|
+
readonly type: string;
|
|
25
|
+
readonly label?: string;
|
|
26
|
+
readonly controller?: ContentControllerDef;
|
|
27
|
+
readonly properties?: Readonly<Record<string, ContentPropertyDef>>;
|
|
28
|
+
readonly items?: ContentPropertyDef;
|
|
29
|
+
readonly required?: boolean;
|
|
30
|
+
readonly rel?: unknown;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface ContentTypeSchema {
|
|
34
|
+
readonly name: string;
|
|
35
|
+
readonly metaData?: { readonly label?: string; readonly previewTextField?: string; readonly previewImageField?: string };
|
|
36
|
+
readonly schemaObject: { readonly properties: Readonly<Record<string, ContentPropertyDef>> };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export enum AssistFieldKind {
|
|
40
|
+
Text = 'text',
|
|
41
|
+
Textarea = 'textarea',
|
|
42
|
+
/** Written as plain paragraphs, never HTML (trap T6). */
|
|
43
|
+
RichText = 'richText',
|
|
44
|
+
Number = 'number',
|
|
45
|
+
Boolean = 'boolean',
|
|
46
|
+
/** One of the field's options. */
|
|
47
|
+
Choice = 'choice',
|
|
48
|
+
/** Some of the field's options. */
|
|
49
|
+
Choices = 'choices',
|
|
50
|
+
/** A list of words. */
|
|
51
|
+
Tags = 'tags',
|
|
52
|
+
/** Not writable — `never` says why. */
|
|
53
|
+
Other = 'other',
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export enum NeverWriteReason {
|
|
57
|
+
Money = 'money',
|
|
58
|
+
Stock = 'stock',
|
|
59
|
+
ProductCode = 'productCode',
|
|
60
|
+
Contact = 'contact',
|
|
61
|
+
Date = 'date',
|
|
62
|
+
WebAddress = 'webAddress',
|
|
63
|
+
Relation = 'relation',
|
|
64
|
+
Media = 'media',
|
|
65
|
+
Secret = 'secret',
|
|
66
|
+
Structure = 'structure',
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface AssistField {
|
|
70
|
+
readonly key: string;
|
|
71
|
+
readonly handle: string;
|
|
72
|
+
readonly label: string;
|
|
73
|
+
readonly kind: AssistFieldKind;
|
|
74
|
+
readonly required: boolean;
|
|
75
|
+
/** Choice / Choices: the option values the field accepts. */
|
|
76
|
+
readonly options?: ReadonlyArray<string>;
|
|
77
|
+
/** multiLang: the locales the field holds, in schema order. */
|
|
78
|
+
readonly locales?: ReadonlyArray<string>;
|
|
79
|
+
readonly never?: NeverWriteReason;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** iox-cms `RESERVED_SCHEMA_PROPERTIES` + read-time bookkeeping + shop catalog bookkeeping — never a field. */
|
|
83
|
+
const NOT_FIELDS: ReadonlySet<string> = new Set([
|
|
84
|
+
'isPublished', 'organization', 'info', 'addedBy', 'created', 'lastUpdate', '_id', 'isSample', 'pricingUnit',
|
|
85
|
+
]);
|
|
86
|
+
|
|
87
|
+
enum Control {
|
|
88
|
+
Text = 'text',
|
|
89
|
+
Tag = 'tag',
|
|
90
|
+
Textarea = 'textarea',
|
|
91
|
+
RichText = 'richText',
|
|
92
|
+
Number = 'number',
|
|
93
|
+
Range = 'range',
|
|
94
|
+
Switch = 'switch',
|
|
95
|
+
Checkbox = 'checkbox',
|
|
96
|
+
Select = 'select',
|
|
97
|
+
MultiSelect = 'multiSelect',
|
|
98
|
+
CheckboxGroup = 'checkboxGroup',
|
|
99
|
+
Tags = 'tags',
|
|
100
|
+
List = 'list',
|
|
101
|
+
MultiLang = 'multiLang',
|
|
102
|
+
Email = 'email',
|
|
103
|
+
Password = 'password',
|
|
104
|
+
Encrypt = 'encrypt',
|
|
105
|
+
Date = 'date',
|
|
106
|
+
Time = 'time',
|
|
107
|
+
Image = 'image',
|
|
108
|
+
Media = 'media',
|
|
109
|
+
Gallery = 'gallery',
|
|
110
|
+
RelationCombobox = 'relationCombobox',
|
|
111
|
+
Money = 'money',
|
|
112
|
+
Price = 'price',
|
|
113
|
+
Currency = 'currency',
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
enum DataType {
|
|
117
|
+
String = 'string',
|
|
118
|
+
Array = 'array',
|
|
119
|
+
Object = 'object',
|
|
120
|
+
Rel = 'rel',
|
|
121
|
+
Encrypt = 'encrypt',
|
|
122
|
+
Date = 'date',
|
|
123
|
+
Money = 'money',
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const KIND_OF_CONTROL: Readonly<Partial<Record<string, AssistFieldKind>>> = {
|
|
127
|
+
[Control.Text]: AssistFieldKind.Text,
|
|
128
|
+
[Control.Tag]: AssistFieldKind.Text,
|
|
129
|
+
[Control.Textarea]: AssistFieldKind.Textarea,
|
|
130
|
+
[Control.RichText]: AssistFieldKind.RichText,
|
|
131
|
+
[Control.Number]: AssistFieldKind.Number,
|
|
132
|
+
[Control.Range]: AssistFieldKind.Number,
|
|
133
|
+
[Control.Switch]: AssistFieldKind.Boolean,
|
|
134
|
+
[Control.Checkbox]: AssistFieldKind.Boolean,
|
|
135
|
+
[Control.Select]: AssistFieldKind.Choice,
|
|
136
|
+
[Control.MultiSelect]: AssistFieldKind.Choices,
|
|
137
|
+
[Control.CheckboxGroup]: AssistFieldKind.Choices,
|
|
138
|
+
[Control.Tags]: AssistFieldKind.Tags,
|
|
139
|
+
[Control.List]: AssistFieldKind.Tags,
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
const LIST_KINDS: ReadonlySet<AssistFieldKind> = new Set([AssistFieldKind.Choices, AssistFieldKind.Tags]);
|
|
143
|
+
const CHOICE_KINDS: ReadonlySet<AssistFieldKind> = new Set([AssistFieldKind.Choice, AssistFieldKind.Choices]);
|
|
144
|
+
|
|
145
|
+
const NEVER_OF_CONTROL: Readonly<Partial<Record<string, NeverWriteReason>>> = {
|
|
146
|
+
[Control.Email]: NeverWriteReason.Contact,
|
|
147
|
+
[Control.Password]: NeverWriteReason.Secret,
|
|
148
|
+
[Control.Encrypt]: NeverWriteReason.Secret,
|
|
149
|
+
[Control.Date]: NeverWriteReason.Date,
|
|
150
|
+
[Control.Time]: NeverWriteReason.Date,
|
|
151
|
+
[Control.Image]: NeverWriteReason.Media,
|
|
152
|
+
[Control.Media]: NeverWriteReason.Media,
|
|
153
|
+
[Control.Gallery]: NeverWriteReason.Media,
|
|
154
|
+
[Control.RelationCombobox]: NeverWriteReason.Relation,
|
|
155
|
+
[Control.Money]: NeverWriteReason.Money,
|
|
156
|
+
[Control.Price]: NeverWriteReason.Money,
|
|
157
|
+
[Control.Currency]: NeverWriteReason.Money,
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
const NEVER_OF_TYPE: Readonly<Partial<Record<string, NeverWriteReason>>> = {
|
|
161
|
+
[DataType.Rel]: NeverWriteReason.Relation,
|
|
162
|
+
[DataType.Encrypt]: NeverWriteReason.Secret,
|
|
163
|
+
[DataType.Date]: NeverWriteReason.Date,
|
|
164
|
+
[DataType.Money]: NeverWriteReason.Money,
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
/** The closed word list: a key or label word that makes a field a fact the owner gives. */
|
|
168
|
+
const NEVER_WORDS: ReadonlyArray<readonly [NeverWriteReason, ReadonlyArray<string>, ReadonlyArray<string>]> = [
|
|
169
|
+
[NeverWriteReason.Money,
|
|
170
|
+
['price', 'prices', 'pricing', 'cost', 'costs', 'amount', 'fee', 'fees', 'currency', 'discount', 'compareat', 'vat', 'tax', 'total', 'salary', 'budget', 'payment'],
|
|
171
|
+
['מחיר', 'עלות', 'תשלום', 'מע"מ', 'הנחה']],
|
|
172
|
+
[NeverWriteReason.Stock, ['stock', 'quantity', 'qty', 'inventory'], ['מלאי', 'כמות']],
|
|
173
|
+
[NeverWriteReason.ProductCode, ['sku', 'barcode', 'ean', 'upc', 'gtin', 'isbn', 'mpn'], ['מק"ט', 'ברקוד']],
|
|
174
|
+
[NeverWriteReason.Contact,
|
|
175
|
+
['phone', 'tel', 'telephone', 'mobile', 'whatsapp', 'email', 'mail', 'fax', 'address', 'street', 'city', 'zip', 'postcode', 'location', 'hours'],
|
|
176
|
+
['טלפון', 'נייד', 'וואטסאפ', 'דוא"ל', 'אימייל', 'מייל', 'כתובת', 'שעות', 'פקס', 'מיקום']],
|
|
177
|
+
[NeverWriteReason.Date, ['date', 'dates', 'time', 'datetime', 'deadline'], ['תאריך']],
|
|
178
|
+
[NeverWriteReason.WebAddress, ['slug', 'url', 'uri', 'href', 'link', 'website', 'route', 'permalink'], ['קישור', 'לינק']],
|
|
179
|
+
];
|
|
180
|
+
|
|
181
|
+
/** `startDate` → start, date · `ticket_link` → ticket, link · `Price (₪)` → price. */
|
|
182
|
+
function words(text: string): string[] {
|
|
183
|
+
return text.replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function neverByWords(key: string, label: string): NeverWriteReason | undefined {
|
|
187
|
+
const english = new Set([...words(key), ...words(label)]);
|
|
188
|
+
const raw = `${key} ${label}`;
|
|
189
|
+
return NEVER_WORDS.find(([, en, he]) => en.some(w => english.has(w)) || he.some(w => raw.includes(w)))?.[0];
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function optionValues(options: unknown): string[] | undefined {
|
|
193
|
+
if (!Array.isArray(options)) return undefined;
|
|
194
|
+
const values = options.map(o => (o && typeof o === 'object' ? (o as { value?: unknown }).value : o))
|
|
195
|
+
.filter(v => v !== undefined && v !== null && v !== '')
|
|
196
|
+
.map(String);
|
|
197
|
+
return values.length ? [...new Set(values)] : undefined;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
interface Shape {
|
|
201
|
+
kind: AssistFieldKind;
|
|
202
|
+
options?: string[];
|
|
203
|
+
never?: NeverWriteReason;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const other = (never: NeverWriteReason): Shape => ({ kind: AssistFieldKind.Other, never });
|
|
207
|
+
|
|
208
|
+
/** What one leaf property is, by its type and control alone. */
|
|
209
|
+
function leafShape(def: ContentPropertyDef): Shape {
|
|
210
|
+
const control = def.controller?.type ?? '';
|
|
211
|
+
const never = NEVER_OF_TYPE[def.type] ?? NEVER_OF_CONTROL[control] ?? (def.items ? NEVER_OF_CONTROL[def.items.controller?.type ?? ''] : undefined);
|
|
212
|
+
if (never) return other(never);
|
|
213
|
+
const kind = KIND_OF_CONTROL[control];
|
|
214
|
+
const isList = def.type === DataType.Array;
|
|
215
|
+
if (!kind || isList !== LIST_KINDS.has(kind)) return other(NeverWriteReason.Structure);
|
|
216
|
+
if (isList && def.items && def.items.type !== DataType.String) return other(NeverWriteReason.Structure);
|
|
217
|
+
if (!CHOICE_KINDS.has(kind)) return { kind };
|
|
218
|
+
const options = optionValues(def.controller?.options);
|
|
219
|
+
return options ? { kind, options } : other(NeverWriteReason.Structure);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const isMultiLang = (def: ContentPropertyDef) => def.controller?.type === Control.MultiLang && !!def.properties;
|
|
223
|
+
|
|
224
|
+
function fieldOf(key: string, def: ContentPropertyDef): AssistField {
|
|
225
|
+
const label = def.label || key;
|
|
226
|
+
const base = { key, handle: fieldHandle(key), label, required: !!def.required };
|
|
227
|
+
if (isMultiLang(def)) {
|
|
228
|
+
const locales = Object.keys(def.properties ?? {});
|
|
229
|
+
const inner = locales.length ? leafShape(def.properties![locales[0]]) : other(NeverWriteReason.Structure);
|
|
230
|
+
const never = inner.never ?? neverByWords(key, label);
|
|
231
|
+
return never ? { ...base, kind: AssistFieldKind.Other, locales, never } : { ...base, ...inner, locales };
|
|
232
|
+
}
|
|
233
|
+
if (def.type === DataType.Object) return { ...base, ...other(NeverWriteReason.Structure) };
|
|
234
|
+
const shape = leafShape(def);
|
|
235
|
+
const never = shape.never ?? neverByWords(key, label);
|
|
236
|
+
return never ? { ...base, kind: AssistFieldKind.Other, never } : { ...base, ...shape };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** A property the item form renders: not bookkeeping, and (a leaf) carrying a control. */
|
|
240
|
+
const isFormField = (key: string, def: ContentPropertyDef) =>
|
|
241
|
+
!NOT_FIELDS.has(key) && !!def && (def.type === DataType.Object || !!def.controller);
|
|
242
|
+
|
|
243
|
+
/** Every form field of the type, in schema order, writable or with the reason it is never written. */
|
|
244
|
+
export function assistFields(schema: ContentTypeSchema): AssistField[] {
|
|
245
|
+
return Object.entries(schema.schemaObject?.properties ?? {})
|
|
246
|
+
.filter(([key, def]) => isFormField(key, def))
|
|
247
|
+
.map(([key, def]) => fieldOf(key, def));
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export const isWritable = (field: AssistField): boolean => !field.never;
|
|
251
|
+
|
|
252
|
+
/** The type's title field: its `@title` role (`metaData.previewTextField`), else its first text field. */
|
|
253
|
+
export function titleField(schema: ContentTypeSchema, fields: ReadonlyArray<AssistField> = assistFields(schema)): AssistField | undefined {
|
|
254
|
+
const role = schema.metaData?.previewTextField;
|
|
255
|
+
return fields.find(f => f.key === role) ?? fields.find(f => f.kind === AssistFieldKind.Text);
|
|
256
|
+
}
|