oakscriptjs 0.23.0 → 0.25.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.
Files changed (310) hide show
  1. package/README.md +25 -1
  2. package/bin/oakscript.mjs +10 -3
  3. package/dist/cjs/box/index.d.ts +348 -289
  4. package/dist/cjs/box/index.d.ts.map +1 -1
  5. package/dist/cjs/box/index.js.map +2 -2
  6. package/dist/cjs/check/node.d.ts.map +1 -1
  7. package/dist/cjs/check/node.js +1 -0
  8. package/dist/cjs/check/node.js.map +2 -2
  9. package/dist/cjs/check/preview.d.ts +31 -0
  10. package/dist/cjs/check/preview.d.ts.map +1 -0
  11. package/dist/cjs/check/preview.js +303 -0
  12. package/dist/cjs/check/preview.js.map +7 -0
  13. package/dist/cjs/color/index.d.ts +11 -11
  14. package/dist/cjs/color/index.js.map +1 -1
  15. package/dist/cjs/color/parse.d.ts +2 -0
  16. package/dist/cjs/color/parse.d.ts.map +1 -1
  17. package/dist/cjs/color/parse.js +6 -0
  18. package/dist/cjs/color/parse.js.map +2 -2
  19. package/dist/cjs/compare/index.d.ts +76 -12
  20. package/dist/cjs/compare/index.d.ts.map +1 -1
  21. package/dist/cjs/compare/index.js.map +2 -2
  22. package/dist/cjs/drawing/registry.d.ts +28 -5
  23. package/dist/cjs/drawing/registry.d.ts.map +1 -1
  24. package/dist/cjs/drawing/registry.js +14 -0
  25. package/dist/cjs/drawing/registry.js.map +2 -2
  26. package/dist/cjs/index.d.ts +1 -1
  27. package/dist/cjs/index.js +1 -1
  28. package/dist/cjs/index.js.map +1 -1
  29. package/dist/cjs/label/index.d.ts +265 -187
  30. package/dist/cjs/label/index.d.ts.map +1 -1
  31. package/dist/cjs/label/index.js +1 -1
  32. package/dist/cjs/label/index.js.map +2 -2
  33. package/dist/cjs/line/index.d.ts +247 -207
  34. package/dist/cjs/line/index.d.ts.map +1 -1
  35. package/dist/cjs/line/index.js.map +2 -2
  36. package/dist/cjs/linefill/index.d.ts +61 -89
  37. package/dist/cjs/linefill/index.d.ts.map +1 -1
  38. package/dist/cjs/linefill/index.js.map +2 -2
  39. package/dist/cjs/math/index.d.ts +49 -40
  40. package/dist/cjs/math/index.d.ts.map +1 -1
  41. package/dist/cjs/math/index.js.map +2 -2
  42. package/dist/cjs/polyline/index.d.ts +57 -78
  43. package/dist/cjs/polyline/index.d.ts.map +1 -1
  44. package/dist/cjs/polyline/index.js.map +2 -2
  45. package/dist/cjs/runtime/input-active.d.ts +2 -2
  46. package/dist/cjs/runtime/input-active.js.map +1 -1
  47. package/dist/cjs/runtime/series.d.ts +241 -161
  48. package/dist/cjs/runtime/series.d.ts.map +1 -1
  49. package/dist/cjs/runtime/series.js +223 -127
  50. package/dist/cjs/runtime/series.js.map +2 -2
  51. package/dist/cjs/script/api/alert.d.ts +37 -0
  52. package/dist/cjs/script/api/alert.d.ts.map +1 -0
  53. package/dist/cjs/script/api/alert.js +17 -0
  54. package/dist/cjs/script/api/alert.js.map +7 -0
  55. package/dist/cjs/script/api/calc.d.ts +232 -0
  56. package/dist/cjs/script/api/calc.d.ts.map +1 -0
  57. package/dist/cjs/script/api/calc.js +17 -0
  58. package/dist/cjs/script/api/calc.js.map +7 -0
  59. package/dist/cjs/script/api/color.d.ts +213 -0
  60. package/dist/cjs/script/api/color.d.ts.map +1 -0
  61. package/dist/cjs/script/api/color.js +17 -0
  62. package/dist/cjs/script/api/color.js.map +7 -0
  63. package/dist/cjs/script/api/context.d.ts +764 -0
  64. package/dist/cjs/script/api/context.d.ts.map +1 -0
  65. package/dist/cjs/script/api/context.js +17 -0
  66. package/dist/cjs/script/api/context.js.map +7 -0
  67. package/dist/cjs/script/api/log.d.ts +58 -0
  68. package/dist/cjs/script/api/log.d.ts.map +1 -0
  69. package/dist/cjs/script/api/log.js +17 -0
  70. package/dist/cjs/script/api/log.js.map +7 -0
  71. package/dist/cjs/script/api/strategy.d.ts +391 -0
  72. package/dist/cjs/script/api/strategy.d.ts.map +1 -0
  73. package/dist/cjs/script/api/strategy.js +17 -0
  74. package/dist/cjs/script/api/strategy.js.map +7 -0
  75. package/dist/cjs/script/api/ta.d.ts +1012 -0
  76. package/dist/cjs/script/api/ta.d.ts.map +1 -0
  77. package/dist/cjs/script/api/ta.js +17 -0
  78. package/dist/cjs/script/api/ta.js.map +7 -0
  79. package/dist/cjs/script/api/table.d.ts +479 -0
  80. package/dist/cjs/script/api/table.d.ts.map +1 -0
  81. package/dist/cjs/script/api/table.js +17 -0
  82. package/dist/cjs/script/api/table.js.map +7 -0
  83. package/dist/cjs/script/constants.d.ts +228 -83
  84. package/dist/cjs/script/constants.d.ts.map +1 -1
  85. package/dist/cjs/script/constants.js +87 -0
  86. package/dist/cjs/script/constants.js.map +2 -2
  87. package/dist/cjs/script/define.d.ts +94 -0
  88. package/dist/cjs/script/define.d.ts.map +1 -0
  89. package/dist/cjs/script/define.js +127 -0
  90. package/dist/cjs/script/define.js.map +7 -0
  91. package/dist/cjs/script/drawing-args.d.ts.map +1 -1
  92. package/dist/cjs/script/drawing-args.js +1 -1
  93. package/dist/cjs/script/drawing-args.js.map +2 -2
  94. package/dist/cjs/script/formula.d.ts +53 -0
  95. package/dist/cjs/script/formula.d.ts.map +1 -0
  96. package/dist/cjs/script/formula.js +402 -0
  97. package/dist/cjs/script/formula.js.map +7 -0
  98. package/dist/cjs/script/globals.d.ts +10 -0
  99. package/dist/cjs/script/globals.d.ts.map +1 -1
  100. package/dist/cjs/script/globals.js.map +1 -1
  101. package/dist/cjs/script/index.d.ts +1065 -1006
  102. package/dist/cjs/script/index.d.ts.map +1 -1
  103. package/dist/cjs/script/index.js +532 -61
  104. package/dist/cjs/script/index.js.map +3 -3
  105. package/dist/cjs/script/json.d.ts +117 -0
  106. package/dist/cjs/script/json.d.ts.map +1 -0
  107. package/dist/cjs/script/json.js +321 -0
  108. package/dist/cjs/script/json.js.map +7 -0
  109. package/dist/cjs/security/other.d.ts +8 -3
  110. package/dist/cjs/security/other.d.ts.map +1 -1
  111. package/dist/cjs/security/other.js +23 -6
  112. package/dist/cjs/security/other.js.map +2 -2
  113. package/dist/cjs/str/index.d.ts +50 -75
  114. package/dist/cjs/str/index.d.ts.map +1 -1
  115. package/dist/cjs/str/index.js +2 -2
  116. package/dist/cjs/str/index.js.map +2 -2
  117. package/dist/cjs/strategy/index.d.ts +102 -1
  118. package/dist/cjs/strategy/index.d.ts.map +1 -1
  119. package/dist/cjs/strategy/index.js.map +2 -2
  120. package/dist/cjs/table/index.d.ts +330 -49
  121. package/dist/cjs/table/index.d.ts.map +1 -1
  122. package/dist/cjs/table/index.js +55 -27
  123. package/dist/cjs/table/index.js.map +2 -2
  124. package/dist/cjs/text/index.d.ts +12 -14
  125. package/dist/cjs/text/index.d.ts.map +1 -1
  126. package/dist/cjs/text/index.js.map +2 -2
  127. package/dist/cjs/types/index.d.ts +15 -8
  128. package/dist/cjs/types/index.d.ts.map +1 -1
  129. package/dist/cjs/types/index.js +12 -3
  130. package/dist/cjs/types/index.js.map +2 -2
  131. package/dist/esm/box/index.d.ts +348 -289
  132. package/dist/esm/box/index.d.ts.map +1 -1
  133. package/dist/esm/box/index.js +276 -276
  134. package/dist/esm/box/index.js.map +1 -1
  135. package/dist/esm/check/node.d.ts.map +1 -1
  136. package/dist/esm/check/node.js +1 -0
  137. package/dist/esm/check/node.js.map +1 -1
  138. package/dist/esm/check/preview.d.ts +31 -0
  139. package/dist/esm/check/preview.d.ts.map +1 -0
  140. package/dist/esm/check/preview.js +296 -0
  141. package/dist/esm/check/preview.js.map +1 -0
  142. package/dist/esm/color/index.d.ts +11 -11
  143. package/dist/esm/color/index.js +11 -11
  144. package/dist/esm/color/parse.d.ts +2 -0
  145. package/dist/esm/color/parse.d.ts.map +1 -1
  146. package/dist/esm/color/parse.js +7 -0
  147. package/dist/esm/color/parse.js.map +1 -1
  148. package/dist/esm/compare/index.d.ts +76 -12
  149. package/dist/esm/compare/index.d.ts.map +1 -1
  150. package/dist/esm/compare/index.js +76 -12
  151. package/dist/esm/compare/index.js.map +1 -1
  152. package/dist/esm/drawing/registry.d.ts +28 -5
  153. package/dist/esm/drawing/registry.d.ts.map +1 -1
  154. package/dist/esm/drawing/registry.js +39 -3
  155. package/dist/esm/drawing/registry.js.map +1 -1
  156. package/dist/esm/index.d.ts +1 -1
  157. package/dist/esm/index.js +1 -1
  158. package/dist/esm/label/index.d.ts +265 -187
  159. package/dist/esm/label/index.d.ts.map +1 -1
  160. package/dist/esm/label/index.js +207 -177
  161. package/dist/esm/label/index.js.map +1 -1
  162. package/dist/esm/line/index.d.ts +247 -207
  163. package/dist/esm/line/index.d.ts.map +1 -1
  164. package/dist/esm/line/index.js +202 -194
  165. package/dist/esm/line/index.js.map +1 -1
  166. package/dist/esm/linefill/index.d.ts +61 -89
  167. package/dist/esm/linefill/index.d.ts.map +1 -1
  168. package/dist/esm/linefill/index.js +61 -89
  169. package/dist/esm/linefill/index.js.map +1 -1
  170. package/dist/esm/math/index.d.ts +49 -40
  171. package/dist/esm/math/index.d.ts.map +1 -1
  172. package/dist/esm/math/index.js +22 -9
  173. package/dist/esm/math/index.js.map +1 -1
  174. package/dist/esm/polyline/index.d.ts +57 -78
  175. package/dist/esm/polyline/index.d.ts.map +1 -1
  176. package/dist/esm/polyline/index.js +57 -78
  177. package/dist/esm/polyline/index.js.map +1 -1
  178. package/dist/esm/runtime/input-active.d.ts +2 -2
  179. package/dist/esm/runtime/input-active.js +2 -2
  180. package/dist/esm/runtime/series.d.ts +241 -161
  181. package/dist/esm/runtime/series.d.ts.map +1 -1
  182. package/dist/esm/runtime/series.js +241 -161
  183. package/dist/esm/runtime/series.js.map +1 -1
  184. package/dist/esm/script/api/alert.d.ts +37 -0
  185. package/dist/esm/script/api/alert.d.ts.map +1 -0
  186. package/dist/esm/script/api/alert.js +7 -0
  187. package/dist/esm/script/api/alert.js.map +1 -0
  188. package/dist/esm/script/api/calc.d.ts +232 -0
  189. package/dist/esm/script/api/calc.d.ts.map +1 -0
  190. package/dist/esm/script/api/calc.js +6 -0
  191. package/dist/esm/script/api/calc.js.map +1 -0
  192. package/dist/esm/script/api/color.d.ts +213 -0
  193. package/dist/esm/script/api/color.d.ts.map +1 -0
  194. package/dist/esm/script/api/color.js +6 -0
  195. package/dist/esm/script/api/color.js.map +1 -0
  196. package/dist/esm/script/api/context.d.ts +764 -0
  197. package/dist/esm/script/api/context.d.ts.map +1 -0
  198. package/dist/esm/script/api/context.js +7 -0
  199. package/dist/esm/script/api/context.js.map +1 -0
  200. package/dist/esm/script/api/log.d.ts +58 -0
  201. package/dist/esm/script/api/log.d.ts.map +1 -0
  202. package/dist/esm/script/api/log.js +6 -0
  203. package/dist/esm/script/api/log.js.map +1 -0
  204. package/dist/esm/script/api/strategy.d.ts +391 -0
  205. package/dist/esm/script/api/strategy.d.ts.map +1 -0
  206. package/dist/esm/script/api/strategy.js +7 -0
  207. package/dist/esm/script/api/strategy.js.map +1 -0
  208. package/dist/esm/script/api/ta.d.ts +1012 -0
  209. package/dist/esm/script/api/ta.d.ts.map +1 -0
  210. package/dist/esm/script/api/ta.js +6 -0
  211. package/dist/esm/script/api/ta.js.map +1 -0
  212. package/dist/esm/script/api/table.d.ts +479 -0
  213. package/dist/esm/script/api/table.d.ts.map +1 -0
  214. package/dist/esm/script/api/table.js +7 -0
  215. package/dist/esm/script/api/table.js.map +1 -0
  216. package/dist/esm/script/constants.d.ts +228 -83
  217. package/dist/esm/script/constants.d.ts.map +1 -1
  218. package/dist/esm/script/constants.js +110 -24
  219. package/dist/esm/script/constants.js.map +1 -1
  220. package/dist/esm/script/define.d.ts +94 -0
  221. package/dist/esm/script/define.d.ts.map +1 -0
  222. package/dist/esm/script/define.js +136 -0
  223. package/dist/esm/script/define.js.map +1 -0
  224. package/dist/esm/script/drawing-args.d.ts.map +1 -1
  225. package/dist/esm/script/drawing-args.js +2 -1
  226. package/dist/esm/script/drawing-args.js.map +1 -1
  227. package/dist/esm/script/formula.d.ts +53 -0
  228. package/dist/esm/script/formula.d.ts.map +1 -0
  229. package/dist/esm/script/formula.js +408 -0
  230. package/dist/esm/script/formula.js.map +1 -0
  231. package/dist/esm/script/globals.d.ts +10 -0
  232. package/dist/esm/script/globals.d.ts.map +1 -1
  233. package/dist/esm/script/globals.js.map +1 -1
  234. package/dist/esm/script/index.d.ts +1065 -1006
  235. package/dist/esm/script/index.d.ts.map +1 -1
  236. package/dist/esm/script/index.js +1099 -153
  237. package/dist/esm/script/index.js.map +1 -1
  238. package/dist/esm/script/json.d.ts +117 -0
  239. package/dist/esm/script/json.d.ts.map +1 -0
  240. package/dist/esm/script/json.js +375 -0
  241. package/dist/esm/script/json.js.map +1 -0
  242. package/dist/esm/security/other.d.ts +8 -3
  243. package/dist/esm/security/other.d.ts.map +1 -1
  244. package/dist/esm/security/other.js +45 -10
  245. package/dist/esm/security/other.js.map +1 -1
  246. package/dist/esm/str/index.d.ts +50 -75
  247. package/dist/esm/str/index.d.ts.map +1 -1
  248. package/dist/esm/str/index.js +51 -76
  249. package/dist/esm/str/index.js.map +1 -1
  250. package/dist/esm/strategy/index.d.ts +102 -1
  251. package/dist/esm/strategy/index.d.ts.map +1 -1
  252. package/dist/esm/strategy/index.js +1 -1
  253. package/dist/esm/strategy/index.js.map +1 -1
  254. package/dist/esm/table/index.d.ts +330 -49
  255. package/dist/esm/table/index.d.ts.map +1 -1
  256. package/dist/esm/table/index.js +372 -61
  257. package/dist/esm/table/index.js.map +1 -1
  258. package/dist/esm/text/index.d.ts +12 -14
  259. package/dist/esm/text/index.d.ts.map +1 -1
  260. package/dist/esm/text/index.js +12 -14
  261. package/dist/esm/text/index.js.map +1 -1
  262. package/dist/esm/types/index.d.ts +15 -8
  263. package/dist/esm/types/index.d.ts.map +1 -1
  264. package/dist/esm/types/index.js +15 -8
  265. package/dist/esm/types/index.js.map +1 -1
  266. package/docs/first-indicator.md +152 -0
  267. package/docs/guide.md +1185 -0
  268. package/docs/inventory.md +772 -0
  269. package/docs/no-code.md +207 -0
  270. package/docs/recipes.md +202 -0
  271. package/package.json +2 -1
  272. package/skills/oakscript/SKILL.md +8 -0
  273. package/skills/oakscript/reference/errors.md +3 -2
  274. package/skills/oakscript/reference/timeframes-symbols.md +4 -0
  275. package/src/box/index.ts +348 -289
  276. package/src/check/node.ts +1 -0
  277. package/src/check/preview.ts +307 -0
  278. package/src/color/index.ts +11 -11
  279. package/src/color/parse.ts +7 -0
  280. package/src/compare/index.ts +76 -12
  281. package/src/drawing/registry.ts +44 -5
  282. package/src/index.ts +1 -1
  283. package/src/label/index.ts +267 -189
  284. package/src/line/index.ts +248 -208
  285. package/src/linefill/index.ts +61 -89
  286. package/src/math/index.ts +51 -42
  287. package/src/polyline/index.ts +57 -78
  288. package/src/runtime/input-active.ts +2 -2
  289. package/src/runtime/series.ts +243 -163
  290. package/src/script/api/alert.ts +43 -0
  291. package/src/script/api/calc.ts +250 -0
  292. package/src/script/api/color.ts +245 -0
  293. package/src/script/api/context.ts +944 -0
  294. package/src/script/api/log.ts +60 -0
  295. package/src/script/api/strategy.ts +410 -0
  296. package/src/script/api/ta.ts +1115 -0
  297. package/src/script/api/table.ts +538 -0
  298. package/src/script/constants.ts +229 -25
  299. package/src/script/define.ts +221 -0
  300. package/src/script/drawing-args.ts +2 -1
  301. package/src/script/formula.ts +438 -0
  302. package/src/script/globals.ts +10 -0
  303. package/src/script/index.ts +1520 -241
  304. package/src/script/json.ts +457 -0
  305. package/src/security/other.ts +43 -9
  306. package/src/str/index.ts +51 -76
  307. package/src/strategy/index.ts +102 -1
  308. package/src/table/index.ts +388 -62
  309. package/src/text/index.ts +12 -14
  310. package/src/types/index.ts +15 -8
