@folijs/agent 0.0.0-stage → 0.1.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.
@@ -0,0 +1,243 @@
1
+ import {
2
+ type ControlValue,
3
+ controlIsReadOnly,
4
+ controlProperties,
5
+ controlsIn,
6
+ controlValues,
7
+ type FieldsReport,
8
+ fieldsIn,
9
+ parseFieldInstruction,
10
+ setControlValue,
11
+ updateFields as updateFieldsOf,
12
+ } from "@folijs/core";
13
+ import { type Changed, type Context, changed } from "./operations.js";
14
+ import { readBlocks } from "./read.js";
15
+ import { type Refusal, type Result, refuse } from "./result.js";
16
+
17
+ /** A content control of the body: a place a template leaves to be filled. */
18
+ export interface Control {
19
+ /** Its own name in the document: what `fillControl` takes to fill this control and no other. */
20
+ id: string;
21
+ /**
22
+ * Its tag, or its title when it has no tag, or its id. `fillControl` takes it too; controls
23
+ * that share a tag are all filled by it.
24
+ */
25
+ name: string;
26
+ tag?: string;
27
+ title?: string;
28
+ kind: ControlValue["kind"];
29
+ /**
30
+ * Text: the text. A list: the chosen item. A date: `yyyy-mm-dd`, or the text typed. A check
31
+ * box: whether it is checked. Null while it is empty, and for kinds that hold no value.
32
+ */
33
+ value: string | boolean | null;
34
+ /** It shows its placeholder: nothing was filled in yet. */
35
+ empty: boolean;
36
+ /** A drop-down list's or combo box's items, as shown. */
37
+ items?: string[];
38
+ /** Locked, or filled from bound data: it cannot be filled. */
39
+ readOnly: boolean;
40
+ /** The handle of the block it is in (the first, when it holds several). */
41
+ block: string;
42
+ }
43
+
44
+ /** A control that was not filled, with why, when others of the same name were. */
45
+ export interface Unfilled {
46
+ id: string;
47
+ name: string;
48
+ code: Refusal["code"];
49
+ message: string;
50
+ }
51
+
52
+ const FILLABLE = new Set(["text", "richText", "dropDown", "comboBox", "date", "checkbox"]);
53
+
54
+ /**
55
+ * The body's controls with what a model needs of each, in document order. Not those in a block
56
+ * that is not read (deleted as a tracked change): they are gone to the agent, as their block is.
57
+ */
58
+ function found(context: Context): Control[] {
59
+ const { editor, handles } = context;
60
+ const doc = editor.state.doc;
61
+ // A read first: handles are issued in the document's order, whatever is asked first.
62
+ const read = new Set(readBlocks(editor.state, handles).map((block) => block.handle));
63
+ const ranges = new Map<string, ReturnType<typeof controlsIn>[number]>();
64
+ // The first range of an id, as `controlValues` reports the first.
65
+ for (const range of controlsIn(doc)) if (!ranges.has(range.id)) ranges.set(range.id, range);
66
+ const out: Control[] = [];
67
+ for (const value of controlValues(editor.state)) {
68
+ const range = ranges.get(value.id);
69
+ const properties = controlProperties(editor.state, value.id);
70
+ if (!range || !properties) continue;
71
+ // The innermost block around the control's content: a paragraph, for all but a row's.
72
+ const $from = doc.resolve(range.contentFrom);
73
+ let depth = $from.depth;
74
+ while (depth > 1 && !$from.node(depth).isBlock) depth--;
75
+ const pos = depth > 0 ? $from.before(depth) : range.from;
76
+ const node = doc.nodeAt(pos);
77
+ if (!node) continue;
78
+ const block = handles.at(pos, node);
79
+ if (!read.has(block)) continue;
80
+ const control: Control = {
81
+ id: value.id,
82
+ name: value.tag || value.title || value.id,
83
+ kind: value.kind,
84
+ value: value.value,
85
+ empty: value.showingPlaceholder,
86
+ readOnly: controlIsReadOnly(properties),
87
+ block,
88
+ };
89
+ if (value.tag) control.tag = value.tag;
90
+ if (value.title) control.title = value.title;
91
+ if (properties.items) control.items = properties.items.map((i) => i.display ?? i.value);
92
+ out.push(control);
93
+ }
94
+ return out;
95
+ }
96
+
97
+ /** @internal */
98
+ export function controls(context: Context): Control[] {
99
+ return found(context);
100
+ }
101
+
102
+ const same = (a: string | undefined, b: string) => a?.trim().toLowerCase() === b;
103
+ const isDay = (text: string) => {
104
+ const day = new Date(`${text}T00:00:00Z`);
105
+ return !Number.isNaN(day.getTime()) && day.toISOString().slice(0, 10) === text;
106
+ };
107
+
108
+ /** Why `control` does not take `value`, known before trying; null when it may. */
109
+ function unfit(control: Control, value: string | boolean | null): Refusal | null {
110
+ const label = JSON.stringify(control.name);
111
+ if (control.readOnly)
112
+ return refuse("read-only", `The control ${label} is locked: it cannot be filled.`);
113
+ if (!FILLABLE.has(control.kind))
114
+ return refuse(
115
+ "read-only",
116
+ `The control ${label} is a ${control.kind} control: it holds no value to fill.`,
117
+ );
118
+ if (control.kind === "checkbox")
119
+ return typeof value === "boolean"
120
+ ? null
121
+ : refuse("invalid", `The control ${label} is a check box: its value is true or false.`);
122
+ if (typeof value === "boolean")
123
+ return refuse("invalid", `The control ${label} takes text, not true or false.`);
124
+ if (control.kind === "dropDown" && value && !control.items?.includes(value))
125
+ return refuse(
126
+ "invalid",
127
+ `The control ${label} is a drop-down list: its value is one of ${(control.items ?? []).map((i) => JSON.stringify(i)).join(", ")}.`,
128
+ );
129
+ if (control.kind === "date" && value && /^\d{4}-\d{2}-\d{2}$/.test(value) && !isDay(value))
130
+ return refuse("invalid", `${JSON.stringify(value)} is not a day of the calendar.`);
131
+ return null;
132
+ }
133
+
134
+ /** @internal */
135
+ export function fillControl(
136
+ context: Context,
137
+ name: string,
138
+ value: string | boolean | null,
139
+ ): Result<Changed & { controls: Control[]; unfilled: Unfilled[] }> {
140
+ const { editor } = context;
141
+ if (typeof name !== "string")
142
+ return refuse("invalid", "A content control is named by its id, tag or title, a string.");
143
+ if (value !== null && typeof value !== "string" && typeof value !== "boolean")
144
+ return refuse("invalid", "A control's value is text, true or false, or null to empty it.");
145
+ const all = found(context);
146
+ const wanted = name.trim().toLowerCase();
147
+ // Its id names one control; a tag every control that has it; then a title.
148
+ const targets = [
149
+ all.filter((c) => c.id === name),
150
+ all.filter((c) => same(c.tag, wanted)),
151
+ all.filter((c) => same(c.title, wanted)),
152
+ ].find((group) => group.length);
153
+ if (!targets) {
154
+ const names = all.map((c) => c.name);
155
+ return refuse(
156
+ "unknown-control",
157
+ names.length
158
+ ? `There is no content control ${JSON.stringify(name)}. The controls are: ${names.join(", ")}.`
159
+ : "The document has no content controls.",
160
+ );
161
+ }
162
+ const filled: string[] = [];
163
+ const unfilled: Unfilled[] = [];
164
+ for (const control of targets) {
165
+ // "true" and "false" are a check box's values too; each control reads the value its way.
166
+ const input =
167
+ control.kind === "checkbox" && (value === "true" || value === "false")
168
+ ? value === "true"
169
+ : value;
170
+ const why =
171
+ unfit(control, input) ??
172
+ // The value it has: nothing to record.
173
+ (control.value === input || (control.empty && (input === null || input === ""))
174
+ ? null
175
+ : editor.run(setControlValue(control.id, input))
176
+ ? null
177
+ : refuse("refused", `The control ${JSON.stringify(control.name)} could not be filled.`));
178
+ if (why)
179
+ unfilled.push({ id: control.id, name: control.name, code: why.code, message: why.message });
180
+ else filled.push(control.block);
181
+ }
182
+ const first = unfilled[0];
183
+ if (!filled.length && first) return refuse(first.code, first.message);
184
+ const ids = new Set(targets.map((t) => t.id));
185
+ const result = changed(context, filled);
186
+ if (unfilled.length) result.text += `\nNot filled: ${unfilled.map((u) => u.message).join(" ")}`;
187
+ return {
188
+ ok: true,
189
+ ...result,
190
+ controls: found(context).filter((c) => ids.has(c.id)),
191
+ unfilled,
192
+ };
193
+ }
194
+
195
+ export interface UpdateFieldsOptions {
196
+ /**
197
+ * Values for the document's merge fields (`«Name»` in a read), by field name, capitals not
198
+ * counting: text, numbers, true or false, dates.
199
+ */
200
+ data?: Readonly<Record<string, string | number | boolean | Date | null>>;
201
+ }
202
+
203
+ const count = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
204
+
205
+ /** @internal */
206
+ export function updateFields(
207
+ context: Context,
208
+ options: UpdateFieldsOptions = {},
209
+ ): Result<FieldsReport & { text: string }> {
210
+ const given = options?.data;
211
+ if (given !== undefined && (given === null || typeof given !== "object" || Array.isArray(given)))
212
+ return refuse("invalid", "data must be an object: merge field names with their values.");
213
+ for (const [key, value] of Object.entries(given ?? {}))
214
+ if (value !== null && !(value instanceof Date) && typeof value === "object")
215
+ return refuse("invalid", `data.${key} must be text, a number, true or false, or a date.`);
216
+ const report = updateFieldsOf(context.editor, given ? { data: given } : {});
217
+
218
+ // What was left, said for a model: by reason, the body's only (the session reads no other).
219
+ const body = report.skipped.filter((s) => s.story === null);
220
+ const pages = body.filter((s) => s.reason === "no-layout").length;
221
+ const noData = new Set(body.filter((s) => s.reason === "no-data").map((s) => s.detail ?? ""));
222
+ // Without data core leaves merge fields alone and does not report them: name them.
223
+ if (!given)
224
+ for (const field of fieldsIn(context.editor.state.doc)) {
225
+ const { name, args } = parseFieldInstruction(field.instruction);
226
+ if (name.toUpperCase() === "MERGEFIELD" && args[0]) noData.add(args[0]);
227
+ }
228
+ noData.delete("");
229
+ const others = body
230
+ .filter((s) => s.reason !== "no-layout" && s.reason !== "no-data")
231
+ .map((s) => `${s.instruction.trim()} (${s.reason}${s.detail ? `: ${s.detail}` : ""})`);
232
+ const done = report.updated + report.rebuilt;
233
+ const text = [
234
+ `${count(done, "field")} updated, ${report.unchanged} unchanged.`,
235
+ ...(noData.size ? [`Merge fields without data: ${[...noData].join(", ")}.`] : []),
236
+ ...(pages
237
+ ? [`${count(pages, "page number")} left: they need a page layout the session does not have.`]
238
+ : []),
239
+ ...(others.length ? [`Left as they were: ${others.join("; ")}.`] : []),
240
+ ...(done ? ["Read again to see the text."] : []),
241
+ ].join(" ");
242
+ return { ok: true, ...report, text };
243
+ }