content-md 0.0.0-stage → 1.0.2
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/CHANGELOG.md +79 -0
- package/LICENSE +21 -0
- package/README.md +114 -2
- package/bin/content-md.js +36 -0
- package/data/aivoice-rates.json +79 -0
- package/data/catalogue.json +1 -0
- package/data/corrections.json +209 -0
- package/data/enriched.json +1 -0
- package/data/failures.json +1 -0
- package/data/industries.json +1437 -0
- package/data/meta.json +1 -0
- package/data/patterns.json +1 -0
- package/data/rules.json +1 -0
- package/data/screens.json +1 -0
- package/data/tone/decider.json +1668 -0
- package/data/tone/model.json +5867 -0
- package/guide/SKILL.md +274 -0
- package/guide/patterns.md +235 -0
- package/guide/rubric.md +13 -0
- package/guide/rules.md +33 -0
- package/guide/voice.md +66 -0
- package/package.json +34 -4
- package/src/aivoice.js +57 -0
- package/src/context.js +143 -0
- package/src/decider.js +109 -0
- package/src/embed.js +65 -0
- package/src/init.js +168 -0
- package/src/product.js +315 -0
- package/src/reference2.js +400 -0
- package/src/repo.js +63 -0
- package/src/server.js +229 -0
- package/src/tools.js +483 -0
package/src/tools.js
ADDED
|
@@ -0,0 +1,483 @@
|
|
|
1
|
+
import { allowMatcher } from "./repo.js";
|
|
2
|
+
import { aiVoice } from "./aivoice.js";
|
|
3
|
+
// The four tools behind the MCP server. Pure functions over the bundled data.
|
|
4
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
|
|
8
|
+
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
9
|
+
const read = (p) => readFileSync(join(ROOT, p), "utf8");
|
|
10
|
+
|
|
11
|
+
export const META = JSON.parse(read("data/meta.json"));
|
|
12
|
+
export const PATTERNS = META.patterns;
|
|
13
|
+
export const ELEMENTS = META.elements;
|
|
14
|
+
// The public build ships without the whole-screen dataset; find_examples is then left out.
|
|
15
|
+
export const HAS_EXAMPLES = existsSync(join(ROOT, "data/screens.json"));
|
|
16
|
+
|
|
17
|
+
let screens, rules, skill, voice, rubric, patternIndex;
|
|
18
|
+
function load() {
|
|
19
|
+
if (!rules) {
|
|
20
|
+
screens = HAS_EXAMPLES ? JSON.parse(read("data/screens.json")) : [];
|
|
21
|
+
rules = JSON.parse(read("data/rules.json"));
|
|
22
|
+
skill = read("guide/SKILL.md");
|
|
23
|
+
voice = read("guide/voice.md");
|
|
24
|
+
rubric = read("guide/rubric.md");
|
|
25
|
+
try { patternIndex = read("guide/patterns.md"); } catch { patternIndex = ""; }
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const STOP = new Set("a an the to of and or for in on is are be your you we it this that with at by from as".split(" "));
|
|
30
|
+
const tokens = (s) => new Set(((s || "").toLowerCase().match(/[a-z0-9']+/g) || []).filter((w) => !STOP.has(w)));
|
|
31
|
+
const overlap = (a, b) => { let n = 0; for (const w of a) if (b.has(w)) n++; return n; };
|
|
32
|
+
|
|
33
|
+
// u.s is a batch-aware rank computed in scripts/build-data.py (raw scores differ by labeler)
|
|
34
|
+
const score = (u) => u.s;
|
|
35
|
+
|
|
36
|
+
export function findExamples({ pattern, element, query, platform, industry, quality = "best", limit = 5, exclude_products }) {
|
|
37
|
+
load();
|
|
38
|
+
// UXW_EXCLUDE_PRODUCTS (comma-separated) lets evals hide the product under test
|
|
39
|
+
const fromEnv = (process.env.UXW_EXCLUDE_PRODUCTS || "").split(",").filter(Boolean);
|
|
40
|
+
const exclude = new Set([...(exclude_products || []), ...fromEnv].map((p) => p.trim().toLowerCase()));
|
|
41
|
+
const q = tokens(query);
|
|
42
|
+
const ranked = [];
|
|
43
|
+
for (const s of screens) {
|
|
44
|
+
if (s.p !== pattern || exclude.has(s.product.toLowerCase())) continue;
|
|
45
|
+
if (platform && s.platform !== platform) continue;
|
|
46
|
+
if (industry && s.industry !== industry) continue;
|
|
47
|
+
let hits = s.copy.filter((u) => !element || u.e === element);
|
|
48
|
+
if (quality === "weak") hits = hits.filter((u) => u.r === "weak");
|
|
49
|
+
if (!hits.length) continue;
|
|
50
|
+
const base = quality === "weak" ? 10 : Math.max(...hits.map(score));
|
|
51
|
+
const words = new Set();
|
|
52
|
+
for (const u of s.copy) for (const w of tokens(u.t + " " + (u.n || ""))) words.add(w);
|
|
53
|
+
// with a query, the match on the situation decides the order and quality breaks ties; no word in common, no result
|
|
54
|
+
const ov = overlap(q, words);
|
|
55
|
+
if (q.size && !ov) continue;
|
|
56
|
+
ranked.push([q.size ? 10 * ov / q.size + base / 6 : base, s]);
|
|
57
|
+
}
|
|
58
|
+
ranked.sort((a, b) => b[0] - a[0]);
|
|
59
|
+
return ranked.slice(0, Math.min(limit, 10)).map(([, s]) => ({
|
|
60
|
+
product: s.product, platform: s.platform, industry: s.industry,
|
|
61
|
+
copy: s.copy.map((u) => ({
|
|
62
|
+
element: u.e, text: u.t, rating: u.r,
|
|
63
|
+
...(u.n ? { note: u.n } : {}),
|
|
64
|
+
})),
|
|
65
|
+
}));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function findRules({ pattern, element, query, limit = 8 }) {
|
|
69
|
+
load();
|
|
70
|
+
const q = tokens(query);
|
|
71
|
+
const ranked = [];
|
|
72
|
+
for (const r of rules) {
|
|
73
|
+
if (pattern && r.pattern !== pattern && r.pattern !== "general") continue;
|
|
74
|
+
if (element && r.element && r.element !== element) continue;
|
|
75
|
+
let s = (r.pattern === pattern ? 2 : 0) + (element && r.element === element ? 1 : 0) + (r.strength === "must" ? 1 : 0);
|
|
76
|
+
s += 2 * overlap(q, new Set([...tokens(r.rule), ...tokens(r.topic)]));
|
|
77
|
+
ranked.push([s, r]);
|
|
78
|
+
}
|
|
79
|
+
ranked.sort((a, b) => b[0] - a[0]);
|
|
80
|
+
return ranked.slice(0, Math.min(limit, 20)).map(([, r]) => ({
|
|
81
|
+
rule: r.rule, why: r.why, do: r.do, dont: r.dont, strength: r.strength, source: r.source,
|
|
82
|
+
}));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// SKILL.md headings for each pattern
|
|
86
|
+
const PLAYBOOK = {
|
|
87
|
+
"empty-state": "Empty state", error: "Error", "toast-snackbar": "Toast", "confirmation-dialog": "Confirmation dialog",
|
|
88
|
+
"settings-destructive": "Account or workspace deletion", onboarding: "Onboarding", "permission-request": "Permission request",
|
|
89
|
+
"loading-progress": "Loading and progress", "search-no-results": "Search with no results", offline: "Offline",
|
|
90
|
+
"push-notification": "Push notification", success: "Success", "paywall-upsell": "Paywall", "auth-form": "Sign-up and login",
|
|
91
|
+
"tooltip-coachmark": "Tooltip", checkout: "Checkout", "ai-chat": "AI chat interface",
|
|
92
|
+
"settings-preferences": "Settings and preferences", "navigation-menu": "Menus and navigation",
|
|
93
|
+
"form-general": "Forms", "verification-kyc": "Identity verification", "invite-share": "Invite and share",
|
|
94
|
+
"referral-rewards": "Referral and rewards", "rating-review-prompt": "Rating and review",
|
|
95
|
+
"subscription-management": "Subscription management", "help-support": "Help and support",
|
|
96
|
+
"update-maintenance": "Updates and maintenance", "consent-privacy": "Consent and privacy", email: "Email",
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
function section(md, level, startsWith) {
|
|
100
|
+
const lines = md.split("\n");
|
|
101
|
+
const prefix = "#".repeat(level) + " ";
|
|
102
|
+
const i = lines.findIndex((l) => l.startsWith(prefix + startsWith));
|
|
103
|
+
if (i < 0) return "";
|
|
104
|
+
let j = i + 1;
|
|
105
|
+
while (j < lines.length && !(/^#{1,6} /.test(lines[j]) && lines[j].match(/^#+/)[0].length <= level)) j++;
|
|
106
|
+
return lines.slice(i, j).join("\n").trim();
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// which pattern-index topics fit a pattern; buttons always come along
|
|
110
|
+
const INDEX_TOPICS = [
|
|
111
|
+
[/error|offline|valid|fail|declin|wrong/, "Validation, errors"], [/empty|search|filter|no-results/, "Search, filters"],
|
|
112
|
+
[/loading|progress|status|update|maintenance|sync|upload/, "Loading, background"], [/delete|confirm|destructive|dialog|cancel|remove/, "Confirmation, review"],
|
|
113
|
+
[/onboard|permission|sign|login|log-in|account|welcome|verif|kyc|password/, "Onboarding, permissions"], [/checkout|pay|billing|subscri|paywall|pric|refund|invoice|plan|trial/, "Checkout, billing"],
|
|
114
|
+
[/privacy|consent|shar|cookie|trust/, "Privacy, consent"], [/notif|push|email|toast|alert|reminder/, "Notifications, alerts"],
|
|
115
|
+
[/\bai\b|ai-|chat|assistant|agent|generat/, "AI assistants"], [/form|field|input|setting|profile/, "Forms and questions"],
|
|
116
|
+
];
|
|
117
|
+
function indexFor(pattern) {
|
|
118
|
+
if (!patternIndex) return "";
|
|
119
|
+
const key = `${pattern} ${PLAYBOOK[pattern] || ""}`.toLowerCase();
|
|
120
|
+
const topics = ["Buttons, links", ...INDEX_TOPICS.filter(([re]) => re.test(key)).map(([, t]) => t)].slice(0, 3);
|
|
121
|
+
const head = patternIndex.split(/\n### /)[0].trim();
|
|
122
|
+
return [head, ...topics.map((t) => section(patternIndex, 3, t)).filter(Boolean)].join("\n\n");
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function getGuide({ pattern, full = false }) {
|
|
126
|
+
load();
|
|
127
|
+
const parts = [voice.trim(), section(skill, 2, "Universal rules")];
|
|
128
|
+
if (pattern) {
|
|
129
|
+
parts.push("## Playbook for this pattern\n\n" + section(skill, 3, PLAYBOOK[pattern]));
|
|
130
|
+
parts.push(rubric.trim());
|
|
131
|
+
parts.push(full ? patternIndex.trim() : indexFor(pattern));
|
|
132
|
+
} else {
|
|
133
|
+
for (const h of ["What screenshots can't show", "Defaults where sources disagree"]) parts.push(section(skill, 2, h));
|
|
134
|
+
parts.push(full ? section(skill, 2, "Pattern playbooks") : `## Patterns\n\nCall get_guide again with one of these for its playbook: ${PATTERNS.join(", ")}.`);
|
|
135
|
+
parts.push(rubric.trim());
|
|
136
|
+
parts.push(section(skill, 2, "Review checklist"));
|
|
137
|
+
}
|
|
138
|
+
return parts.filter(Boolean).join("\n\n");
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// --- lint ---------------------------------------------------------------
|
|
142
|
+
|
|
143
|
+
const FILLER = [/\bsuccessfully\b/gi, /\bsimply\b/gi, /\bplease note\b/gi, /\bit looks like\b/gi,
|
|
144
|
+
/\bit seems\b/gi, /\boops\b/gi, /\bwhoops\b/gi, /\bno worries\b/gi, /\bto get started\b/gi,
|
|
145
|
+
/\bin order to\b/gi, /\bkindly\b/gi, /\beasily\b/gi, /\bseamless(ly)?\b/gi, /\buh[- ]?oh\b/gi, /\byikes\b/gi, /\bwhoopsie\b/gi];
|
|
146
|
+
// misspellings that turn up in shipped strings; a typo was the most common reason labelers scored a line 1
|
|
147
|
+
const TYPOS = { occured: "occurred", occuring: "occurring", occurence: "occurrence", recieve: "receive", recieved: "received", recieving: "receiving", seperate: "separate", seperately: "separately", untill: "until", sucess: "success", sucessful: "successful", succesful: "successful", sucessfully: "successfully", succesfully: "successfully", adress: "address", accomodate: "accommodate", definately: "definitely", wich: "which", thier: "their", existant: "existent", independant: "independent", refered: "referred", begining: "beginning", commited: "committed", transfered: "transferred", alot: "a lot", teh: "the", recomend: "recommend", reccomend: "recommend", neccessary: "necessary", necesary: "necessary", priviledge: "privilege", acheive: "achieve", wierd: "weird", tommorow: "tomorrow", tomorow: "tomorrow", calender: "calendar", embarass: "embarrass", guarentee: "guarantee", maintainance: "maintenance", noticable: "noticeable", publically: "publicly", occassion: "occasion", supercede: "supersede", accross: "across", agressive: "aggressive", arguement: "argument", beleive: "believe", buisness: "business", collegue: "colleague", concious: "conscious", enviroment: "environment", foward: "forward", goverment: "government", happend: "happened", immediatly: "immediately", knowlege: "knowledge", lenght: "length", paymnet: "payment", passowrd: "password", pasword: "password", acount: "account", accout: "account", verfiy: "verify", verifcation: "verification", notifcation: "notification", subcription: "subscription", subscribtion: "subscription", availible: "available", avaliable: "available", sumbit: "submit", submision: "submission", submited: "submitted" };
|
|
148
|
+
const VAGUE = [
|
|
149
|
+
[/\bjust\b/gi, "just", "cut 'just' if it only softens; keep it when it means 'only' or 'a moment ago'"],
|
|
150
|
+
[/\b(for (a|your) better experience|for your convenience|to meet your needs|get the most out of)\b/gi, "vague-benefit", "name the concrete benefit or end the sentence sooner"],
|
|
151
|
+
[/\b(all done|taken care of|that's sorted)\b/gi, "vague-completion", "name what was done, and what wasn't, if the person can't otherwise tell"],
|
|
152
|
+
[/\b(here you can|this (page|screen|section|tab) (lets|allows|enables) you to|(allows|enables) you to)\b/gi, "capability-wrapper", "start with the verb: 'Export your data', not 'Here you can export your data'"],
|
|
153
|
+
[/\b(sit tight|hang tight|working (our|its) magic|grab a coffee|good things take time)\b/gi, "loading-performance", "say what's loading, or how long, or nothing"],
|
|
154
|
+
[/\b(click|tap) here\b/gi, "click-here", "make the link the words that say where it goes"],
|
|
155
|
+
[/\b(designed to help you|built to help you|we've made it (simple|easy)|we made it (simple|easy))\b/gi, "design-intent", "describe what the person can do, not what the team intended"],
|
|
156
|
+
[/\b(we're|we are) (excited|thrilled|delighted|happy) to (introduce|announce|share|launch)\b/gi, "company-excitement", "lead with what's new for the person"],
|
|
157
|
+
[/\b(your journey starts here|the possibilities are endless|the sky's the limit|let the magic begin)\b/gi, "pep-talk", "say what to add first and what it gives them"],
|
|
158
|
+
];
|
|
159
|
+
const GENERIC_CTA = new Set(["ok", "okay", "yes", "no", "click here", "proceed", "go"]);
|
|
160
|
+
// standard labels people expect; only a note, because a repo's own glossary may ask for them
|
|
161
|
+
const STANDARD_CTA = new Set(["submit", "continue", "next", "confirm"]);
|
|
162
|
+
const BLAME = [/\binvalid\b/gi, /\billegal\b/gi, /\byou (forgot|didn't|did not|failed)\b/gi];
|
|
163
|
+
// a verdict is fine when the same line gives the fix ("Something went wrong. Try again.")
|
|
164
|
+
const VERDICT = [/\bfailed to\b/gi, /\b(went|gone) wrong\b/gi, /\ban? (unexpected |unknown )?error (has )?occurred\b/gi];
|
|
165
|
+
const hasFix = (t) => t.split(/(?<=[.!?:;])\s+|,\s+(?=(?:please\s+)?[a-z]+\b)/i).some((z) => FIX_VERB.test(z.replace(/^\s*(please|then|or|and|so)\s+/i, "").split(/\s+/).slice(0, 2).join(" "))) || /\b(try again|contact (us|support)|reach out|get in touch|check (your|the|that)|make sure|you can (try|retry|still)|later|for (support|help))\b/i.test(t);
|
|
166
|
+
const FIX_VERB = /^(try|visit|see|read|follow|check|tap|click|go to|use|remove|clear|contact|email|reach|ask|write to|sign in|log in|reload|refresh|wait|choose|pick|select|update|reconnect|enter|add|make sure|restart|open|turn on|allow)\b/i;
|
|
167
|
+
const ABSOLUTES = [/\bnever\b/gi, /\balways\b/gi, /\bguarantee[ds]?\b/gi, /\b100% (secure|safe|private|accurate|guaranteed|reliable|free|uptime|satisf\w*)/gi];
|
|
168
|
+
const LEAK = [/\bNaN\b/g, /\[object/gi, /%[sd]\b/g];
|
|
169
|
+
// "null"/"undefined" leak only where a value was meant to be: not after words that make it prose ("returns null", "is undefined")
|
|
170
|
+
const LEAK_WORD = /(?<!\b(?:is|be|are|was|were|returns?|or|to|as|of|when|if|set|and|not|a|the|means?)\s)\b(null|undefined)\b/gi;
|
|
171
|
+
const CODE = [/\b(error|err)[ _-]?\d{2,}\b/gi, /\b[A-Z]{2,}_[A-Z_]{2,}\b/g, /\b0x[0-9a-f]+\b/gi, /\b[A-Z]\w+Exception\b/g];
|
|
172
|
+
const SENTENCE_ELEMENTS = new Set(["body", "helper-text", "inline-error", "legal-fineprint"]);
|
|
173
|
+
const LIMITS = { headline: 10, "primary-cta": 4, "secondary-cta": 4, "tertiary-link": 5, toast: 12, body: 35, "inline-error": 20, badge: 3, label: 4, "title-bar": 5 };
|
|
174
|
+
const HIGH_STAKES = new Set(["error", "checkout", "settings-destructive", "confirmation-dialog", "offline", "paywall-upsell"]);
|
|
175
|
+
const EMOJI = /[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/u;
|
|
176
|
+
|
|
177
|
+
const find = (pats, t) => pats.flatMap((p) => [...t.matchAll(new RegExp(p.source, p.flags.includes("g") ? p.flags : p.flags + "g"))].map((m) => m[0]));
|
|
178
|
+
|
|
179
|
+
// state-claim words and the state evidence that justifies each
|
|
180
|
+
const STATE_CLAIMS = [
|
|
181
|
+
[/\b(approved|accepted)\b/i, /approved|accepted|"decision":"(approved|accepted)"|"approvals":[1-9]/i, "approved or accepted"],
|
|
182
|
+
[/\bdelivered\b/i, /delivered_at":"|"(message_status|status|state|delivery)":"delivered"|"delivered":true/i, "delivered"],
|
|
183
|
+
[/\b(read|seen|opened)\b(?! (the|our|this))/i, /read_at":"|opened_at":"|"(read|seen|opened)":true/i, "read or opened"],
|
|
184
|
+
[/\b(charged|paid|deducted|taken from)\b/i, /"captured":true|"(payment|status|state)":"(charged|paid|captured)"|"charged":true|"paid":true/i, "charged or paid"],
|
|
185
|
+
[/\b(live|published)\b/i, /"page_live":true|"published":true|"(status|state|post|page)":"(live|published)"/i, "live or published"],
|
|
186
|
+
[/\b(verified|checked)\b/i, /"verified":true|"(status|state)":"verified"/i, "verified"],
|
|
187
|
+
[/\b(synced|backed up)\b/i, /"synced":true|"(status|state)":"(synced|backed_up|complete)"/i, "synced or backed up"],
|
|
188
|
+
[/\b(completed?|done|finished)\b/i, /"(file_ready|ready|completed|done)":true|"(status|state|export|backup|job)":"(complete|completed|ready|done|finished)"/i, "complete or ready"],
|
|
189
|
+
[/\b(confirmed|booked|reserved)\b/i, /"confirmed[a-z_]*":true|"(status|state)":"(confirmed|booked|reserved)"|carrier_confirmed":true/i, "confirmed or booked"],
|
|
190
|
+
[/\b(arrived|joined|refunded|returned|settled)\b/i, /"(arrived|joined|refunded|settled|received|accepted|member|money_returned)":true|"(status|state|transfer|payout|order|refund)":"(arrived|joined|refunded|settled|received|delivered|returned)"|"delivered":true|bank_credit":"/i, "arrived, joined, refunded or settled"],
|
|
191
|
+
];
|
|
192
|
+
const NEG_BEFORE = /(not|n't|never|no|yet|until|before|once|when|after|if|unless|soon|will|'ll|won't|going to|should|would|expect\w*|can't|gets?|may|might|could|whether|to be|to get)\W*(\w+\W+){0,6}$/i;
|
|
193
|
+
const CASUAL = /\b(yay|hooray|awesome|oops|whoops|uh[- ]oh|great news|woohoo|nice one|hang tight|good news)\b/i;
|
|
194
|
+
// verbs that usually need an object on a button; a lone noun or a brand name ("Akahu", "Billing") isn't flagged
|
|
195
|
+
const ACTION_VERBS = new Set("add create make new import export connect link unlink disconnect invite join leave open view show hide manage change set reset update upgrade downgrade renew restore archive unarchive move rename duplicate merge split assign transfer pay buy order book schedule reschedule cancel approve reject decline accept request claim redeem enable disable activate deactivate install uninstall sync refresh run start stop pause resume send resend submit post reply forward print sign register subscribe unsubscribe follow unfollow block unblock report mute unmute pin unpin lock unlock verify test try configure customize select choose pick generate convert attach detach review preview".split(" "));
|
|
196
|
+
const ONE_WORD_OK = new Set(["add", "open", "view", "create", "new", "export", "import", "invite", "join", "follow", "pay", "buy", "reply", "post", "print", "sign in", "log in", "accept", "decline", "approve", "reject", "connect", "install", "update", "upgrade", "refresh", "reset", "archive", "restore", "pause", "resume", "start", "stop", "play", "filter", "sort", "select", "preview", "review", "cancel", "close", "back", "next", "done", "skip", "retry", "dismiss", "later", "ok", "okay", "continue", "submit", "confirm", "accept", "agree", "start", "finish", "verify", "resend", "save", "send", "edit", "delete", "remove", "share", "copy", "undo", "search", "apply", "publish", "upload", "download", "inbox", "terms", "privacy", "settings", "help", "home", "more"]);
|
|
197
|
+
|
|
198
|
+
// typographic quotes and apostrophes ("won’t", “Save”) read the same as straight ones for every check
|
|
199
|
+
const norm = (t) => String(t ?? "").replace(/[\u2018\u2019\u02BC\u2032]/g, "'").replace(/[\u201C\u201D\u2033]/g, '"').replace(/\u2026/g, "...").replace(/\u00A0/g, " ");
|
|
200
|
+
const ELEMENT_ALIAS = { button: "primary-cta", cta: "primary-cta", "primary-button": "primary-cta", "secondary-button": "secondary-cta", link: "tertiary-link", title: "headline", heading: "headline", description: "body", text: "body", paragraph: "body", error: "inline-error", "error-message": "inline-error", snackbar: "toast", notification: "toast", hint: "helper-text", "helper": "helper-text", caption: "helper-text", input: "label", "field-label": "label", "nav-item": "tertiary-link", tab: "tertiary-link" };
|
|
201
|
+
export const normElement = (e) => ELEMENT_ALIAS[String(e || "").toLowerCase()] || e;
|
|
202
|
+
|
|
203
|
+
export function lintCopy({ units, pattern, state, stakes, expected_pieces, original, allow }) {
|
|
204
|
+
units = (units || []).map((u) => ({ ...u, element: normElement(u.element), text: norm(u.text) }));
|
|
205
|
+
if (Array.isArray(original)) original = original.map((o) => ({ ...o, element: normElement(o.element), text: norm(o.text) }));
|
|
206
|
+
const out = [];
|
|
207
|
+
const add = (unit, severity, rule, detail) => out.push({ unit, severity, rule, detail });
|
|
208
|
+
const texts = units.map((u) => u.text || "");
|
|
209
|
+
units.forEach((u, i) => {
|
|
210
|
+
const el = u.element || "", t = u.text || "";
|
|
211
|
+
const low = t.trim().toLowerCase().replace(/[.!]+$/, "");
|
|
212
|
+
const words = t.split(/\s+/).filter(Boolean).length;
|
|
213
|
+
if (!t.trim()) { add(i, "block", "empty-text", `the ${el || "piece"} has no text; write it, or drop the piece`); return; }
|
|
214
|
+
for (const w of t.toLowerCase().match(/[a-z]+/g) || []) if (TYPOS[w]) add(i, "warn", "typo", `'${w}' should be '${TYPOS[w]}'`);
|
|
215
|
+
for (const m of find(LEAK, t)) add(i, "block", "template-leak", `'${m}' looks like an unfilled variable`);
|
|
216
|
+
if (/^are you sure\b/i.test(t.trim())) add(i, /[.?!]\s+\S/.test(t.trim()) ? "note" : "warn", "are-you-sure", "'Are you sure' asks for confidence, not a decision; name the action and what it costs ('Delete this draft? You can't undo this.')");
|
|
217
|
+
if (el === "headline" && /^(nothing (to see )?here|nothing (here )?yet|it's (quiet|empty) (in )?here|there (are|is) no\b[^.!?]*\b(here|yet|at the moment|right now|currently|to show|found|available)\b|you (don't|do not) have any\b|you haven't\b.*\byet\b|no \w+( \w+)? (found|available|at the moment|right now|currently|to show))/i.test(t.trim())) add(i, "warn", "absence-headline", `'${t.trim()}' leads with what's missing; lead with what the person gets or can do ("Add your first contact")`);
|
|
218
|
+
if (el !== "helper-text" && el !== "legal-fineprint") for (const m of t.match(LEAK_WORD) || []) add(i, "block", "template-leak", `'${m}' looks like an unfilled variable`);
|
|
219
|
+
for (const m of t.match(/\{[^}]*\}/g) || []) add(i, "note", "variable", `'${m}': check it reads well for every value, including empty, 1 and long ones`);
|
|
220
|
+
for (const m of find(CODE, t)) add(i, "block", "raw-code", `'${m}' is a system code; say what happened and the fix`);
|
|
221
|
+
for (const m of find(FILLER, t)) add(i, "warn", "filler", `cut '${m}'`);
|
|
222
|
+
for (const [re, id, msg] of VAGUE) for (const m of t.match(re) || []) add(i, "note", id, `'${m}': ${msg}`);
|
|
223
|
+
if ((el === "primary-cta" || el === "secondary-cta") && GENERIC_CTA.has(low)) add(i, "warn", "generic-button", `'${t}' doesn't say what happens; use verb + object`);
|
|
224
|
+
if ((el === "primary-cta" || el === "secondary-cta") && STANDARD_CTA.has(low)) add(i, "note", "standard-button", `'${t}' is a standard label; fine where the next step is obvious or the repo's glossary asks for it, otherwise name the action`);
|
|
225
|
+
if (el === "headline" && ["success", "error", "warning", "oops", "uh oh"].includes(low)) add(i, "warn", "empty-headline", `'${t}' names a state, not what happened`);
|
|
226
|
+
const isFailure = el === "inline-error" || pattern === "error" || /^(failed to|couldn't|could not|unable to|something went wrong|an? (unexpected |unknown )?error)\b/i.test(t) || (el === "toast" && /\b(couldn't|can't|cannot|failed|unable|error|wrong|not (be )?(saved|sent|found|added|deleted))\b/i.test(t));
|
|
227
|
+
if (isFailure) {
|
|
228
|
+
for (const m of find(BLAME, t)) add(i, "warn", "blame-or-verdict", `'${m}' judges the person or their input; say what's needed instead`);
|
|
229
|
+
if (!hasFix(t)) for (const m of find(VERDICT, t)) add(i, "warn", "verdict-no-fix", `'${m}' gives the verdict with no fix; say what to do next, or what still works`);
|
|
230
|
+
if (t.includes("!")) add(i, "warn", "exclaiming-at-failure", "no exclamation marks on errors");
|
|
231
|
+
}
|
|
232
|
+
for (const m of find(ABSOLUTES, t)) add(i, "note", "absolute", `'${m}': only promise what is always true`);
|
|
233
|
+
if (/\b0 (items|results|\w+s)\b/i.test(t) && (pattern === "empty-state" || pattern === "search-no-results")) add(i, "warn", "literal-zero", "don't show a count of zero; say what will appear and how");
|
|
234
|
+
if (["primary-cta", "secondary-cta", "tertiary-link"].includes(el) && ["LOGIN", "Login"].includes(t.trim())) add(i, "note", "login-noun", "the verb is 'Log in'");
|
|
235
|
+
const alpha = t.replace(/[^A-Za-z ]/g, "").split(/\s+/).filter(Boolean);
|
|
236
|
+
if (alpha.length >= 2 && t === t.toUpperCase() && !/\d/.test(t) && alpha.some((w) => w.length > 4)) add(i, "note", "all-caps", "sentence case reads faster; 95% of exemplars use it");
|
|
237
|
+
else if (["headline", "primary-cta", "secondary-cta", "title-bar"].includes(el) && alpha.length >= 3 &&
|
|
238
|
+
alpha.slice(1).filter((w) => w[0] === w[0].toUpperCase()).length >= Math.max(2, alpha.length - 2)) add(i, "note", "title-case", "use sentence case");
|
|
239
|
+
if (LIMITS[el] && words > LIMITS[el]) add(i, "note", "long", `${words} words; exemplar ${el}s rarely pass ${LIMITS[el]}`);
|
|
240
|
+
if (SENTENCE_ELEMENTS.has(el) && words > 6 && !/[.?!:)"']$/.test(t.trim())) add(i, "note", "punctuation", "full-sentence copy ends with a full stop");
|
|
241
|
+
if (HIGH_STAKES.has(pattern) && EMOJI.test(t)) add(i, "warn", "emoji-at-stakes", "no emoji where money, data or access is at stake");
|
|
242
|
+
});
|
|
243
|
+
// state overclaim: a claim word with no supporting evidence in the tool state
|
|
244
|
+
if (state && Object.keys(state).length) {
|
|
245
|
+
const sj = JSON.stringify(state).replace(/\s/g, "");
|
|
246
|
+
units.forEach((u, i) => {
|
|
247
|
+
const x = u.text || "";
|
|
248
|
+
for (const [re, support, label] of STATE_CLAIMS) {
|
|
249
|
+
const g = new RegExp(re.source, "gi"); let m;
|
|
250
|
+
while ((m = g.exec(x))) {
|
|
251
|
+
if (NEG_BEFORE.test(x.slice(Math.max(0, m.index - 30), m.index))) continue;
|
|
252
|
+
if (!support.test(sj) && !sj.toLowerCase().includes(m[0].toLowerCase())) add(i, "block", "state-overclaim", `'${m[0]}' claims ${label}, but the state you were given does not show it; say what the state supports`);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
// structural tics measured against shipped copy: "No X yet" empty states, narrating where things will appear, two even sentences
|
|
258
|
+
units.forEach((u, i) => {
|
|
259
|
+
const x = (u.text || "").trim();
|
|
260
|
+
if (u.element === "headline" && /^no\b[^.!?]*\byet\b/i.test(x)) add(i, "warn", "no-x-yet", `'${x}' is the most common model empty-state headline (49% of model lines, 5.5% of shipped); lead with what the person gets or can do ("Add your first contact")`);
|
|
261
|
+
if (/\b(will|'ll)\s+(show up|appear|be listed|be shown|be displayed)\s+here\b|\blisted here\b|\byou('ll| will) see (it|them|\w+) here\b/i.test(x)) add(i, "warn", "narrating-location", "says where content will appear instead of what the person gets; say what it is and what to do");
|
|
262
|
+
if (u.element === "body") {
|
|
263
|
+
const sents = x.split(/(?<=[.!?])\s+/).filter((t) => t.split(/\s+/).length > 1);
|
|
264
|
+
const wc = sents.map((z) => z.split(/\s+/).length);
|
|
265
|
+
// "Couldn't save. Try again." is a verdict and its fix, not a rhythm problem
|
|
266
|
+
if (sents.length === 2 && Math.abs(wc[0] - wc[1]) <= 2 && Math.min(...wc) >= 7 && !/^(please |try |check |make sure |contact |go to |tap |click |select |choose |enter |add |use )/i.test(sents[1])) add(i, "note", "even-sentences", "two sentences of near-equal length read mechanical; give them different jobs and lengths, or use one");
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
// rewrite: short originals that already worked should stay unless there is a reason
|
|
270
|
+
if (Array.isArray(original)) original.forEach((o) => {
|
|
271
|
+
const ow = (o.text || "").trim();
|
|
272
|
+
if (!ow || ow.split(/\s+/).length > 3) return;
|
|
273
|
+
const same = units.find((u) => u.element === o.element && (u.text || "").trim() === ow);
|
|
274
|
+
if (!same && units.some((u) => u.element === o.element)) add(null, "note", "changed-short-original", `the original ${o.element} '${ow}' was short; keep it unless it is wrong for the state, unclear or misses a fact`);
|
|
275
|
+
});
|
|
276
|
+
// tics: describing the screen, inventing a cause, hinting at an outcome the facts do not give
|
|
277
|
+
units.forEach((u, i) => {
|
|
278
|
+
const x = u.text || "";
|
|
279
|
+
if (/\b(shown|displayed|appears?|visible)\s+(before|when|after|while|until)\b/i.test(x) || /\bthis (screen|page|message|notice|popup) (shows|lists|displays|contains|is where|appears)\b/i.test(x) || /\bthis (message|notice|popup)\b/i.test(x))
|
|
280
|
+
add(i, "warn", "screen-meta", "the copy describes the screen instead of the situation; say what is happening to the person");
|
|
281
|
+
if (state && Object.keys(state).length) {
|
|
282
|
+
const sj2 = JSON.stringify(state).toLowerCase();
|
|
283
|
+
for (const m of x.matchAll(/\b(because|due to|as a result of)\s+([a-z' ]{3,40})/gi)) {
|
|
284
|
+
const words = m[2].toLowerCase().split(/\s+/).filter((w) => w.length > 3);
|
|
285
|
+
if (words.length && !words.some((w) => sj2.includes(w))) add(i, "warn", "invented-cause", `'${m[0].trim()}': the state you were given does not give this reason; drop it or say only what is known`);
|
|
286
|
+
}
|
|
287
|
+
if (/\b(received|submitted|got) your (application|request|submission|claim|order)\b/i.test(x) && !/(offer|approv|accept|eligible)/i.test(sj2))
|
|
288
|
+
add(i, "note", "outcome-hint", "make sure 'received' does not suggest a result the facts do not show");
|
|
289
|
+
}
|
|
290
|
+
});
|
|
291
|
+
// tone fence at high stakes
|
|
292
|
+
if (stakes === "high") units.forEach((u, i) => {
|
|
293
|
+
if ((u.text || "").includes("!")) add(i, "warn", "tone-fence", "no exclamation marks when the stakes are high");
|
|
294
|
+
if (CASUAL.test(u.text || "")) add(i, "warn", "tone-fence", `'${(u.text.match(CASUAL) || [""])[0]}' is too light for high stakes`);
|
|
295
|
+
});
|
|
296
|
+
// plural and variable handling
|
|
297
|
+
units.forEach((u, i) => {
|
|
298
|
+
const x = u.text || "";
|
|
299
|
+
for (const m of x.match(/\b\w+\(s\)/g) || []) add(i, "warn", "plural", `'${m}': write the singular and plural forms (plural rule) instead of (s)`);
|
|
300
|
+
for (const m of x.match(/\{(count|n|num|number|total|qty|amount)(_\w+|[A-Z]\w*)?\}\s+[a-z]+/g) || []) add(i, "warn", "plural", `'${m}': a count variable needs plural forms for 1 and other`);
|
|
301
|
+
for (const m of x.match(/\b1 [a-z]+s\b/gi) || []) add(i, "warn", "plural", `'${m}': singular needed for one`);
|
|
302
|
+
});
|
|
303
|
+
// action-label specificity: one word, no object
|
|
304
|
+
units.forEach((u, i) => {
|
|
305
|
+
if (!["primary-cta", "secondary-cta"].includes(u.element)) return;
|
|
306
|
+
const w = (u.text || "").trim().split(/\s+/).filter(Boolean);
|
|
307
|
+
const lw = w[0]?.toLowerCase().replace(/[.!]/g, "");
|
|
308
|
+
// a bare verb is fine when the headline or body on the same screen names the object ("Delete this draft?" / "Delete")
|
|
309
|
+
const named = units.some((v) => ["headline", "body", "title-bar"].includes(v.element) && v.text.trim());
|
|
310
|
+
if (w.length === 1 && !named && !ONE_WORD_OK.has(lw) && ACTION_VERBS.has(lw)) add(i, "note", "action-label", `'${u.text}' is a verb alone; name the thing it acts on unless the screen already does`);
|
|
311
|
+
});
|
|
312
|
+
// missing pieces
|
|
313
|
+
if (Array.isArray(expected_pieces)) for (const e of expected_pieces) if (!units.some((u) => u.element === e)) add(null, "block", "missing-piece", `no '${e}' in the copy; the screen needs it`);
|
|
314
|
+
const heads = units.flatMap((u, i) => (u.element === "headline" ? [i] : []));
|
|
315
|
+
const bodies = units.flatMap((u, i) => (u.element === "body" ? [i] : []));
|
|
316
|
+
for (const h of heads) for (const b of bodies) {
|
|
317
|
+
const ht = tokens(texts[h]);
|
|
318
|
+
const ov = ht.size ? overlap(ht, tokens(texts[b])) / ht.size : 0;
|
|
319
|
+
if (ov >= 0.7) add(b, "warn", "body-repeats-headline", "the body should add why, what's lost, or what's next");
|
|
320
|
+
else if (ov >= 0.5) add(b, "note", "body-repeats-headline", "half the headline's words come back in the body; check it adds something");
|
|
321
|
+
}
|
|
322
|
+
const ctas = units.filter((u) => u.element === "primary-cta" || u.element === "secondary-cta");
|
|
323
|
+
for (const c of ctas) {
|
|
324
|
+
const ct = (c.text || "").trim().toLowerCase();
|
|
325
|
+
if (ct.split(/\s+/).length < 2) continue;
|
|
326
|
+
bodies.forEach((b) => { if ((texts[b] || "").toLowerCase().includes(ct)) add(b, "note", "body-repeats-button", `the body repeats '${c.text}'; the button already says it`); });
|
|
327
|
+
}
|
|
328
|
+
const labels = units.flatMap((u, i) => (["label", "field-label"].includes(u.element) ? [i] : []));
|
|
329
|
+
units.forEach((u, i) => {
|
|
330
|
+
if (!["helper-text", "tooltip", "placeholder"].includes(u.element)) return;
|
|
331
|
+
for (const l of labels) {
|
|
332
|
+
const lt = tokens(texts[l]); const ut = tokens(texts[i]);
|
|
333
|
+
if (lt.size && ut.size <= lt.size + 3 && overlap(lt, ut) / lt.size >= 0.8) add(i, "note", "helper-echoes-label", `'${u.text}' restates the label; give the format, limit or example instead`);
|
|
334
|
+
}
|
|
335
|
+
});
|
|
336
|
+
if (ctas.length === 2 && ctas.every((c) => /\bcancel\b/i.test(c.text))) add(null, "warn", "cancel-cancel", "both buttons say Cancel; name each outcome ('Keep plan' / 'Cancel plan')");
|
|
337
|
+
const prose = texts.join(" ").trim();
|
|
338
|
+
const latin = (prose.match(/[A-Za-z]/g) || []).length / Math.max(1, (prose.match(/\p{L}/gu) || []).length);
|
|
339
|
+
const english = /\b(the|to|you|your|we|is|are|was|can|not|of|and|try|this|it|in|on|for)\b/i.test(prose) || prose.split(/\s+/).length <= 3;
|
|
340
|
+
if (["error", "offline", "search-no-results"].includes(pattern) && prose && latin > 0.7 && english &&
|
|
341
|
+
!units.some((u) => ["primary-cta", "secondary-cta", "tertiary-link"].includes(u.element) && u.text.trim()) &&
|
|
342
|
+
!texts.some((x) => hasFix(x) || /\b(try|check|tap|go to|use|remove|clear|contact|email|reach|ask|write to|sign in|log in|reload|refresh|wait|choose|pick|select|update|reconnect|visit)\b/i.test(x))) add(null, "warn", "no-way-forward", "nothing tells people what to do next");
|
|
343
|
+
units.forEach((u, i) => { for (const f of aiVoice(u.text, u.element)) add(i, f.severity, f.rule, f.detail); });
|
|
344
|
+
const order = { block: 0, warn: 1, note: 2 };
|
|
345
|
+
// the repo's own accepted words and lines (allow list or .content-md.json) never get flagged
|
|
346
|
+
const ok = allowMatcher(allow);
|
|
347
|
+
const kept = !ok.any ? out : out.filter((f) => {
|
|
348
|
+
if (f.rule === "state-overclaim" || f.rule === "missing-piece") return true;
|
|
349
|
+
if (f.unit != null && ok.line(units[f.unit]?.text || "")) return false;
|
|
350
|
+
const quoted = [...(f.detail || "").matchAll(/'([^']+)'/g)].map((m) => m[1]);
|
|
351
|
+
return !quoted.length || !quoted.every((q) => ok.word(q) || ok.line(q));
|
|
352
|
+
});
|
|
353
|
+
return kept.sort((a, b) => order[a.severity] - order[b.severity]);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// --- reference-first ----------------------------------------------------
|
|
357
|
+
// find_reference: the single closest real line for one element in one situation, with its shape.
|
|
358
|
+
// compare_to_reference: deterministic shape check of a candidate against its reference (rubric check 4).
|
|
359
|
+
|
|
360
|
+
const PRONOUN_START = new Set(["you", "you're", "you'll", "you've", "your", "we", "we're", "we'll", "we've", "our", "i", "i'm", "my", "they", "their", "this", "that", "it", "it's", "there", "these"]);
|
|
361
|
+
const FRAME_START = new Set(["when", "before", "after", "if", "once", "while", "until", "in", "on", "at", "by", "for", "from", "with", "during", "every", "each", "a", "an", "the", "here", "to"]);
|
|
362
|
+
const NOT_VERBS = new Set(["no", "not", "all", "new", "more", "free", "only", "now", "today", "almost", "nothing", "something", "everything", "welcome", "thanks", "thank", "sorry", "hi", "hello", "oops", "success", "error"]);
|
|
363
|
+
const COMMON_VERBS = new Set(("get find save add try start create make keep see view open share invite join use set turn choose pick select upload download " +
|
|
364
|
+
"send check review edit delete remove cancel upgrade unlock explore browse discover search learn read write track manage connect allow enable " +
|
|
365
|
+
"continue sign log go take build plan book pay buy apply verify confirm update restore retry change finish complete stay leave let enter type tap " +
|
|
366
|
+
"click follow meet earn claim redeem show hide stop pause resume reset submit import export move copy sync back ask contact talk call watch listen").split(" "));
|
|
367
|
+
|
|
368
|
+
const words = (t) => (t || "").trim().split(/\s+/).filter(Boolean);
|
|
369
|
+
const sentences = (t) => ((t || "").trim().match(/[^.!?]+[.!?]*/g) || []).filter((s) => /[A-Za-z0-9]/.test(s)).length || 1;
|
|
370
|
+
|
|
371
|
+
export function shapeOf(text) {
|
|
372
|
+
const w = words(text);
|
|
373
|
+
const first = (w[0] || "").toLowerCase().replace(/[^a-z']/g, "");
|
|
374
|
+
let opening;
|
|
375
|
+
if (PRONOUN_START.has(first)) opening = "subject";
|
|
376
|
+
else if (/^\d/.test(w[0] || "")) opening = "number";
|
|
377
|
+
else if (FRAME_START.has(first)) opening = "frame";
|
|
378
|
+
else if (COMMON_VERBS.has(first) || (!NOT_VERBS.has(first) && /^[A-Z][a-z]+$/.test(w[0] || "") && !first.endsWith("s") && !first.endsWith("ing") && w.length > 1 && /^(a|an|the|your|you|my|our|it|them|more|new|all|\w+)$/i.test(w[1] || "") && COMMON_VERBS.has(first))) opening = "verb";
|
|
379
|
+
else if (first.endsWith("ing")) opening = "verb-ing";
|
|
380
|
+
else opening = "noun";
|
|
381
|
+
const label = { subject: `Subject first ('${w[0]} …')`, verb: `Verb first ('${w[0]} …')`, "verb-ing": `-ing verb first ('${w[0]} …')`,
|
|
382
|
+
number: `Number first ('${w[0]} …')`, frame: `Frame first ('${w.slice(0, 2).join(" ")} …'): time, place, condition or article`, noun: `Noun first ('${w[0]} …')` }[opening];
|
|
383
|
+
const n = w.length;
|
|
384
|
+
return {
|
|
385
|
+
opening, first_word: w[0] || "", sentences: sentences(text), words: n,
|
|
386
|
+
length_range: [Math.max(1, Math.ceil(n * 0.7 - 1e-9)), Math.max(1, Math.floor(n * 1.3 + 1e-9))],
|
|
387
|
+
summary: `${label} · ${sentences(text)} sentence${sentences(text) > 1 ? "s" : ""} · ${n} words (stay within ${Math.max(1, Math.floor(n * 0.7))} to ${Math.ceil(n * 1.3)})`,
|
|
388
|
+
question: /\?\s*$/.test((text || "").trim()),
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// Ratings only break ties: a line that fits the moment must beat a prettier line that does not.
|
|
393
|
+
const SUPPORT = new Set(["helper-text", "body", "subtitle", "description"]);
|
|
394
|
+
const stem = (w) => w.replace(/(ing|ed|es|s)$/, "").slice(0, 6);
|
|
395
|
+
const stems = (set) => new Set([...set].map(stem));
|
|
396
|
+
let momentIdf = null;
|
|
397
|
+
function idfOf() {
|
|
398
|
+
if (momentIdf) return momentIdf;
|
|
399
|
+
const df = new Map(); let n = 0;
|
|
400
|
+
for (const s of screens) for (const u of s.copy) if (u.m) { n++; for (const w of stems(tokens(u.m))) df.set(w, (df.get(w) || 0) + 1); }
|
|
401
|
+
momentIdf = (w) => Math.log((n + 1) / ((df.get(w) || 0) + 1));
|
|
402
|
+
return momentIdf;
|
|
403
|
+
}
|
|
404
|
+
const weighted = (a, b, idf) => { let t = 0; for (const w of a) if (b.has(w)) t += idf(w); return t; };
|
|
405
|
+
|
|
406
|
+
const RATING_W = { gold: 1.5, strong: 1, solid: 0.5, weak: -5 };
|
|
407
|
+
|
|
408
|
+
export function findReference({ element, situation, pattern, draft, platform, limit = 3, exclude_products }) {
|
|
409
|
+
load();
|
|
410
|
+
const fromEnv = (process.env.UXW_EXCLUDE_PRODUCTS || "").split(",").filter(Boolean);
|
|
411
|
+
const exclude = new Set([...(exclude_products || []), ...fromEnv].map((p) => p.trim().toLowerCase()));
|
|
412
|
+
const q = tokens(situation);
|
|
413
|
+
const idf = idfOf();
|
|
414
|
+
const qs = stems(q);
|
|
415
|
+
const dq = tokens(draft);
|
|
416
|
+
const dn = draft ? words(draft).length : 0;
|
|
417
|
+
const ranked = [];
|
|
418
|
+
for (const s of screens) {
|
|
419
|
+
if (exclude.has(s.product.toLowerCase())) continue;
|
|
420
|
+
if (platform && s.platform !== platform) continue;
|
|
421
|
+
const ctx = new Set();
|
|
422
|
+
for (const u of s.copy) for (const w of tokens(u.t + " " + (u.n || ""))) ctx.add(w);
|
|
423
|
+
const ctxHit = overlap(q, ctx);
|
|
424
|
+
for (const u of s.copy) {
|
|
425
|
+
const fam = SUPPORT.has(element) && SUPPORT.has(u.e);
|
|
426
|
+
if ((u.e !== element && !fam) || u.r === "weak") continue;
|
|
427
|
+
const own = tokens(u.t + " " + (u.n || ""));
|
|
428
|
+
const mom = tokens(u.m || "");
|
|
429
|
+
const momHit = weighted(qs, stems(mom), idf);
|
|
430
|
+
let score = (u.e === element ? 0 : -2) + (RATING_W[u.r] || 0) + 3 * momHit + 2 * overlap(q, own) + 0.5 * ctxHit + (pattern && s.p === pattern ? 2 : 0);
|
|
431
|
+
if (draft) {
|
|
432
|
+
score += 1.5 * overlap(dq, tokens(u.t));
|
|
433
|
+
const n = words(u.t).length;
|
|
434
|
+
if (n >= dn * 0.5 && n <= dn * 2) score += 1;
|
|
435
|
+
}
|
|
436
|
+
if (q.size && overlap(q, own) + ctxHit + momHit === 0) score -= 4;
|
|
437
|
+
ranked.push([score, s, u]);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
ranked.sort((a, b) => b[0] - a[0]);
|
|
441
|
+
const seen = new Set();
|
|
442
|
+
const out = [];
|
|
443
|
+
for (const [score, s, u] of ranked) {
|
|
444
|
+
const key = u.t.toLowerCase();
|
|
445
|
+
if (seen.has(key)) continue;
|
|
446
|
+
seen.add(key);
|
|
447
|
+
const head = s.copy.find((x) => x.e === "headline");
|
|
448
|
+
out.push({
|
|
449
|
+
product: s.product, pattern: s.p, platform: s.platform, element: u.e, text: u.t, rating: u.r,
|
|
450
|
+
...(u.n ? { note: u.n } : {}),
|
|
451
|
+
...(u.m ? { moment: u.m, job: u.j } : {}),
|
|
452
|
+
...(head && head.t !== u.t ? { headline_on_screen: head.t } : {}),
|
|
453
|
+
shape: shapeOf(u.t).summary, match_score: Math.round(score * 10) / 10,
|
|
454
|
+
});
|
|
455
|
+
if (out.length >= Math.min(limit, 8)) break;
|
|
456
|
+
}
|
|
457
|
+
return out;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
export function compareToReference({ reference, candidate }) {
|
|
461
|
+
const r = shapeOf(reference), c = shapeOf(candidate);
|
|
462
|
+
const rt = tokens(reference), ct = tokens(candidate);
|
|
463
|
+
const shared = [...rt].filter((w) => ct.has(w));
|
|
464
|
+
const checks = {
|
|
465
|
+
same_opening_move: r.opening === c.opening,
|
|
466
|
+
same_sentence_count: r.sentences === c.sentences,
|
|
467
|
+
length_within_30_percent: c.words >= r.length_range[0] && c.words <= r.length_range[1],
|
|
468
|
+
same_ending: r.question === c.question,
|
|
469
|
+
};
|
|
470
|
+
const failed = Object.entries(checks).filter(([, v]) => !v).map(([k]) => k);
|
|
471
|
+
return {
|
|
472
|
+
verdict: failed.length ? "off-shape" : "on-shape",
|
|
473
|
+
checks, failed,
|
|
474
|
+
reference_shape: r.summary, candidate_shape: c.summary,
|
|
475
|
+
shared_words: shared,
|
|
476
|
+
hint: failed.length ? failed.map((f) => ({
|
|
477
|
+
same_opening_move: `The reference opens ${r.opening === "verb" ? "with a verb" : r.opening === "subject" ? "with a subject doing something" : `with a ${r.opening}`} ('${r.first_word}'); yours opens with '${c.first_word}'. Use the same opening move.`,
|
|
478
|
+
same_sentence_count: `The reference has ${r.sentences} sentence(s); yours has ${c.sentences}.`,
|
|
479
|
+
length_within_30_percent: `The reference is ${r.words} words; aim for ${r.length_range[0]} to ${r.length_range[1]}. Yours is ${c.words}.`,
|
|
480
|
+
same_ending: r.question ? "The reference asks a question; yours doesn't." : "The reference makes a statement; yours ends on a question.",
|
|
481
|
+
})[f]) : ["Matches the reference's shape. Now check the facts against the code."],
|
|
482
|
+
};
|
|
483
|
+
}
|