@@ -0,0 +1,303 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var preview_exports = {};
30
+ __export(preview_exports, {
31
+ previewMain: () => previewMain,
32
+ previewRun: () => previewRun,
33
+ startPreview: () => startPreview
34
+ });
35
+ module.exports = __toCommonJS(preview_exports);
36
+ var import_node_http = require("node:http");
37
+ var import_node_fs = require("node:fs");
38
+ var import_node_module = require("node:module");
39
+ var import_node_path = __toESM(require("node:path"), 1);
40
+ var import_script = require("../script/index.js");
41
+ var import_harness = require("./harness.js");
42
+ var import_node = require("./node.js");
43
+ const CDN = "https://unpkg.com/lightweight-charts@5/dist/lightweight-charts.standalone.production.js";
44
+ function localChartLibrary(from) {
45
+ try {
46
+ const require2 = (0, import_node_module.createRequire)(import_node_path.default.resolve(from, "package.json"));
47
+ const pkg = require2.resolve("lightweight-charts/package.json");
48
+ const file = import_node_path.default.join(import_node_path.default.dirname(pkg), "dist", "lightweight-charts.standalone.production.js");
49
+ return (0, import_node_fs.existsSync)(file) ? file : null;
50
+ } catch {
51
+ return null;
52
+ }
53
+ }
54
+ function previewRun(file, bars, inputs = {}) {
55
+ try {
56
+ const source = (0, import_node_fs.readFileSync)(file, "utf8");
57
+ const body = file.toLowerCase().endsWith(".json") ? (0, import_script.indicatorBodyFromJson)(source) : (0, import_harness.compileScript)(source);
58
+ const run = (0, import_script.executeScript)(body, bars, inputs, (0, import_harness.testChart)(bars), { strict: true, palette: true });
59
+ return {
60
+ ok: true,
61
+ metadata: run.metadata,
62
+ inputConfig: run.inputConfig,
63
+ plotConfig: run.plotConfig,
64
+ hlineConfig: run.hlineConfig,
65
+ result: run.result,
66
+ warnings: run.warnings
67
+ };
68
+ } catch (err) {
69
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
70
+ }
71
+ }
72
+ function startPreview(options) {
73
+ const file = import_node_path.default.resolve(options.file);
74
+ if (!(0, import_node_fs.existsSync)(file)) return Promise.reject(new Error(`oakscript preview: there is no file ${file}`));
75
+ const bars = options.barsFile ? (0, import_node.readBars)(import_node_path.default.resolve(options.barsFile)) : (0, import_harness.syntheticBars)(500, 86400);
76
+ const lib = localChartLibrary(import_node_path.default.dirname(file)) ?? localChartLibrary(process.cwd());
77
+ const clients = /* @__PURE__ */ new Set();
78
+ let watcher = null;
79
+ let timer = null;
80
+ const handle = (req, res) => {
81
+ const url = new URL(req.url ?? "/", "http://localhost");
82
+ if (url.pathname === "/") {
83
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
84
+ res.end(page(import_node_path.default.basename(file), lib ? "/lightweight-charts.js" : CDN));
85
+ } else if (url.pathname === "/lightweight-charts.js" && lib) {
86
+ res.writeHead(200, { "content-type": "text/javascript" });
87
+ res.end((0, import_node_fs.readFileSync)(lib));
88
+ } else if (url.pathname === "/run") {
89
+ let inputs;
90
+ try {
91
+ inputs = JSON.parse(url.searchParams.get("inputs") ?? "{}");
92
+ } catch {
93
+ inputs = {};
94
+ }
95
+ res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });
96
+ res.end(JSON.stringify({ ...previewRun(file, bars, inputs), bars }));
97
+ } else if (url.pathname === "/events") {
98
+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
99
+ res.write(": connected\n\n");
100
+ clients.add(res);
101
+ req.on("close", () => clients.delete(res));
102
+ } else {
103
+ res.writeHead(404);
104
+ res.end();
105
+ }
106
+ };
107
+ const server = (0, import_node_http.createServer)(handle);
108
+ watcher = (0, import_node_fs.watch)(file, () => {
109
+ if (timer) clearTimeout(timer);
110
+ timer = setTimeout(() => {
111
+ for (const c of clients) c.write("data: changed\n\n");
112
+ }, 100);
113
+ });
114
+ return new Promise((resolve, reject) => {
115
+ server.once("error", reject);
116
+ server.listen(options.port ?? 4173, options.host ?? "0.0.0.0", () => {
117
+ const address = server.address();
118
+ const port = typeof address === "object" && address ? address.port : options.port ?? 4173;
119
+ resolve({
120
+ url: `http://localhost:${port}/`,
121
+ port,
122
+ server,
123
+ close: () => new Promise((done) => {
124
+ watcher?.close();
125
+ if (timer) clearTimeout(timer);
126
+ for (const c of clients) c.end();
127
+ clients.clear();
128
+ server.close(() => done());
129
+ })
130
+ });
131
+ });
132
+ });
133
+ }
134
+ const PREVIEW_USAGE = `Usage: oakscript preview <script.js | indicator.json> [options]
135
+
136
+ Draws the indicator on a chart in the browser and draws it again each time the file is saved. Its settings are a
137
+ form beside the chart; a mistake shows above it.
138
+
139
+ Options:
140
+ --bars <file.csv|json> bars to draw (time, open, high, low, close, volume); default: 500 synthetic daily bars
141
+ --port <n> port (default 4173)
142
+ --host <address> address to listen on (default 0.0.0.0)`;
143
+ async function previewMain(argv, print = (t) => process.stdout.write(t + "\n")) {
144
+ const args = argv[0] === "preview" ? argv.slice(1) : [...argv];
145
+ if (!args.length || args.includes("--help") || args.includes("-h")) {
146
+ print(PREVIEW_USAGE);
147
+ return args.length ? 0 : 1;
148
+ }
149
+ const o = { file: "" };
150
+ for (let k = 0; k < args.length; k++) {
151
+ const a = args[k];
152
+ const next = () => {
153
+ const v = args[++k];
154
+ if (v === void 0) throw new Error(`${a} needs a value`);
155
+ return v;
156
+ };
157
+ if (a === "--bars") o.barsFile = next();
158
+ else if (a === "--port") o.port = Number(next());
159
+ else if (a === "--host") o.host = next();
160
+ else if (a.startsWith("--")) {
161
+ print(`Unknown option ${a}
162
+
163
+ ${PREVIEW_USAGE}`);
164
+ return 1;
165
+ } else o.file = a;
166
+ }
167
+ try {
168
+ const p = await startPreview(o);
169
+ print(`Preview of ${o.file}: ${p.url} (open it in a browser; it updates when the file is saved, Ctrl+C stops)`);
170
+ return 0;
171
+ } catch (err) {
172
+ print(err instanceof Error ? err.message : String(err));
173
+ return 1;
174
+ }
175
+ }
176
+ function page(name, library) {
177
+ return `<!doctype html>
178
+ <html lang="en">
179
+ <head>
180
+ <meta charset="utf-8">
181
+ <meta name="viewport" content="width=device-width, initial-scale=1">
182
+ <title>${escapeHtml(name)} \u2013 preview</title>
183
+ <style>
184
+ body { margin: 0; font: 14px system-ui, sans-serif; background: #131722; color: #d1d4dc; display: flex; height: 100vh; }
185
+ #main { flex: 1; display: flex; flex-direction: column; min-width: 0; }
186
+ #head { padding: 8px 12px; border-bottom: 1px solid #2a2e39; }
187
+ #title { font-weight: 600; }
188
+ #msg { white-space: pre-wrap; font-family: ui-monospace, monospace; padding: 8px 12px; display: none; }
189
+ #msg.error { display: block; background: #4a1c1f; color: #ffb4b4; }
190
+ #msg.warn { display: block; background: #4a3b12; color: #ffe08a; }
191
+ #chart { flex: 1; min-height: 0; }
192
+ #side { width: 260px; border-left: 1px solid #2a2e39; padding: 12px; overflow: auto; }
193
+ #side h3 { margin: 0 0 8px; font-size: 13px; text-transform: uppercase; color: #868993; }
194
+ label { display: block; margin: 0 0 10px; }
195
+ label span { display: block; margin-bottom: 3px; color: #b2b5be; }
196
+ input, select { width: 100%; box-sizing: border-box; background: #1e222d; color: #d1d4dc; border: 1px solid #363a45; border-radius: 4px; padding: 5px; }
197
+ input[type=checkbox] { width: auto; }
198
+ button { background: #2962ff; color: white; border: 0; border-radius: 4px; padding: 6px 10px; cursor: pointer; }
199
+ </style>
200
+ <script src="${library}"></script>
201
+ </head>
202
+ <body>
203
+ <div id="main">
204
+ <div id="head"><span id="title">${escapeHtml(name)}</span> <span id="status"></span></div>
205
+ <div id="msg"></div>
206
+ <div id="chart"></div>
207
+ </div>
208
+ <div id="side"><h3>Settings</h3><form id="form"></form><button id="reset" type="button">Default settings</button></div>
209
+ <script>
210
+ const LWC = window.LightweightCharts;
211
+ const values = {};
212
+ let chart = null;
213
+ const $ = (id) => document.getElementById(id);
214
+ function show(kind, text) { const m = $('msg'); m.className = text ? kind : ''; m.textContent = text || ''; }
215
+ const POS = { aboveBar: 'aboveBar', belowBar: 'belowBar', top: 'aboveBar', bottom: 'belowBar', absolute: 'inBar' };
216
+ const SHAPE = { triangleUp: 'arrowUp', arrowUp: 'arrowUp', labelUp: 'arrowUp', triangleDown: 'arrowDown', arrowDown: 'arrowDown', labelDown: 'arrowDown', square: 'square' };
217
+ function draw(data) {
218
+ if (!LWC) { show('error', 'lightweight-charts could not be loaded: install it (npm install lightweight-charts) or check the network.'); return; }
219
+ if (chart) chart.remove();
220
+ chart = LWC.createChart($('chart'), { autoSize: true, layout: { background: { color: '#131722' }, textColor: '#d1d4dc', panes: { separatorColor: '#2a2e39' } }, grid: { vertLines: { color: '#1e222d' }, horzLines: { color: '#1e222d' } }, timeScale: { timeVisible: false } });
221
+ const barColors = new Map(((data.result && data.result.barColors) || []).map((b) => [b.time, b.color]));
222
+ const candles = chart.addSeries(LWC.CandlestickSeries, { upColor: '#26a69a', downColor: '#ef5350', borderVisible: false, wickUpColor: '#26a69a', wickDownColor: '#ef5350' }, 0);
223
+ candles.setData(data.bars.map((b) => { const c = barColors.get(b.time); return c ? { time: b.time, open: b.open, high: b.high, low: b.low, close: b.close, color: c, wickColor: c } : { time: b.time, open: b.open, high: b.high, low: b.low, close: b.close }; }));
224
+ if (!data.ok) return;
225
+ const pane = data.metadata.overlay ? 0 : 1;
226
+ let first = null;
227
+ for (const p of data.plotConfig) {
228
+ const points = (data.result.plots[p.id] || []);
229
+ const style = p.style || 'line';
230
+ const Kind = style === 'histogram' || style === 'columns' ? LWC.HistogramSeries : style === 'area' ? LWC.AreaSeries : LWC.LineSeries;
231
+ const opts = { color: p.color, lineWidth: p.lineWidth || 1, title: p.title, priceLineVisible: false, lastValueVisible: true };
232
+ // the levels (price lines) count in the scale of the pane
233
+ const levels = (data.hlineConfig || []).map((h) => h.price).filter((x) => Number.isFinite(x));
234
+ if (pane === 1 && levels.length) opts.autoscaleInfoProvider = (original) => {
235
+ const r = original();
236
+ if (!r || !r.priceRange) return r;
237
+ return { ...r, priceRange: { minValue: Math.min(r.priceRange.minValue, ...levels), maxValue: Math.max(r.priceRange.maxValue, ...levels) } };
238
+ };
239
+ if (style === 'circles' || style === 'cross') Object.assign(opts, { lineVisible: false, pointMarkersVisible: true });
240
+ if (style === 'stepline') opts.lineType = 1;
241
+ if (Kind === LWC.AreaSeries) Object.assign(opts, { lineColor: p.color, topColor: p.color + '55', bottomColor: p.color + '05' });
242
+ const s = chart.addSeries(Kind, opts, pane);
243
+ s.setData(points.map((x) => (x.color ? { time: x.time, value: x.value, color: x.color } : { time: x.time, value: x.value })));
244
+ first = first || s;
245
+ }
246
+ const host = pane === 0 ? candles : first;
247
+ if (host) for (const h of data.hlineConfig || []) host.createPriceLine({ price: h.price, color: h.color || '#787b86', lineStyle: h.linestyle === 'solid' ? 0 : h.linestyle === 'dotted' ? 1 : 2, lineWidth: h.linewidth || 1, title: h.title || '' });
248
+ const markers = (data.result.markers || []).map((m) => ({ time: m.time, position: POS[m.position] || 'aboveBar', shape: SHAPE[m.shape] || 'circle', color: m.color || '#2962ff', text: m.text || '' }));
249
+ for (const l of data.result.labels || []) if (l.time !== undefined) markers.push({ time: l.time, position: 'aboveBar', shape: 'circle', color: l.color || '#2962ff', text: l.text || '' });
250
+ if (markers.length && LWC.createSeriesMarkers) LWC.createSeriesMarkers(pane === 0 || !first ? candles : first, markers.sort((a, b) => a.time - b.time));
251
+ const bg = data.result.bgColors || [];
252
+ if (bg.length) {
253
+ const s = chart.addSeries(LWC.HistogramSeries, { priceScaleId: 'bg', priceLineVisible: false, lastValueVisible: false }, pane);
254
+ s.priceScale().applyOptions({ scaleMargins: { top: 0, bottom: 0 }, visible: false });
255
+ s.setData(bg.map((b) => ({ time: b.time, value: 1, color: b.color })));
256
+ }
257
+ if (pane === 1 && chart.panes().length > 1) chart.panes()[1].setHeight(Math.round($('chart').clientHeight * 0.3));
258
+ }
259
+ function form(config) {
260
+ const f = $('form');
261
+ f.innerHTML = '';
262
+ for (const c of config || []) {
263
+ const l = document.createElement('label');
264
+ const t = document.createElement('span');
265
+ t.textContent = c.title || c.id;
266
+ l.appendChild(t);
267
+ let el;
268
+ const value = c.id in values ? values[c.id] : c.defval;
269
+ if (c.options) { el = document.createElement('select'); for (const o of c.options) { const op = document.createElement('option'); op.value = String(o); op.textContent = (c.optionsTitles && c.optionsTitles[o]) || String(o); el.appendChild(op); } el.value = String(value); }
270
+ else if (c.type === 'bool') { el = document.createElement('input'); el.type = 'checkbox'; el.checked = Boolean(value); }
271
+ else if (c.type === 'color') { el = document.createElement('input'); el.type = 'color'; el.value = String(value).slice(0, 7); }
272
+ else { el = document.createElement('input'); el.type = ['int', 'float', 'price'].includes(c.type) ? 'number' : 'text'; if (c.min !== undefined) el.min = c.min; if (c.max !== undefined) el.max = c.max; if (c.step !== undefined) el.step = c.step; el.value = String(value); }
273
+ el.onchange = () => {
274
+ let v = el.type === 'checkbox' ? el.checked : el.value;
275
+ if (['int', 'float', 'price'].includes(c.type)) v = Number(v);
276
+ if (c.options && typeof c.defval === 'number') v = Number(v);
277
+ values[c.id] = v;
278
+ load();
279
+ };
280
+ l.appendChild(el);
281
+ f.appendChild(l);
282
+ }
283
+ }
284
+ async function load() {
285
+ $('status').textContent = '\u2026';
286
+ const r = await fetch('/run?inputs=' + encodeURIComponent(JSON.stringify(values)));
287
+ const data = await r.json();
288
+ $('status').textContent = data.ok ? '' : '(error)';
289
+ if (data.ok) { $('title').textContent = data.metadata.title; form(data.inputConfig); show(data.warnings.length ? 'warn' : '', data.warnings.join('\\n')); }
290
+ else show('error', data.error);
291
+ draw(data);
292
+ }
293
+ $('reset').onclick = () => { for (const k of Object.keys(values)) delete values[k]; load(); };
294
+ new EventSource('/events').onmessage = () => load();
295
+ load();
296
+ </script>
297
+ </body>
298
+ </html>`;
299
+ }
300
+ function escapeHtml(s) {
301
+ return s.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
302
+ }
303
+ //# sourceMappingURL=preview.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/check/preview.ts"],
4
+ "sourcesContent": ["/**\n * `oakscript preview <file>`: a chart of a script (`.js`, the format of `oakscript check`) or of an indicator in JSON\n * (`.json`, see `defineIndicatorFromJson`) in the browser, drawn again each time the file is saved. The settings of the\n * indicator are a form beside the chart; a mistake shows as a message above it. Node.js only, no dependency: the page\n * loads lightweight-charts from the project's node_modules when it is installed, else from a CDN.\n */\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';\nimport { existsSync, readFileSync, watch, type FSWatcher } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport type { Bar } from '../types/index.js';\nimport { executeScript, indicatorBodyFromJson } from '../script/index.js';\nimport { compileScript, syntheticBars, testChart } from './harness.js';\nimport { readBars } from './node.js';\n\nexport interface PreviewOptions {\n /** The script (.js) or the indicator in JSON (.json). */\n file: string;\n /** Bars to draw (CSV or JSON file); default: 500 synthetic daily bars. */\n barsFile?: string;\n /** Port (default 4173; 0: any free port). */\n port?: number;\n /** Host to listen on (default 0.0.0.0: the page opens from another computer of the network too). */\n host?: string;\n}\n\nexport interface PreviewServer {\n url: string;\n port: number;\n server: Server;\n close(): Promise<void>;\n}\n\nconst CDN = 'https://unpkg.com/lightweight-charts@5/dist/lightweight-charts.standalone.production.js';\n\n/** The standalone build of lightweight-charts in the project of `from`, when it is installed. */\nfunction localChartLibrary(from: string): string | null {\n try {\n const require = createRequire(path.resolve(from, 'package.json'));\n const pkg = require.resolve('lightweight-charts/package.json');\n const file = path.join(path.dirname(pkg), 'dist', 'lightweight-charts.standalone.production.js');\n return existsSync(file) ? file : null;\n } catch {\n return null;\n }\n}\n\n/** One run of the file on the bars: what the page draws, or the error. */\nexport function previewRun(file: string, bars: Bar[], inputs: Record<string, unknown> = {}): Record<string, unknown> {\n try {\n const source = readFileSync(file, 'utf8');\n const body = file.toLowerCase().endsWith('.json') ? indicatorBodyFromJson(source) : compileScript(source);\n const run = executeScript(body, bars, inputs, testChart(bars), { strict: true, palette: true });\n return {\n ok: true,\n metadata: run.metadata,\n inputConfig: run.inputConfig,\n plotConfig: run.plotConfig,\n hlineConfig: run.hlineConfig,\n result: run.result,\n warnings: run.warnings,\n };\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n}\n\n/** Starts the preview server; `close()` stops it and the file watch. */\nexport function startPreview(options: PreviewOptions): Promise<PreviewServer> {\n const file = path.resolve(options.file);\n if (!existsSync(file)) return Promise.reject(new Error(`oakscript preview: there is no file ${file}`));\n const bars = options.barsFile ? readBars(path.resolve(options.barsFile)) : syntheticBars(500, 86400);\n const lib = localChartLibrary(path.dirname(file)) ?? localChartLibrary(process.cwd());\n const clients = new Set<ServerResponse>();\n let watcher: FSWatcher | null = null;\n let timer: ReturnType<typeof setTimeout> | null = null;\n\n const handle = (req: IncomingMessage, res: ServerResponse): void => {\n const url = new URL(req.url ?? '/', 'http://localhost');\n if (url.pathname === '/') {\n res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' });\n res.end(page(path.basename(file), lib ? '/lightweight-charts.js' : CDN));\n } else if (url.pathname === '/lightweight-charts.js' && lib) {\n res.writeHead(200, { 'content-type': 'text/javascript' });\n res.end(readFileSync(lib));\n } else if (url.pathname === '/run') {\n let inputs: Record<string, unknown>;\n try {\n inputs = JSON.parse(url.searchParams.get('inputs') ?? '{}') as Record<string, unknown>;\n } catch {\n inputs = {};\n }\n res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' });\n res.end(JSON.stringify({ ...previewRun(file, bars, inputs), bars }));\n } else if (url.pathname === '/events') {\n res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' });\n res.write(': connected\\n\\n');\n clients.add(res);\n req.on('close', () => clients.delete(res));\n } else {\n res.writeHead(404);\n res.end();\n }\n };\n\n const server = createServer(handle);\n watcher = watch(file, () => {\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => {\n for (const c of clients) c.write('data: changed\\n\\n');\n }, 100);\n });\n\n return new Promise((resolve, reject) => {\n server.once('error', reject);\n server.listen(options.port ?? 4173, options.host ?? '0.0.0.0', () => {\n const address = server.address();\n const port = typeof address === 'object' && address ? address.port : options.port ?? 4173;\n resolve({\n url: `http://localhost:${port}/`,\n port,\n server,\n close: () =>\n new Promise<void>((done) => {\n watcher?.close();\n if (timer) clearTimeout(timer);\n for (const c of clients) c.end();\n clients.clear();\n server.close(() => done());\n }),\n });\n });\n });\n}\n\nconst PREVIEW_USAGE = `Usage: oakscript preview <script.js | indicator.json> [options]\n\nDraws the indicator on a chart in the browser and draws it again each time the file is saved. Its settings are a\nform beside the chart; a mistake shows above it.\n\nOptions:\n --bars <file.csv|json> bars to draw (time, open, high, low, close, volume); default: 500 synthetic daily bars\n --port <n> port (default 4173)\n --host <address> address to listen on (default 0.0.0.0)`;\n\n/** `oakscript preview` of the command line: starts the server and prints its address. */\nexport async function previewMain(argv: string[], print: (text: string) => void = (t) => process.stdout.write(t + '\\n')): Promise<number> {\n const args = argv[0] === 'preview' ? argv.slice(1) : [...argv];\n if (!args.length || args.includes('--help') || args.includes('-h')) {\n print(PREVIEW_USAGE);\n return args.length ? 0 : 1;\n }\n const o: PreviewOptions = { file: '' };\n for (let k = 0; k < args.length; k++) {\n const a = args[k]!;\n const next = (): string => {\n const v = args[++k];\n if (v === undefined) throw new Error(`${a} needs a value`);\n return v;\n };\n if (a === '--bars') o.barsFile = next();\n else if (a === '--port') o.port = Number(next());\n else if (a === '--host') o.host = next();\n else if (a.startsWith('--')) {\n print(`Unknown option ${a}\\n\\n${PREVIEW_USAGE}`);\n return 1;\n } else o.file = a;\n }\n try {\n const p = await startPreview(o);\n print(`Preview of ${o.file}: ${p.url} (open it in a browser; it updates when the file is saved, Ctrl+C stops)`);\n return 0;\n } catch (err) {\n print(err instanceof Error ? err.message : String(err));\n return 1;\n }\n}\n\n/** The page: the chart, the settings form, the messages; it asks /run again on each change of the file. */\nfunction page(name: string, library: string): string {\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>${escapeHtml(name)} \u2013 preview</title>\n<style>\n body { margin: 0; font: 14px system-ui, sans-serif; background: #131722; color: #d1d4dc; display: flex; height: 100vh; }\n #main { flex: 1; display: flex; flex-direction: column; min-width: 0; }\n #head { padding: 8px 12px; border-bottom: 1px solid #2a2e39; }\n #title { font-weight: 600; }\n #msg { white-space: pre-wrap; font-family: ui-monospace, monospace; padding: 8px 12px; display: none; }\n #msg.error { display: block; background: #4a1c1f; color: #ffb4b4; }\n #msg.warn { display: block; background: #4a3b12; color: #ffe08a; }\n #chart { flex: 1; min-height: 0; }\n #side { width: 260px; border-left: 1px solid #2a2e39; padding: 12px; overflow: auto; }\n #side h3 { margin: 0 0 8px; font-size: 13px; text-transform: uppercase; color: #868993; }\n label { display: block; margin: 0 0 10px; }\n label span { display: block; margin-bottom: 3px; color: #b2b5be; }\n input, select { width: 100%; box-sizing: border-box; background: #1e222d; color: #d1d4dc; border: 1px solid #363a45; border-radius: 4px; padding: 5px; }\n input[type=checkbox] { width: auto; }\n button { background: #2962ff; color: white; border: 0; border-radius: 4px; padding: 6px 10px; cursor: pointer; }\n</style>\n<script src=\"${library}\"></script>\n</head>\n<body>\n<div id=\"main\">\n <div id=\"head\"><span id=\"title\">${escapeHtml(name)}</span> <span id=\"status\"></span></div>\n <div id=\"msg\"></div>\n <div id=\"chart\"></div>\n</div>\n<div id=\"side\"><h3>Settings</h3><form id=\"form\"></form><button id=\"reset\" type=\"button\">Default settings</button></div>\n<script>\nconst LWC = window.LightweightCharts;\nconst values = {};\nlet chart = null;\nconst $ = (id) => document.getElementById(id);\nfunction show(kind, text) { const m = $('msg'); m.className = text ? kind : ''; m.textContent = text || ''; }\nconst POS = { aboveBar: 'aboveBar', belowBar: 'belowBar', top: 'aboveBar', bottom: 'belowBar', absolute: 'inBar' };\nconst SHAPE = { triangleUp: 'arrowUp', arrowUp: 'arrowUp', labelUp: 'arrowUp', triangleDown: 'arrowDown', arrowDown: 'arrowDown', labelDown: 'arrowDown', square: 'square' };\nfunction draw(data) {\n if (!LWC) { show('error', 'lightweight-charts could not be loaded: install it (npm install lightweight-charts) or check the network.'); return; }\n if (chart) chart.remove();\n chart = LWC.createChart($('chart'), { autoSize: true, layout: { background: { color: '#131722' }, textColor: '#d1d4dc', panes: { separatorColor: '#2a2e39' } }, grid: { vertLines: { color: '#1e222d' }, horzLines: { color: '#1e222d' } }, timeScale: { timeVisible: false } });\n const barColors = new Map(((data.result && data.result.barColors) || []).map((b) => [b.time, b.color]));\n const candles = chart.addSeries(LWC.CandlestickSeries, { upColor: '#26a69a', downColor: '#ef5350', borderVisible: false, wickUpColor: '#26a69a', wickDownColor: '#ef5350' }, 0);\n candles.setData(data.bars.map((b) => { const c = barColors.get(b.time); return c ? { time: b.time, open: b.open, high: b.high, low: b.low, close: b.close, color: c, wickColor: c } : { time: b.time, open: b.open, high: b.high, low: b.low, close: b.close }; }));\n if (!data.ok) return;\n const pane = data.metadata.overlay ? 0 : 1;\n let first = null;\n for (const p of data.plotConfig) {\n const points = (data.result.plots[p.id] || []);\n const style = p.style || 'line';\n const Kind = style === 'histogram' || style === 'columns' ? LWC.HistogramSeries : style === 'area' ? LWC.AreaSeries : LWC.LineSeries;\n const opts = { color: p.color, lineWidth: p.lineWidth || 1, title: p.title, priceLineVisible: false, lastValueVisible: true };\n // the levels (price lines) count in the scale of the pane\n const levels = (data.hlineConfig || []).map((h) => h.price).filter((x) => Number.isFinite(x));\n if (pane === 1 && levels.length) opts.autoscaleInfoProvider = (original) => {\n const r = original();\n if (!r || !r.priceRange) return r;\n return { ...r, priceRange: { minValue: Math.min(r.priceRange.minValue, ...levels), maxValue: Math.max(r.priceRange.maxValue, ...levels) } };\n };\n if (style === 'circles' || style === 'cross') Object.assign(opts, { lineVisible: false, pointMarkersVisible: true });\n if (style === 'stepline') opts.lineType = 1;\n if (Kind === LWC.AreaSeries) Object.assign(opts, { lineColor: p.color, topColor: p.color + '55', bottomColor: p.color + '05' });\n const s = chart.addSeries(Kind, opts, pane);\n s.setData(points.map((x) => (x.color ? { time: x.time, value: x.value, color: x.color } : { time: x.time, value: x.value })));\n first = first || s;\n }\n const host = pane === 0 ? candles : first;\n if (host) for (const h of data.hlineConfig || []) host.createPriceLine({ price: h.price, color: h.color || '#787b86', lineStyle: h.linestyle === 'solid' ? 0 : h.linestyle === 'dotted' ? 1 : 2, lineWidth: h.linewidth || 1, title: h.title || '' });\n const markers = (data.result.markers || []).map((m) => ({ time: m.time, position: POS[m.position] || 'aboveBar', shape: SHAPE[m.shape] || 'circle', color: m.color || '#2962ff', text: m.text || '' }));\n for (const l of data.result.labels || []) if (l.time !== undefined) markers.push({ time: l.time, position: 'aboveBar', shape: 'circle', color: l.color || '#2962ff', text: l.text || '' });\n if (markers.length && LWC.createSeriesMarkers) LWC.createSeriesMarkers(pane === 0 || !first ? candles : first, markers.sort((a, b) => a.time - b.time));\n const bg = data.result.bgColors || [];\n if (bg.length) {\n const s = chart.addSeries(LWC.HistogramSeries, { priceScaleId: 'bg', priceLineVisible: false, lastValueVisible: false }, pane);\n s.priceScale().applyOptions({ scaleMargins: { top: 0, bottom: 0 }, visible: false });\n s.setData(bg.map((b) => ({ time: b.time, value: 1, color: b.color })));\n }\n if (pane === 1 && chart.panes().length > 1) chart.panes()[1].setHeight(Math.round($('chart').clientHeight * 0.3));\n}\nfunction form(config) {\n const f = $('form');\n f.innerHTML = '';\n for (const c of config || []) {\n const l = document.createElement('label');\n const t = document.createElement('span');\n t.textContent = c.title || c.id;\n l.appendChild(t);\n let el;\n const value = c.id in values ? values[c.id] : c.defval;\n if (c.options) { el = document.createElement('select'); for (const o of c.options) { const op = document.createElement('option'); op.value = String(o); op.textContent = (c.optionsTitles && c.optionsTitles[o]) || String(o); el.appendChild(op); } el.value = String(value); }\n else if (c.type === 'bool') { el = document.createElement('input'); el.type = 'checkbox'; el.checked = Boolean(value); }\n else if (c.type === 'color') { el = document.createElement('input'); el.type = 'color'; el.value = String(value).slice(0, 7); }\n else { el = document.createElement('input'); el.type = ['int', 'float', 'price'].includes(c.type) ? 'number' : 'text'; if (c.min !== undefined) el.min = c.min; if (c.max !== undefined) el.max = c.max; if (c.step !== undefined) el.step = c.step; el.value = String(value); }\n el.onchange = () => {\n let v = el.type === 'checkbox' ? el.checked : el.value;\n if (['int', 'float', 'price'].includes(c.type)) v = Number(v);\n if (c.options && typeof c.defval === 'number') v = Number(v);\n values[c.id] = v;\n load();\n };\n l.appendChild(el);\n f.appendChild(l);\n }\n}\nasync function load() {\n $('status').textContent = '\u2026';\n const r = await fetch('/run?inputs=' + encodeURIComponent(JSON.stringify(values)));\n const data = await r.json();\n $('status').textContent = data.ok ? '' : '(error)';\n if (data.ok) { $('title').textContent = data.metadata.title; form(data.inputConfig); show(data.warnings.length ? 'warn' : '', data.warnings.join('\\\\n')); }\n else show('error', data.error);\n draw(data);\n}\n$('reset').onclick = () => { for (const k of Object.keys(values)) delete values[k]; load(); };\nnew EventSource('/events').onmessage = () => load();\nload();\n</script>\n</body>\n</html>`;\n}\n\nfunction escapeHtml(s: string): string {\n return s.replace(/[&<>\"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;' })[c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AAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA+FpD;AAEA,SAAS,WAAW,GAAmB;AACrC,SAAO,EAAE,QAAQ,WAAW,CAAC,OAAO,EAAE,KAAK,SAAS,KAAK,QAAQ,KAAK,QAAQ,KAAK,SAAS,GAAG,CAAC,CAAE;AACpG;",
6
+ "names": ["require", "path"]
7
+ }
@@ -31,7 +31,7 @@ import type { color, int, float, simple_int, simple_float } from '../types/index
31
31
  * transparent
