@graview/tools 0.1.63 → 0.1.65

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.
Files changed (60) hide show
  1. package/dist/ai.d.ts +19 -0
  2. package/dist/ai.d.ts.map +1 -1
  3. package/dist/ai.js.map +1 -1
  4. package/dist/dev-ai.d.ts +4 -0
  5. package/dist/dev-ai.d.ts.map +1 -1
  6. package/dist/dev-ai.js +104 -8
  7. package/dist/dev-ai.js.map +1 -1
  8. package/dist/draft.d.ts +1 -0
  9. package/dist/draft.d.ts.map +1 -1
  10. package/dist/draft.js +2 -0
  11. package/dist/draft.js.map +1 -1
  12. package/dist/facts.d.ts +24 -0
  13. package/dist/facts.d.ts.map +1 -0
  14. package/dist/facts.js +48 -0
  15. package/dist/facts.js.map +1 -0
  16. package/dist/graph-plan.d.ts +178 -0
  17. package/dist/graph-plan.d.ts.map +1 -0
  18. package/dist/graph-plan.js +570 -0
  19. package/dist/graph-plan.js.map +1 -0
  20. package/dist/inline-ai.d.ts +41 -2
  21. package/dist/inline-ai.d.ts.map +1 -1
  22. package/dist/inline-ai.js +423 -12
  23. package/dist/inline-ai.js.map +1 -1
  24. package/dist/reshape.d.ts +55 -2
  25. package/dist/reshape.d.ts.map +1 -1
  26. package/dist/reshape.js +2 -0
  27. package/dist/reshape.js.map +1 -1
  28. package/dist/say-change.d.ts +59 -0
  29. package/dist/say-change.d.ts.map +1 -0
  30. package/dist/say-change.js +156 -0
  31. package/dist/say-change.js.map +1 -0
  32. package/dist/section.d.ts +120 -0
  33. package/dist/section.d.ts.map +1 -0
  34. package/dist/section.js +351 -0
  35. package/dist/section.js.map +1 -0
  36. package/dist/sentences.d.ts +13 -0
  37. package/dist/sentences.d.ts.map +1 -0
  38. package/dist/sentences.js +30 -0
  39. package/dist/sentences.js.map +1 -0
  40. package/dist/suggest.js +2 -2
  41. package/dist/suggest.js.map +1 -1
  42. package/dist/workflows/run-agent.d.ts.map +1 -1
  43. package/dist/workflows/run-agent.js +8 -4
  44. package/dist/workflows/run-agent.js.map +1 -1
  45. package/dist/workflows/run-classify.d.ts.map +1 -1
  46. package/dist/workflows/run-classify.js +22 -9
  47. package/dist/workflows/run-classify.js.map +1 -1
  48. package/dist/workflows/run.d.ts +1 -1
  49. package/dist/workflows/run.d.ts.map +1 -1
  50. package/dist/workflows/run.js +40 -2
  51. package/dist/workflows/run.js.map +1 -1
  52. package/dist/workflows/types.d.ts +51 -2
  53. package/dist/workflows/types.d.ts.map +1 -1
  54. package/dist/workflows/types.js +2 -1
  55. package/dist/workflows/types.js.map +1 -1
  56. package/dist/workflows.d.ts +2 -1
  57. package/dist/workflows.d.ts.map +1 -1
  58. package/dist/workflows.js +1 -0
  59. package/dist/workflows.js.map +1 -1
  60. package/package.json +7 -3
