v1.5.0
AtheraStudio Code
- (function () {
- "use strict";
-
- var A = window.Athera;
- var util = A.util;
- var ai = A.ai;
- var t = ai.t;
-
- var RECIPES_DIR = ".private/recipes";
- var QUALITY_EXT = /\.(html?|php|phtml|inc|css|scss|js|mjs|json)$/i;
- var READ_ONLY = /^(create_file|edit_file|overwrite_file|delete_file|move_file|copy_file|save_crawl)$/;
-
- function target() {
- var tab = A.tabs && A.tabs.active;
- if (tab && tab.kind === "text") return tab.path != null ? tab.path : tab.name;
- return "";
- }
-
- function targetText() {
- var p = target();
- return p ? "the file " + p : "the project (start from its main pages)";
- }
-
- function selection() {
- var tab = A.tabs && A.tabs.active;
- if (!tab || tab.kind !== "text") return "";
- var sel = A.editor.view.state.selection.main;
- return sel.empty ? "" : A.editor.view.state.sliceDoc(sel.from, sel.to);
- }
-
- function dataPart(source, text) {
- return { type: "text", text: "[" + t("ai.tool.data_header", { source: source }) + "]\n" + text };
- }
-
- function diagnosticsPart() {
- var p = target();
- var lines = [];
- if (p) {
- try {
- A.intellisense.lintText(A.tabs.textOf(A.tabs.active), p).slice(0, 30).forEach(function (d) {
- lines.push(p + ":" + d.line + " [" + d.severity + "] " + d.message);
- });
- } catch (e) { }
- }
- A.console.entries().filter(function (e) { return e.level === "error" || e.level === "warn"; }).slice(-15).forEach(function (e) {
- lines.push("preview [" + e.level + "] " + String(e.text).slice(0, 240) + (e.label ? " (" + e.label + ")" : ""));
- });
- (A.preview.missing ? A.preview.missing() : []).forEach(function (m) { lines.push("preview [error] missing file: " + m); });
- return lines.length ? dataPart(t("ai.cmd.diag_source"), lines.join("\n")) : null;
- }
-
- var BUILTIN = {
- help: { local: true },
- seo: {
- purpose: "audit",
- prompt: function () {
- return "Do an SEO pass on " + targetText() + ": title and meta description (unique, right length), one h1 and logical headings, lang attribute, canonical, Open Graph and Twitter tags, descriptive link text, image alt texts, structured data where it clearly fits, internal links, robots and sitemap if relevant, performance basics that affect ranking. Apply safe fixes with small edits. For anything that needs real content (texts, images, business data), list it as a question instead of inventing it.";
- }
- },
- a11y: {
- purpose: "audit",
- prompt: function () {
- return "Do an accessibility pass (WCAG 2.2 AA) on " + targetText() + ": landmarks and heading order, labels for every form control, error messages linked to fields, alt texts, link and button names, keyboard access and visible focus, colour contrast, target size, language attributes, reduced motion, ARIA only where native HTML is not enough. Fix what you can with small edits and list what needs the user's decision.";
- }
- },
- responsive: {
- purpose: "verify",
- viewer: true,
- prompt: function () {
- return "Make " + targetText() + " work well on phones, tablets and desktops. Use the responsiveness report below (and screenshots if attached). Fix horizontal overflow, cramped or tiny tap targets, unreadable text and broken layouts with mobile-first CSS and minimal changes. Check again with the preview tools after fixing.";
- }
- },
- audit: {
- purpose: "audit",
- viewer: true,
- readOnly: true,
- prompt: function () {
- return "Review the responsiveness and quality report below for " + targetText() + " (and the screenshots if attached). List the problems by priority, each with the exact fix you would make (file and change). Do not change any files now; ask which fixes to apply.";
- }
- },
- translate: {
- purpose: "translate",
- args: true,
- prompt: function (args) {
- var lang = args || "English";
- var sel = selection();
- return sel
- ? "Translate the selected text into " + lang + ". Keep all markup, attributes, code, URLs and placeholders unchanged. Reply with the translation only."
- : "Translate the human-readable texts of " + targetText() + " into " + lang + ": visible text, alt, title, aria-label, placeholder, meta description and title. Keep markup, ids, classes, URLs and code unchanged, and update the lang attribute. Edit the file with small edits.";
- }
- },
- explain: {
- purpose: "summary",
- readOnly: true,
- prompt: function () {
- return selection()
- ? "Explain the selected code: what it does, how it works, and any problems or risks you notice. Do not change any files."
- : "Explain " + targetText() + ": its purpose, structure and how the parts work together, plus any problems or risks you notice. Do not change any files.";
- }
- },
- fix: {
- purpose: "fix",
- diag: true,
- prompt: function (args) {
- return "Fix the problems in " + targetText() + (args ? " (" + args + ")" : "") + ". Use the diagnostics below and the preview tools if available. Find the root cause, make small edits, and verify the result.";
- }
- },
- plan: {
- purpose: "plan",
- args: true,
- prompt: function (args) {
- return "Plan this task: " + (args || "(the user did not describe it; ask what to plan)") + "\nWrite the plan to .private/plan.md (create it or replace its content) as a short Markdown checklist: one line per step with the files involved and the tier that suits it in brackets: [cheap] for discovery and mechanical edits, [fast] for small edits, [mid] for normal changes and design, [top] for architecture or hard bugs. Keep it under 12 steps. Do not change any other file. Then summarise the plan in the chat and tell the user to type /do to run it.";
- }
- },
- "do": {
- purpose: null,
- prompt: function (args) {
- return "Carry out the plan in .private/plan.md" + (args ? " (" + args + ")" : "") + ": read it, work through the unchecked steps in order with small edits, and mark each finished step as [x] in .private/plan.md. Stop and ask if a step needs a decision. Finish with a short summary.";
- }
- },
- design: {
- purpose: "design",
- prompt: function (args) {
- return "Create or update the design profile in .private/design.md" + (args ? " (" + args + ")" : "") + ". If the project already has CSS, derive the profile from it (custom properties, colours, fonts, spacing, radii); otherwise propose a small, concrete, non-generic profile that fits the site. Format: palette as CSS custom properties with roles, font stacks and sizes (fluid with clamp), spacing scale, radius and shadow tokens, tone of voice, and short rules for buttons, cards, forms and navigation. Keep it under 60 lines and save it with a tool (the user approves the file). Then summarise it.";
- }
- }
- };
-
- var ORDER = ["help", "seo", "a11y", "responsive", "audit", "fix", "explain", "translate", "plan", "do", "design"];
-
- function parseFrontMatter(text) {
- var m = /^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/.exec(String(text || "").replace(/\r/g, ""));
- var meta = {};
- var body = String(text || "");
- if (m) {
- m[1].split("\n").forEach(function (line) {
- var kv = /^\s*([\w-]+)\s*:\s*(.*)$/.exec(line);
- if (kv) meta[kv[1].toLowerCase()] = kv[2].trim().replace(/^["']|["']$/g, "");
- });
- body = m[2];
- }
- return { meta: meta, body: body.trim() };
- }
-
- var recipeCache = { key: null, list: [] };
-
- async function loadRecipes(force) {
- if (!A.fs.provider) return [];
- var key = A.fs.provider.name;
- if (!force && recipeCache.key === key) return recipeCache.list;
- var list = [];
- try {
- if (await ai.tools.io.exists(RECIPES_DIR)) {
- var entries = await ai.tools.io.list(RECIPES_DIR);
- for (var e of entries) {
- if (e.kind !== "file" || !/\.md$/i.test(e.name)) continue;
- var path = RECIPES_DIR + "/" + e.name;
- var parsed = parseFrontMatter(await ai.tools.io.read(path));
- var name = (parsed.meta.name || e.name.replace(/\.md$/i, "")).toLowerCase().replace(/[^a-z0-9-]/g, "-");
- if (!name || BUILTIN[name] || !parsed.body) continue;
- list.push({ name: name, path: path, description: parsed.meta.description || "", tier: ai.ROLES.indexOf(parsed.meta.tier) >= 0 ? parsed.meta.tier : null, template: parsed.body });
- }
- }
- } catch (err) {
- list = [];
- }
- recipeCache = { key: key, list: list };
- return list;
- }
-
- A.on("files-changed", function () { recipeCache.key = null; });
- A.on("ai-change", function () { recipeCache.key = null; });
- A.on("workspace", function () { recipeCache.key = null; });
-
- function fill(template, args) {
- var picked = ai.viewer && ai.viewer.picked();
- var sel = selection();
- return template
- .replace(/\{selection\}/g, sel || "(no selection)")
- .replace(/\{file\}/g, target() || "(no file open)")
- .replace(/\{picked\}/g, picked ? picked.info.selector + " (details attached)" : "(no element picked)")
- .replace(/\{args\}/g, args || "");
- }
-
- async function helpText() {
- var lines = ["**" + t("ai.cmd.help_title") + "**", ""];
- ORDER.forEach(function (name) { lines.push("- `/" + name + "`: " + t("ai.cmd.desc_" + name)); });
- var recipes = await loadRecipes();
- if (recipes.length) {
- lines.push("", "**" + t("ai.cmd.recipes_title") + "**", "");
- recipes.forEach(function (r) { lines.push("- `/" + r.name + "`: " + (r.description || r.path)); });
- }
- lines.push("", t("ai.cmd.help_footer"));
- return lines.join("\n");
- }
-
- async function resolve(text) {
- var m = /^\/([a-z0-9-]+)(?:\s+([\s\S]*))?$/i.exec(String(text || "").trim());
- if (!m) return null;
- var name = m[1].toLowerCase();
- var args = (m[2] || "").trim();
- var cmd = BUILTIN[name];
- if (cmd) {
- if (cmd.local) return { local: true, text: await helpText() };
- var out = { name: name, text: cmd.prompt(args), purpose: cmd.purpose || null, readOnly: !!cmd.readOnly, extra: [] };
- if (cmd.diag) {
- var d = diagnosticsPart();
- if (d) out.extra.push(d);
- }
- if (cmd.viewer) {
- if (ai.allowed("preview") && A.preview.open && A.preview.target) {
- try {
- var report = await ai.viewer.audit({ screenshots: ai.allowed("screenshot") });
- out.extra = out.extra.concat(ai.viewer.auditParts(report, true));
- } catch (e) {
- out.extra.push(dataPart(t("ai.viewer.audit_source"), e.message));
- }
- } else {
- out.extra.push({ type: "text", text: t("ai.cmd.no_preview_note") });
- }
- }
- return out;
- }
- var recipe = (await loadRecipes()).find(function (r) { return r.name === name; });
- if (recipe) return { name: name, text: fill(recipe.template, args), override: recipe.tier ? { role: recipe.tier } : null, extra: [] };
- return { error: t("ai.cmd.unknown", { name: name }) };
- }
-
- async function suggestions(prefix) {
- var p = String(prefix || "").replace(/^\//, "").toLowerCase();
- var list = ORDER.map(function (n) { return { name: n, description: t("ai.cmd.desc_" + n), builtin: true }; })
- .concat((await loadRecipes()).map(function (r) { return { name: r.name, description: r.description || r.path, builtin: false }; }));
- return list.filter(function (c) { return c.name.indexOf(p) === 0; });
- }
-
- var RECIPE_TEMPLATE = "---\nname: {name}\ndescription: {description}\ntier: mid\n---\n{body}\n";
-
- async function createRecipe(name) {
- var slug = String(name || "").toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
- if (!slug) throw new Error(t("ai.cmd.recipe_bad_name"));
- if (BUILTIN[slug]) throw new Error(t("ai.cmd.recipe_reserved", { name: slug }));
- var file = "recipes/" + slug + ".md";
- if (await ai.private.exists(file)) throw new Error(t("ai.tool.err_exists", { path: ai.private.path(file) }));
- var text = RECIPE_TEMPLATE.replace("{name}", slug).replace("{description}", t("ai.cmd.recipe_tpl_desc")).replace("{body}", t("ai.cmd.recipe_tpl_body"));
- if (!(await ai.private.write(file, text))) return null;
- recipeCache.key = null;
- return ai.private.path(file);
- }
-
- var PHP_RULES = [
- { re: /(->\s*(?:query|exec)|mysqli_query|mysql_query|pg_query)\s*\([^;]*\$_(GET|POST|REQUEST|COOKIE)/i, key: "ai.quality.sql_input", high: true },
- { re: /(->\s*(?:query|exec)|mysqli_query|mysql_query)\s*\(\s*(["'])[^"']*\$\w+/i, key: "ai.quality.sql_concat", high: true },
- { re: /(->\s*(?:query|exec)|mysqli_query)\s*\([^;)]*["']\s*\.\s*\$\w+/i, key: "ai.quality.sql_concat", high: true },
- { re: /\b(echo|print)\b(?![^;]*htmlspecialchars)[^;]*\$_(GET|POST|REQUEST|COOKIE|SERVER\[\s*["'](?:PHP_SELF|REQUEST_URI|QUERY_STRING)["'])/i, key: "ai.quality.xss", high: true },
- { re: /<\?=\s*\$_(GET|POST|REQUEST|COOKIE)/i, key: "ai.quality.xss", high: true },
- { re: /\b(include|require)(_once)?\s*\(?[^;]*\$_(GET|POST|REQUEST|COOKIE)/i, key: "ai.quality.include", high: true },
- { re: /\beval\s*\(/i, key: "ai.quality.eval", high: true },
- { re: /\bunserialize\s*\(\s*\$_(GET|POST|REQUEST|COOKIE)/i, key: "ai.quality.unserialize", high: true },
- { re: /\bextract\s*\(\s*\$_/i, key: "ai.quality.extract", high: true },
- { re: /\b(md5|sha1)\s*\([^)]*pass/i, key: "ai.quality.weak_hash", high: true },
- { re: /ini_set\s*\(\s*["']display_errors["']\s*,\s*["']?(1|on|true)/i, key: "ai.quality.display_errors", high: false },
- { re: /\b(shell_exec|system|passthru|exec|popen)\s*\([^;]*\$_(GET|POST|REQUEST|COOKIE)/i, key: "ai.quality.command", high: true }
- ];
-
- function phpChecks(path, text) {
- var out = [];
- var lines = text.split("\n");
- lines.forEach(function (line, i) {
- PHP_RULES.forEach(function (r) {
- if (r.re.test(line) && out.length < 20) out.push({ path: path, line: i + 1, severity: r.high ? "error" : "warning", security: true, message: t(r.key) });
- });
- });
- var postForm = /<form\b[^>]*method\s*=\s*["']?post/i.test(text);
- var handlesPost = /\$_POST\b/.test(text) || /\$_SERVER\s*\[\s*["']REQUEST_METHOD["']\s*\]/.test(text);
- if (postForm && handlesPost && !/csrf|_token|token/i.test(text)) out.push({ path: path, line: 1, severity: "warning", security: true, message: t("ai.quality.csrf") });
- return out;
- }
-
- async function check(paths) {
- var problems = [];
- var seen = {};
- for (var p of paths || []) {
- if (!p || seen[p] || ai.tools.isPrivate(p) || !QUALITY_EXT.test(p)) continue;
- seen[p] = true;
- var text;
- try {
- if (!(await ai.tools.io.exists(p))) continue;
- text = await ai.tools.io.read(p);
- } catch (e) {
- continue;
- }
- try {
- A.intellisense.lintText(text, p).forEach(function (d) {
- if (d.severity === "info") return;
- problems.push({ path: p, line: d.line, severity: d.severity, security: false, message: d.message });
- });
- } catch (e) { }
- if (/\.(php|phtml|inc)$/i.test(p)) problems = problems.concat(phpChecks(p, text));
- }
- var blocking = problems.filter(function (x) { return x.severity === "error"; });
- var text2 = problems.slice(0, 40).map(function (x) {
- return x.path + ":" + x.line + " [" + x.severity + (x.security ? ", security" : "") + "] " + x.message;
- }).join("\n");
- var parts = problems.length ? [dataPart(t("ai.quality.source"), t("ai.quality.head") + "\n" + text2 + "\n\n" + t("ai.quality.instruction"))] : [];
- return { problems: problems, blocking: blocking, parts: parts };
- }
-
- ai.commands = {
- BUILTIN: BUILTIN,
- ORDER: ORDER,
- resolve: resolve,
- suggestions: suggestions,
- loadRecipes: loadRecipes,
- createRecipe: createRecipe,
- parseFrontMatter: parseFrontMatter,
- readOnlyFilter: function (tools) {
- return tools.filter(function (x) { return !READ_ONLY.test(x.name); });
- }
- };
-
- ai.quality = { check: check, phpChecks: phpChecks };
- })();
-