32
32
  *
33
33
  * @example
34
- * ```typescript
34
+ * ```js
35
35
  * color.rgb(255, 0, 0) // Returns: "rgb(255, 0, 0)" - Red
36
36
  * color.rgb(0, 255, 0, 50) // Returns: "rgba(0, 255, 0, 0.5)" - Semi-transparent green
37
37
  * color.rgb(300, 0, 0) // Returns: "rgb(255, 0, 0)" - Clamped to 255
@@ -52,7 +52,7 @@ export declare function rgb(red: simple_int, green: simple_int, blue: simple_int
52
52
  * - Format: RRGGBB where each component is 00-FF
53
53
  *
54
54
  * @example
55
- * ```typescript
55
+ * ```js
56
56
  * color.from_hex("#FF0000") // Returns: "rgb(255, 0, 0)" - Red
57
57
  * color.from_hex("00FF00", 50) // Returns: "rgba(0, 255, 0, 0.5)" - Semi-transparent green
58
58
  * color.from_hex("#0000FF") // Returns: "rgb(0, 0, 255)" - Blue
@@ -78,7 +78,7 @@ export declare function from_hex(hex: string, transp?: simple_float): string;
78
78
  * `color.new(color(na), 30)` is computed at compile time and stays na; a JS function cannot tell the two apart.
79
79
  *
80
80
  * @example
81
- * ```typescript
81
+ * ```js
82
82
  * const red = color.rgb(255, 0, 0)
83
83
  * color.new_color(red, 50) // Returns: "rgba(255, 0, 0, 0.5)" - Semi-transparent red
84
84
  * color.new_color(red, 0) // Returns: "rgb(255, 0, 0)" - Fully opaque
@@ -93,7 +93,7 @@ export declare function new_color(baseColor: color | null | undefined, transp: s
93
93
  * @returns Red component value (0-255)
94
94
  *
95
95
  * @example
96
- * ```typescript
96
+ * ```js
97
97
  * color.r(color.rgb(255, 128, 64)) // Returns: 255
98
98
  * color.r(color.from_hex("#FF0000")) // Returns: 255
99
99
  * color.r(color.from_hex("#FFA500")) // Returns: 255 (orange)
@@ -107,7 +107,7 @@ export declare function r(clr: color): int;
107
107
  * @returns Green component value (0-255)
108
108
  *
109
109
  * @example
110
- * ```typescript
110
+ * ```js
111
111
  * color.g(color.rgb(255, 128, 64)) // Returns: 128
112
112
  * color.g(color.from_hex("#00FF00")) // Returns: 255
113
113
  * color.g(color.from_hex("#FFA500")) // Returns: 165 (orange)
@@ -121,7 +121,7 @@ export declare function g(clr: color): int;
121
121
  * @returns Blue component value (0-255)
122
122
  *
123
123
  * @example
124
- * ```typescript
124
+ * ```js
125
125
  * color.b(color.rgb(255, 128, 64)) // Returns: 64
126
126
  * color.b(color.from_hex("#0000FF")) // Returns: 255
127
127
  * color.b(color.from_hex("#FFA500")) // Returns: 0 (orange)
@@ -142,7 +142,7 @@ export declare function b(clr: color): int;
142
142
  * - an `na` colour (null / undefined) is fully transparent: 100
143
143
  *
144
144
  * @example
145
- * ```typescript
145
+ * ```js
146
146
  * color.t(color.rgb(255, 0, 0)) // Returns: 0 (opaque)
147
147
  * color.t(color.rgb(255, 0, 0, 50)) // Returns: 50
148
148
  * color.t(color.rgb(255, 0, 0, 100)) // Returns: 100 (fully transparent)
@@ -256,7 +256,7 @@ export declare const yellow = "#FDD835";
256
256
  * - Works with rgb(), rgba() and hex (#RRGGBB, #RRGGBBAA) colours
257
257
  *
258
258
  * @example
259
- * ```typescript
259
+ * ```js
260
260
  * // Value at middle of range gets middle color
261
261
  * const midColor = color.from_gradient(50, 0, 100,
262
262
  * color.rgb(255, 0, 0), // Red at bottom
@@ -264,8 +264,8 @@ export declare const yellow = "#FDD835";
264
264
  * ); // Returns color between red and green
265
265
  *
266
266
  * // Value at extremes
267
- * const lowColor = color.from_gradient(-10, 0, 100, red, green); // Returns red
268
- * const highColor = color.from_gradient(150, 0, 100, red, green); // Returns green
267
+ * const lowColor = color.from_gradient(-10, 0, 100, color.red, color.green); // red: at or below the bottom
268
+ * const highColor = color.from_gradient(150, 0, 100, color.red, color.green); // green: at or above the top
269
269
  * ```
270
270
  */
271
271
  export declare function from_gradient(value: float, bottom_value: float, top_value: float, bottom_color: color, top_color: color): string;
@@ -281,7 +281,7 @@ export declare function from_gradient(value: float, bottom_value: float, top_val
281
281
  * This is an alias for `new_color()` to match PineScript's `color.new()` syntax.
282
282
  *
283
283
  * @example
284
- * ```typescript
284
+ * ```js
285
285
  * const redColor = color.rgb(255, 0, 0);
286
286
  * const transparentRed = color.new(redColor, 50); // 50% transparent red
287
287
  * ```
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/color/index.ts"],
4
- "sourcesContent": ["/**\n * Color namespace\n * Mirrors PineScript's color.* functions for color creation and manipulation.\n *\n * @remarks\n * All color functions in this namespace follow PineScript v6 API specifications.\n * Colors are represented as RGB or RGBA strings.\n * Transparency values range from 0 (fully opaque) to 100 (fully transparent).\n *\n * @version 6\n */\n\nimport type { color, int, float, simple_int, simple_float } from '../types/index.js';\nimport { alphaByte, parseColor } from './parse.js';\n\n/** Channel of color.rgb: na is 0, a fraction is truncated. */\nconst channel = (v: number): int =>\n v === null || v === undefined || Number.isNaN(v) ? 0 : Math.max(0, Math.min(255, Math.trunc(v)));\n\n/**\n * Alpha (0-1) of a transparency given to color.rgb / color.new: na is fully transparent, clamped to 0..100.\n * `1 - t / 100` as in PineScript: `color.new(c, 90)` has the alpha byte 25 (0.09999999999999998 * 255 rounded).\n */\nconst alphaOf = (transp: number): float =>\n transp === null || Number.isNaN(transp) ? 0 : 1 - Math.max(0, Math.min(100, transp)) / 100;\n\n/**\n * Creates a color from RGB values with optional transparency.\n *\n * @param red - Red component (0-255, values are clamped)\n * @param green - Green component (0-255, values are clamped)\n * @param blue - Blue component (0-255, values are clamped)\n * @param transp - Optional transparency (0-100). 0 = opaque, 100 = fully transparent\n * @returns Color string in rgb() or rgba() format\n *\n * @remarks\n * - RGB values are automatically clamped to the 0-255 range\n * - Transparency of 0 or omitted results in rgb() format\n * - Transparency > 0 results in rgba() format\n * - Transparency is converted to alpha channel (0-1 range)\n *\n * PineScript rules:\n * - an `na` channel is 0; a fractional channel is truncated (127.6 is 127)\n * - the transparency is clamped to 0..100 (140 is fully transparent, -5 is opaque); an `na` transparency is fully\n * transparent\n *\n * @example\n * ```typescript\n * color.rgb(255, 0, 0) // Returns: \"rgb(255, 0, 0)\" - Red\n * color.rgb(0, 255, 0, 50) // Returns: \"rgba(0, 255, 0, 0.5)\" - Semi-transparent green\n * color.rgb(300, 0, 0) // Returns: \"rgb(255, 0, 0)\" - Clamped to 255\n * ```\n */\nexport function rgb(red: simple_int, green: simple_int, blue: simple_int, transp?: simple_float): string {\n const r = channel(red);\n const g = channel(green);\n const b = channel(blue);\n const a = transp !== undefined ? alphaOf(transp) : 1;\n\n if (a === 1) {\n return `rgb(${r}, ${g}, ${b})`;\n }\n return `rgba(${r}, ${g}, ${b}, ${a})`;\n}\n\n/**\n * Creates a color from a hexadecimal string with optional transparency.\n *\n * @param hex - Hex color string (with or without '#' prefix, e.g., \"#FF0000\" or \"FF0000\")\n * @param transp - Optional transparency (0-100). 0 = opaque, 100 = fully transparent\n * @returns Color string in rgb() or rgba() format\n *\n * @remarks\n * - Accepts hex strings with or without '#' prefix\n * - Case-insensitive (accepts both \"FF0000\" and \"ff0000\")\n * - Must be 6 characters (excluding '#')\n * - Format: RRGGBB where each component is 00-FF\n *\n * @example\n * ```typescript\n * color.from_hex(\"#FF0000\") // Returns: \"rgb(255, 0, 0)\" - Red\n * color.from_hex(\"00FF00\", 50) // Returns: \"rgba(0, 255, 0, 0.5)\" - Semi-transparent green\n * color.from_hex(\"#0000FF\") // Returns: \"rgb(0, 0, 255)\" - Blue\n * color.from_hex(\"FFA500\") // Returns: \"rgb(255, 165, 0)\" - Orange\n * ```\n */\nexport function from_hex(hex: string, transp?: simple_float): string {\n // Remove # if present\n hex = hex.replace('#', '');\n\n const r = parseInt(hex.substring(0, 2), 16);\n const g = parseInt(hex.substring(2, 4), 16);\n const b = parseInt(hex.substring(4, 6), 16);\n\n return rgb(r, g, b, transp);\n}\n\n/**\n * Creates a new color with modified transparency, preserving RGB components.\n *\n * @param baseColor - The base color to modify\n * @param transp - New transparency value (0-100). 0 = opaque, 100 = fully transparent\n * @returns New color with updated transparency\n *\n * @remarks\n * - Preserves the RGB values from the base color\n * - Replaces the transparency with the new value\n * - Useful for creating semi-transparent versions of existing colors\n * - PineScript clamps the transparency to 0..100 (`color.new(c, 140)` is fully transparent, `color.new(c, -5)` is\n * opaque); an `na` transparency is fully transparent (measured: the colour is not na, its RGB is kept)\n * - an `na` colour (null / undefined) gives black with the new transparency: `color.new(na, 30)` is\n * `rgba(0, 0, 0, 0.7)`, as PineScript does for an na colour variable (measured, #150). In PineScript, the constant\n * `color.new(color(na), 30)` is computed at compile time and stays na; a JS function cannot tell the two apart.\n *\n * @example\n * ```typescript\n * const red = color.rgb(255, 0, 0)\n * color.new_color(red, 50) // Returns: \"rgba(255, 0, 0, 0.5)\" - Semi-transparent red\n * color.new_color(red, 0) // Returns: \"rgb(255, 0, 0)\" - Fully opaque\n * color.new_color(red, 100) // Returns: \"rgba(255, 0, 0, 0)\" - Fully transparent\n * ```\n */\nexport function new_color(baseColor: color | null | undefined, transp: simple_float): string {\n if (baseColor === null || baseColor === undefined) return rgb(0, 0, 0, transp); // na colour: black\n if (typeof baseColor !== 'string') {\n const rgba = parseColor(baseColor);\n return rgb(rgba.r, rgba.g, rgba.b, transp);\n }\n // The same colour with the same transparency on every bar and every run: the text is made once.\n let byTransp = newColors.get(baseColor);\n if (byTransp === undefined) {\n if (newColors.size >= NEW_COLORS_KEPT) newColors.clear();\n newColors.set(baseColor, (byTransp = new Map()));\n }\n let text = byTransp.get(transp);\n if (text === undefined) {\n const rgba = parseColor(baseColor);\n text = rgb(rgba.r, rgba.g, rgba.b, transp);\n if (byTransp.size >= NEW_COLORS_KEPT) byTransp.clear();\n byTransp.set(transp, text);\n }\n return text;\n}\n\n/** color.new results by base colour, then transparency. */\nconst newColors = new Map<string, Map<number, string>>();\nconst NEW_COLORS_KEPT = 1024;\n\n/**\n * Extracts the red component from a color.\n *\n * @param clr - The color to extract from\n * @returns Red component value (0-255)\n *\n * @example\n * ```typescript\n * color.r(color.rgb(255, 128, 64)) // Returns: 255\n * color.r(color.from_hex(\"#FF0000\")) // Returns: 255\n * color.r(color.from_hex(\"#FFA500\")) // Returns: 255 (orange)\n * ```\n */\nexport function r(clr: color): int {\n return parseColor(clr).r;\n}\n\n/**\n * Extracts the green component from a color.\n *\n * @param clr - The color to extract from\n * @returns Green component value (0-255)\n *\n * @example\n * ```typescript\n * color.g(color.rgb(255, 128, 64)) // Returns: 128\n * color.g(color.from_hex(\"#00FF00\")) // Returns: 255\n * color.g(color.from_hex(\"#FFA500\")) // Returns: 165 (orange)\n * ```\n */\nexport function g(clr: color): int {\n return parseColor(clr).g;\n}\n\n/**\n * Extracts the blue component from a color.\n *\n * @param clr - The color to extract from\n * @returns Blue component value (0-255)\n *\n * @example\n * ```typescript\n * color.b(color.rgb(255, 128, 64)) // Returns: 64\n * color.b(color.from_hex(\"#0000FF\")) // Returns: 255\n * color.b(color.from_hex(\"#FFA500\")) // Returns: 0 (orange)\n * ```\n */\nexport function b(clr: color): int {\n return parseColor(clr).b;\n}\n\n/**\n * Extracts the transparency component from a color.\n *\n * @param clr - The color to extract from\n * @returns Transparency value (0-100). 0 = fully opaque, 100 = fully transparent\n *\n * @remarks\n * - Returns 0 for colors without transparency (rgb format)\n * - Converts alpha channel (0-1) to transparency (0-100)\n * - PineScript stores the alpha as a byte (0-255) and returns an integer transparency:\n * `color.t(color.new(c, 33.3))` is 33\n * - an `na` colour (null / undefined) is fully transparent: 100\n *\n * @example\n * ```typescript\n * color.t(color.rgb(255, 0, 0)) // Returns: 0 (opaque)\n * color.t(color.rgb(255, 0, 0, 50)) // Returns: 50\n * color.t(color.rgb(255, 0, 0, 100)) // Returns: 100 (fully transparent)\n * ```\n */\nexport function t(clr: color | null | undefined): float {\n if (clr === null || clr === undefined) return 100;\n return Math.round((1 - alphaByte(parseColor(clr).a) / 255) * 100);\n}\n\n// Predefined color constants of PineScript v6.\n// PineScript v5 differs for red (#FF5252), teal (#00897B) and yellow (#FFEB3B).\n/**\n * Aqua/Cyan color constant\n * @constant {string} #00BCD4 - RGB(0, 188, 212)\n */\nexport const aqua = '#00BCD4';\n\n/**\n * Black color constant\n * @constant {string} #363A45 - RGB(54, 58, 69)\n */\nexport const black = '#363A45';\n\n/**\n * Blue color constant\n * @constant {string} #2962FF - RGB(41, 98, 255)\n */\nexport const blue = '#2962FF';\n\n/**\n * Fuchsia/Magenta color constant\n * @constant {string} #E040FB - RGB(224, 64, 251)\n */\nexport const fuchsia = '#E040FB';\n\n/**\n * Gray color constant\n * @constant {string} #787B86 - RGB(120, 123, 134)\n */\nexport const gray = '#787B86';\n\n/**\n * Green color constant (same as lime)\n * @constant {string} #4CAF50 - RGB(76, 175, 80)\n */\nexport const green = '#4CAF50';\n\n/**\n * Lime color constant (same as green)\n * @constant {string} #00E676 - RGB(0, 230, 118)\n */\nexport const lime = '#00E676';\n\n/**\n * Maroon color constant\n * @constant {string} #880E4F - RGB(136, 14, 79)\n */\nexport const maroon = '#880E4F';\n\n/**\n * Navy color constant\n * @constant {string} #311B92 - RGB(49, 27, 146)\n */\nexport const navy = '#311B92';\n\n/**\n * Olive color constant\n * @constant {string} #808000 - RGB(128, 128, 0)\n */\nexport const olive = '#808000';\n\n/**\n * Orange color constant\n * @constant {string} #FF9800 - RGB(255, 152, 0)\n */\nexport const orange = '#FF9800';\n\n/**\n * Purple color constant\n * @constant {string} #9C27B0 - RGB(156, 39, 176)\n */\nexport const purple = '#9C27B0';\n\n/**\n * Red color constant\n * @constant {string} #F23645 - RGB(242, 54, 69)\n */\nexport const red = '#F23645';\n\n/**\n * Silver color constant\n * @constant {string} #B2B5BE - RGB(178, 181, 190)\n */\nexport const silver = '#B2B5BE';\n\n/**\n * Teal color constant\n * @constant {string} #089981 - RGB(8, 153, 129)\n */\nexport const teal = '#089981';\n\n/**\n * White color constant\n * @constant {string} #FFFFFF - RGB(255, 255, 255)\n */\nexport const white = '#FFFFFF';\n\n/**\n * Yellow color constant\n * @constant {string} #FDD835 - RGB(253, 216, 53)\n */\nexport const yellow = '#FDD835';\n\n/**\n * Creates a color from a gradient based on value position.\n *\n * @param value - Value to calculate position-dependent color\n * @param bottom_value - Bottom position value corresponding to bottom_color\n * @param top_value - Top position value corresponding to top_color\n * @param bottom_color - Bottom position color\n * @param top_color - Top position color\n * @returns Color calculated from linear gradient\n *\n * @remarks\n * PineScript rules:\n * - If value <= bottom_value, returns bottom_color; else if value >= top_value, returns top_color\n * - An inverted range (bottom_value > top_value) returns bottom_color, wherever the value is\n * - Otherwise the colours are mixed with their transparency (premultiplied alpha, alpha as a byte); the RGB channels\n * and the alpha are truncated. PineScript's float rounding order is not known: a channel can differ by 1 when the\n * exact result is an integer (same RGB at both ends)\n * - An na value or bottom_value / top_value, or bottom_value == top_value, gives a fully transparent colour\n * - An na colour counts as fully transparent\n * - Works with rgb(), rgba() and hex (#RRGGBB, #RRGGBBAA) colours\n *\n * @example\n * ```typescript\n * // Value at middle of range gets middle color\n * const midColor = color.from_gradient(50, 0, 100,\n * color.rgb(255, 0, 0), // Red at bottom\n * color.rgb(0, 255, 0) // Green at top\n * ); // Returns color between red and green\n *\n * // Value at extremes\n * const lowColor = color.from_gradient(-10, 0, 100, red, green); // Returns red\n * const highColor = color.from_gradient(150, 0, 100, red, green); // Returns green\n * ```\n */\nexport function from_gradient(\n value: float,\n bottom_value: float,\n top_value: float,\n bottom_color: color,\n top_color: color\n): string {\n const transparent = 'rgba(0, 0, 0, 0)';\n if ([value, bottom_value, top_value].some((v) => v === null || v === undefined || Number.isNaN(v)) || bottom_value === top_value) {\n return transparent;\n }\n const k =\n value <= bottom_value || bottom_value > top_value\n ? 0\n : value >= top_value\n ? 1\n : (value - bottom_value) / (top_value - bottom_value);\n // alpha as a byte (0-255), as PineScript stores it; an na colour (null / undefined, or 'transparent', the\n // library's form of na) is fully transparent\n const rgba = (c: color) => {\n if (c === null || c === undefined || (typeof c === 'string' && c.trim().toLowerCase() === 'transparent')) return { r: 0, g: 0, b: 0, a: 0 };\n const p = parseColor(c);\n return { r: p.r, g: p.g, b: p.b, a: alphaByte(p.a) };\n };\n const c1 = rgba(bottom_color);\n const c2 = rgba(top_color);\n const a = c1.a * (1 - k) + c2.a * k;\n if (a === 0) return transparent;\n // PineScript order (bit for bit, #146): premultiplied channels ((alpha / 255) * channel) * weight, divided by the\n // byte-alpha mix / 255, truncated. At an end (k = 0 / 1) this is floor(x * a / a): the end colour or one unit less.\n const scale = a / 255;\n const w1 = c1.a / 255;\n const w2 = c2.a / 255;\n const mix = (x1: number, x2: number) => Math.floor(((w1 * x1) * (1 - k) + (w2 * x2) * k) / scale);\n const [r, g, b] = [mix(c1.r, c2.r), mix(c1.g, c2.g), mix(c1.b, c2.b)];\n const alpha = Math.floor(a);\n return alpha === 255 ? `rgb(${r}, ${g}, ${b})` : `rgba(${r}, ${g}, ${b}, ${alpha / 255})`;\n}\n\n/**\n * Alias for new_color function.\n * Creates a new color with specified transparency from an existing color.\n *\n * @param baseColor - The base color\n * @param transp - Transparency value (0-100). 0 = fully opaque, 100 = fully transparent\n * @returns New color with applied transparency\n *\n * @remarks\n * This is an alias for `new_color()` to match PineScript's `color.new()` syntax.\n *\n * @example\n * ```typescript\n * const redColor = color.rgb(255, 0, 0);\n * const transparentRed = color.new(redColor, 50); // 50% transparent red\n * ```\n */\nexport { new_color as new };\n"],
4
+ "sourcesContent": ["/**\n * Color namespace\n * Mirrors PineScript's color.* functions for color creation and manipulation.\n *\n * @remarks\n * All color functions in this namespace follow PineScript v6 API specifications.\n * Colors are represented as RGB or RGBA strings.\n * Transparency values range from 0 (fully opaque) to 100 (fully transparent).\n *\n * @version 6\n */\n\nimport type { color, int, float, simple_int, simple_float } from '../types/index.js';\nimport { alphaByte, parseColor } from './parse.js';\n\n/** Channel of color.rgb: na is 0, a fraction is truncated. */\nconst channel = (v: number): int =>\n v === null || v === undefined || Number.isNaN(v) ? 0 : Math.max(0, Math.min(255, Math.trunc(v)));\n\n/**\n * Alpha (0-1) of a transparency given to color.rgb / color.new: na is fully transparent, clamped to 0..100.\n * `1 - t / 100` as in PineScript: `color.new(c, 90)` has the alpha byte 25 (0.09999999999999998 * 255 rounded).\n */\nconst alphaOf = (transp: number): float =>\n transp === null || Number.isNaN(transp) ? 0 : 1 - Math.max(0, Math.min(100, transp)) / 100;\n\n/**\n * Creates a color from RGB values with optional transparency.\n *\n * @param red - Red component (0-255, values are clamped)\n * @param green - Green component (0-255, values are clamped)\n * @param blue - Blue component (0-255, values are clamped)\n * @param transp - Optional transparency (0-100). 0 = opaque, 100 = fully transparent\n * @returns Color string in rgb() or rgba() format\n *\n * @remarks\n * - RGB values are automatically clamped to the 0-255 range\n * - Transparency of 0 or omitted results in rgb() format\n * - Transparency > 0 results in rgba() format\n * - Transparency is converted to alpha channel (0-1 range)\n *\n * PineScript rules:\n * - an `na` channel is 0; a fractional channel is truncated (127.6 is 127)\n * - the transparency is clamped to 0..100 (140 is fully transparent, -5 is opaque); an `na` transparency is fully\n * transparent\n *\n * @example\n * ```js\n * color.rgb(255, 0, 0) // Returns: \"rgb(255, 0, 0)\" - Red\n * color.rgb(0, 255, 0, 50) // Returns: \"rgba(0, 255, 0, 0.5)\" - Semi-transparent green\n * color.rgb(300, 0, 0) // Returns: \"rgb(255, 0, 0)\" - Clamped to 255\n * ```\n */\nexport function rgb(red: simple_int, green: simple_int, blue: simple_int, transp?: simple_float): string {\n const r = channel(red);\n const g = channel(green);\n const b = channel(blue);\n const a = transp !== undefined ? alphaOf(transp) : 1;\n\n if (a === 1) {\n return `rgb(${r}, ${g}, ${b})`;\n }\n return `rgba(${r}, ${g}, ${b}, ${a})`;\n}\n\n/**\n * Creates a color from a hexadecimal string with optional transparency.\n *\n * @param hex - Hex color string (with or without '#' prefix, e.g., \"#FF0000\" or \"FF0000\")\n * @param transp - Optional transparency (0-100). 0 = opaque, 100 = fully transparent\n * @returns Color string in rgb() or rgba() format\n *\n * @remarks\n * - Accepts hex strings with or without '#' prefix\n * - Case-insensitive (accepts both \"FF0000\" and \"ff0000\")\n * - Must be 6 characters (excluding '#')\n * - Format: RRGGBB where each component is 00-FF\n *\n * @example\n * ```js\n * color.from_hex(\"#FF0000\") // Returns: \"rgb(255, 0, 0)\" - Red\n * color.from_hex(\"00FF00\", 50) // Returns: \"rgba(0, 255, 0, 0.5)\" - Semi-transparent green\n * color.from_hex(\"#0000FF\") // Returns: \"rgb(0, 0, 255)\" - Blue\n * color.from_hex(\"FFA500\") // Returns: \"rgb(255, 165, 0)\" - Orange\n * ```\n */\nexport function from_hex(hex: string, transp?: simple_float): string {\n // Remove # if present\n hex = hex.replace('#', '');\n\n const r = parseInt(hex.substring(0, 2), 16);\n const g = parseInt(hex.substring(2, 4), 16);\n const b = parseInt(hex.substring(4, 6), 16);\n\n return rgb(r, g, b, transp);\n}\n\n/**\n * Creates a new color with modified transparency, preserving RGB components.\n *\n * @param baseColor - The base color to modify\n * @param transp - New transparency value (0-100). 0 = opaque, 100 = fully transparent\n * @returns New color with updated transparency\n *\n * @remarks\n * - Preserves the RGB values from the base color\n * - Replaces the transparency with the new value\n * - Useful for creating semi-transparent versions of existing colors\n * - PineScript clamps the transparency to 0..100 (`color.new(c, 140)` is fully transparent, `color.new(c, -5)` is\n * opaque); an `na` transparency is fully transparent (measured: the colour is not na, its RGB is kept)\n * - an `na` colour (null / undefined) gives black with the new transparency: `color.new(na, 30)` is\n * `rgba(0, 0, 0, 0.7)`, as PineScript does for an na colour variable (measured, #150). In PineScript, the constant\n * `color.new(color(na), 30)` is computed at compile time and stays na; a JS function cannot tell the two apart.\n *\n * @example\n * ```js\n * const red = color.rgb(255, 0, 0)\n * color.new_color(red, 50) // Returns: \"rgba(255, 0, 0, 0.5)\" - Semi-transparent red\n * color.new_color(red, 0) // Returns: \"rgb(255, 0, 0)\" - Fully opaque\n * color.new_color(red, 100) // Returns: \"rgba(255, 0, 0, 0)\" - Fully transparent\n * ```\n */\nexport function new_color(baseColor: color | null | undefined, transp: simple_float): string {\n if (baseColor === null || baseColor === undefined) return rgb(0, 0, 0, transp); // na colour: black\n if (typeof baseColor !== 'string') {\n const rgba = parseColor(baseColor);\n return rgb(rgba.r, rgba.g, rgba.b, transp);\n }\n // The same colour with the same transparency on every bar and every run: the text is made once.\n let byTransp = newColors.get(baseColor);\n if (byTransp === undefined) {\n if (newColors.size >= NEW_COLORS_KEPT) newColors.clear();\n newColors.set(baseColor, (byTransp = new Map()));\n }\n let text = byTransp.get(transp);\n if (text === undefined) {\n const rgba = parseColor(baseColor);\n text = rgb(rgba.r, rgba.g, rgba.b, transp);\n if (byTransp.size >= NEW_COLORS_KEPT) byTransp.clear();\n byTransp.set(transp, text);\n }\n return text;\n}\n\n/** color.new results by base colour, then transparency. */\nconst newColors = new Map<string, Map<number, string>>();\nconst NEW_COLORS_KEPT = 1024;\n\n/**\n * Extracts the red component from a color.\n *\n * @param clr - The color to extract from\n * @returns Red component value (0-255)\n *\n * @example\n * ```js\n * color.r(color.rgb(255, 128, 64)) // Returns: 255\n * color.r(color.from_hex(\"#FF0000\")) // Returns: 255\n * color.r(color.from_hex(\"#FFA500\")) // Returns: 255 (orange)\n * ```\n */\nexport function r(clr: color): int {\n return parseColor(clr).r;\n}\n\n/**\n * Extracts the green component from a color.\n *\n * @param clr - The color to extract from\n * @returns Green component value (0-255)\n *\n * @example\n * ```js\n * color.g(color.rgb(255, 128, 64)) // Returns: 128\n * color.g(color.from_hex(\"#00FF00\")) // Returns: 255\n * color.g(color.from_hex(\"#FFA500\")) // Returns: 165 (orange)\n * ```\n */\nexport function g(clr: color): int {\n return parseColor(clr).g;\n}\n\n/**\n * Extracts the blue component from a color.\n *\n * @param clr - The color to extract from\n * @returns Blue component value (0-255)\n *\n * @example\n * ```js\n * color.b(color.rgb(255, 128, 64)) // Returns: 64\n * color.b(color.from_hex(\"#0000FF\")) // Returns: 255\n * color.b(color.from_hex(\"#FFA500\")) // Returns: 0 (orange)\n * ```\n */\nexport function b(clr: color): int {\n return parseColor(clr).b;\n}\n\n/**\n * Extracts the transparency component from a color.\n *\n * @param clr - The color to extract from\n * @returns Transparency value (0-100). 0 = fully opaque, 100 = fully transparent\n *\n * @remarks\n * - Returns 0 for colors without transparency (rgb format)\n * - Converts alpha channel (0-1) to transparency (0-100)\n * - PineScript stores the alpha as a byte (0-255) and returns an integer transparency:\n * `color.t(color.new(c, 33.3))` is 33\n * - an `na` colour (null / undefined) is fully transparent: 100\n *\n * @example\n * ```js\n * color.t(color.rgb(255, 0, 0)) // Returns: 0 (opaque)\n * color.t(color.rgb(255, 0, 0, 50)) // Returns: 50\n * color.t(color.rgb(255, 0, 0, 100)) // Returns: 100 (fully transparent)\n * ```\n */\nexport function t(clr: color | null | undefined): float {\n if (clr === null || clr === undefined) return 100;\n return Math.round((1 - alphaByte(parseColor(clr).a) / 255) * 100);\n}\n\n// Predefined color constants of PineScript v6.\n// PineScript v5 differs for red (#FF5252), teal (#00897B) and yellow (#FFEB3B).\n/**\n * Aqua/Cyan color constant\n * @constant {string} #00BCD4 - RGB(0, 188, 212)\n */\nexport const aqua = '#00BCD4';\n\n/**\n * Black color constant\n * @constant {string} #363A45 - RGB(54, 58, 69)\n */\nexport const black = '#363A45';\n\n/**\n * Blue color constant\n * @constant {string} #2962FF - RGB(41, 98, 255)\n */\nexport const blue = '#2962FF';\n\n/**\n * Fuchsia/Magenta color constant\n * @constant {string} #E040FB - RGB(224, 64, 251)\n */\nexport const fuchsia = '#E040FB';\n\n/**\n * Gray color constant\n * @constant {string} #787B86 - RGB(120, 123, 134)\n */\nexport const gray = '#787B86';\n\n/**\n * Green color constant (same as lime)\n * @constant {string} #4CAF50 - RGB(76, 175, 80)\n */\nexport const green = '#4CAF50';\n\n/**\n * Lime color constant (same as green)\n * @constant {string} #00E676 - RGB(0, 230, 118)\n */\nexport const lime = '#00E676';\n\n/**\n * Maroon color constant\n * @constant {string} #880E4F - RGB(136, 14, 79)\n */\nexport const maroon = '#880E4F';\n\n/**\n * Navy color constant\n * @constant {string} #311B92 - RGB(49, 27, 146)\n */\nexport const navy = '#311B92';\n\n/**\n * Olive color constant\n * @constant {string} #808000 - RGB(128, 128, 0)\n */\nexport const olive = '#808000';\n\n/**\n * Orange color constant\n * @constant {string} #FF9800 - RGB(255, 152, 0)\n */\nexport const orange = '#FF9800';\n\n/**\n * Purple color constant\n * @constant {string} #9C27B0 - RGB(156, 39, 176)\n */\nexport const purple = '#9C27B0';\n\n/**\n * Red color constant\n * @constant {string} #F23645 - RGB(242, 54, 69)\n */\nexport const red = '#F23645';\n\n/**\n * Silver color constant\n * @constant {string} #B2B5BE - RGB(178, 181, 190)\n */\nexport const silver = '#B2B5BE';\n\n/**\n * Teal color constant\n * @constant {string} #089981 - RGB(8, 153, 129)\n */\nexport const teal = '#089981';\n\n/**\n * White color constant\n * @constant {string} #FFFFFF - RGB(255, 255, 255)\n */\nexport const white = '#FFFFFF';\n\n/**\n * Yellow color constant\n * @constant {string} #FDD835 - RGB(253, 216, 53)\n */\nexport const yellow = '#FDD835';\n\n/**\n * Creates a color from a gradient based on value position.\n *\n * @param value - Value to calculate position-dependent color\n * @param bottom_value - Bottom position value corresponding to bottom_color\n * @param top_value - Top position value corresponding to top_color\n * @param bottom_color - Bottom position color\n * @param top_color - Top position color\n * @returns Color calculated from linear gradient\n *\n * @remarks\n * PineScript rules:\n * - If value <= bottom_value, returns bottom_color; else if value >= top_value, returns top_color\n * - An inverted range (bottom_value > top_value) returns bottom_color, wherever the value is\n * - Otherwise the colours are mixed with their transparency (premultiplied alpha, alpha as a byte); the RGB channels\n * and the alpha are truncated. PineScript's float rounding order is not known: a channel can differ by 1 when the\n * exact result is an integer (same RGB at both ends)\n * - An na value or bottom_value / top_value, or bottom_value == top_value, gives a fully transparent colour\n * - An na colour counts as fully transparent\n * - Works with rgb(), rgba() and hex (#RRGGBB, #RRGGBBAA) colours\n *\n * @example\n * ```js\n * // Value at middle of range gets middle color\n * const midColor = color.from_gradient(50, 0, 100,\n * color.rgb(255, 0, 0), // Red at bottom\n * color.rgb(0, 255, 0) // Green at top\n * ); // Returns color between red and green\n *\n * // Value at extremes\n * const lowColor = color.from_gradient(-10, 0, 100, color.red, color.green); // red: at or below the bottom\n * const highColor = color.from_gradient(150, 0, 100, color.red, color.green); // green: at or above the top\n * ```\n */\nexport function from_gradient(\n value: float,\n bottom_value: float,\n top_value: float,\n bottom_color: color,\n top_color: color\n): string {\n const transparent = 'rgba(0, 0, 0, 0)';\n if ([value, bottom_value, top_value].some((v) => v === null || v === undefined || Number.isNaN(v)) || bottom_value === top_value) {\n return transparent;\n }\n const k =\n value <= bottom_value || bottom_value > top_value\n ? 0\n : value >= top_value\n ? 1\n : (value - bottom_value) / (top_value - bottom_value);\n // alpha as a byte (0-255), as PineScript stores it; an na colour (null / undefined, or 'transparent', the\n // library's form of na) is fully transparent\n const rgba = (c: color) => {\n if (c === null || c === undefined || (typeof c === 'string' && c.trim().toLowerCase() === 'transparent')) return { r: 0, g: 0, b: 0, a: 0 };\n const p = parseColor(c);\n return { r: p.r, g: p.g, b: p.b, a: alphaByte(p.a) };\n };\n const c1 = rgba(bottom_color);\n const c2 = rgba(top_color);\n const a = c1.a * (1 - k) + c2.a * k;\n if (a === 0) return transparent;\n // PineScript order (bit for bit, #146): premultiplied channels ((alpha / 255) * channel) * weight, divided by the\n // byte-alpha mix / 255, truncated. At an end (k = 0 / 1) this is floor(x * a / a): the end colour or one unit less.\n const scale = a / 255;\n const w1 = c1.a / 255;\n const w2 = c2.a / 255;\n const mix = (x1: number, x2: number) => Math.floor(((w1 * x1) * (1 - k) + (w2 * x2) * k) / scale);\n const [r, g, b] = [mix(c1.r, c2.r), mix(c1.g, c2.g), mix(c1.b, c2.b)];\n const alpha = Math.floor(a);\n return alpha === 255 ? `rgb(${r}, ${g}, ${b})` : `rgba(${r}, ${g}, ${b}, ${alpha / 255})`;\n}\n\n/**\n * Alias for new_color function.\n * Creates a new color with specified transparency from an existing color.\n *\n * @param baseColor - The base color\n * @param transp - Transparency value (0-100). 0 = fully opaque, 100 = fully transparent\n * @returns New color with applied transparency\n *\n * @remarks\n * This is an alias for `new_color()` to match PineScript's `color.new()` syntax.\n *\n * @example\n * ```js\n * const redColor = color.rgb(255, 0, 0);\n * const transparentRed = color.new(redColor, 50); // 50% transparent red\n * ```\n */\nexport { new_color as new };\n"],
5
5
  "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAaA,mBAAsC;AAGtC,MAAM,UAAU,CAAC,MACf,MAAM,QAAQ,MAAM,UAAa,OAAO,MAAM,CAAC,IAAI,IAAI,KAAK,IAAI,GAAG,KAAK,IAAI,KAAK,KAAK,MAAM,CAAC,CAAC,CAAC;AAMjG,MAAM,UAAU,CAAC,WACf,WAAW,QAAQ,OAAO,MAAM,MAAM,IAAI,IAAI,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AAQ,MAAM,UAAc,OAAO,MAAM,YAAY,EAAE,KAAK,EAAE,YAAY,MAAM,cAAgB,QAAO,EAAE,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,EAAE;AAC1I,UAAM,QAAI,yBAAW,CAAC;AACtB,WAAO,EAAE,GAAG,EAAE,GAAG,GAAG,EAAE,GAAG,GAAG,EAAE,GAAG,OAAG,wBAAU,EAAE,CAAC,EAAE;AAAA,EACrD;AACA,QAAM,KAAK,KAAK,YAAY;AAC5B,QAAM,KAAK,KAAK,SAAS;AACzB,QAAM,IAAI,GAAG,KAAK,IAAI,KAAK,GAAG,IAAI;AAClC,MAAI,MAAM,EAAG,QAAO;AAGpB,QAAM,QAAQ,IAAI;AAClB,QAAM,KAAK,GAAG,IAAI;AAClB,QAAM,KAAK,GAAG,IAAI;AAClB,QAAM,MAAM,CAAC,IAAY,OAAe,KAAK,OAAQ,KAAK,MAAO,IAAI,KAAM,KAAK,KAAM,KAAK,KAAK;AAChG,QAAM,CAACF,IAAGC,IAAGC,EAAC,IAAI,CAAC,IAAI,GAAG,GAAG,GAAG,CAAC,GAAG,IAAI,GAAG,GAAG,GAAG,CAAC,GAAG,IAAI,GAAG,GAAG,GAAG,CAAC,CAAC;AACpE,QAAM,QAAQ,KAAK,MAAM,CAAC;AAC1B,SAAO,UAAU,MAAM,OAAOF,EAAC,KAAKC,EAAC,KAAKC,EAAC,MAAM,QAAQF,EAAC,KAAKC,EAAC,KAAKC,EAAC,KAAK,QAAQ,GAAG;AACxF;",
6
6
  "names": ["red", "green", "blue", "r", "g", "b"]
7
7
  }
@@ -14,6 +14,8 @@ export interface ParsedColor {
14
14
  * The result is shared between calls: do not change it.
15
15
  */
16
16
  export declare function parseColor(clr: color): ParsedColor;
17
+ /** The text is a colour {@link parseColor} reads (hex or rgb() / rgba()), not one it takes for opaque black. */
18
+ export declare function isColorText(clr: unknown): boolean;
17
19
  /** Alpha byte (0-255) of an alpha (0-1), as PineScript stores it. */
18
20
  export declare const alphaByte: (a: float) => int;
19
21
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"parse.d.ts","sourceRoot":"","sources":["../../../src/color/parse.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAE3D,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC;IAChB,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC;IAChB,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC;IAChB,QAAQ,CAAC,CAAC,EAAE,KAAK,CAAC;CACnB;AAQD;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,KAAK,GAAG,WAAW,CASlD;AAwBD,qEAAqE;AACrE,eAAO,MAAM,SAAS,GAAI,GAAG,KAAK,KAAG,GAA0B,CAAC;AAEhE;;;;;;;;;;GAUG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,KAAK,GAAG,KAAK,CAStD"}
1
+ {"version":3,"file":"parse.d.ts","sourceRoot":"","sources":["../../../src/color/parse.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAE3D,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC;IAChB,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC;IAChB,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC;IAChB,QAAQ,CAAC,CAAC,EAAE,KAAK,CAAC;CACnB;AAQD;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,KAAK,GAAG,WAAW,CASlD;AAwBD,gHAAgH;AAChH,wBAAgB,WAAW,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAIjD;AAED,qEAAqE;AACrE,eAAO,MAAM,SAAS,GAAI,GAAG,KAAK,KAAG,GAA0B,CAAC;AAEhE;;;;;;;;;;GAUG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,KAAK,GAAG,KAAK,CAStD"}
@@ -20,6 +20,7 @@ var parse_exports = {};
20
20
  __export(parse_exports, {
21
21
  alphaByte: () => alphaByte,
22
22
  inputColorDefault: () => inputColorDefault,
23
+ isColorText: () => isColorText,
23
24
  parseColor: () => parseColor
24
25
  });
25
26
  module.exports = __toCommonJS(parse_exports);
@@ -57,6 +58,11 @@ function parseText(clr) {
57
58
  }
58
59
  return BLACK;
59
60
  }
61
+ function isColorText(clr) {
62
+ if (typeof clr !== "string") return false;
63
+ const s = clr.trim();
64
+ return /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(s) || /^rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(,\s*[\d.]+\s*)?\)$/i.test(s);
65
+ }
60
66
  const alphaByte = (a) => Math.round(a * 255);
61
67
  function inputColorDefault(defval) {
62
68
  if (typeof defval !== "string") return defval;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/color/parse.ts"],
4
- "sourcesContent": ["/**\n * Colour parsing shared by the color namespace and input.color (internal, not part of the public API).\n */\n\nimport type { color, int, float } from '../types/index.js';\n\nexport interface ParsedColor {\n readonly r: int;\n readonly g: int;\n readonly b: int;\n readonly a: float;\n}\n\nconst BLACK: ParsedColor = { r: 0, g: 0, b: 0, a: 1 };\n\n/** Parsed colours by text: a script reads the same few colours on every bar, and again on each run. */\nconst parsed = new Map<string, ParsedColor>();\nconst PARSED_KEPT = 4096;\n\n/**\n * Parses a colour string to its channels (0-255) and alpha (0-1).\n * Hex: #RRGGBB, #RRGGBBAA (PineScript literals), #RGB, #RGBA; rgb() / rgba(). Anything else is opaque black.\n * The result is shared between calls: do not change it.\n */\nexport function parseColor(clr: color): ParsedColor {\n if (typeof clr !== 'string') return BLACK;\n let p = parsed.get(clr);\n if (p === undefined) {\n p = parseText(clr);\n if (parsed.size >= PARSED_KEPT) parsed.clear();\n parsed.set(clr, p);\n }\n return p;\n}\n\nfunction parseText(clr: string): ParsedColor {\n {\n const hex = /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(clr.trim());\n if (hex) {\n let digits = hex[1]!;\n if (digits.length <= 4) digits = [...digits].map((c) => c + c).join('');\n const byte = (k: number) => parseInt(digits.slice(k, k + 2), 16);\n return { r: byte(0), g: byte(2), b: byte(4), a: digits.length === 8 ? byte(6) / 255 : 1 };\n }\n const match = clr.match(/rgba?\\((\\d+),\\s*(\\d+),\\s*(\\d+)(?:,\\s*([\\d.]+))?\\)/);\n if (match) {\n return {\n r: parseInt(match[1]!),\n g: parseInt(match[2]!),\n b: parseInt(match[3]!),\n a: match[4] ? parseFloat(match[4]) : 1,\n };\n }\n }\n return BLACK;\n}\n\n/** Alpha byte (0-255) of an alpha (0-1), as PineScript stores it. */\nexport const alphaByte = (a: float): int => Math.round(a * 255);\n\n/**\n * The colour a script receives for the default of `input.color(defval)`.\n *\n * PineScript rules (measured):\n * - the default is stored with an alpha of 2 decimals: a `color.new(c, t)` / `color.rgb(r, g, b, t)` default keeps\n * `(100 - trunc(t)) / 100` (90 gives 0.1, 9.9 gives 0.91), a hex literal `#RRGGBBAA` keeps `round(AA / 255, 2)`\n * - the input value is then the alpha byte `round(255 * alpha)`: `color.new(c, 90)` as an input default has the\n * byte 26, where `color.new(c, 90)` in the script has 25\n *\n * A default whose alpha byte does not change is returned unchanged.\n */\nexport function inputColorDefault(defval: color): color {\n if (typeof defval !== 'string') return defval;\n const p = parseColor(defval);\n const hex = defval.trim().startsWith('#');\n // rgba() from color.new / color.rgb: alpha = 1 - t / 100, so alpha * 100 = 100 - t (float noise removed first)\n const stored = hex ? Math.round(p.a * 100) / 100 : Math.ceil(Math.round(p.a * 100 * 1e6) / 1e6) / 100;\n const byte = alphaByte(stored);\n if (byte === alphaByte(p.a)) return defval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,MAAM,CAAC,IAAI,WAAW,MAAM,CAAC,CAAC,IAAI;AAAA,MACvC;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAGO,MAAM,YAAY,CAAC,MAAkB,KAAK,MAAM,IAAI,GAAG;AAavD,SAAS,kBAAkB,QAAsB;AACtD,MAAI,OAAO,WAAW,SAAU,QAAO;AACvC,QAAM,IAAI,WAAW,MAAM;AAC3B,QAAM,MAAM,OAAO,KAAK,EAAE,WAAW,GAAG;AAExC,QAAM,SAAS,MAAM,KAAK,MAAM,EAAE,IAAI,GAAG,IAAI,MAAM,KAAK,KAAK,KAAK,MAAM,EAAE,IAAI,MAAM,GAAG,IAAI,GAAG,IAAI;AAClG,QAAM,OAAO,UAAU,MAAM;AAC7B,MAAI,SAAS,UAAU,EAAE,CAAC,EAAG,QAAO;AACpC,SAAO,SAAS,MAAM,OAAO,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,MAAM,QAAQ,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,OAAO,GAAG;AAClG;",
4
+ "sourcesContent": ["/**\n * Colour parsing shared by the color namespace and input.color (internal, not part of the public API).\n */\n\nimport type { color, int, float } from '../types/index.js';\n\nexport interface ParsedColor {\n readonly r: int;\n readonly g: int;\n readonly b: int;\n readonly a: float;\n}\n\nconst BLACK: ParsedColor = { r: 0, g: 0, b: 0, a: 1 };\n\n/** Parsed colours by text: a script reads the same few colours on every bar, and again on each run. */\nconst parsed = new Map<string, ParsedColor>();\nconst PARSED_KEPT = 4096;\n\n/**\n * Parses a colour string to its channels (0-255) and alpha (0-1).\n * Hex: #RRGGBB, #RRGGBBAA (PineScript literals), #RGB, #RGBA; rgb() / rgba(). Anything else is opaque black.\n * The result is shared between calls: do not change it.\n */\nexport function parseColor(clr: color): ParsedColor {\n if (typeof clr !== 'string') return BLACK;\n let p = parsed.get(clr);\n if (p === undefined) {\n p = parseText(clr);\n if (parsed.size >= PARSED_KEPT) parsed.clear();\n parsed.set(clr, p);\n }\n return p;\n}\n\nfunction parseText(clr: string): ParsedColor {\n {\n const hex = /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(clr.trim());\n if (hex) {\n let digits = hex[1]!;\n if (digits.length <= 4) digits = [...digits].map((c) => c + c).join('');\n const byte = (k: number) => parseInt(digits.slice(k, k + 2), 16);\n return { r: byte(0), g: byte(2), b: byte(4), a: digits.length === 8 ? byte(6) / 255 : 1 };\n }\n const match = clr.match(/rgba?\\((\\d+),\\s*(\\d+),\\s*(\\d+)(?:,\\s*([\\d.]+))?\\)/);\n if (match) {\n return {\n r: parseInt(match[1]!),\n g: parseInt(match[2]!),\n b: parseInt(match[3]!),\n a: match[4] ? parseFloat(match[4]) : 1,\n };\n }\n }\n return BLACK;\n}\n\n/** The text is a colour {@link parseColor} reads (hex or rgb() / rgba()), not one it takes for opaque black. */\nexport function isColorText(clr: unknown): boolean {\n if (typeof clr !== 'string') return false;\n const s = clr.trim();\n return /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(s) || /^rgba?\\(\\s*\\d+\\s*,\\s*\\d+\\s*,\\s*\\d+\\s*(,\\s*[\\d.]+\\s*)?\\)$/i.test(s);\n}\n\n/** Alpha byte (0-255) of an alpha (0-1), as PineScript stores it. */\nexport const alphaByte = (a: float): int => Math.round(a * 255);\n\n/**\n * The colour a script receives for the default of `input.color(defval)`.\n *\n * PineScript rules (measured):\n * - the default is stored with an alpha of 2 decimals: a `color.new(c, t)` / `color.rgb(r, g, b, t)` default keeps\n * `(100 - trunc(t)) / 100` (90 gives 0.1, 9.9 gives 0.91), a hex literal `#RRGGBBAA` keeps `round(AA / 255, 2)`\n * - the input value is then the alpha byte `round(255 * alpha)`: `color.new(c, 90)` as an input default has the\n * byte 26, where `color.new(c, 90)` in the script has 25\n *\n * A default whose alpha byte does not change is returned unchanged.\n */\nexport function inputColorDefault(defval: color): color {\n if (typeof defval !== 'string') return defval;\n const p = parseColor(defval);\n const hex = defval.trim().startsWith('#');\n // rgba() from color.new / color.rgb: alpha = 1 - t / 100, so alpha * 100 = 100 - t (float noise removed first)\n const stored = hex ? Math.round(p.a * 100) / 100 : Math.ceil(Math.round(p.a * 100 * 1e6) / 1e6) / 100;\n const byte = alphaByte(stored);\n if (byte === alphaByte(p.a)) return defval;\n return byte === 255 ? `rgb(${p.r}, ${p.g}, ${p.b})` : `rgba(${p.r}, ${p.g}, ${p.b}, ${byte / 255})`;\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAaA,MAAM,QAAqB,EAAE,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,EAAE;AAGpD,MAAM,SAAS,oBAAI,IAAyB;AAC5C,MAAM,cAAc;AAOb,SAAS,WAAW,KAAyB;AAClD,MAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,MAAI,IAAI,OAAO,IAAI,GAAG;AACtB,MAAI,MAAM,QAAW;AACnB,QAAI,UAAU,GAAG;AACjB,QAAI,OAAO,QAAQ,YAAa,QAAO,MAAM;AAC7C,WAAO,IAAI,KAAK,CAAC;AAAA,EACnB;AACA,SAAO;AACT;AAEA,SAAS,UAAU,KAA0B;AAC3C;AACE,UAAM,MAAM,8CAA8C,KAAK,IAAI,KAAK,CAAC;AACzE,QAAI,KAAK;AACP,UAAI,SAAS,IAAI,CAAC;AAClB,UAAI,OAAO,UAAU,EAAG,UAAS,CAAC,GAAG,MAAM,EAAE,IAAI,CAAC,MAAM,IAAI,CAAC,EAAE,KAAK,EAAE;AACtE,YAAM,OAAO,CAAC,MAAc,SAAS,OAAO,MAAM,GAAG,IAAI,CAAC,GAAG,EAAE;AAC/D,aAAO,EAAE,GAAG,KAAK,CAAC,GAAG,GAAG,KAAK,CAAC,GAAG,GAAG,KAAK,CAAC,GAAG,GAAG,OAAO,WAAW,IAAI,KAAK,CAAC,IAAI,MAAM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