@@ -0,0 +1,156 @@
1
+ import { labelOf, nodeRefArgs, pluralOf } from "@graview/core";
2
+ import { peopleKinds } from "./graph-plan.js";
3
+ const DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
4
+ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
5
+ /** "2026-09-07" → "Monday, Sep 7". */
6
+ export function dayWords(value) {
7
+ const day = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
8
+ if (!day)
9
+ return undefined;
10
+ const at = new Date(Date.UTC(Number(day[1]), Number(day[2]) - 1, Number(day[3])));
11
+ return `${DAYS[at.getUTCDay()]}, ${MONTHS[at.getUTCMonth()]} ${at.getUTCDate()}`;
12
+ }
13
+ /** The change said as one sentence, its values and its count in it. */
14
+ export function sayChange(store, change) {
15
+ const schema = store.schema;
16
+ /*
17
+ * ONE RECORD: the act's own sentence for it, where the app wrote one
18
+ * ("Bo Ferreira steps back", "Move "Book the van" to Today"), its quotes
19
+ * made a person's and its days said by name. A title is not a sentence
20
+ * about a record: "They have stepped back" read as "They Bo Ferreira…".
21
+ */
22
+ if (change.records.length === 1 && typeof change.act.describe === "function" && change.act.subject) {
23
+ try {
24
+ const said = change.act.describe({ ...change.args, [change.act.subject.arg]: change.records[0] }, store.graph);
25
+ if (typeof said === "string" && said.trim()) {
26
+ // A record's name in quotes, so it is never read as the act's own words ("Move “Move the broadband” to Someday"); a person's name as it is.
27
+ const people = peopleKinds(store);
28
+ // The record acted on is quoted; where it goes ("to Someday") is said as it is.
29
+ const named = [change.records[0]]
30
+ .filter((id) => store.graph.getNode(id) !== undefined)
31
+ .map((id) => store.graph.getNode(id))
32
+ .filter((node) => !people.includes(node.kind))
33
+ .map((node) => labelOf(schema.tryDefinition(node.kind), node))
34
+ .sort((a, b) => b.length - a.length);
35
+ let quoted = said.trim().replace(/"([^"]*)"/g, "“$1”");
36
+ for (const name of named)
37
+ if (!quoted.includes(`“${name}”`))
38
+ quoted = quoted.replace(name, `“${name}”`);
39
+ const words = quoted
40
+ .replace(/\b(\d{4}-\d{2}-\d{2})\b/g, (day) => dayWords(day) ?? day)
41
+ .replace(/[.!]+$/, "");
42
+ return `${words.charAt(0).toUpperCase()}${words.slice(1)}.`;
43
+ }
44
+ }
45
+ catch {
46
+ // A sentence that could not be written for these values: the title, said below.
47
+ }
48
+ }
49
+ const nameOf = (id) => {
50
+ const node = store.graph.getNode(id);
51
+ return node ? labelOf(schema.tryDefinition(node.kind), node) : undefined;
52
+ };
53
+ const refs = nodeRefArgs(change.act.input);
54
+ const subject = change.act.subject?.arg;
55
+ // The values, said: a record by its name, a day by its name, words in quotes, a number as it is.
56
+ const values = Object.entries(change.args)
57
+ .filter(([arg, value]) => arg !== subject && value !== undefined && value !== null && value !== "")
58
+ .map(([arg, value]) => {
59
+ const ref = refs.find((one) => one.name === arg);
60
+ if (ref && typeof value === "string") {
61
+ const node = store.graph.getNode(value);
62
+ const name = nameOf(value) ?? value;
63
+ return { arg, said: node ? name : value, ref: true };
64
+ }
65
+ if (typeof value === "string")
66
+ return { arg, said: dayWords(value) ?? `“${value}”`, ref: false };
67
+ return { arg, said: String(value), ref: false };
68
+ });
69
+ const first = change.records[0] ? store.graph.getNode(change.records[0]) : undefined;
70
+ const kind = first?.kind;
71
+ const noun = kind ? (schema.tryDefinition(kind)?.noun ?? kind).toLowerCase() : "record";
72
+ const count = change.records.length;
73
+ const object = change.itself && count === 1 && change.records[0]
74
+ ? (nameOf(change.records[0]) ? `“${nameOf(change.records[0])}”` : "it")
75
+ : `the ${count}${change.narrowed ? ` ${change.narrowed}` : ""} ${count === 1 ? noun : (kind ? pluralOf(schema, kind).toLowerCase() : "records")}${change.where ? ` ${change.where}` : ""}`;
76
+ let words = (change.act.title ?? change.act.name).trim().replace(/[.!]+$/, "");
77
+ // The records: where the title says "it" (or "the task", "this"), else just after its first word.
78
+ const pronoun = /\b(it|this|the (?:task|list|shift|record|song|item))\b/i;
79
+ // A title that is a sentence about its record ("They have stepped back", "It is done"): the record in the pronoun's place.
80
+ if (/^(they|it|this|she|he|somebody|someone)\b/i.test(words)) {
81
+ words = words.replace(/^(they|it|this|she|he|somebody|someone)\b/i, object).replace(/^(\S.*?)\s+\b(have|are)\b/i, (_, who, verb) => `${who} ${count === 1 ? (verb.toLowerCase() === "have" ? "has" : "is") : verb}`);
82
+ return `${words.charAt(0).toUpperCase()}${words.slice(1)}.`;
83
+ }
84
+ // "Move the date" acts on a part of each: "Move the date of the 5 tasks in This week".
85
+ words = pronoun.test(words) ? words.replace(pronoun, object) : /^\S+ the \w+$/i.test(words) ? `${words} of ${object}` : words.replace(/^(\S+)/, `$1 ${object}`);
86
+ // The values: in place of "another …" where the title says so, else "to …", or "with …" for a person.
87
+ for (const value of values) {
88
+ if (/\b(?:to|into|on) another \w+/i.test(words))
89
+ words = words.replace(/\b(to|into|on) another \w+/i, `$1 ${value.said}`);
90
+ else if (/\banother \w+/i.test(words))
91
+ words = words.replace(/\banother \w+/i, value.said);
92
+ else
93
+ words = `${words} ${value.ref && !/\bto\b/i.test(words) && /^(cover|assign|give)/i.test(words) ? "with" : "to"} ${value.said}`;
94
+ }
95
+ return `${words.charAt(0).toUpperCase()}${words.slice(1)}.`;
96
+ }
97
+ /**
98
+ * NOTHING TO CHANGE, SAID FROM THE RECORDS: where every record is already as
99
+ * the act would leave it, the card says what each already is — "“Order
100
+ * boxes” is already done.", "Ada Nowak's status is already available." —
101
+ * from the fields the act writes and their values now, never the act's
102
+ * title in quotes or a record "itself".
103
+ */
104
+ export function sayNothingToChange(store, act, records) {
105
+ const schema = store.schema;
106
+ const people = peopleKinds(store);
107
+ const nameOf = (id) => {
108
+ const node = store.graph.getNode(id);
109
+ if (!node)
110
+ return id;
111
+ const name = labelOf(schema.tryDefinition(node.kind), node);
112
+ return people.includes(node.kind) ? name : `“${name}”`;
113
+ };
114
+ const field = act.writes?.[0];
115
+ const first = records[0] ? store.graph.getNode(records[0]) : undefined;
116
+ const value = field && first ? first[field] : undefined;
117
+ const who = records.length === 1 ? nameOf(records[0]) : `All ${records.length} of them`;
118
+ const are = records.length === 1 ? "is" : "are";
119
+ if (field && typeof value === "boolean")
120
+ return `Nothing to change: ${who} ${are} already ${value ? "" : "not "}${field.replace(/[A-Z]/g, (letter) => ` ${letter.toLowerCase()}`)}.`;
121
+ if (field && (typeof value === "string" || typeof value === "number"))
122
+ return `Nothing to change: ${records.length === 1 ? `${who}'s` : "their"} ${field.replace(/[A-Z]/g, (letter) => ` ${letter.toLowerCase()}`)} ${are === "is" ? "is" : "are"} already ${dayWords(String(value)) ?? value}.`;
123
+ return `Nothing to change: ${who} ${are} already as that would leave ${records.length === 1 ? "it" : "them"}.`;
124
+ }
125
+ /** Said where an instruction found nothing here to do it with. */
126
+ export const CANNOT_DO_IT = "I can't do that here: nothing in this app does what you asked. Try saying it another way.";
127
+ /** Words that tell of a change as made ("is taken off the shift", "has been moved", "Marked it done"), with no "can't" or "not" in them. */
128
+ export function saysDone(text) {
129
+ if (/\b(can'?t|cannot|couldn'?t|won'?t|not|no|isn'?t|doesn'?t|don'?t|unable|nothing|never)\b/i.test(text))
130
+ return false;
131
+ return /\b(is|are|was|were|has been|have been|got|gets)\s+(now\s+)?(\w+ed|done|taken|set|put|given|made|gone|off|out|away|moved|removed)\b/i.test(text) || /^(i'?ve|i have|done|marked|moved|removed|archived|renamed|assigned|added|scheduled|deleted|dropped|finished|closed|updated|changed|set|put|took|taken)\b/i.test(text.trim()) || /\b(i'?ve|i have)\s+\w+ed\b/i.test(text);
132
+ }
133
+ /** Words that say someone or something is not here. */
134
+ const ABSENT = /\b(not in (this|the) app|isn'?t in (this|the) app|is not in (this|the) app|not (yet )?(a|one of the) (user|member|person|people|volunteer|record)s?|doesn'?t exist|does not exist|no one (called|named)|nobody (called|named)|not found|no such|there is no|there'?s no|no (user|person|member|volunteer|record|one) (called|named))\b/i;
135
+ /**
136
+ * NEVER SOMETHING FALSE ABOUT THE APP: the records an answer says are not
137
+ * here, where the graph holds them — "Sam is not in this app yet" while Sam
138
+ * is one of its users. Answers the records it named and said were absent.
139
+ */
140
+ export function claimedAbsent(store, text) {
141
+ if (!ABSENT.test(text))
142
+ return [];
143
+ const schema = store.schema;
144
+ const people = peopleKinds(store);
145
+ const words = text.toLowerCase();
146
+ return store.graph
147
+ .allNodes()
148
+ .flatMap((node) => {
149
+ const name = labelOf(schema.tryDefinition(node.kind), node);
150
+ const first = name.split(/\s+/)[0];
151
+ const named = name.length >= 3 && (words.includes(name.toLowerCase()) || (people.includes(node.kind) && first.length >= 3 && new RegExp(`\\b${first.toLowerCase().replace(/[^\p{L}\p{N}]/gu, "")}\\b`, "u").test(words)));
152
+ return named ? [{ id: node.id, name, kind: node.kind }] : [];
153
+ })
154
+ .slice(0, 5);
155
+ }
156
+ //# sourceMappingURL=say-change.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"say-change.js","sourceRoot":"","sources":["../src/say-change.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,QAAQ,EAA8B,MAAM,eAAe,CAAC;AAC3F,OAAO,EAAE,WAAW,EAAE,MAAM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EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAC/D,CAAC,CAAC;SACD,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AACjB,CAAC"}
@@ -0,0 +1,120 @@
1
+ import type { HostAi, ThinkingReply } from "./ai.js";
2
+ /** A span of the script, by offsets: `[start, end)`. */
3
+ export interface SourceSpan {
4
+ readonly start: number;
5
+ readonly end: number;
6
+ }
7
+ /** One rule of the view's stylesheet, where it stands in the script. */
8
+ export interface SectionRule extends SourceSpan {
9
+ readonly selector: string;
10
+ readonly text: string;
11
+ /** The stylesheet string it is in (its index among the script's `graview.style` strings). */
12
+ readonly sheet: number;
13
+ }
14
+ /** A stylesheet string the script hands `graview.style`: where its text stands, and how it is quoted. */
15
+ export interface StyleString extends SourceSpan {
16
+ readonly quote: "`" | '"' | "'";
17
+ }
18
+ /** A section found in a view's script. */
19
+ export interface LocatedSection {
20
+ /** Its name, as found. */
21
+ readonly name: string;
22
+ /** Its markup, whole: from its opening tag to its closing one (or a heading to the next as high). */
23
+ readonly markup: SourceSpan & {
24
+ readonly text: string;
25
+ };
26
+ /** The rules that style only it: replaced with what the model answers. */
27
+ readonly rules: readonly SectionRule[];
28
+ /** Rules that style it and something else too: told, never changed. */
29
+ readonly shared: readonly SectionRule[];
30
+ /** The classes and ids its markup draws (`.name`, `#name`). */
31
+ readonly names: readonly string[];
32
+ /** The script's stylesheet strings. */
33
+ readonly sheets: readonly StyleString[];
34
+ }
35
+ /** The section revised, as the model answers it. */
36
+ export interface SectionRevised {
37
+ readonly markup: string;
38
+ readonly css: string;
39
+ readonly said: string;
40
+ }
41
+ /** The `graview.style(…)` strings of a script: where each one's text stands, and its quote. */
42
+ export declare function styleStringsOf(source: string): StyleString[];
43
+ /**
44
+ * THE SECTION, FOUND IN THE VIEW'S SCRIPT: the element named so — marked
45
+ * `data-section`, a landmark by its label or its heading — innermost
46
+ * first, else the block a heading of those words begins; and the rules
47
+ * that style it. Undefined when the script draws no section of that name.
48
+ */
49
+ export declare function locateSection(source: string, name: string): LocatedSection | undefined;
50
+ /**
51
+ * THE VIEW COMPOSED WHOLE WITH ITS SECTION REVISED: the section's markup
52
+ * replaced, the rules that styled only it replaced by the revision's where
53
+ * the first of them stood (else added to the script's first stylesheet, or
54
+ * a stylesheet of its own at the top), and every other byte as it was.
55
+ */
56
+ export declare function composeSection(source: string, located: LocatedSection, revised: Pick<SectionRevised, "markup" | "css">): string;
57
+ /** How a person asked: the model alone, in their words, or in their words about the part they pointed at. */
58
+ export type SectionMode = "just" | "describe" | "highlight";
59
+ export declare const SECTION_SYSTEM: string;
60
+ /** What the model is asked, as one JSON prompt. */
61
+ export declare function sectionPrompt(ask: {
62
+ readonly located: LocatedSection;
63
+ readonly mode: SectionMode;
64
+ readonly words?: string;
65
+ readonly highlighted?: readonly string[];
66
+ readonly theme?: Readonly<Record<string, string>>;
67
+ readonly shows?: string;
68
+ readonly findings?: readonly string[];
69
+ readonly last?: SectionRevised;
70
+ }): string;
71
+ /** The model's answer read: the section's markup, its rules and the sentence; undefined when it is none of those. */
72
+ export declare function readSectionReply(text: string): SectionRevised | undefined;
73
+ /** Each model asked, timed, and what it spent. */
74
+ export interface SectionStage {
75
+ readonly stage: "light" | "thinking";
76
+ readonly model: string;
77
+ readonly ms: number;
78
+ readonly usage?: ThinkingReply["usage"];
79
+ }
80
+ export interface ReviseSectionOptions {
81
+ readonly ai: HostAi;
82
+ /** The view's whole script, as it draws now. */
83
+ readonly source: string;
84
+ /** The section, by the name the menu said. */
85
+ readonly section: string;
86
+ readonly mode: SectionMode;
87
+ /** The person's words: "What should change?". */
88
+ readonly words?: string;
89
+ /** What they pointed at, in words ("the three day columns"). */
90
+ readonly highlighted?: readonly string[];
91
+ readonly theme?: Readonly<Record<string, string>>;
92
+ /** The words the section shows now. */
93
+ readonly shows?: string;
94
+ /**
95
+ * THE PAGE'S JUDGMENT of a composed view: the findings that keep it from
96
+ * being offered (empty when it may be), in sentences — drawn as a draft,
97
+ * the host's own checks, compared with what it replaces.
98
+ */
99
+ readonly judge: (source: string) => Promise<readonly string[]>;
100
+ }
101
+ export type ReviseSectionResult = {
102
+ readonly ok: true;
103
+ readonly source: string;
104
+ readonly said: string;
105
+ readonly located: LocatedSection;
106
+ readonly repaired: boolean;
107
+ readonly stages: readonly SectionStage[];
108
+ } | {
109
+ readonly ok: false;
110
+ readonly refused: string;
111
+ readonly stages: readonly SectionStage[];
112
+ };
113
+ /**
114
+ * REVISE A SECTION: the light model first — the full one where the light
115
+ * one's answer cannot be read — composed whole and judged; what fails is
116
+ * handed back once, with the findings, to the full model; what fails again
117
+ * is refused in words. Nothing is kept here: the page offers what passes.
118
+ */
119
+ export declare function reviseSection(options: ReviseSectionOptions): Promise<ReviseSectionResult>;
120
+ //# sourceMappingURL=section.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"section.d.ts","sourceRoot":"","sources":["../src/section.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAoB,aAAa,EAAE,MAAM,SAAS,CAAC;AAwBvE,wDAAwD;AACxD,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACtB;AAED,wEAAwE;AACxE,MAAM,WAAW,WAAY,SAAQ,UAAU;IAC7C,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,6FAA6F;IAC7F,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACxB;AAED,yGAAyG;AACzG,MAAM,WAAW,WAAY,SAAQ,UAAU;IAC7C,QAAQ,CAAC,KAAK,EAAE,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC;CACjC;AAED,0CAA0C;AAC1C,MAAM,WAAW,cAAc;IAC7B,0BAA0B;IAC1B,QAAQ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AuC;IACvC,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB;;;;OAIG;IACH,QAAQ,CAAC,KAAK,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,SAAS,MAAM,EAAE,CAAC,CAAC;CAChE;AAED,MAAM,MAAM,mBAAmB,GAC3B;IAAE,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,cAAc,CAAC;IAAC,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,SAAS,YAAY,EAAE,CAAA;CAAE,GAC7K;IAAE,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,SAAS,YAAY,EAAE,CAAA;CAAE,CAAC;AAE/F;;;;;GAKG;AACH,wBAAsB,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAoC/F"}
@@ -0,0 +1,351 @@
1
+ import { thinkingOf } from "./inline-ai.js";
2
+ const VOID = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]);
3
+ const LANDMARKS = new Set(["section", "article", "nav", "aside", "header", "footer", "main", "form", "search"]);
4
+ const HEADING = /^h([1-6])$/;
5
+ /* A tag: its name, and attributes that may hold quoted values and `${…}` interpolations. */
6
+ const TAG = /<(\/?)([a-zA-Z][\w-]*)((?:"[^"]*"|'[^']*'|\$\{(?:[^{}]|\{[^{}]*\})*\}|[^>"'$]|\$(?!\{))*)>/g;
7
+ const said = (text) => text.replace(/\s+/g, " ").trim();
8
+ const plain = (markup) => said(markup.replace(/\$\{(?:[^{}]|\{[^{}]*\})*\}/g, " ").replace(/<[^>]*>/g, " "));
9
+ const same = (a, b) => said(a).toLowerCase() === said(b).toLowerCase();
10
+ function tagsOf(source) {
11
+ const tags = [];
12
+ for (const match of source.matchAll(TAG)) {
13
+ const name = match[2].toLowerCase();
14
+ const attrs = match[3] ?? "";
15
+ tags.push({ start: match.index, end: match.index + match[0].length, name, closing: match[1] === "/", attrs: VOID.has(name) || attrs.trimEnd().endsWith("/") ? `${attrs}\u0000void` : attrs });
16
+ }
17
+ return tags;
18
+ }
19
+ const isVoid = (tag) => VOID.has(tag.name) || tag.attrs.endsWith("\u0000void");
20
+ /** An attribute's literal value in a tag, if it has one. */
21
+ function attrOf(tag, name) {
22
+ const match = new RegExp(`(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'>]+))`, "i").exec(tag.attrs);
23
+ const value = match ? (match[1] ?? match[2] ?? match[3]) : undefined;
24
+ return value === undefined || value.includes("${") ? undefined : value;
25
+ }
26
+ /** The index of the tag that closes the one at `at`, or -1. */
27
+ function closeOf(tags, at) {
28
+ const open = tags[at];
29
+ let depth = 0;
30
+ for (let index = at + 1; index < tags.length; index++) {
31
+ const tag = tags[index];
32
+ if (tag.name !== open.name || isVoid(tag))
33
+ continue;
34
+ if (!tag.closing)
35
+ depth += 1;
36
+ else if (depth === 0)
37
+ return index;
38
+ else
39
+ depth -= 1;
40
+ }
41
+ return -1;
42
+ }
43
+ /** The words of the element whose `id` is this, in the script. */
44
+ function textOfId(source, tags, id) {
45
+ const at = tags.findIndex((tag) => !tag.closing && attrOf(tag, "id") === id);
46
+ if (at < 0)
47
+ return undefined;
48
+ const close = closeOf(tags, at);
49
+ return close < 0 ? undefined : plain(source.slice(tags[at].end, tags[close].start));
50
+ }
51
+ /** A landmark's name in the script, as `sectionUnder` names it on the page. */
52
+ function landmarkName(source, tags, at, close) {
53
+ const tag = tags[at];
54
+ const marked = attrOf(tag, "data-section");
55
+ if (marked)
56
+ return said(marked);
57
+ const label = attrOf(tag, "aria-label");
58
+ if (label)
59
+ return said(label);
60
+ const by = attrOf(tag, "aria-labelledby");
61
+ if (by) {
62
+ const named = by
63
+ .split(/\s+/)
64
+ .filter(Boolean)
65
+ .map((id) => textOfId(source, tags, id) ?? "")
66
+ .filter(Boolean)
67
+ .join(" ");
68
+ if (named)
69
+ return named;
70
+ }
71
+ for (let index = at + 1; index < close; index++) {
72
+ const inner = tags[index];
73
+ if (inner.closing || !HEADING.test(inner.name))
74
+ continue;
75
+ const end = closeOf(tags, index);
76
+ if (end > 0)
77
+ return plain(source.slice(inner.end, tags[end].start));
78
+ }
79
+ return "";
80
+ }
81
+ /** The `graview.style(…)` strings of a script: where each one's text stands, and its quote. */
82
+ export function styleStringsOf(source) {
83
+ const sheets = [];
84
+ for (const match of source.matchAll(/graview\.style\(\s*([`"'])/g)) {
85
+ const quote = match[1];
86
+ const start = match.index + match[0].length;
87
+ let at = start;
88
+ while (at < source.length && source[at] !== quote)
89
+ at += source[at] === "\\" ? 2 : 1;
90
+ if (at < source.length)
91
+ sheets.push({ start, end: at, quote });
92
+ }
93
+ return sheets;
94
+ }
95
+ /** The rules of a stylesheet, at the top level: an at-rule's block is one rule, named by the selectors inside it. */
96
+ function rulesOf(css, offset, sheet) {
97
+ const rules = [];
98
+ let at = 0;
99
+ while (at < css.length) {
100
+ const open = css.indexOf("{", at);
101
+ if (open < 0)
102
+ break;
103
+ let depth = 0;
104
+ let close = open;
105
+ for (; close < css.length; close++) {
106
+ if (css[close] === "{")
107
+ depth += 1;
108
+ else if (css[close] === "}" && --depth === 0)
109
+ break;
110
+ }
111
+ if (close >= css.length)
112
+ break;
113
+ // The rule begins after whitespace and comments.
114
+ let start = at;
115
+ while (start < open && /\s/.test(css[start]))
116
+ start += 1;
117
+ while (css.startsWith("/*", start)) {
118
+ const done = css.indexOf("*/", start);
119
+ start = done < 0 ? open : done + 2;
120
+ while (start < open && /\s/.test(css[start]))
121
+ start += 1;
122
+ }
123
+ const head = css.slice(start, open).trim();
124
+ const selector = head.startsWith("@") ? [...css.slice(open + 1, close).matchAll(/([^{}]+)\{/g)].map((inner) => inner[1].trim()).join(", ") : head;
125
+ rules.push({ start: offset + start, end: offset + close + 1, selector, text: css.slice(start, close + 1), sheet });
126
+ at = close + 1;
127
+ }
128
+ return rules;
129
+ }
130
+ /** The classes (`.name`) and ids (`#name`) a selector names. */
131
+ const namesIn = (selector) => [...selector.replace(/\[[^\]]*\]|:[\w-]+\([^)]*\)/g, " ").matchAll(/([.#])(-?[_a-zA-Z][\w-]*)/g)].map((match) => `${match[1]}${match[2]}`);
132
+ /** The classes and ids markup draws, as written (interpolated ones left out). */
133
+ function namesDrawn(markup) {
134
+ const names = new Set();
135
+ for (const tag of tagsOf(markup)) {
136
+ if (tag.closing)
137
+ continue;
138
+ const classes = /(?:^|\s)class\s*=\s*(?:"([^"]*)"|'([^']*)')/i.exec(tag.attrs);
139
+ for (const one of (classes?.[1] ?? classes?.[2] ?? "").replace(/\$\{(?:[^{}]|\{[^{}]*\})*\}/g, " ").split(/\s+/))
140
+ if (one)
141
+ names.add(`.${one}`);
142
+ const id = attrOf(tag, "id");
143
+ if (id)
144
+ names.add(`#${id}`);
145
+ }
146
+ return names;
147
+ }
148
+ /**
149
+ * THE SECTION, FOUND IN THE VIEW'S SCRIPT: the element named so — marked
150
+ * `data-section`, a landmark by its label or its heading — innermost
151
+ * first, else the block a heading of those words begins; and the rules
152
+ * that style it. Undefined when the script draws no section of that name.
153
+ */
154
+ export function locateSection(source, name) {
155
+ const tags = tagsOf(source);
156
+ let markup;
157
+ let best = Infinity;
158
+ for (let at = 0; at < tags.length; at++) {
159
+ const tag = tags[at];
160
+ if (tag.closing || isVoid(tag))
161
+ continue;
162
+ const candidate = LANDMARKS.has(tag.name) || attrOf(tag, "data-section") !== undefined || attrOf(tag, "role") === "region";
163
+ if (!candidate)
164
+ continue;
165
+ const close = closeOf(tags, at);
166
+ if (close < 0)
167
+ continue;
168
+ const end = tags[close].end;
169
+ if (end - tag.start < best && same(landmarkName(source, tags, at, close), name)) {
170
+ best = end - tag.start;
171
+ markup = { start: tag.start, end, text: source.slice(tag.start, end) };
172
+ }
173
+ }
174
+ /* A heading's block: the heading, and what follows it up to the next heading as high, or the end of what holds it. */
175
+ if (!markup) {
176
+ for (let at = 0; at < tags.length && !markup; at++) {
177
+ const tag = tags[at];
178
+ const level = HEADING.exec(tag.name);
179
+ if (tag.closing || !level)
180
+ continue;
181
+ const close = closeOf(tags, at);
182
+ if (close < 0 || !same(plain(source.slice(tag.end, tags[close].start)), name))
183
+ continue;
184
+ let depth = 0;
185
+ let end = tags[close].end;
186
+ for (let index = close + 1; index < tags.length; index++) {
187
+ const next = tags[index];
188
+ if (isVoid(next))
189
+ continue;
190
+ const higher = HEADING.exec(next.name);
191
+ if (depth === 0 && !next.closing && higher && Number(higher[1]) <= Number(level[1]))
192
+ break;
193
+ if (next.closing && depth === 0)
194
+ break;
195
+ depth += next.closing ? -1 : 1;
196
+ end = next.end;
197
+ }
198
+ markup = { start: tag.start, end, text: source.slice(tag.start, end) };
199
+ }
200
+ }
201
+ if (!markup)
202
+ return undefined;
203
+ const names = namesDrawn(markup.text);
204
+ const sheets = styleStringsOf(source);
205
+ const rules = [];
206
+ const shared = [];
207
+ sheets.forEach((sheet, index) => {
208
+ for (const rule of rulesOf(source.slice(sheet.start, sheet.end), sheet.start, index)) {
209
+ const parts = rule.selector.split(",").map((part) => namesIn(part));
210
+ const touches = parts.some((part) => part.some((one) => names.has(one)));
211
+ if (!touches)
212
+ continue;
213
+ // Its own when every selector in it names the section's markup; otherwise it styles something else too.
214
+ if (parts.every((part) => part.some((one) => names.has(one))))
215
+ rules.push(rule);
216
+ else
217
+ shared.push(rule);
218
+ }
219
+ });
220
+ return { name, markup, rules, shared, names: [...names], sheets };
221
+ }
222
+ /** Text put inside a quoted string of the script, so it stays inside it. */
223
+ function quoted(text, quote) {
224
+ if (quote === "`")
225
+ return text.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/g, "\\${");
226
+ return text.replace(/\\/g, "\\\\").replace(new RegExp(quote, "g"), `\\${quote}`).replace(/\n/g, "\\n");
227
+ }
228
+ /**
229
+ * THE VIEW COMPOSED WHOLE WITH ITS SECTION REVISED: the section's markup
230
+ * replaced, the rules that styled only it replaced by the revision's where
231
+ * the first of them stood (else added to the script's first stylesheet, or
232
+ * a stylesheet of its own at the top), and every other byte as it was.
233
+ */
234
+ export function composeSection(source, located, revised) {
235
+ const edits = [{ start: located.markup.start, end: located.markup.end, text: revised.markup }];
236
+ const css = revised.css.trim();
237
+ const [first, ...rest] = located.rules;
238
+ if (first) {
239
+ const sheet = located.sheets[first.sheet];
240
+ edits.push({ start: first.start, end: first.end, text: quoted(css, sheet.quote) });
241
+ for (const rule of rest)
242
+ edits.push({ start: rule.start, end: rule.end, text: "" });
243
+ }
244
+ else if (css) {
245
+ const sheet = located.sheets[0];
246
+ if (sheet)
247
+ edits.push({ start: sheet.end, end: sheet.end, text: quoted(`\n${css}\n`, sheet.quote) });
248
+ else
249
+ edits.push({ start: 0, end: 0, text: `graview.style(\`\n${quoted(css, "`")}\n\`);\n` });
250
+ }
251
+ edits.sort((a, b) => b.start - a.start);
252
+ let out = source;
253
+ for (const edit of edits)
254
+ out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
255
+ return out;
256
+ }
257
+ export const SECTION_SYSTEM = [
258
+ "You revise one section of a view in a Graview app.",
259
+ "The view is a plain script: it draws HTML with graview.html`…` templates and styles it with graview.style(css).",
260
+ "You are given the section's markup exactly as it stands in the script's template. It may hold ${…} interpolations: keep each one you keep exactly as written, and never name a variable that is not already in them.",
261
+ "You are given the stylesheet rules that style only this section (you rewrite them), the rules it shares with the rest of the view (never restate or change those), the app's look (its scheme and the values of its --graview-* tokens), and the words the section shows now.",
262
+ 'Answer with one JSON object and nothing else: {"markup": "<the section\'s whole new markup>", "css": "<every rule that styles it now>", "said": "<one sentence to the person saying what you changed>"}.',
263
+ "Keep the same outer element, and keep its name — its label or its heading's words — so it is still found. Show the same data. Style every class the markup uses, or stop using it. Use var(--graview-…) tokens for colors, type and corners, never colors of your own.",
264
+ "Never use import, export, require, <script>, <style>, or on…= attributes.",
265
+ ].join(" ");
266
+ /** What the model is asked, as one JSON prompt. */
267
+ export function sectionPrompt(ask) {
268
+ const asked = ask.mode === "just"
269
+ ? "Make this section better: easier to read at a glance, laid out cleanly at a phone's width and at a desk's, in the app's own look. Change no data it shows."
270
+ : (ask.words ?? "").trim();
271
+ return JSON.stringify({
272
+ section: ask.located.name,
273
+ asked,
274
+ ...(ask.mode === "highlight" && ask.highlighted?.length ? { pointed_at: ask.highlighted } : {}),
275
+ markup: ask.located.markup.text,
276
+ rules: ask.located.rules.map((rule) => rule.text),
277
+ shared_rules: ask.located.shared.map((rule) => rule.text),
278
+ ...(ask.theme ? { look: ask.theme } : {}),
279
+ ...(ask.shows ? { shows: ask.shows.slice(0, 1200) } : {}),
280
+ ...(ask.findings?.length ? { your_last_answer: ask.last, what_broke: ask.findings, repair: "Your last answer broke the view as said in what_broke. Answer again, fixing each one." } : {}),
281
+ });
282
+ }
283
+ /** The model's answer read: the section's markup, its rules and the sentence; undefined when it is none of those. */
284
+ export function readSectionReply(text) {
285
+ const fenced = /```(?:json)?\s*([\s\S]*?)```/.exec(text)?.[1] ?? text;
286
+ const start = fenced.indexOf("{");
287
+ const end = fenced.lastIndexOf("}");
288
+ if (start < 0 || end <= start)
289
+ return undefined;
290
+ try {
291
+ const parsed = JSON.parse(fenced.slice(start, end + 1));
292
+ if (typeof parsed.markup !== "string" || !parsed.markup.trim().startsWith("<"))
293
+ return undefined;
294
+ return { markup: parsed.markup.trim(), css: typeof parsed.css === "string" ? parsed.css : "", said: typeof parsed.said === "string" && parsed.said.trim() ? parsed.said.trim() : "Revised this section." };
295
+ }
296
+ catch {
297
+ return undefined;
298
+ }
299
+ }
300
+ /**
301
+ * REVISE A SECTION: the light model first — the full one where the light
302
+ * one's answer cannot be read — composed whole and judged; what fails is
303
+ * handed back once, with the findings, to the full model; what fails again
304
+ * is refused in words. Nothing is kept here: the page offers what passes.
305
+ */
306
+ export async function reviseSection(options) {
307
+ const stages = [];
308
+ const located = locateSection(options.source, options.section);
309
+ if (!located)
310
+ return { ok: false, refused: `“${options.section}” could not be found in the view's code, so it cannot be revised on its own.`, stages };
311
+ const light = options.ai.off ? undefined : options.ai.light;
312
+ const full = thinkingOf(options.ai);
313
+ const first = light ?? full;
314
+ if (!first)
315
+ return { ok: false, refused: options.ai.withoutModel ?? "Revising a section needs AI, and none is on here.", stages };
316
+ const ask = async (provider, stage, prompt) => {
317
+ const began = Date.now();
318
+ try {
319
+ const reply = await provider.think({ system: SECTION_SYSTEM, prompt, state: {}, catalog: { candidates: [] } });
320
+ stages.push({ stage, model: provider.model, ms: Date.now() - began, ...(reply.usage ? { usage: reply.usage } : {}) });
321
+ return readSectionReply(reply.text);
322
+ }
323
+ catch {
324
+ stages.push({ stage, model: provider.model, ms: Date.now() - began });
325
+ return undefined;
326
+ }
327
+ };
328
+ const base = { located, mode: options.mode, ...(options.words ? { words: options.words } : {}), ...(options.highlighted ? { highlighted: options.highlighted } : {}), ...(options.theme ? { theme: options.theme } : {}), ...(options.shows ? { shows: options.shows } : {}) };
329
+ const firstStage = light ? "light" : "thinking";
330
+ let revised = await ask(first, firstStage, sectionPrompt(base));
331
+ // The light model's answer could not be read: the full one, once.
332
+ if (!revised && light && full && full !== light)
333
+ revised = await ask(full, "thinking", sectionPrompt(base));
334
+ if (!revised)
335
+ return { ok: false, refused: "The model did not answer with a revision of this section.", stages };
336
+ let source = composeSection(options.source, located, revised);
337
+ let findings = await options.judge(source);
338
+ if (findings.length === 0)
339
+ return { ok: true, source, said: revised.said, located, repaired: false, stages };
340
+ /* Once, with what broke: the full model where there is one. */
341
+ const repairer = full ?? first;
342
+ const again = await ask(repairer, repairer === light ? "light" : "thinking", sectionPrompt({ ...base, findings, last: revised }));
343
+ if (!again)
344
+ return { ok: false, refused: `It could not be revised without breaking the view: ${findings.join(" ")}`, stages };
345
+ source = composeSection(options.source, located, again);
346
+ findings = await options.judge(source);
347
+ if (findings.length > 0)
348
+ return { ok: false, refused: `It could not be revised without breaking the view: ${findings.join(" ")}`, stages };
349
+ return { ok: true, source, said: again.said, located, repaired: true, stages };
350
+ }
351
+ //# sourceMappingURL=section.js.map