@alphacharts/script 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"builtins-BXxWK58s.js","names":["KEYWORDS","RESERVED","OPS2","OPS1","isDigit","c","isIdStart","isIdPart","isHex","lex","out","n","src","i","depth","indents","atLineStart","push","value","j","rep","width","top","ch","s","k","text","e","v","q","val","closed","hex","two","one","len","FLOAT_S","INT_S","BOOL_S","t","tuple","nullProto","o","OUTSIDE_FIELDS","NAMESPACES","BUILTIN_SERIES","MEMBER_CONSTS","enumOf","ns","ENUMS","N","I","LEN","SIGS","add","name","extra","num","x","m1","f","a","b","TA_TR","studyParam","studyFnName","id","def","ALL_STUDIES","completionNames","p"],"sources":["../src/lexer.ts","../src/builtins.ts"],"sourcesContent":["// Lexer: source text -> tokens, with Python-style INDENT/DEDENT blocks.\n//\n// Lines inside (), [] continue; blank and comment-only lines are ignored; tabs\n// are refused (indentation is spaces). Only ASCII identifiers; any other\n// character outside strings and comments is a diagnostic, never skipped\n// silently.\n\nimport type { Reporter } from \"./diag.js\";\n\nexport type TokKind = \"num\" | \"str\" | \"color\" | \"ident\" | \"kw\" | \"op\" | \"newline\" | \"indent\" | \"dedent\" | \"eof\";\n\nexport interface Token {\n kind: TokKind;\n /** Text for ident/kw/op; decoded value for str; digits for num; \"#rrggbb[aa]\" for color. */\n text: string;\n value?: number;\n from: number;\n to: number;\n}\n\nexport const KEYWORDS: ReadonlySet<string> = new Set([\"if\", \"else\", \"for\", \"to\", \"by\", \"var\", \"and\", \"or\", \"not\", \"true\", \"false\"]);\n/** Words that belong to other languages (or to features this one leaves out): refused with a pointer. */\nexport const RESERVED: Readonly<Record<string, string>> = Object.assign(Object.create(null) as Record<string, string>, Object.fromEntries(Object.entries({\n while: \"'while' is not supported: loops must be bounded, use 'for i = a to b'\",\n switch: \"'switch' is not supported: use if / else\",\n function: \"functions are not supported\",\n return: \"'return' is not supported\",\n import: \"'import' is not supported\",\n export: \"'export' is not supported\",\n break: \"'break' is not supported: loops are bounded\",\n continue: \"'continue' is not supported\",\n class: \"'class' is not supported\",\n eval: \"'eval' is not part of the language\",\n this: \"'this' is not part of the language\",\n null: \"there is no 'null'; use na\",\n undefined: \"there is no 'undefined'; use na\",\n constructor: \"'constructor' is a reserved name\",\n prototype: \"'prototype' is a reserved name\",\n}).concat([[\"__proto__\", \"'__proto__' is a reserved name\"]])));\n\nconst OPS3 = new Set<string>([]);\nconst OPS2 = new Set([\":=\", \"==\", \"!=\", \"<=\", \">=\", \"+=\", \"-=\", \"*=\", \"/=\", \"%=\"]);\nconst OPS1 = new Set([\"+\", \"-\", \"*\", \"/\", \"%\", \"<\", \">\", \"=\", \"?\", \":\", \"(\", \")\", \"[\", \"]\", \",\", \".\"]);\n\nconst isDigit = (c: number) => c >= 48 && c <= 57;\nconst isIdStart = (c: number) => (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c === 95;\nconst isIdPart = (c: number) => isIdStart(c) || isDigit(c);\nconst isHex = (c: number) => isDigit(c) || (c >= 65 && c <= 70) || (c >= 97 && c <= 102);\n\nexport function lex(src: string, rep: Reporter): Token[] {\n const out: Token[] = [];\n const n = src.length;\n let i = 0;\n let depth = 0;\n const indents = [0];\n let atLineStart = true;\n const push = (kind: TokKind, text: string, from: number, to: number, value?: number) => {\n out.push(value === undefined ? { kind, text, from, to } : { kind, text, from, to, value });\n };\n\n while (i < n) {\n if (atLineStart && depth === 0) {\n // measure indentation of this line\n let j = i;\n while (j < n && src.charCodeAt(j) === 32) j++;\n if (j < n && src.charCodeAt(j) === 9) {\n rep.error(\"tab characters are not allowed; indent with spaces\", { from: j, to: j + 1 });\n while (j < n && src.charCodeAt(j) === 9) j++;\n }\n const c = src.charCodeAt(j);\n const blank = j >= n || c === 10 || c === 13 || (c === 47 && src.charCodeAt(j + 1) === 47);\n if (blank) {\n // skip to end of line\n while (j < n && src.charCodeAt(j) !== 10) j++;\n i = j < n ? j + 1 : j;\n continue;\n }\n const width = j - i;\n const top = indents[indents.length - 1]!;\n if (width > top) {\n indents.push(width);\n push(\"indent\", \"\", i, j);\n } else if (width < top) {\n while (indents.length > 1 && indents[indents.length - 1]! > width) {\n indents.pop();\n push(\"dedent\", \"\", i, j);\n }\n if (indents[indents.length - 1]! !== width) {\n rep.error(\"indentation does not match any outer block\", { from: i, to: j });\n indents.push(width);\n }\n }\n i = j;\n atLineStart = false;\n continue;\n }\n const ch = src.charCodeAt(i);\n if (ch === 10) {\n if (depth === 0) {\n push(\"newline\", \"\\n\", i, i + 1);\n atLineStart = true;\n }\n i++;\n continue;\n }\n if (ch === 32 || ch === 13) { i++; continue; }\n if (ch === 9) {\n rep.error(\"tab characters are not allowed; indent with spaces\", { from: i, to: i + 1 });\n i++;\n continue;\n }\n if (ch === 47 && src.charCodeAt(i + 1) === 47) {\n while (i < n && src.charCodeAt(i) !== 10) i++;\n continue;\n }\n // numbers\n if (isDigit(ch) || (ch === 46 && isDigit(src.charCodeAt(i + 1)))) {\n const s = i;\n while (i < n && isDigit(src.charCodeAt(i))) i++;\n if (src.charCodeAt(i) === 46 && isDigit(src.charCodeAt(i + 1))) {\n i++;\n while (i < n && isDigit(src.charCodeAt(i))) i++;\n } else if (src.charCodeAt(i) === 46 && !isIdStart(src.charCodeAt(i + 1))) {\n i++; // \"1.\" is a float\n }\n if (src.charCodeAt(i) === 101 || src.charCodeAt(i) === 69) {\n let k = i + 1;\n if (src.charCodeAt(k) === 43 || src.charCodeAt(k) === 45) k++;\n if (isDigit(src.charCodeAt(k))) {\n while (isDigit(src.charCodeAt(k))) k++;\n i = k;\n }\n }\n const text = src.slice(s, i);\n if (isIdStart(src.charCodeAt(i))) {\n let e = i;\n while (e < n && isIdPart(src.charCodeAt(e))) e++;\n rep.error(`invalid number \"${src.slice(s, e)}\"`, { from: s, to: e });\n i = e;\n push(\"num\", \"0\", s, e, 0);\n continue;\n }\n const v = Number(text);\n if (!Number.isFinite(v)) rep.error(`number \"${text}\" is out of range`, { from: s, to: i });\n push(\"num\", text, s, i, Number.isFinite(v) ? v : 0);\n continue;\n }\n if (isIdStart(ch)) {\n const s = i;\n while (i < n && isIdPart(src.charCodeAt(i))) i++;\n const text = src.slice(s, i);\n if (text in RESERVED) {\n rep.error(RESERVED[text]!, { from: s, to: i });\n push(\"ident\", \"_reserved\", s, i);\n } else push(KEYWORDS.has(text) ? \"kw\" : \"ident\", text, s, i);\n continue;\n }\n if (ch === 34 || ch === 39) {\n const s = i;\n const q = ch;\n i++;\n let val = \"\";\n let closed = false;\n while (i < n) {\n const c = src.charCodeAt(i);\n if (c === 10) break;\n if (c === q) { i++; closed = true; break; }\n if (c === 92) {\n const e = src[i + 1];\n if (e === \"n\") val += \"\\n\";\n else if (e === \"t\") val += \"\\t\";\n else if (e === \"\\\\\" || e === '\"' || e === \"'\") val += e;\n else rep.error(`unknown escape \"\\\\${e ?? \"\"}\"`, { from: i, to: Math.min(n, i + 2) });\n i += 2;\n continue;\n }\n val += src[i];\n i++;\n }\n if (!closed) rep.error(\"unterminated string\", { from: s, to: i });\n push(\"str\", val, s, i);\n continue;\n }\n if (ch === 35) {\n const s = i;\n i++;\n while (i < n && isHex(src.charCodeAt(i))) i++;\n const hex = src.slice(s + 1, i);\n if (hex.length !== 6 && hex.length !== 8) rep.error(`invalid color \"${src.slice(s, i)}\": use #RRGGBB or #RRGGBBAA`, { from: s, to: i });\n push(\"color\", `#${hex}`.toLowerCase(), s, i);\n continue;\n }\n const two = src.slice(i, i + 2);\n if (OPS2.has(two)) {\n push(\"op\", two, i, i + 2);\n i += 2;\n continue;\n }\n const one = src[i]!;\n if (OPS1.has(one)) {\n if (one === \"(\" || one === \"[\") depth++;\n else if (one === \")\" || one === \"]\") depth = Math.max(0, depth - 1);\n push(\"op\", one, i, i + 1);\n i++;\n continue;\n }\n void OPS3;\n const cp = src.codePointAt(i)!;\n const len = cp > 0xffff ? 2 : 1;\n rep.error(`unexpected character ${JSON.stringify(src.slice(i, i + len))}`, { from: i, to: i + len });\n i += len;\n }\n if (depth > 0) rep.error(\"unclosed bracket\", { from: n, to: n });\n if (out.length > 0 && out[out.length - 1]!.kind !== \"newline\") push(\"newline\", \"\\n\", n, n);\n while (indents.length > 1) {\n indents.pop();\n push(\"dedent\", \"\", n, n);\n }\n push(\"eof\", \"\", n, n);\n return out;\n}\n","// The language's built-in names: series, namespaces, constants, and the\n// signatures of every callable. Lowering lives in codegen.ts; the checker uses\n// only this table.\n\nimport { ALL_STUDIES } from \"@alphacharts/indicators/all\";\nimport type { InputDef, StudyDef } from \"@alphacharts/indicators\";\nimport type { FeedField } from \"@alphacharts/indicators\";\nimport type { Ty } from \"./ast.js\";\n\nexport const FLOAT_S: Ty = { b: \"float\", q: \"series\" };\nexport const INT_S: Ty = { b: \"int\", q: \"series\" };\nexport const BOOL_S: Ty = { b: \"bool\", q: \"series\" };\nexport const t = (b: Ty[\"b\"], q: Ty[\"q\"] = \"const\"): Ty => ({ b, q });\nexport const tuple = (elems: Ty[]): Ty => ({ b: \"tuple\", q: \"series\", elems });\n\n/** Tables indexed by names from a script have no prototype: \"__proto__\" and \"constructor\" are not entries. */\nfunction nullProto<T extends object>(o: T): T {\n return Object.assign(Object.create(null) as T, o);\n}\n\n/** The fields of an outside series a script can read. */\nexport const OUTSIDE_FIELDS = [\"open\", \"high\", \"low\", \"close\", \"volume\"] as const satisfies readonly FeedField[];\n\nexport const NAMESPACES: ReadonlySet<string> = new Set([\"ta\", \"math\", \"color\", \"input\", \"plot\", \"shape\", \"location\", \"hline\", \"str\"]);\n\n/** Series available everywhere. `needs` is what the study must be given. */\nexport const BUILTIN_SERIES: Readonly<Record<string, { ty: Ty; needs: \"value\" | \"ohlc\" | \"ohlcv\" }>> = nullProto({\n close: { ty: FLOAT_S, needs: \"value\" },\n open: { ty: FLOAT_S, needs: \"ohlc\" },\n high: { ty: FLOAT_S, needs: \"ohlc\" },\n low: { ty: FLOAT_S, needs: \"ohlc\" },\n hl2: { ty: FLOAT_S, needs: \"ohlc\" },\n hlc3: { ty: FLOAT_S, needs: \"ohlc\" },\n ohlc4: { ty: FLOAT_S, needs: \"ohlc\" },\n hlcc4: { ty: FLOAT_S, needs: \"ohlc\" },\n volume: { ty: FLOAT_S, needs: \"ohlcv\" },\n time: { ty: FLOAT_S, needs: \"value\" },\n bar_index: { ty: INT_S, needs: \"value\" },\n bars_per_year: { ty: FLOAT_S, needs: \"value\" },\n});\n\nexport const COLORS: Readonly<Record<string, string>> = {\n aqua: \"#00bcd4\", black: \"#000000\", blue: \"#2962ff\", fuchsia: \"#e040fb\", gray: \"#787b86\", green: \"#4caf50\", lime: \"#00e676\",\n maroon: \"#880e4f\", navy: \"#311b92\", olive: \"#808000\", orange: \"#ff9800\", purple: \"#9c27b0\", red: \"#f23645\", silver: \"#b2b5be\",\n teal: \"#089981\", white: \"#ffffff\", yellow: \"#fdd835\",\n};\n\n/** Constants reachable as `namespace.name`. */\nexport const MEMBER_CONSTS: Readonly<Record<string, { ty: Ty; value: number | string }>> = nullProto({\n \"math.pi\": { ty: t(\"float\"), value: Math.PI },\n \"math.e\": { ty: t(\"float\"), value: Math.E },\n ...Object.fromEntries(Object.entries(COLORS).map(([k, v]) => [`color.${k}`, { ty: t(\"color\"), value: v }])),\n \"plot.style_line\": { ty: t(\"string\"), value: \"line\" },\n \"plot.style_histogram\": { ty: t(\"string\"), value: \"histogram\" },\n \"plot.style_area\": { ty: t(\"string\"), value: \"area\" },\n \"hline.style_solid\": { ty: t(\"string\"), value: \"solid\" },\n \"hline.style_dashed\": { ty: t(\"string\"), value: \"dashed\" },\n \"hline.style_dotted\": { ty: t(\"string\"), value: \"dotted\" },\n \"shape.circle\": { ty: t(\"string\"), value: \"circle\" },\n \"shape.square\": { ty: t(\"string\"), value: \"square\" },\n \"shape.diamond\": { ty: t(\"string\"), value: \"diamond\" },\n \"shape.triangleup\": { ty: t(\"string\"), value: \"triangleUp\" },\n \"shape.triangledown\": { ty: t(\"string\"), value: \"triangleDown\" },\n \"shape.arrowup\": { ty: t(\"string\"), value: \"arrowUp\" },\n \"shape.arrowdown\": { ty: t(\"string\"), value: \"arrowDown\" },\n \"shape.xcross\": { ty: t(\"string\"), value: \"cross\" },\n \"shape.cross\": { ty: t(\"string\"), value: \"cross\" },\n \"location.abovebar\": { ty: t(\"string\"), value: \"above\" },\n \"location.belowbar\": { ty: t(\"string\"), value: \"below\" },\n \"location.absolute\": { ty: t(\"string\"), value: \"value\" },\n});\nconst enumOf = (ns: string): string[] => Object.keys(MEMBER_CONSTS).filter((k) => k.startsWith(`${ns}.`)).map((k) => MEMBER_CONSTS[k]!.value as string);\nexport const ENUMS = {\n plotStyle: enumOf(\"plot\"),\n lineStyle: enumOf(\"hline\"),\n shape: enumOf(\"shape\"),\n location: enumOf(\"location\"),\n};\n\n// ---- signatures -----------------------------------------------------------------\n\n/**\n * series: a numeric (or bool) series, any qualifier. num/int/bool/string/color: simple values (const or input).\n * `enum`: one of a set, written as the namespace constant. strlist: an array literal of string literals.\n */\nexport type PKind = \"series\" | \"num\" | \"int\" | \"bool\" | \"string\" | \"color\" | \"enum\" | \"strlist\" | \"plot\" | \"any\";\n\nexport interface Param {\n name: string;\n kind: PKind;\n opt?: boolean;\n /** For \"enum\". */\n oneOf?: readonly string[];\n /** For \"int\"/\"num\": bounds checked when the argument is a literal; checked again at build otherwise. */\n min?: number;\n max?: number;\n /** For generic study inputs: the input this parameter feeds. */\n input?: InputDef;\n}\n\nexport interface Sig {\n /** Fully qualified name: \"ta.sma\", \"nz\". */\n name: string;\n params: Param[];\n ret: Ty;\n /** What the study must be given for this call to work. */\n needs?: \"value\" | \"ohlc\" | \"ohlcv\";\n /** Kind of lowering. */\n op: \"scalar\" | \"kernel\" | \"study\" | \"special\";\n /** Scalar math: elementwise. */\n fn?: (...a: number[]) => number;\n /** Generic study: the definition and the order of its non-source inputs. */\n study?: StudyDef;\n}\n\nconst S = (name: string): Param => ({ name, kind: \"series\" });\nconst SO = (name: string): Param => ({ name, kind: \"series\", opt: true });\nconst N = (name: string, o: Partial<Param> = {}): Param => ({ name, kind: \"num\", ...o });\nconst I = (name: string, o: Partial<Param> = {}): Param => ({ name, kind: \"int\", ...o });\nconst LEN: Param = I(\"length\", { min: 1, max: 5000 });\n\nexport const SIGS: Map<string, Sig> = new Map();\nconst add = (name: string, params: Param[], ret: Ty, op: Sig[\"op\"], extra: Partial<Sig> = {}) => SIGS.set(name, { name, params, ret, op, ...extra });\nconst num = (x: number) => (Number.isFinite(x) ? x : Number.NaN);\n\n// math.*: elementwise; a non-finite result is na (never an Infinity on a chart)\nconst m1 = (name: string, f: (x: number) => number) => add(`math.${name}`, [S(\"x\")], FLOAT_S, \"scalar\", { fn: (x) => num(f(x)) });\nfor (const [k, f] of Object.entries({ abs: Math.abs, sqrt: Math.sqrt, log: Math.log, log10: Math.log10, exp: Math.exp, sin: Math.sin, cos: Math.cos, tan: Math.tan, asin: Math.asin, acos: Math.acos, atan: Math.atan, sinh: Math.sinh, cosh: Math.cosh, tanh: Math.tanh, ceil: Math.ceil, floor: Math.floor, trunc: Math.trunc, sign: Math.sign, round: Math.round, toradians: (x: number) => (x * Math.PI) / 180, todegrees: (x: number) => (x * 180) / Math.PI })) m1(k, f);\nadd(\"math.pow\", [S(\"base\"), S(\"exponent\")], FLOAT_S, \"scalar\", { fn: (a, b) => num(a ** b) });\nadd(\"math.max\", [S(\"a\"), S(\"b\")], FLOAT_S, \"scalar\", { fn: (a, b) => (a !== a || b !== b ? Number.NaN : a > b ? a : b) });\nadd(\"math.min\", [S(\"a\"), S(\"b\")], FLOAT_S, \"scalar\", { fn: (a, b) => (a !== a || b !== b ? Number.NaN : a < b ? a : b) });\nadd(\"math.avg\", [S(\"a\"), S(\"b\")], FLOAT_S, \"scalar\", { fn: (a, b) => (a + b) / 2 });\nadd(\"nz\", [S(\"x\"), { name: \"replacement\", kind: \"series\", opt: true }], FLOAT_S, \"special\");\nadd(\"na\", [S(\"x\")], BOOL_S, \"special\");\nadd(\"math.sum\", [S(\"source\"), LEN], FLOAT_S, \"kernel\");\n\n// ta.* kernels on the graph\nfor (const k of [\"sma\", \"ema\", \"wma\", \"rma\", \"highest\", \"lowest\", \"sum\"]) add(`ta.${k}`, [S(\"source\"), LEN], FLOAT_S, \"kernel\");\n// deviation and variance: population (divide by n) unless sample=true (divide by n - 1, the estimator Sharpe and volatility use; n >= 2)\nfor (const k of [\"stdev\", \"variance\"]) add(`ta.${k}`, [S(\"source\"), LEN, { name: \"sample\", kind: \"bool\", opt: true }], FLOAT_S, \"kernel\");\n// bars since the extreme: a whole number (or na until the window is full), so it types int and can be an offset or an int variable's value\nfor (const k of [\"highestbars\", \"lowestbars\"]) add(`ta.${k}`, [S(\"source\"), LEN], INT_S, \"kernel\");\n// a line through one point is undefined: the least length is 2\nadd(\"ta.linreg\", [S(\"source\"), I(\"length\", { min: 2, max: 5000 })], FLOAT_S, \"kernel\");\nadd(\"ta.atr\", [LEN], FLOAT_S, \"kernel\", { needs: \"ohlc\" });\nadd(\"ta.change\", [S(\"source\"), I(\"length\", { opt: true, min: 1, max: 5000 })], FLOAT_S, \"special\");\nfor (const k of [\"crossover\", \"crossunder\", \"cross\"]) add(`ta.${k}`, [S(\"a\"), S(\"b\")], BOOL_S, \"special\");\nadd(\"ta.bb\", [S(\"source\"), I(\"length\", { min: 1, max: 5000 }), N(\"mult\", { min: 0, max: 100 })], tuple([FLOAT_S, FLOAT_S, FLOAT_S]), \"special\");\n\nexport const TA_TR: Ty = FLOAT_S;\n\n// every other built-in study as ta.<id>(source?, ...inputs)\nfunction studyParam(i: InputDef): Param {\n switch (i.type) {\n case \"int\": return { name: i.key, kind: \"int\", opt: true, ...(i.min !== undefined && { min: i.min }), ...(i.max !== undefined && { max: i.max }), input: i };\n case \"float\": return { name: i.key, kind: \"num\", opt: true, ...(i.min !== undefined && { min: i.min }), ...(i.max !== undefined && { max: i.max }), input: i };\n case \"bool\": return { name: i.key, kind: \"bool\", opt: true, input: i };\n case \"source\": return { name: i.key, kind: \"series\", opt: true, input: i };\n case \"select\": return { name: i.key, kind: \"string\", opt: true, input: i, ...(i.options && { oneOf: i.options }) };\n }\n}\nexport const studyFnName = (id: string): string => `ta.${id.replace(/-/g, \"_\")}`;\nfor (const def of ALL_STUDIES) {\n if (def.family === \"math\") continue;\n const name = studyFnName(def.id);\n if (SIGS.has(name)) continue;\n // The `source` input, when there is one, is the first parameter; the others follow in the study's order.\n const params = [...def.inputs.filter((i) => i.key === \"source\"), ...def.inputs.filter((i) => i.key !== \"source\")].map(studyParam);\n const ret = def.columns.length === 1 ? FLOAT_S : tuple(def.columns.map(() => FLOAT_S));\n add(name, params, ret, \"study\", { study: def, needs: def.needs });\n}\n\n// ---- plotting and declarations ---------------------------------------------------------\n\nadd(\"indicator\", [{ name: \"title\", kind: \"string\" }, { name: \"shorttitle\", kind: \"string\", opt: true }, { name: \"overlay\", kind: \"bool\", opt: true }, { name: \"scale\", kind: \"string\", opt: true, oneOf: [\"left\", \"right\"] }], t(\"void\"), \"special\");\nadd(\"plot\", [S(\"series\"), { name: \"title\", kind: \"string\", opt: true }, { name: \"color\", kind: \"color\", opt: true }, I(\"linewidth\", { opt: true, min: 1, max: 8 }), { name: \"style\", kind: \"enum\", oneOf: ENUMS.plotStyle, opt: true }, I(\"offset\", { opt: true, min: -5000, max: 5000 }), { name: \"color_down\", kind: \"color\", opt: true }], t(\"plot\"), \"special\");\nadd(\"hline\", [N(\"price\"), { name: \"title\", kind: \"string\", opt: true }, { name: \"color\", kind: \"color\", opt: true }, { name: \"linestyle\", kind: \"enum\", oneOf: ENUMS.lineStyle, opt: true }], t(\"void\"), \"special\");\nadd(\"fill\", [{ name: \"plot1\", kind: \"plot\" }, { name: \"plot2\", kind: \"plot\" }, { name: \"color\", kind: \"color\", opt: true }, { name: \"title\", kind: \"string\", opt: true }], t(\"void\"), \"special\");\nadd(\"plotshape\", [{ name: \"series\", kind: \"any\" }, { name: \"title\", kind: \"string\", opt: true }, { name: \"style\", kind: \"enum\", oneOf: ENUMS.shape, opt: true }, { name: \"location\", kind: \"enum\", oneOf: ENUMS.location, opt: true }, { name: \"color\", kind: \"color\", opt: true }, I(\"offset\", { opt: true, min: -5000, max: 5000 }), I(\"last\", { opt: true, min: 1, max: 5000 }), I(\"within\", { opt: true, min: 1, max: 5000 })], t(\"void\"), \"special\");\n// bar colours and pane shading: output statements like plot(); the condition is a bool series, the colour a constant\nadd(\"barcolor\", [{ name: \"condition\", kind: \"any\" }, { name: \"color\", kind: \"color\" }], t(\"void\"), \"special\");\nadd(\"bgcolor\", [{ name: \"condition\", kind: \"any\" }, { name: \"color\", kind: \"color\" }], t(\"void\"), \"special\");\n// a number series of another instrument and/or another timeframe, joined onto this chart's bars by the host's bars\n// (symbol and timeframe are string literals or na; the checker reads them, the host loads them)\nadd(\"outside\", [{ name: \"symbol\", kind: \"any\", opt: true }, { name: \"field\", kind: \"string\", opt: true, oneOf: OUTSIDE_FIELDS }, { name: \"timeframe\", kind: \"any\", opt: true }], FLOAT_S, \"special\");\nadd(\"color.new\", [{ name: \"color\", kind: \"color\" }, N(\"transp\", { min: 0, max: 100 })], t(\"color\"), \"special\");\n\n// inputs: `name = input.x(defval, title, ...)` — the whole right-hand side of a top-level declaration\nadd(\"input.int\", [I(\"defval\"), { name: \"title\", kind: \"string\", opt: true }, I(\"minval\", { opt: true }), I(\"maxval\", { opt: true }), I(\"step\", { opt: true })], t(\"int\", \"input\"), \"special\");\nadd(\"input.float\", [N(\"defval\"), { name: \"title\", kind: \"string\", opt: true }, N(\"minval\", { opt: true }), N(\"maxval\", { opt: true }), N(\"step\", { opt: true })], t(\"float\", \"input\"), \"special\");\nadd(\"input.bool\", [{ name: \"defval\", kind: \"bool\" }, { name: \"title\", kind: \"string\", opt: true }], t(\"bool\", \"input\"), \"special\");\nadd(\"input.string\", [{ name: \"defval\", kind: \"string\" }, { name: \"title\", kind: \"string\", opt: true }, { name: \"options\", kind: \"strlist\" }], t(\"string\", \"input\"), \"special\");\nadd(\"input.source\", [{ name: \"defval\", kind: \"any\" }, { name: \"title\", kind: \"string\", opt: true }], FLOAT_S, \"special\");\nadd(\"input.color\", [{ name: \"defval\", kind: \"color\" }, { name: \"title\", kind: \"string\", opt: true }], t(\"color\", \"input\"), \"special\");\n\n/** Names the editor can offer: every callable, every constant, the series and the keywords. */\nexport function completionNames(): { label: string; kind: \"function\" | \"constant\" | \"variable\" | \"keyword\" | \"namespace\"; detail?: string }[] {\n const out: { label: string; kind: \"function\" | \"constant\" | \"variable\" | \"keyword\" | \"namespace\"; detail?: string }[] = [];\n for (const s of SIGS.values()) out.push({ label: s.name, kind: \"function\", detail: `(${s.params.map((p) => (p.opt ? `${p.name}?` : p.name)).join(\", \")})` });\n for (const k of Object.keys(MEMBER_CONSTS)) out.push({ label: k, kind: \"constant\" });\n for (const k of Object.keys(BUILTIN_SERIES)) out.push({ label: k, kind: \"variable\" });\n out.push({ label: \"ta.tr\", kind: \"variable\" }, { label: \"na\", kind: \"constant\" });\n for (const k of NAMESPACES) out.push({ label: k, kind: \"namespace\" });\n return out;\n}\n"],"mappings":";;AAoBA,IAAaA,oBAAgC,IAAI,IAAI;CAAC;CAAM;CAAQ;CAAO;CAAM;CAAM;CAAO;CAAO;CAAM;CAAO;CAAQ;AAAO,CAAC,GAErHC,IAA6C,OAAO,OAAO,OAAO,OAAO,IAAI,GAA6B,OAAO,YAAY,OAAO,QAAQ;CACvJ,OAAO;CACP,QAAQ;CACR,UAAU;CACV,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,OAAO;CACP,UAAU;CACV,OAAO;CACP,MAAM;CACN,MAAM;CACN,MAAM;CACN,WAAW;CACX,aAAa;CACb,WAAW;AACb,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,aAAa,gCAAgC,CAAC,CAAC,CAAC,CAAC,GAGvDC,oBAAO,IAAI,IAAI;CAAC;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;AAAI,CAAC,GAC3EC,oBAAO,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,EAAE;CAAG,CAAC;CAC3J,KAAK,IAAM7C,KAAK,OAAO,KAAKqB,CAAa,GAAG,EAAI,KAAK;EAAE,OAAOrB;EAAG,MAAM;CAAW,CAAC;CACnF,KAAK,IAAMA,KAAK,OAAO,KAAKoB,CAAc,GAAG,EAAI,KAAK;EAAE,OAAOpB;EAAG,MAAM;CAAW,CAAC;CACpF,EAAI,KAAK;EAAE,OAAO;EAAS,MAAM;CAAW,GAAG;EAAE,OAAO;EAAM,MAAM;CAAW,CAAC;CAChF,KAAK,IAAMA,KAAKmB,GAAY,EAAI,KAAK;EAAE,OAAOnB;EAAG,MAAM;CAAY,CAAC;CACpE,OAAOf;AACT"}
package/dist/editor.js ADDED
@@ -0,0 +1,211 @@
1
+ import { a as e, c as t, u as n } from "./builtins-BXxWK58s.js";
2
+ import { autocompletion as r, closeBrackets as i, closeBracketsKeymap as a } from "@codemirror/autocomplete";
3
+ import { defaultKeymap as o, history as s, historyKeymap as c } from "@codemirror/commands";
4
+ import { HighlightStyle as l, StreamLanguage as u, syntaxHighlighting as d } from "@codemirror/language";
5
+ import { setDiagnostics as f } from "@codemirror/lint";
6
+ import { EditorState as p, Prec as m } from "@codemirror/state";
7
+ import { EditorView as h, drawSelection as g, highlightActiveLine as _, keymap as v, lineNumbers as y, placeholder as b } from "@codemirror/view";
8
+ import { tags as x } from "@lezer/highlight";
9
+ //#region src/editor/index.ts
10
+ var S = /* @__PURE__ */ new Set([
11
+ "int",
12
+ "float",
13
+ "bool",
14
+ "string",
15
+ "color"
16
+ ]), C = u.define({
17
+ token(t) {
18
+ if (t.eatSpace()) return null;
19
+ if (t.match("//")) return t.skipToEnd(), "comment";
20
+ let r = t.peek();
21
+ if (r === "\"" || r === "'") {
22
+ t.next();
23
+ let e = !1, n;
24
+ for (; (n = t.next()) !== void 0 && (n !== r || e);) e = !e && n === "\\";
25
+ return "string";
26
+ }
27
+ if (t.match(/^#[0-9a-fA-F]{6}(?:[0-9a-fA-F]{2})?/)) return "atom";
28
+ if (t.match(/^(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/)) return "number";
29
+ if (t.match(/^[A-Za-z_][A-Za-z0-9_]*/)) {
30
+ let r = t.current();
31
+ return n.has(r) ? r === "true" || r === "false" ? "atom" : "keyword" : S.has(r) && t.match(/^\s+[A-Za-z_]/, !1) ? "typeName" : r === "na" ? "atom" : e.has(r) && t.peek() === "." ? "namespace" : t.peek() === "(" ? "variableName.function" : "variableName";
32
+ }
33
+ return t.match(/^(?::=|[-+*\/%]=|==|!=|<=|>=)/) || t.match(/^[-+*\/%<>=?:]/) ? "operator" : (t.next(), null);
34
+ },
35
+ startState: () => ({}),
36
+ languageData: { commentTokens: { line: "//" } }
37
+ }), w = l.define([
38
+ {
39
+ tag: x.keyword,
40
+ color: "var(--ac-script-keyword, #c678dd)"
41
+ },
42
+ {
43
+ tag: x.comment,
44
+ color: "var(--ac-script-comment, #7f848e)",
45
+ fontStyle: "italic"
46
+ },
47
+ {
48
+ tag: x.string,
49
+ color: "var(--ac-script-string, #98c379)"
50
+ },
51
+ {
52
+ tag: x.number,
53
+ color: "var(--ac-script-number, #d19a66)"
54
+ },
55
+ {
56
+ tag: x.atom,
57
+ color: "var(--ac-script-atom, #d19a66)"
58
+ },
59
+ {
60
+ tag: x.typeName,
61
+ color: "var(--ac-script-type, #e5c07b)"
62
+ },
63
+ {
64
+ tag: x.namespace,
65
+ color: "var(--ac-script-namespace, #61afef)"
66
+ },
67
+ {
68
+ tag: x.function(x.variableName),
69
+ color: "var(--ac-script-function, #61afef)"
70
+ },
71
+ {
72
+ tag: x.operator,
73
+ color: "var(--ac-script-operator, #56b6c2)"
74
+ }
75
+ ]), T = {
76
+ function: "function",
77
+ constant: "constant",
78
+ variable: "variable",
79
+ keyword: "keyword",
80
+ namespace: "namespace"
81
+ };
82
+ function E(e) {
83
+ let t = /* @__PURE__ */ new Set();
84
+ for (let n of e.matchAll(/^[ ]*(?:var[ ]+)?(?:(?:int|float|bool|string|color)[ ]+)?([A-Za-z_]\w*)[ ]*=(?!=)/gm)) t.add(n[1]);
85
+ for (let n of e.matchAll(/^[ ]*for[ ]+([A-Za-z_]\w*)[ ]*=/gm)) t.add(n[1]);
86
+ for (let n of e.matchAll(/^[ ]*\[([^\]\n]*)\][ ]*=(?!=)/gm)) for (let e of n[1].split(",")) /^\s*[A-Za-z_]\w*\s*$/.test(e) && t.add(e.trim());
87
+ return [...t];
88
+ }
89
+ var D = null;
90
+ function O() {
91
+ return D ??= [
92
+ ...t().map((e) => ({
93
+ label: e.label,
94
+ type: T[e.kind],
95
+ ...e.detail && { detail: e.detail },
96
+ boost: +(e.kind === "function")
97
+ })),
98
+ ...[...n].map((e) => ({
99
+ label: e,
100
+ type: "keyword",
101
+ boost: -1
102
+ })),
103
+ ...[
104
+ "int",
105
+ "float",
106
+ "bool",
107
+ "string",
108
+ "color"
109
+ ].map((e) => ({
110
+ label: e,
111
+ type: "type",
112
+ boost: -1
113
+ }))
114
+ ];
115
+ }
116
+ function k(e, t) {
117
+ return [...E(e).map((e) => ({
118
+ label: e,
119
+ type: "variable",
120
+ boost: 2
121
+ })), ...O()].filter((e) => e.label.startsWith(t) && e.label !== t);
122
+ }
123
+ function A(e) {
124
+ let t = e.matchBefore(/[A-Za-z_][\w]*(?:\.[\w]*)?|\.\w*/);
125
+ if (!t || t.from === t.to && !e.explicit) return null;
126
+ let n = k(e.state.doc.toString(), t.text);
127
+ return n.length ? {
128
+ from: t.from,
129
+ options: n,
130
+ validFor: /^[\w.]*$/
131
+ } : null;
132
+ }
133
+ function j(e, t) {
134
+ return t.map((t) => {
135
+ let n = t.from;
136
+ if (typeof n != "number") {
137
+ let r = e.line(Math.min(Math.max(1, t.line), e.lines));
138
+ n = Math.min(r.from + Math.max(0, t.column - 1), r.to);
139
+ }
140
+ let r = typeof t.to == "number" ? t.to : n + 1;
141
+ return {
142
+ from: Math.min(n, e.length),
143
+ to: Math.min(Math.max(r, n + 1), e.length),
144
+ severity: t.severity,
145
+ message: t.message
146
+ };
147
+ });
148
+ }
149
+ function M() {
150
+ return { mount(e, t) {
151
+ let n = new h({
152
+ parent: e,
153
+ state: p.create({
154
+ doc: t.value,
155
+ extensions: [
156
+ y(),
157
+ s(),
158
+ g(),
159
+ _(),
160
+ i(),
161
+ C,
162
+ d(w),
163
+ r({ override: [A] }),
164
+ b("plot(ta.sma(close, 20))"),
165
+ m.highest(v.of([{
166
+ key: "Mod-Enter",
167
+ run: (e) => (t.onRun(e.state.doc.toString()), !0)
168
+ }, {
169
+ key: "Tab",
170
+ run: (e) => (e.dispatch(e.state.replaceSelection(" ")), !0)
171
+ }])),
172
+ v.of([
173
+ ...a,
174
+ ...o,
175
+ ...c
176
+ ]),
177
+ h.updateListener.of((e) => {
178
+ e.docChanged && t.onChange(e.state.doc.toString());
179
+ }),
180
+ h.theme({
181
+ "&": {
182
+ height: "100%",
183
+ color: "var(--ac-script-fg, inherit)",
184
+ backgroundColor: "var(--ac-script-bg, transparent)"
185
+ },
186
+ ".cm-scroller": {
187
+ fontFamily: "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",
188
+ fontSize: "13px",
189
+ lineHeight: "1.5"
190
+ },
191
+ ".cm-gutters": {
192
+ backgroundColor: "transparent",
193
+ color: "var(--ac-script-gutter, #7f848e)",
194
+ border: "none"
195
+ },
196
+ "&.cm-focused": { outline: "none" },
197
+ ".cm-content": { caretColor: "var(--ac-script-caret, currentColor)" }
198
+ })
199
+ ]
200
+ })
201
+ }), l = (e) => n.dispatch(f(n.state, j(n.state.doc, e)));
202
+ return l(t.diagnostics), {
203
+ setDiagnostics: l,
204
+ destroy: () => n.destroy()
205
+ };
206
+ } };
207
+ }
208
+ //#endregion
209
+ export { k as completionsFor, M as createScriptEditorAdapter, E as declaredNames, C as scriptLanguage };
210
+
211
+ //# sourceMappingURL=editor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"editor.js","names":["t","lintSet","NAMESPACES","completionNames","KEYWORDS","TYPES","scriptLanguage","StreamLanguage","stream","q","esc","c","w","highlight","HighlightStyle","tags","KIND","declaredNames","out","m","text","n","cached","base","k","completionsFor","word","source","ctx","options","toCm","list","from","d","line","doc","to","createScriptEditorAdapter","view","EditorView","el","EditorState","opts","lineNumbers","history","drawSelection","highlightActiveLine","closeBrackets","syntaxHighlighting","autocompletion","placeholder","Prec","keymap","v","closeBracketsKeymap","defaultKeymap","historyKeymap","u","apply","setDiagnostics"],"sources":["../src/editor/index.ts"],"sourcesContent":["// A framework-free script editor on CodeMirror 6: highlighting, inline\n// diagnostics, autocomplete of ta.* / math.* / inputs, Mod-Enter to run.\n//\n// This subpath is the only place the package touches CodeMirror. The adapter\n// interface is what @alphacharts/ui consumes.\n\nimport { autocompletion, closeBrackets, closeBracketsKeymap, type Completion, type CompletionContext, type CompletionResult } from \"@codemirror/autocomplete\";\nimport { defaultKeymap, history, historyKeymap } from \"@codemirror/commands\";\nimport { HighlightStyle, StreamLanguage, syntaxHighlighting, type StringStream } from \"@codemirror/language\";\nimport { setDiagnostics as lintSet, type Diagnostic as CmDiagnostic } from \"@codemirror/lint\";\nimport { EditorState, Prec } from \"@codemirror/state\";\nimport { EditorView, keymap, lineNumbers, drawSelection, highlightActiveLine, placeholder } from \"@codemirror/view\";\nimport { tags as t } from \"@lezer/highlight\";\nimport { completionNames, NAMESPACES } from \"../builtins.js\";\nimport { KEYWORDS } from \"../lexer.js\";\nimport type { Diagnostic } from \"../diag.js\";\n\nexport interface ScriptEditorAdapter {\n mount(\n el: HTMLElement,\n opts: { value: string; onChange(v: string): void; onRun(v: string): void; diagnostics: Diagnostic[] },\n ): { setDiagnostics(d: Diagnostic[]): void; destroy(): void };\n}\n\n// ---- language -------------------------------------------------------------------------\n\nconst TYPES = new Set([\"int\", \"float\", \"bool\", \"string\", \"color\"]);\n\ninterface LState { }\n\nexport const scriptLanguage = StreamLanguage.define<LState>({\n token(stream: StringStream): string | null {\n if (stream.eatSpace()) return null;\n if (stream.match(\"//\")) { stream.skipToEnd(); return \"comment\"; }\n const q = stream.peek();\n if (q === '\"' || q === \"'\") {\n stream.next();\n let esc = false, c: string | void;\n while ((c = stream.next()) !== undefined) {\n if (c === q && !esc) break;\n esc = !esc && c === \"\\\\\";\n }\n return \"string\";\n }\n if (stream.match(/^#[0-9a-fA-F]{6}(?:[0-9a-fA-F]{2})?/)) return \"atom\";\n if (stream.match(/^(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][+-]?\\d+)?/)) return \"number\";\n if (stream.match(/^[A-Za-z_][A-Za-z0-9_]*/)) {\n const w = stream.current();\n if (KEYWORDS.has(w)) return w === \"true\" || w === \"false\" ? \"atom\" : \"keyword\";\n if (TYPES.has(w) && stream.match(/^\\s+[A-Za-z_]/, false)) return \"typeName\";\n if (w === \"na\") return \"atom\";\n if (NAMESPACES.has(w) && stream.peek() === \".\") return \"namespace\";\n if (stream.peek() === \"(\") return \"variableName.function\";\n return \"variableName\";\n }\n if (stream.match(/^(?::=|[-+*\\/%]=|==|!=|<=|>=)/) || stream.match(/^[-+*\\/%<>=?:]/)) return \"operator\";\n stream.next();\n return null;\n },\n startState: () => ({}),\n languageData: { commentTokens: { line: \"//\" } },\n});\n\nconst highlight = HighlightStyle.define([\n { tag: t.keyword, color: \"var(--ac-script-keyword, #c678dd)\" },\n { tag: t.comment, color: \"var(--ac-script-comment, #7f848e)\", fontStyle: \"italic\" },\n { tag: t.string, color: \"var(--ac-script-string, #98c379)\" },\n { tag: t.number, color: \"var(--ac-script-number, #d19a66)\" },\n { tag: t.atom, color: \"var(--ac-script-atom, #d19a66)\" },\n { tag: t.typeName, color: \"var(--ac-script-type, #e5c07b)\" },\n { tag: t.namespace, color: \"var(--ac-script-namespace, #61afef)\" },\n { tag: t.function(t.variableName), color: \"var(--ac-script-function, #61afef)\" },\n { tag: t.operator, color: \"var(--ac-script-operator, #56b6c2)\" },\n]);\n\n// ---- completion -----------------------------------------------------------------------------\n\nconst KIND: Record<string, Completion[\"type\"]> = { function: \"function\", constant: \"constant\", variable: \"variable\", keyword: \"keyword\", namespace: \"namespace\" };\n\n/** Names declared in the text (variables, inputs, loop counters): `name =`, `var name =`, `float name =`, `for i =`, `[a, b] =`. */\nexport function declaredNames(text: string): string[] {\n const out = new Set<string>();\n for (const m of text.matchAll(/^[ ]*(?:var[ ]+)?(?:(?:int|float|bool|string|color)[ ]+)?([A-Za-z_]\\w*)[ ]*=(?!=)/gm)) out.add(m[1]!);\n for (const m of text.matchAll(/^[ ]*for[ ]+([A-Za-z_]\\w*)[ ]*=/gm)) out.add(m[1]!);\n for (const m of text.matchAll(/^[ ]*\\[([^\\]\\n]*)\\][ ]*=(?!=)/gm)) for (const n of m[1]!.split(\",\")) if (/^\\s*[A-Za-z_]\\w*\\s*$/.test(n)) out.add(n.trim());\n return [...out];\n}\n\nlet cached: Completion[] | null = null;\nfunction base(): Completion[] {\n return (cached ??= [\n ...completionNames().map((c): Completion => ({ label: c.label, type: KIND[c.kind]!, ...(c.detail && { detail: c.detail }), boost: c.kind === \"function\" ? 1 : 0 })),\n ...[...KEYWORDS].map((k): Completion => ({ label: k, type: \"keyword\", boost: -1 })),\n ...[\"int\", \"float\", \"bool\", \"string\", \"color\"].map((k): Completion => ({ label: k, type: \"type\", boost: -1 })),\n ]);\n}\n\n/** Completion options for the word before the cursor (exported for tests). */\nexport function completionsFor(text: string, word: string): Completion[] {\n const own = declaredNames(text).map((n): Completion => ({ label: n, type: \"variable\", boost: 2 }));\n const all = [...own, ...base()];\n return all.filter((c) => c.label.startsWith(word) && c.label !== word);\n}\n\nfunction source(ctx: CompletionContext): CompletionResult | null {\n const w = ctx.matchBefore(/[A-Za-z_][\\w]*(?:\\.[\\w]*)?|\\.\\w*/);\n if (!w || (w.from === w.to && !ctx.explicit)) return null;\n const options = completionsFor(ctx.state.doc.toString(), w.text);\n return options.length ? { from: w.from, options, validFor: /^[\\w.]*$/ } : null;\n}\n\n// ---- adapter ------------------------------------------------------------------------------------\n\nfunction toCm(doc: EditorState[\"doc\"], list: Diagnostic[]): CmDiagnostic[] {\n return list.map((d) => {\n // A host may report a diagnostic by line and column only (no offsets).\n let from = d.from;\n if (typeof from !== \"number\") {\n const line = doc.line(Math.min(Math.max(1, d.line), doc.lines));\n from = Math.min(line.from + Math.max(0, d.column - 1), line.to);\n }\n const to = typeof d.to === \"number\" ? d.to : from + 1;\n return { from: Math.min(from, doc.length), to: Math.min(Math.max(to, from + 1), doc.length), severity: d.severity, message: d.message };\n });\n}\n\nexport function createScriptEditorAdapter(): ScriptEditorAdapter {\n return {\n mount(el, opts) {\n const run = (view: EditorView) => { opts.onRun(view.state.doc.toString()); return true; };\n const view = new EditorView({\n parent: el,\n state: EditorState.create({\n doc: opts.value,\n extensions: [\n lineNumbers(), history(), drawSelection(), highlightActiveLine(), closeBrackets(), scriptLanguage, syntaxHighlighting(highlight),\n autocompletion({ override: [source] }),\n placeholder(\"plot(ta.sma(close, 20))\"),\n Prec.highest(keymap.of([\n { key: \"Mod-Enter\", run },\n // tabs are not allowed in scripts: Tab inserts the indent\n { key: \"Tab\", run: (v) => { v.dispatch(v.state.replaceSelection(\" \")); return true; } },\n ])),\n keymap.of([...closeBracketsKeymap, ...defaultKeymap, ...historyKeymap]),\n EditorView.updateListener.of((u) => { if (u.docChanged) opts.onChange(u.state.doc.toString()); }),\n EditorView.theme({\n \"&\": { height: \"100%\", color: \"var(--ac-script-fg, inherit)\", backgroundColor: \"var(--ac-script-bg, transparent)\" },\n \".cm-scroller\": { fontFamily: \"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace\", fontSize: \"13px\", lineHeight: \"1.5\" },\n \".cm-gutters\": { backgroundColor: \"transparent\", color: \"var(--ac-script-gutter, #7f848e)\", border: \"none\" },\n \"&.cm-focused\": { outline: \"none\" },\n \".cm-content\": { caretColor: \"var(--ac-script-caret, currentColor)\" },\n }),\n ],\n }),\n });\n const apply = (d: Diagnostic[]) => view.dispatch(lintSet(view.state, toCm(view.state.doc, d)));\n apply(opts.diagnostics);\n return { setDiagnostics: apply, destroy: () => view.dest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