@loccal/core 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,18 @@
1
+ export type FileIconSpec = {
2
+ /** Identificador estavel do tipo (ex.: "typescript", "image"). */
3
+ id: string;
4
+ /** Sigla de 1 a 3 caracteres desenhada no selo. */
5
+ label: string;
6
+ /** Cor do selo (hex). */
7
+ color: string;
8
+ /** Cor da sigla (hex), escolhida pelo contraste com o selo. */
9
+ ink: string;
10
+ };
11
+ /** Tipo do arquivo pelo nome completo e depois pela extensao; undefined = sem icone especifico. */
12
+ export declare function fileTypeId(name: string): string | undefined;
13
+ /** Especificacao do icone de um arquivo, ou undefined para o icone generico de arquivo. */
14
+ export declare function fileIconFor(name: string): FileIconSpec | undefined;
15
+ /** Todos os tipos com icone (para galerias e testes). */
16
+ export declare const fileIconTypes: readonly string[];
17
+ /** SVG do selo (string). `size` em px. */
18
+ export declare function fileIconSvg(spec: FileIconSpec, size?: number): string;
@@ -0,0 +1,136 @@
1
+ // Icones de tipo de arquivo (linguagens, formatos e extensoes mais usadas). Vanilla e sem DOM:
2
+ // `fileIconFor` escolhe o icone pelo nome; `fileIconSvg` o desenha como um selo colorido de 16x16 com a sigla do tipo.
3
+ // As formas sao proprias da Loccal UI (selo + sigla), nao reproduzem logotipos de terceiros.
4
+ const DARK = "#1b1b1f";
5
+ const LIGHT = "#ffffff";
6
+ const BY_TYPE = {
7
+ javascript: ["JS", "#f0db4f", DARK],
8
+ typescript: ["TS", "#3178c6"],
9
+ jsx: ["JX", "#f0db4f", DARK],
10
+ tsx: ["TX", "#3178c6"],
11
+ json: ["{}", "#d4a72c", DARK],
12
+ html: ["<>", "#e34f26"],
13
+ xml: ["<>", "#d9822b", DARK],
14
+ svg: ["SV", "#e8912d", DARK],
15
+ css: ["#", "#1572b6"],
16
+ scss: ["S", "#cd6799"],
17
+ less: ["L", "#2b4a7a"],
18
+ vue: ["V", "#41b883", DARK],
19
+ svelte: ["SV", "#ff3e00"],
20
+ go: ["GO", "#00a7c4"],
21
+ rust: ["RS", "#b7410e"],
22
+ c: ["C", "#5560bf"],
23
+ cpp: ["C+", "#00599c"],
24
+ header: ["H", "#7c6fcf"],
25
+ csharp: ["C#", "#8a3f96"],
26
+ java: ["JV", "#d9730d"],
27
+ kotlin: ["KT", "#7f52ff"],
28
+ swift: ["SW", "#f05138"],
29
+ dart: ["DT", "#0175c2"],
30
+ php: ["PH", "#777bb3"],
31
+ python: ["PY", "#3776ab"],
32
+ ruby: ["RB", "#cc342d"],
33
+ lua: ["LU", "#2c2d72"],
34
+ perl: ["PL", "#39457e"],
35
+ elixir: ["EX", "#6e4a7e"],
36
+ haskell: ["HS", "#5e5086"],
37
+ scala: ["SC", "#dc322f"],
38
+ zig: ["ZG", "#f7a41d", DARK],
39
+ r: ["R", "#276dc3"],
40
+ shell: [">_", "#3d9a3a"],
41
+ powershell: ["PS", "#2671be"],
42
+ batch: [">_", "#5a6169"],
43
+ sql: ["DB", "#e38c00", DARK],
44
+ yaml: ["YM", "#c2353a"],
45
+ toml: ["TM", "#9c4221"],
46
+ config: ["CF", "#6b7280"],
47
+ env: ["EN", "#6b7280"],
48
+ markdown: ["MD", "#3b82a0"],
49
+ text: ["TX", "#6b7280"],
50
+ log: ["LG", "#6b7280"],
51
+ docker: ["DK", "#2496ed"],
52
+ make: ["MK", "#6d8086"],
53
+ git: ["GT", "#e0432b"],
54
+ diff: ["±", "#6b7280"],
55
+ license: ["LI", "#6b7280"],
56
+ lock: ["LK", "#7a6f5c"],
57
+ csv: ["CS", "#2e9d6a"],
58
+ database: ["DB", "#7b61a8"],
59
+ pdf: ["PD", "#d63a35"],
60
+ doc: ["DC", "#2b6cb0"],
61
+ sheet: ["XL", "#1f8a4c"],
62
+ slides: ["PP", "#d2562a"],
63
+ image: ["IM", "#1f9e91"],
64
+ video: ["VD", "#9c3fb0"],
65
+ audio: ["AU", "#d6336c"],
66
+ font: ["Aa", "#6b7280"],
67
+ archive: ["ZP", "#8a6d52"],
68
+ binary: ["01", "#4b5563"],
69
+ executable: ["EX", "#4b5563"],
70
+ };
71
+ const EXT = {
72
+ js: "javascript", mjs: "javascript", cjs: "javascript", jsx: "jsx", ts: "typescript", mts: "typescript", cts: "typescript", tsx: "tsx",
73
+ json: "json", jsonc: "json", json5: "json", map: "json", webmanifest: "json", ipynb: "json",
74
+ html: "html", htm: "html", xhtml: "html", xml: "xml", xsd: "xml", xsl: "xml", plist: "xml", csproj: "xml", xaml: "xml", rss: "xml", svg: "svg",
75
+ css: "css", scss: "scss", sass: "scss", less: "less", vue: "vue", svelte: "svelte", astro: "html",
76
+ go: "go", rs: "rust", c: "c", h: "header", hpp: "header", hh: "header", cpp: "cpp", cc: "cpp", cxx: "cpp", ino: "cpp", cs: "csharp",
77
+ java: "java", kt: "kotlin", kts: "kotlin", swift: "swift", dart: "dart", php: "php", py: "python", pyw: "python", pyi: "python",
78
+ rb: "ruby", rake: "ruby", lua: "lua", pl: "perl", pm: "perl", ex: "elixir", exs: "elixir", hs: "haskell", scala: "scala", sc: "scala",
79
+ zig: "zig", r: "r",
80
+ sh: "shell", bash: "shell", zsh: "shell", fish: "shell", ksh: "shell", ps1: "powershell", psm1: "powershell", psd1: "powershell", bat: "batch", cmd: "batch",
81
+ sql: "sql", yaml: "yaml", yml: "yaml", toml: "toml", ini: "config", cfg: "config", conf: "config", properties: "config", editorconfig: "config", env: "env",
82
+ md: "markdown", markdown: "markdown", mdx: "markdown", rst: "text", txt: "text", log: "log", diff: "diff", patch: "diff",
83
+ mk: "make", mak: "make", lock: "lock", csv: "csv", tsv: "csv", db: "database", sqlite: "database", sqlite3: "database", parquet: "database",
84
+ pdf: "pdf", doc: "doc", docx: "doc", odt: "doc", rtf: "doc", xls: "sheet", xlsx: "sheet", ods: "sheet", ppt: "slides", pptx: "slides", odp: "slides",
85
+ png: "image", jpg: "image", jpeg: "image", gif: "image", webp: "image", bmp: "image", ico: "image", avif: "image", tif: "image", tiff: "image", heic: "image", icns: "image",
86
+ mp4: "video", mkv: "video", mov: "video", avi: "video", webm: "video", m4v: "video",
87
+ mp3: "audio", wav: "audio", flac: "audio", ogg: "audio", m4a: "audio", aac: "audio", opus: "audio",
88
+ ttf: "font", otf: "font", woff: "font", woff2: "font", eot: "font",
89
+ zip: "archive", tar: "archive", gz: "archive", tgz: "archive", bz2: "archive", xz: "archive", "7z": "archive", rar: "archive", zst: "archive", iso: "archive", jar: "archive", war: "archive",
90
+ exe: "executable", msi: "executable", app: "executable", apk: "executable", bin: "binary", dll: "binary", so: "binary", dylib: "binary", o: "binary", obj: "binary", class: "binary", wasm: "binary", pyc: "binary",
91
+ };
92
+ const NAME = {
93
+ dockerfile: "docker", ".dockerignore": "docker", "docker-compose.yml": "docker", "docker-compose.yaml": "docker", "compose.yaml": "docker", "compose.yml": "docker",
94
+ makefile: "make", gnumakefile: "make", ".gitignore": "git", ".gitattributes": "git", ".gitmodules": "git", ".gitconfig": "git",
95
+ license: "license", "license.md": "license", "license.txt": "license", copying: "license", notice: "license",
96
+ "package-lock.json": "lock", "pnpm-lock.yaml": "lock", "yarn.lock": "lock", "go.sum": "lock", "cargo.lock": "lock", "poetry.lock": "lock", "composer.lock": "lock", gemfile: "ruby", rakefile: "ruby",
97
+ "go.mod": "go", "go.work": "go", ".env": "env", ".npmrc": "config", ".editorconfig": "config", ".prettierrc": "json", ".eslintrc": "json",
98
+ ".bashrc": "shell", ".zshrc": "shell", ".profile": "shell", readme: "markdown",
99
+ };
100
+ /** Tipo do arquivo pelo nome completo e depois pela extensao; undefined = sem icone especifico. */
101
+ export function fileTypeId(name) {
102
+ const base = name.replace(/\\/g, "/").split("/").pop().toLowerCase();
103
+ if (NAME[base])
104
+ return NAME[base];
105
+ if (base.startsWith(".env."))
106
+ return "env";
107
+ const dot = base.lastIndexOf(".");
108
+ if (dot <= 0)
109
+ return undefined;
110
+ const ext = base.slice(dot + 1);
111
+ if (base.endsWith(".d.ts"))
112
+ return "typescript";
113
+ return EXT[ext];
114
+ }
115
+ /** Especificacao do icone de um arquivo, ou undefined para o icone generico de arquivo. */
116
+ export function fileIconFor(name) {
117
+ const id = fileTypeId(name);
118
+ if (!id)
119
+ return undefined;
120
+ const e = BY_TYPE[id];
121
+ if (!e)
122
+ return undefined;
123
+ return { id, label: e[0], color: e[1], ink: e[2] ?? LIGHT };
124
+ }
125
+ /** Todos os tipos com icone (para galerias e testes). */
126
+ export const fileIconTypes = Object.keys(BY_TYPE);
127
+ const escXml = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
128
+ /** SVG do selo (string). `size` em px. */
129
+ export function fileIconSvg(spec, size = 16) {
130
+ const n = [...spec.label].length;
131
+ const fs = n === 1 ? 9.5 : n === 2 ? 7 : 5.5;
132
+ return (`<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 16 16" aria-hidden="true" focusable="false" data-file-type="${spec.id}">` +
133
+ `<rect x="0.75" y="0.75" width="14.5" height="14.5" rx="3.25" fill="${spec.color}"/>` +
134
+ `<text x="8" y="${(8 + fs * 0.36).toFixed(2)}" text-anchor="middle" font-family="ui-monospace,SFMono-Regular,Menlo,Consolas,monospace" font-size="${fs}" font-weight="700" fill="${spec.ink}">${escXml(spec.label)}</text>` +
135
+ `</svg>`);
136
+ }
@@ -0,0 +1,16 @@
1
+ export type TokenType = "comment" | "string" | "number" | "keyword" | "type" | "function" | "constant" | "operator" | "punctuation" | "tag" | "attr" | "property" | "variable" | "meta" | "heading" | "inserted" | "deleted" | "plain";
2
+ export type Token = {
3
+ type: TokenType;
4
+ text: string;
5
+ };
6
+ export type LanguageId = "javascript" | "typescript" | "jsx" | "tsx" | "json" | "html" | "xml" | "css" | "scss" | "less" | "go" | "rust" | "c" | "cpp" | "csharp" | "java" | "kotlin" | "swift" | "dart" | "php" | "python" | "ruby" | "lua" | "shell" | "powershell" | "batch" | "sql" | "yaml" | "toml" | "ini" | "markdown" | "dockerfile" | "makefile" | "diff" | "zig" | "scala" | "r" | "perl" | "elixir" | "haskell" | "plaintext";
7
+ /** Linguagem de um arquivo pelo nome (nome completo primeiro, depois extensao). */
8
+ export declare function languageForFile(name: string): LanguageId;
9
+ /** Normaliza um identificador de linguagem (aceita extensoes e apelidos). */
10
+ export declare function resolveLanguage(lang: string): LanguageId;
11
+ /** Tokeniza o texto inteiro. A concatenacao dos tokens sempre reproduz exatamente a entrada. */
12
+ export declare function tokenize(code: string, lang: LanguageId | string): Token[];
13
+ /** Divide os tokens por linha (sem o "\n"), preservando tokens que atravessam linhas (comentarios de bloco, strings). */
14
+ export declare function tokenizeLinesOf(code: string, lang: LanguageId | string): Token[][];
15
+ /** HTML com <span class="lt-<tipo">; as cores vem do CSS (ver --code-* nos tokens). */
16
+ export declare function highlightToHtml(code: string, lang: LanguageId | string): string;
@@ -0,0 +1,538 @@
1
+ // Realce de sintaxe vanilla: sem dependencias e sem DOM. Um tokenizador de uma passada por linguagem, pensado para
2
+ // visualizar arquivos (nao e um parser). Cobre as linguagens mais usadas e cai em texto simples nas demais.
3
+ const words = (s) => new Set(s.split(/\s+/).filter(Boolean));
4
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\/-]/g, "\\$&");
5
+ const sticky = (re) => new RegExp(re.source, re.flags.includes("y") ? re.flags : re.flags + "y");
6
+ const NUMBER = /(?:0[xX][0-9a-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:\d[\d_]*\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)[a-zA-Z]{0,3}\b/;
7
+ const OPERATOR = /[+\-*/%=<>!&|^~?:]+/;
8
+ const PUNCT = /[{}()[\];,.]/;
9
+ function compile(def) {
10
+ const rules = [];
11
+ const flag = def.caseInsensitive ? "i" : "";
12
+ for (const b of def.block ?? [])
13
+ rules.push(["comment", sticky(new RegExp(`${esc(b[0])}[\\s\\S]*?(?:${esc(b[1])}|$)`))]);
14
+ for (const l of def.line ?? [])
15
+ rules.push(["comment", sticky(new RegExp(`${esc(l)}.*`))]);
16
+ for (const q of def.multiline ?? [])
17
+ rules.push(["string", sticky(new RegExp(`${esc(q)}[\\s\\S]*?(?:${esc(q)}|$)`))]);
18
+ for (const q of def.strings ?? []) {
19
+ const multi = q === "`";
20
+ rules.push(["string", sticky(new RegExp(`${esc(q)}(?:\\\\[\\s\\S]|[^\\\\${multi ? "" : "\\n"}${esc(q)}])*(?:${esc(q)}|$)`))]);
21
+ }
22
+ if (def.regex)
23
+ rules.push(["string", sticky(/\/(?![/*])(?:\\.|\[(?:\\.|[^\]\\\n])*\]|[^/\\\n[])+\/[dgimsuvy]*/)]);
24
+ if (def.meta)
25
+ rules.push(["meta", sticky(def.meta)]);
26
+ rules.push(["number", sticky(NUMBER)]);
27
+ if (def.varPrefix)
28
+ rules.push(["variable", sticky(new RegExp(`[${esc(def.varPrefix)}][A-Za-z_][\\w]*|\\$\\{[^}\\n]*\\}`))]);
29
+ rules.push(["plain", sticky(/[A-Za-z_À-￿][\wÀ-￿]*/)]);
30
+ rules.push(["operator", sticky(def.operators ?? OPERATOR)]);
31
+ rules.push(["punctuation", sticky(PUNCT)]);
32
+ const norm = (s) => (flag ? s.toLowerCase() : s);
33
+ const classify = (id, next) => {
34
+ const k = norm(id);
35
+ if (def.keywords?.has(k))
36
+ return "keyword";
37
+ if (def.constants?.has(k))
38
+ return "constant";
39
+ if (def.types?.has(k))
40
+ return "type";
41
+ if (next === "(")
42
+ return "function";
43
+ if (def.pascalTypes && /^[A-Z][A-Za-z0-9_]*[a-z]/.test(id))
44
+ return "type";
45
+ return "plain";
46
+ };
47
+ return { rules, classify };
48
+ }
49
+ const JS_KW = "as async await break case catch class const continue debugger default delete do else enum export extends finally for from function get if implements import in instanceof interface let new of package private protected public readonly return set static super switch this throw try type typeof var void while with yield declare namespace abstract satisfies keyof infer is override";
50
+ const JS_CONST = "true false null undefined NaN Infinity";
51
+ const JS_TYPES = "string number boolean any unknown never object symbol bigint Array Promise Map Set Record Partial Readonly Date Error RegExp";
52
+ const DEFS = {
53
+ javascript: { line: ["//"], block: [["/*", "*/"]], strings: ['"', "'", "`"], regex: true, keywords: words(JS_KW), constants: words(JS_CONST), pascalTypes: true, meta: /@[A-Za-z_]\w*/ },
54
+ go: { line: ["//"], block: [["/*", "*/"]], strings: ['"', "'", "`"], keywords: words("break case chan const continue default defer else fallthrough for func go goto if import interface map package range return select struct switch type var"), constants: words("true false nil iota"), types: words("string int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr float32 float64 complex64 complex128 bool byte rune error any comparable") },
55
+ rust: { line: ["//"], block: [["/*", "*/"]], strings: ['"', "'"], keywords: words("as async await break const continue crate dyn else enum extern fn for if impl in let loop match mod move mut pub ref return self Self static struct super trait type unsafe use where while"), constants: words("true false None Some Ok Err"), types: words("i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize f32 f64 bool char str String Vec Option Result Box Rc Arc"), pascalTypes: true, meta: /#!?\[[^\]\n]*\]/, operators: /[+\-*/%=<>!&|^~?:]+/ },
56
+ c: { line: ["//"], block: [["/*", "*/"]], strings: ['"', "'"], keywords: words("auto break case const continue default do else enum extern for goto if inline register restrict return sizeof static struct switch typedef union volatile while"), constants: words("true false NULL"), types: words("void char short int long float double signed unsigned size_t bool uint8_t uint16_t uint32_t uint64_t int8_t int16_t int32_t int64_t FILE"), meta: /#\s*[a-z]+(?:[ \t]*<[^>\n]*>)?/ },
57
+ cpp: { line: ["//"], block: [["/*", "*/"]], strings: ['"', "'"], keywords: words("alignas alignof and asm auto break case catch class concept const consteval constexpr constinit const_cast continue co_await co_return co_yield decltype default delete do dynamic_cast else enum explicit export extern for friend goto if inline mutable namespace new noexcept not operator or private protected public register reinterpret_cast requires return sizeof static static_assert static_cast struct switch template this throw try typedef typeid typename union using virtual volatile while override final"), constants: words("true false nullptr NULL"), types: words("void char short int long float double signed unsigned bool size_t wchar_t string vector map set unique_ptr shared_ptr optional"), meta: /#\s*[a-z]+(?:[ \t]*<[^>\n]*>)?/ },
58
+ csharp: { line: ["//"], block: [["/*", "*/"]], strings: ['"', "'"], keywords: words("abstract as async await base break case catch checked class const continue default delegate do else enum event explicit extern finally fixed for foreach goto if implicit in interface internal is lock namespace new operator out override params private protected public readonly ref return sealed sizeof stackalloc static struct switch this throw try typeof unchecked unsafe using virtual volatile while var record get set init yield where"), constants: words("true false null"), types: words("bool byte char decimal double float int long object sbyte short string uint ulong ushort void dynamic"), pascalTypes: true, meta: /#\s*[a-z]+/ },
59
+ java: { line: ["//"], block: [["/*", "*/"]], strings: ['"', "'"], keywords: words("abstract assert break case catch class const continue default do else enum extends final finally for goto if implements import instanceof interface native new package private protected public return static strictfp super switch synchronized this throw throws transient try var volatile while record sealed permits"), constants: words("true false null"), types: words("boolean byte char double float int long short void String Object Integer List Map Set"), pascalTypes: true, meta: /@[A-Za-z_]\w*/ },
60
+ kotlin: { line: ["//"], block: [["/*", "*/"]], strings: ['"', "'"], multiline: ['"""'], keywords: words("abstract annotation as break by catch class companion const constructor continue crossinline data delegate do else enum expect external final finally for fun get if import in infix init inline inner interface internal is lateinit noinline object open operator out override package private protected public reified return sealed set super suspend tailrec this throw try typealias val var vararg when where while"), constants: words("true false null"), types: words("Int Long Short Byte Float Double Boolean Char String Unit Any Nothing List Map Set Array"), pascalTypes: true, meta: /@[A-Za-z_]\w*/ },
61
+ swift: { line: ["//"], block: [["/*", "*/"]], strings: ['"'], multiline: ['"""'], keywords: words("actor as associatedtype async await break case catch class continue default defer deinit do else enum extension fallthrough fileprivate for func guard if import in init inout internal is let nil open operator override private protocol public repeat rethrows return self Self static struct subscript super switch throw throws try typealias var where while"), constants: words("true false nil"), types: words("Int Double Float Bool String Character Array Dictionary Set Optional Any AnyObject Void"), pascalTypes: true, meta: /[@#][A-Za-z_]\w*/ },
62
+ dart: { line: ["//"], block: [["/*", "*/"]], strings: ['"', "'"], keywords: words("abstract as assert async await break case catch class const continue covariant default deferred do dynamic else enum export extends extension external factory final finally for Function get hide if implements import in interface is late library mixin new on operator part required rethrow return set show static super switch sync this throw try typedef var void while with yield"), constants: words("true false null"), types: words("int double num bool String List Map Set Future Stream Object dynamic void"), pascalTypes: true, meta: /@[A-Za-z_]\w*/ },
63
+ php: { line: ["//", "#"], block: [["/*", "*/"]], strings: ['"', "'"], varPrefix: "$", caseInsensitive: true, keywords: words("abstract and as break callable case catch class clone const continue declare default do echo else elseif empty enddeclare endfor endforeach endif endswitch endwhile enum extends final finally fn for foreach function global goto if implements include include_once instanceof insteadof interface isset list match namespace new or print private protected public readonly require require_once return static switch throw trait try unset use var while xor yield"), constants: words("true false null"), types: words("int float string bool array object mixed void never iterable callable self parent"), meta: /<\?php|<\?=|\?>/ },
64
+ python: { line: ["#"], strings: ['"', "'"], multiline: ['"""', "'''"], keywords: words("and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield match case"), constants: words("True False None self cls"), types: words("int float str bool list dict set tuple bytes object type complex range"), pascalTypes: true, meta: /@[A-Za-z_][\w.]*/ },
65
+ ruby: { line: ["#"], block: [["=begin", "=end"]], strings: ['"', "'", "`"], keywords: words("alias and begin break case class def defined? do else elsif end ensure for if in module next not or redo rescue retry return self super then undef unless until when while yield require require_relative include extend attr_accessor attr_reader attr_writer private protected public"), constants: words("true false nil"), pascalTypes: true, varPrefix: "@$" },
66
+ lua: { line: ["--"], block: [["--[[", "]]"]], strings: ['"', "'"], multiline: ["[[", "[=["], keywords: words("and break do else elseif end for function goto if in local not or repeat return then until while"), constants: words("true false nil self") },
67
+ shell: { line: ["#"], strings: ['"', "'", "`"], varPrefix: "$", keywords: words("if then else elif fi for while until do done case esac in function select time return exit break continue export local readonly declare unset source alias set shift trap eval exec cd echo printf read test"), constants: words("true false"), operators: /[|&;<>=!]+/ },
68
+ powershell: { line: ["#"], block: [["<#", "#>"]], strings: ['"', "'"], varPrefix: "$", caseInsensitive: true, keywords: words("begin break catch class continue data do dynamicparam else elseif end enum exit filter finally for foreach from function if in param process return switch throw trap try until using var while workflow"), constants: words("true false null"), operators: /[|&;<>=!+\-*/%]+/ },
69
+ batch: { line: ["rem ", "::"], strings: ['"'], caseInsensitive: true, keywords: words("echo set if else for in do goto call exit not exist defined errorlevel pause start setlocal endlocal shift cd mkdir rmdir copy move del type cls"), varPrefix: "%" },
70
+ sql: { line: ["--"], block: [["/*", "*/"]], strings: ["'", '"'], caseInsensitive: true, keywords: words("add all alter and as asc between by case check column commit constraint create cross database default delete desc distinct drop else end exists foreign from full group having if in index inner insert into is join key left like limit not null offset on or order outer primary references replace right rollback select set table then top union unique update values view when where with returning begin transaction"), constants: words("true false null"), types: words("int integer bigint smallint varchar char text boolean date datetime timestamp numeric decimal float real json uuid serial") },
71
+ zig: { line: ["//"], strings: ['"', "'"], keywords: words("align allowzero and anyframe anytype asm async await break callconv catch comptime const continue defer else enum errdefer error export extern fn for if inline linksection noalias nosuspend opaque or orelse packed pub resume return struct suspend switch test threadlocal try union unreachable usingnamespace var volatile while"), constants: words("true false null undefined"), types: words("u8 u16 u32 u64 i8 i16 i32 i64 usize isize f32 f64 bool void type anyerror"), meta: /@[A-Za-z_]\w*/ },
72
+ scala: { line: ["//"], block: [["/*", "*/"]], strings: ['"', "'"], multiline: ['"""'], keywords: words("abstract case catch class def do else extends final finally for forSome if implicit import lazy match new object override package private protected return sealed super this throw trait try type val var while with yield given using enum then"), constants: words("true false null"), pascalTypes: true, meta: /@[A-Za-z_]\w*/ },
73
+ r: { line: ["#"], strings: ['"', "'"], keywords: words("if else repeat while function for next break in library require return"), constants: words("TRUE FALSE NULL NA NA_integer_ NA_real_ NA_character_ Inf NaN") },
74
+ perl: { line: ["#"], strings: ['"', "'"], varPrefix: "$@%", keywords: words("my our local use no package sub if elsif else unless while until for foreach last next redo return die warn print say require do eval and or not"), },
75
+ elixir: { line: ["#"], strings: ['"', "'"], multiline: ['"""'], keywords: words("def defp defmodule defmacro defstruct defprotocol defimpl do end fn if else unless case cond when with for in import require alias use quote unquote raise rescue try catch after receive send spawn and or not"), constants: words("true false nil"), pascalTypes: true, meta: /@[a-z_]\w*/ },
76
+ haskell: { line: ["--"], block: [["{-", "-}"]], strings: ['"', "'"], keywords: words("case class data default deriving do else family forall foreign if import in infix infixl infixr instance let module newtype of qualified then type where"), constants: words("True False Nothing Just Left Right"), pascalTypes: true },
77
+ };
78
+ /** TS/JSX/TSX compartilham a definicao do JS. */
79
+ DEFS.typescript = DEFS.javascript;
80
+ DEFS.jsx = DEFS.javascript;
81
+ DEFS.tsx = DEFS.javascript;
82
+ const ALIASES = {
83
+ js: "javascript", mjs: "javascript", cjs: "javascript", ts: "typescript", mts: "typescript", cts: "typescript",
84
+ jsx: "jsx", tsx: "tsx", json: "json", jsonc: "json", json5: "json", webmanifest: "json", map: "json", ipynb: "json",
85
+ html: "html", htm: "html", xhtml: "html", vue: "html", svelte: "html", astro: "html", xml: "xml", svg: "xml", xsd: "xml", xsl: "xml",
86
+ plist: "xml", csproj: "xml", props: "xml", targets: "xml", rss: "xml", atom: "xml", xaml: "xml",
87
+ css: "css", scss: "scss", sass: "scss", less: "less", go: "go", rs: "rust", c: "c", h: "c", cpp: "cpp", cc: "cpp", cxx: "cpp",
88
+ hpp: "cpp", hh: "cpp", hxx: "cpp", ino: "cpp", cs: "csharp", java: "java", kt: "kotlin", kts: "kotlin", swift: "swift", dart: "dart",
89
+ php: "php", py: "python", pyw: "python", pyi: "python", rb: "ruby", rake: "ruby", gemspec: "ruby", lua: "lua", sh: "shell", bash: "shell",
90
+ zsh: "shell", fish: "shell", ksh: "shell", ps1: "powershell", psm1: "powershell", psd1: "powershell", bat: "batch", cmd: "batch",
91
+ sql: "sql", yaml: "yaml", yml: "yaml", toml: "toml", ini: "ini", cfg: "ini", conf: "ini", properties: "ini", env: "ini", editorconfig: "ini",
92
+ md: "markdown", markdown: "markdown", mdx: "markdown", dockerfile: "dockerfile", mk: "makefile", mak: "makefile",
93
+ diff: "diff", patch: "diff", zig: "zig", scala: "scala", sc: "scala", r: "r", pl: "perl", pm: "perl", ex: "elixir", exs: "elixir", hs: "haskell",
94
+ txt: "plaintext", log: "plaintext", csv: "plaintext", tsv: "plaintext",
95
+ };
96
+ const BY_NAME = {
97
+ dockerfile: "dockerfile", makefile: "makefile", gnumakefile: "makefile", ".bashrc": "shell", ".zshrc": "shell", ".profile": "shell",
98
+ ".gitignore": "ini", ".gitattributes": "ini", ".gitconfig": "ini", ".npmrc": "ini", ".env": "ini", "cargo.lock": "toml", "go.mod": "go", "go.work": "go",
99
+ gemfile: "ruby", rakefile: "ruby", "tsconfig.json": "json", "package.json": "json", ".eslintrc": "json", ".prettierrc": "json",
100
+ };
101
+ /** Linguagem de um arquivo pelo nome (nome completo primeiro, depois extensao). */
102
+ export function languageForFile(name) {
103
+ const base = name.replace(/\\/g, "/").split("/").pop().toLowerCase();
104
+ if (BY_NAME[base])
105
+ return BY_NAME[base];
106
+ const dot = base.lastIndexOf(".");
107
+ if (dot < 0)
108
+ return "plaintext";
109
+ if (dot === 0)
110
+ return BY_NAME[base] ?? "plaintext";
111
+ return ALIASES[base.slice(dot + 1)] ?? "plaintext";
112
+ }
113
+ /** Normaliza um identificador de linguagem (aceita extensoes e apelidos). */
114
+ export function resolveLanguage(lang) {
115
+ const l = lang.toLowerCase();
116
+ return (ALIASES[l] ?? (l in DEFS || ["json", "html", "xml", "css", "scss", "less", "yaml", "toml", "ini", "markdown", "dockerfile", "makefile", "diff", "plaintext"].includes(l) ? l : "plaintext"));
117
+ }
118
+ const cache = new Map();
119
+ function compiled(lang) {
120
+ let c = cache.get(lang);
121
+ if (!c) {
122
+ c = compile(DEFS[lang]);
123
+ cache.set(lang, c);
124
+ }
125
+ return c;
126
+ }
127
+ function push(out, type, text) {
128
+ if (!text)
129
+ return;
130
+ const last = out[out.length - 1];
131
+ if (last && last.type === type)
132
+ last.text += text;
133
+ else
134
+ out.push({ type, text });
135
+ }
136
+ function scan(code, lang, out) {
137
+ const { rules, classify } = compiled(lang);
138
+ let i = 0;
139
+ while (i < code.length) {
140
+ let hit = false;
141
+ for (const [type, re] of rules) {
142
+ re.lastIndex = i;
143
+ const m = re.exec(code);
144
+ if (!m || m[0].length === 0)
145
+ continue;
146
+ let t = type;
147
+ if (type === "plain")
148
+ t = classify(m[0], code[i + m[0].length] ?? "");
149
+ push(out, t, m[0]);
150
+ i += m[0].length;
151
+ hit = true;
152
+ break;
153
+ }
154
+ if (!hit) {
155
+ push(out, "plain", code[i]);
156
+ i++;
157
+ }
158
+ }
159
+ }
160
+ // ---------- linguagens com gramatica propria
161
+ function tokenizeJson(code, out) {
162
+ const re = /("(?:\\.|[^"\\\n])*")(\s*:)?|(-?\d+\.?\d*(?:[eE][+-]?\d+)?)|(\btrue\b|\bfalse\b|\bnull\b)|(\/\/.*|\/\*[\s\S]*?\*\/)|([{}[\],:])|(\s+)|([\s\S])/gy;
163
+ let m;
164
+ while ((m = re.exec(code))) {
165
+ if (m[1]) {
166
+ push(out, m[2] ? "property" : "string", m[1]);
167
+ if (m[2])
168
+ push(out, "punctuation", m[2]);
169
+ }
170
+ else if (m[3])
171
+ push(out, "number", m[3]);
172
+ else if (m[4])
173
+ push(out, "constant", m[4]);
174
+ else if (m[5])
175
+ push(out, "comment", m[5]);
176
+ else if (m[6])
177
+ push(out, "punctuation", m[6]);
178
+ else
179
+ push(out, "plain", m[7] ?? m[8]);
180
+ }
181
+ }
182
+ function tokenizeMarkup(code, out) {
183
+ let i = 0;
184
+ while (i < code.length) {
185
+ if (code.startsWith("<!--", i)) {
186
+ const end = code.indexOf("-->", i + 4);
187
+ const stop = end < 0 ? code.length : end + 3;
188
+ push(out, "comment", code.slice(i, stop));
189
+ i = stop;
190
+ }
191
+ else if (/^<!\[CDATA\[/.test(code.slice(i, i + 9))) {
192
+ const end = code.indexOf("]]>", i);
193
+ const stop = end < 0 ? code.length : end + 3;
194
+ push(out, "string", code.slice(i, stop));
195
+ i = stop;
196
+ }
197
+ else if (code[i] === "<" && /[A-Za-z/!?]/.test(code[i + 1] ?? "")) {
198
+ const open = /^<(\/?)([!?]?[A-Za-z][\w:.-]*|[!?])/.exec(code.slice(i, i + 80));
199
+ if (!open) {
200
+ push(out, "plain", code[i]);
201
+ i++;
202
+ continue;
203
+ }
204
+ push(out, "punctuation", "<" + open[1]);
205
+ push(out, "tag", open[2]);
206
+ i += open[0].length;
207
+ // atributos ate o fecha-tag
208
+ const attr = /\s*(?:([A-Za-z_:@#.][\w:.@#-]*)(\s*=\s*)?("[^"]*"?|'[^']*'?|[^\s"'<>=`]+)?|(\/?>)|([\s\S]))/y;
209
+ let closed = false;
210
+ while (i < code.length && !closed) {
211
+ attr.lastIndex = i;
212
+ const a = attr.exec(code);
213
+ if (!a || a[0].length === 0)
214
+ break;
215
+ if (a[0].trim() === "") {
216
+ push(out, "plain", a[0]);
217
+ }
218
+ else {
219
+ const lead = a[0].match(/^\s*/)[0];
220
+ push(out, "plain", lead);
221
+ if (a[1]) {
222
+ push(out, "attr", a[1]);
223
+ if (a[2])
224
+ push(out, "operator", a[2]);
225
+ if (a[3])
226
+ push(out, "string", a[3]);
227
+ }
228
+ else if (a[4]) {
229
+ push(out, "punctuation", a[4]);
230
+ closed = true;
231
+ }
232
+ else if (a[5])
233
+ push(out, "plain", a[5].trim());
234
+ }
235
+ i += a[0].length;
236
+ }
237
+ const name = open[2].toLowerCase();
238
+ if (closed && !open[1] && (name === "script" || name === "style")) {
239
+ const end = code.toLowerCase().indexOf("</" + name, i);
240
+ const stop = end < 0 ? code.length : end;
241
+ const body = code.slice(i, stop);
242
+ if (name === "script")
243
+ scan(body, "javascript", out);
244
+ else
245
+ tokenizeCss(body, out);
246
+ i = stop;
247
+ }
248
+ }
249
+ else if (code[i] === "&") {
250
+ const e = /^&#?\w+;/.exec(code.slice(i, i + 12));
251
+ if (e) {
252
+ push(out, "constant", e[0]);
253
+ i += e[0].length;
254
+ }
255
+ else {
256
+ push(out, "plain", "&");
257
+ i++;
258
+ }
259
+ }
260
+ else {
261
+ let j = i + 1;
262
+ while (j < code.length && code[j] !== "<" && code[j] !== "&")
263
+ j++;
264
+ push(out, "plain", code.slice(i, j));
265
+ i = j;
266
+ }
267
+ }
268
+ }
269
+ const CSS_RE = /(\/\*[\s\S]*?(?:\*\/|$))|("(?:\\.|[^"\\\n])*"?|'(?:\\.|[^'\\\n])*'?)|(@[\w-]+)|(#[0-9a-fA-F]{3,8}\b)|(-?(?:\d+\.?\d*|\.\d+)(?:%|[a-zA-Z]{1,4})?)|([A-Za-z_-][\w-]*)(?=\s*\()|(--[\w-]+)|(!important)|([A-Za-z-]+)(?=\s*:(?!:))|([{}();,>+~*=[\]])|(\s+)|([\s\S])/gy;
270
+ function tokenizeCss(code, out, scss = false) {
271
+ CSS_RE.lastIndex = 0;
272
+ let m;
273
+ let depth = 0;
274
+ while ((m = CSS_RE.exec(code))) {
275
+ if (m[1])
276
+ push(out, "comment", m[1]);
277
+ else if (m[2])
278
+ push(out, "string", m[2]);
279
+ else if (m[3])
280
+ push(out, "keyword", m[3]);
281
+ else if (m[4])
282
+ push(out, "number", m[4]);
283
+ else if (m[5])
284
+ push(out, "number", m[5]);
285
+ else if (m[6])
286
+ push(out, "function", m[6]);
287
+ else if (m[7])
288
+ push(out, "variable", m[7]);
289
+ else if (m[8])
290
+ push(out, "keyword", m[8]);
291
+ else if (m[9])
292
+ push(out, depth > 0 ? "property" : "tag", m[9]);
293
+ else if (m[10]) {
294
+ if (m[10] === "{")
295
+ depth++;
296
+ else if (m[10] === "}")
297
+ depth = Math.max(0, depth - 1);
298
+ push(out, "punctuation", m[10]);
299
+ }
300
+ else if (m[11])
301
+ push(out, "plain", m[11]);
302
+ else {
303
+ // seletores fora de blocos: .classe, #id, tags, :pseudo
304
+ const rest = m[12];
305
+ if (scss && rest === "$")
306
+ push(out, "variable", rest);
307
+ else if (depth === 0 && /[.:&#]/.test(rest)) {
308
+ const w = /[\w-]*/y;
309
+ w.lastIndex = CSS_RE.lastIndex;
310
+ const word = w.exec(code)[0];
311
+ CSS_RE.lastIndex += word.length;
312
+ push(out, "tag", rest + word);
313
+ }
314
+ else
315
+ push(out, "plain", rest);
316
+ }
317
+ }
318
+ }
319
+ function tokenizeLines(code, out, rules) {
320
+ const lines = code.split("\n");
321
+ lines.forEach((line, i) => {
322
+ for (const t of rules(line))
323
+ push(out, t.type, t.text);
324
+ if (i < lines.length - 1)
325
+ push(out, "plain", "\n");
326
+ });
327
+ }
328
+ function tokenizeYamlLike(code, out, mode) {
329
+ tokenizeLines(code, out, (line) => {
330
+ const r = [];
331
+ const comment = mode === "ini" ? /^(\s*[;#].*)$/ : /^(\s*#.*)$/;
332
+ let m = comment.exec(line);
333
+ if (m)
334
+ return [{ type: "comment", text: m[1] }];
335
+ if (mode !== "yaml") {
336
+ m = /^(\s*)(\[\[?)([^\]\n]*)(\]\]?)(.*)$/.exec(line);
337
+ if (m)
338
+ return [{ type: "plain", text: m[1] }, { type: "punctuation", text: m[2] }, { type: "tag", text: m[3] }, { type: "punctuation", text: m[4] }, { type: "comment", text: m[5] }];
339
+ }
340
+ m = (mode === "yaml" ? /^(\s*(?:-\s+)*)([^\s#:'"][^:#]*?|"[^"]*"|'[^']*')(\s*:)(?=\s|$)(.*)$/ : /^(\s*)([^\s=#;][^=]*?)(\s*=)(.*)$/).exec(line);
341
+ let rest = line;
342
+ if (m) {
343
+ r.push({ type: "plain", text: m[1] }, { type: "property", text: m[2] }, { type: "punctuation", text: m[3] });
344
+ rest = m[4];
345
+ }
346
+ else {
347
+ const d = /^(\s*-\s+)(.*)$/.exec(line);
348
+ if (d) {
349
+ r.push({ type: "punctuation", text: d[1] });
350
+ rest = d[2];
351
+ }
352
+ }
353
+ const v = /^(\s*)(.*?)(\s+#.*)?$/.exec(rest);
354
+ if (!v)
355
+ return [...r, { type: "plain", text: rest }];
356
+ r.push({ type: "plain", text: v[1] });
357
+ const val = v[2];
358
+ let t = "plain";
359
+ if (/^("|')/.test(val))
360
+ t = "string";
361
+ else if (/^(true|false|null|~|yes|no|on|off)$/i.test(val))
362
+ t = "constant";
363
+ else if (/^[-+]?(\d[\d_]*\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(val) || /^0x[0-9a-f]+$/i.test(val))
364
+ t = "number";
365
+ else if (/^[&*!][\w-]+/.test(val))
366
+ t = "meta";
367
+ else if (/^[|>][+-]?$/.test(val))
368
+ t = "punctuation";
369
+ else if (m && mode !== "yaml" && val)
370
+ t = "string";
371
+ r.push({ type: t, text: val });
372
+ if (v[3])
373
+ r.push({ type: "comment", text: v[3] });
374
+ return r;
375
+ });
376
+ }
377
+ function tokenizeMarkdown(code, out) {
378
+ let fence = null;
379
+ const lines = code.split("\n");
380
+ lines.forEach((line, i) => {
381
+ const nl = i < lines.length - 1 ? "\n" : "";
382
+ const f = /^(\s*)(```+|~~~+)(.*)$/.exec(line);
383
+ if (f) {
384
+ fence = fence ? null : f[2];
385
+ push(out, "meta", line + nl);
386
+ }
387
+ else if (fence)
388
+ push(out, "string", line + nl);
389
+ else if (/^#{1,6}\s/.test(line))
390
+ push(out, "heading", line + nl);
391
+ else if (/^\s*>/.test(line))
392
+ push(out, "comment", line + nl);
393
+ else if (/^\s*([-*+]|\d+[.)])\s/.test(line)) {
394
+ const m = /^(\s*(?:[-*+]|\d+[.)])\s)(.*)$/.exec(line);
395
+ push(out, "punctuation", m[1]);
396
+ inlineMd(m[2] + nl, out);
397
+ }
398
+ else if (/^\s*(---+|\*\*\*+|___+)\s*$/.test(line))
399
+ push(out, "punctuation", line + nl);
400
+ else
401
+ inlineMd(line + nl, out);
402
+ });
403
+ }
404
+ function inlineMd(text, out) {
405
+ const re = /(`[^`\n]+`)|(\*\*[^*\n]+\*\*|__[^_\n]+__)|(\[[^\]\n]*\]\([^)\n]*\))|(\*[^*\n]+\*|_[^_\n]+_)|([\s\S])/gy;
406
+ let m;
407
+ while ((m = re.exec(text))) {
408
+ if (m[1])
409
+ push(out, "string", m[1]);
410
+ else if (m[2])
411
+ push(out, "keyword", m[2]);
412
+ else if (m[3])
413
+ push(out, "function", m[3]);
414
+ else if (m[4])
415
+ push(out, "type", m[4]);
416
+ else
417
+ push(out, "plain", m[5]);
418
+ }
419
+ }
420
+ function tokenizeDiff(code, out) {
421
+ const lines = code.split("\n");
422
+ lines.forEach((line, i) => {
423
+ const nl = i < lines.length - 1 ? "\n" : "";
424
+ if (/^(diff |index |--- |\+\+\+ )/.test(line))
425
+ push(out, "meta", line + nl);
426
+ else if (line.startsWith("@@"))
427
+ push(out, "heading", line + nl);
428
+ else if (line.startsWith("+"))
429
+ push(out, "inserted", line + nl);
430
+ else if (line.startsWith("-"))
431
+ push(out, "deleted", line + nl);
432
+ else
433
+ push(out, "plain", line + nl);
434
+ });
435
+ }
436
+ function tokenizeDockerfile(code, out) {
437
+ tokenizeLines(code, out, (line) => {
438
+ const m = /^(\s*)(FROM|RUN|CMD|LABEL|MAINTAINER|EXPOSE|ENV|ADD|COPY|ENTRYPOINT|VOLUME|USER|WORKDIR|ARG|ONBUILD|STOPSIGNAL|HEALTHCHECK|SHELL)\b(.*)$/i.exec(line);
439
+ if (/^\s*#/.test(line))
440
+ return [{ type: "comment", text: line }];
441
+ if (!m)
442
+ return [{ type: "plain", text: line }];
443
+ const rest = [];
444
+ for (const part of m[3].split(/(\$\{?\w+\}?|"[^"]*"|'[^']*')/)) {
445
+ if (!part)
446
+ continue;
447
+ rest.push({ type: /^\$/.test(part) ? "variable" : /^["']/.test(part) ? "string" : "plain", text: part });
448
+ }
449
+ return [{ type: "plain", text: m[1] }, { type: "keyword", text: m[2] }, ...rest];
450
+ });
451
+ }
452
+ function tokenizeMakefile(code, out) {
453
+ tokenizeLines(code, out, (line) => {
454
+ if (/^\s*#/.test(line))
455
+ return [{ type: "comment", text: line }];
456
+ let m = /^([A-Za-z_.][\w.-]*)(\s*[:+?]?=)(.*)$/.exec(line);
457
+ if (m)
458
+ return [{ type: "variable", text: m[1] }, { type: "operator", text: m[2] }, { type: "plain", text: m[3] }];
459
+ m = /^([^\s:#=][^:#=]*)(:)(?!=)(.*)$/.exec(line);
460
+ if (m)
461
+ return [{ type: "function", text: m[1] }, { type: "punctuation", text: m[2] }, { type: "plain", text: m[3] }];
462
+ m = /^(\s*)(ifn?eq|ifn?def|else|endif|include|-include|define|endef|export)\b(.*)$/.exec(line);
463
+ if (m)
464
+ return [{ type: "plain", text: m[1] }, { type: "keyword", text: m[2] }, { type: "plain", text: m[3] }];
465
+ return [{ type: "plain", text: line }];
466
+ });
467
+ }
468
+ /** Tokeniza o texto inteiro. A concatenacao dos tokens sempre reproduz exatamente a entrada. */
469
+ export function tokenize(code, lang) {
470
+ const id = (DEFS[lang] || ["json", "html", "xml", "css", "scss", "less", "yaml", "toml", "ini", "markdown", "dockerfile", "makefile", "diff", "plaintext", "batch", "shell"].includes(lang) ? lang : resolveLanguage(lang));
471
+ const text = code.replace(/\r\n?/g, "\n");
472
+ const out = [];
473
+ switch (id) {
474
+ case "plaintext":
475
+ return text ? [{ type: "plain", text }] : [];
476
+ case "json":
477
+ tokenizeJson(text, out);
478
+ break;
479
+ case "html":
480
+ case "xml":
481
+ tokenizeMarkup(text, out);
482
+ break;
483
+ case "css":
484
+ case "less":
485
+ tokenizeCss(text, out);
486
+ break;
487
+ case "scss":
488
+ tokenizeCss(text, out, true);
489
+ break;
490
+ case "yaml":
491
+ case "toml":
492
+ case "ini":
493
+ tokenizeYamlLike(text, out, id);
494
+ break;
495
+ case "markdown":
496
+ tokenizeMarkdown(text, out);
497
+ break;
498
+ case "diff":
499
+ tokenizeDiff(text, out);
500
+ break;
501
+ case "dockerfile":
502
+ tokenizeDockerfile(text, out);
503
+ break;
504
+ case "makefile":
505
+ tokenizeMakefile(text, out);
506
+ break;
507
+ default:
508
+ if (DEFS[id])
509
+ scan(text, id, out);
510
+ else
511
+ return text ? [{ type: "plain", text }] : [];
512
+ }
513
+ return out;
514
+ }
515
+ /** Divide os tokens por linha (sem o "\n"), preservando tokens que atravessam linhas (comentarios de bloco, strings). */
516
+ export function tokenizeLinesOf(code, lang) {
517
+ const lines = [[]];
518
+ for (const t of tokenize(code, lang)) {
519
+ const parts = t.text.split("\n");
520
+ parts.forEach((p, i) => {
521
+ if (i > 0)
522
+ lines.push([]);
523
+ if (p)
524
+ lines[lines.length - 1].push({ type: t.type, text: p });
525
+ });
526
+ }
527
+ return lines;
528
+ }
529
+ const HTML_ESC = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" };
530
+ /** HTML com <span class="lt-<tipo">; as cores vem do CSS (ver --code-* nos tokens). */
531
+ export function highlightToHtml(code, lang) {
532
+ return tokenize(code, lang)
533
+ .map((t) => {
534
+ const text = t.text.replace(/[&<>"]/g, (c) => HTML_ESC[c]);
535
+ return t.type === "plain" ? text : `<span class="lt-${t.type}">${text}</span>`;
536
+ })
537
+ .join("");
538
+ }
package/dist/index.d.ts CHANGED
@@ -33,3 +33,5 @@ export * from "./static.ts";
33
33
  export * from "./machines/toggle.ts";
34
34
  export * from "./machines/disclosure.ts";
35
35
  export * from "./machines/choice.ts";
36
+ export * from "./highlight.ts";
37
+ export * from "./file-icons.ts";
package/dist/index.js CHANGED
@@ -33,3 +33,5 @@ export * from "./static.js";
33
33
  export * from "./machines/toggle.js";
34
34
  export * from "./machines/disclosure.js";
35
35
  export * from "./machines/choice.js";
36
+ export * from "./highlight.js";
37
+ export * from "./file-icons.js";
package/package.json CHANGED
@@ -1,112 +1,112 @@
1
- {
2
- "name": "@loccal/core",
3
- "version": "0.1.0",
4
- "description": "Loccal Core: nucleo headless vanilla (maquinas de estado, teclado, ARIA, foco, i18n e tokens CSS) do Loccal UI.",
5
- "license": "MIT",
6
- "author": "Marcelo Matzembacher",
7
- "keywords": [
8
- "headless",
9
- "state-machine",
10
- "accessibility",
11
- "a11y",
12
- "design-tokens"
13
- ],
14
- "type": "module",
15
- "sideEffects": [
16
- "**/*.css"
17
- ],
18
- "files": [
19
- "dist",
20
- "src/tokens/tokens.css",
21
- "README.md",
22
- "LICENSE"
23
- ],
24
- "scripts": {
25
- "build": "node ../node_modules/typescript/bin/tsc -p tsconfig.build.json",
26
- "test": "node --test test/*.test.ts",
27
- "typecheck": "node ../node_modules/typescript/bin/tsc -p tsconfig.build.json --noEmit"
28
- },
29
- "publishConfig": {
30
- "access": "public",
31
- "provenance": false
32
- },
33
- "exports": {
34
- ".": {
35
- "types": "./dist/index.d.ts",
36
- "import": "./dist/index.js",
37
- "default": "./dist/index.js"
38
- },
39
- "./machine": {
40
- "types": "./dist/machine.d.ts",
41
- "import": "./dist/machine.js",
42
- "default": "./dist/machine.js"
43
- },
44
- "./i18n": {
45
- "types": "./dist/i18n.d.ts",
46
- "import": "./dist/i18n.js",
47
- "default": "./dist/i18n.js"
48
- },
49
- "./labels": {
50
- "types": "./dist/labels.d.ts",
51
- "import": "./dist/labels.js",
52
- "default": "./dist/labels.js"
53
- },
54
- "./a11y/focus": {
55
- "types": "./dist/a11y/focus.d.ts",
56
- "import": "./dist/a11y/focus.js",
57
- "default": "./dist/a11y/focus.js"
58
- },
59
- "./a11y/ids": {
60
- "types": "./dist/a11y/ids.d.ts",
61
- "import": "./dist/a11y/ids.js",
62
- "default": "./dist/a11y/ids.js"
63
- },
64
- "./machines/button": {
65
- "types": "./dist/machines/button.d.ts",
66
- "import": "./dist/machines/button.js",
67
- "default": "./dist/machines/button.js"
68
- },
69
- "./machines/dialog": {
70
- "types": "./dist/machines/dialog.d.ts",
71
- "import": "./dist/machines/dialog.js",
72
- "default": "./dist/machines/dialog.js"
73
- },
74
- "./machines/select": {
75
- "types": "./dist/machines/select.d.ts",
76
- "import": "./dist/machines/select.js",
77
- "default": "./dist/machines/select.js"
78
- },
79
- "./machines/tabs": {
80
- "types": "./dist/machines/tabs.d.ts",
81
- "import": "./dist/machines/tabs.js",
82
- "default": "./dist/machines/tabs.js"
83
- },
84
- "./machines/tab-list": {
85
- "types": "./dist/machines/tab-list.d.ts",
86
- "import": "./dist/machines/tab-list.js",
87
- "default": "./dist/machines/tab-list.js"
88
- },
89
- "./machines/status-bar": {
90
- "types": "./dist/machines/status-bar.d.ts",
91
- "import": "./dist/machines/status-bar.js",
92
- "default": "./dist/machines/status-bar.js"
93
- },
94
- "./tokens.css": "./src/tokens/tokens.css",
95
- "./package.json": "./package.json",
96
- "./dom": {
97
- "types": "./dist/dom.d.ts",
98
- "import": "./dist/dom.js",
99
- "default": "./dist/dom.js"
100
- },
101
- "./icons": {
102
- "types": "./dist/icons.d.ts",
103
- "import": "./dist/icons.js",
104
- "default": "./dist/icons.js"
105
- },
106
- "./icon-shapes": {
107
- "types": "./dist/icon-shapes.d.ts",
108
- "import": "./dist/icon-shapes.js",
109
- "default": "./dist/icon-shapes.js"
110
- }
111
- }
112
- }
1
+ {
2
+ "name": "@loccal/core",
3
+ "version": "0.1.1",
4
+ "description": "Loccal Core: nucleo headless vanilla (maquinas de estado, teclado, ARIA, foco, i18n e tokens CSS) do Loccal UI.",
5
+ "license": "MIT",
6
+ "author": "Marcelo Matzembacher",
7
+ "keywords": [
8
+ "headless",
9
+ "state-machine",
10
+ "accessibility",
11
+ "a11y",
12
+ "design-tokens"
13
+ ],
14
+ "type": "module",
15
+ "sideEffects": [
16
+ "**/*.css"
17
+ ],
18
+ "files": [
19
+ "dist",
20
+ "src/tokens/tokens.css",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "scripts": {
25
+ "build": "node ../node_modules/typescript/bin/tsc -p tsconfig.build.json",
26
+ "test": "node --test test/*.test.ts",
27
+ "typecheck": "node ../node_modules/typescript/bin/tsc -p tsconfig.build.json --noEmit"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public",
31
+ "provenance": false
32
+ },
33
+ "exports": {
34
+ ".": {
35
+ "types": "./dist/index.d.ts",
36
+ "import": "./dist/index.js",
37
+ "default": "./dist/index.js"
38
+ },
39
+ "./machine": {
40
+ "types": "./dist/machine.d.ts",
41
+ "import": "./dist/machine.js",
42
+ "default": "./dist/machine.js"
43
+ },
44
+ "./i18n": {
45
+ "types": "./dist/i18n.d.ts",
46
+ "import": "./dist/i18n.js",
47
+ "default": "./dist/i18n.js"
48
+ },
49
+ "./labels": {
50
+ "types": "./dist/labels.d.ts",
51
+ "import": "./dist/labels.js",
52
+ "default": "./dist/labels.js"
53
+ },
54
+ "./a11y/focus": {
55
+ "types": "./dist/a11y/focus.d.ts",
56
+ "import": "./dist/a11y/focus.js",
57
+ "default": "./dist/a11y/focus.js"
58
+ },
59
+ "./a11y/ids": {
60
+ "types": "./dist/a11y/ids.d.ts",
61
+ "import": "./dist/a11y/ids.js",
62
+ "default": "./dist/a11y/ids.js"
63
+ },
64
+ "./machines/button": {
65
+ "types": "./dist/machines/button.d.ts",
66
+ "import": "./dist/machines/button.js",
67
+ "default": "./dist/machines/button.js"
68
+ },
69
+ "./machines/dialog": {
70
+ "types": "./dist/machines/dialog.d.ts",
71
+ "import": "./dist/machines/dialog.js",
72
+ "default": "./dist/machines/dialog.js"
73
+ },
74
+ "./machines/select": {
75
+ "types": "./dist/machines/select.d.ts",
76
+ "import": "./dist/machines/select.js",
77
+ "default": "./dist/machines/select.js"
78
+ },
79
+ "./machines/tabs": {
80
+ "types": "./dist/machines/tabs.d.ts",
81
+ "import": "./dist/machines/tabs.js",
82
+ "default": "./dist/machines/tabs.js"
83
+ },
84
+ "./machines/tab-list": {
85
+ "types": "./dist/machines/tab-list.d.ts",
86
+ "import": "./dist/machines/tab-list.js",
87
+ "default": "./dist/machines/tab-list.js"
88
+ },
89
+ "./machines/status-bar": {
90
+ "types": "./dist/machines/status-bar.d.ts",
91
+ "import": "./dist/machines/status-bar.js",
92
+ "default": "./dist/machines/status-bar.js"
93
+ },
94
+ "./tokens.css": "./src/tokens/tokens.css",
95
+ "./package.json": "./package.json",
96
+ "./dom": {
97
+ "types": "./dist/dom.d.ts",
98
+ "import": "./dist/dom.js",
99
+ "default": "./dist/dom.js"
100
+ },
101
+ "./icons": {
102
+ "types": "./dist/icons.d.ts",
103
+ "import": "./dist/icons.js",
104
+ "default": "./dist/icons.js"
105
+ },
106
+ "./icon-shapes": {
107
+ "types": "./dist/icon-shapes.d.ts",
108
+ "import": "./dist/icon-shapes.js",
109
+ "default": "./dist/icon-shapes.js"
110
+ }
111
+ }
112
+ }