oakscriptjs 0.15.3 → 0.15.4

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 (144) hide show
  1. package/dist/cjs/check/format.d.ts.map +1 -1
  2. package/dist/cjs/check/format.js +5 -0
  3. package/dist/cjs/check/format.js.map +2 -2
  4. package/dist/cjs/check/harness.d.ts +24 -0
  5. package/dist/cjs/check/harness.d.ts.map +1 -1
  6. package/dist/cjs/check/harness.js +33 -0
  7. package/dist/cjs/check/harness.js.map +2 -2
  8. package/dist/cjs/check/index.d.ts +9 -0
  9. package/dist/cjs/check/index.d.ts.map +1 -1
  10. package/dist/cjs/check/index.js +7 -0
  11. package/dist/cjs/check/index.js.map +2 -2
  12. package/dist/cjs/color/index.d.ts.map +1 -1
  13. package/dist/cjs/color/index.js +19 -2
  14. package/dist/cjs/color/index.js.map +2 -2
  15. package/dist/cjs/color/parse.d.ts +8 -6
  16. package/dist/cjs/color/parse.d.ts.map +1 -1
  17. package/dist/cjs/color/parse.js +15 -2
  18. package/dist/cjs/color/parse.js.map +2 -2
  19. package/dist/cjs/drawing/registry.d.ts +29 -0
  20. package/dist/cjs/drawing/registry.d.ts.map +1 -1
  21. package/dist/cjs/drawing/registry.js +83 -2
  22. package/dist/cjs/drawing/registry.js.map +2 -2
  23. package/dist/cjs/index.d.ts +2 -1
  24. package/dist/cjs/index.d.ts.map +1 -1
  25. package/dist/cjs/index.js +3 -1
  26. package/dist/cjs/index.js.map +2 -2
  27. package/dist/cjs/runtime/series.d.ts +16 -0
  28. package/dist/cjs/runtime/series.d.ts.map +1 -1
  29. package/dist/cjs/runtime/series.js +19 -2
  30. package/dist/cjs/runtime/series.js.map +2 -2
  31. package/dist/cjs/script/closure-writes.d.ts +16 -0
  32. package/dist/cjs/script/closure-writes.d.ts.map +1 -0
  33. package/dist/cjs/script/closure-writes.js +435 -0
  34. package/dist/cjs/script/closure-writes.js.map +7 -0
  35. package/dist/cjs/script/globals.d.ts +2 -0
  36. package/dist/cjs/script/globals.d.ts.map +1 -1
  37. package/dist/cjs/script/globals.js.map +1 -1
  38. package/dist/cjs/script/incremental.d.ts +140 -0
  39. package/dist/cjs/script/incremental.d.ts.map +1 -0
  40. package/dist/cjs/script/incremental.js +142 -0
  41. package/dist/cjs/script/incremental.js.map +7 -0
  42. package/dist/cjs/script/index.d.ts +116 -31
  43. package/dist/cjs/script/index.d.ts.map +1 -1
  44. package/dist/cjs/script/index.js +471 -25
  45. package/dist/cjs/script/index.js.map +3 -3
  46. package/dist/cjs/str/numberformat.d.ts.map +1 -1
  47. package/dist/cjs/str/numberformat.js +23 -0
  48. package/dist/cjs/str/numberformat.js.map +2 -2
  49. package/dist/cjs/strategy/index.d.ts +8 -0
  50. package/dist/cjs/strategy/index.d.ts.map +1 -1
  51. package/dist/cjs/strategy/index.js.map +1 -1
  52. package/dist/cjs/ta/running-sum.d.ts.map +1 -1
  53. package/dist/cjs/ta/running-sum.js +72 -3
  54. package/dist/cjs/ta/running-sum.js.map +2 -2
  55. package/dist/cjs/ta/step.d.ts +476 -0
  56. package/dist/cjs/ta/step.d.ts.map +1 -0
  57. package/dist/cjs/ta/step.js +1000 -0
  58. package/dist/cjs/ta/step.js.map +7 -0
  59. package/dist/cjs/ta-series.d.ts +1 -1
  60. package/dist/cjs/ta-series.js +3 -3
  61. package/dist/cjs/ta-series.js.map +1 -1
  62. package/dist/esm/check/format.d.ts.map +1 -1
  63. package/dist/esm/check/format.js +5 -0
  64. package/dist/esm/check/format.js.map +1 -1
  65. package/dist/esm/check/harness.d.ts +24 -0
  66. package/dist/esm/check/harness.d.ts.map +1 -1
  67. package/dist/esm/check/harness.js +40 -6
  68. package/dist/esm/check/harness.js.map +1 -1
  69. package/dist/esm/check/index.d.ts +9 -0
  70. package/dist/esm/check/index.d.ts.map +1 -1
  71. package/dist/esm/check/index.js +11 -1
  72. package/dist/esm/check/index.js.map +1 -1
  73. package/dist/esm/color/index.d.ts.map +1 -1
  74. package/dist/esm/color/index.js +23 -3
  75. package/dist/esm/color/index.js.map +1 -1
  76. package/dist/esm/color/parse.d.ts +8 -6
  77. package/dist/esm/color/parse.d.ts.map +1 -1
  78. package/dist/esm/color/parse.js +19 -2
  79. package/dist/esm/color/parse.js.map +1 -1
  80. package/dist/esm/drawing/registry.d.ts +29 -0
  81. package/dist/esm/drawing/registry.d.ts.map +1 -1
  82. package/dist/esm/drawing/registry.js +102 -3
  83. package/dist/esm/drawing/registry.js.map +1 -1
  84. package/dist/esm/index.d.ts +2 -1
  85. package/dist/esm/index.d.ts.map +1 -1
  86. package/dist/esm/index.js +3 -1
  87. package/dist/esm/index.js.map +1 -1
  88. package/dist/esm/runtime/series.d.ts +16 -0
  89. package/dist/esm/runtime/series.d.ts.map +1 -1
  90. package/dist/esm/runtime/series.js +21 -1
  91. package/dist/esm/runtime/series.js.map +1 -1
  92. package/dist/esm/script/closure-writes.d.ts +16 -0
  93. package/dist/esm/script/closure-writes.d.ts.map +1 -0
  94. package/dist/esm/script/closure-writes.js +323 -0
  95. package/dist/esm/script/closure-writes.js.map +1 -0
  96. package/dist/esm/script/globals.d.ts +2 -0
  97. package/dist/esm/script/globals.d.ts.map +1 -1
  98. package/dist/esm/script/globals.js.map +1 -1
  99. package/dist/esm/script/incremental.d.ts +140 -0
  100. package/dist/esm/script/incremental.d.ts.map +1 -0
  101. package/dist/esm/script/incremental.js +173 -0
  102. package/dist/esm/script/incremental.js.map +1 -0
  103. package/dist/esm/script/index.d.ts +116 -31
  104. package/dist/esm/script/index.d.ts.map +1 -1
  105. package/dist/esm/script/index.js +561 -24
  106. package/dist/esm/script/index.js.map +1 -1
  107. package/dist/esm/str/numberformat.d.ts.map +1 -1
  108. package/dist/esm/str/numberformat.js +30 -0
  109. package/dist/esm/str/numberformat.js.map +1 -1
  110. package/dist/esm/strategy/index.d.ts +8 -0
  111. package/dist/esm/strategy/index.d.ts.map +1 -1
  112. package/dist/esm/ta/running-sum.d.ts.map +1 -1
  113. package/dist/esm/ta/running-sum.js +79 -4
  114. package/dist/esm/ta/running-sum.js.map +1 -1
  115. package/dist/esm/ta/step.d.ts +476 -0
  116. package/dist/esm/ta/step.d.ts.map +1 -0
  117. package/dist/esm/ta/step.js +1089 -0
  118. package/dist/esm/ta/step.js.map +1 -0
  119. package/dist/esm/ta-series.d.ts +1 -1
  120. package/dist/esm/ta-series.js +4 -4
  121. package/package.json +1 -1
  122. package/skills/oakscript/SKILL.md +2 -2
  123. package/skills/oakscript/reference/check.md +5 -0
  124. package/skills/oakscript/reference/errors.md +0 -1
  125. package/skills/oakscript/reference/pine-differences.md +1 -2
  126. package/skills/oakscript/reference/plotting.md +5 -7
  127. package/skills/oakscript/reference/script-structure.md +6 -0
  128. package/src/check/format.ts +7 -0
  129. package/src/check/harness.ts +57 -0
  130. package/src/check/index.ts +16 -0
  131. package/src/color/index.ts +22 -3
  132. package/src/color/parse.ts +28 -3
  133. package/src/drawing/registry.ts +115 -3
  134. package/src/index.ts +4 -1
  135. package/src/runtime/series.ts +33 -1
  136. package/src/script/closure-writes.ts +279 -0
  137. package/src/script/globals.ts +2 -0
  138. package/src/script/incremental.ts +246 -0
  139. package/src/script/index.ts +695 -26
  140. package/src/str/numberformat.ts +29 -0
  141. package/src/strategy/index.ts +8 -0
  142. package/src/ta/running-sum.ts +78 -3
  143. package/src/ta/step.ts +1145 -0
  144. package/src/ta-series.ts +4 -4
@@ -185,6 +185,25 @@ export function historyError(bar: number, barsBack: number): string {
185
185
  );
186
186
  }
187
187
 
188
+ /**
189
+ * Hooks of an incremental script run (#196, set by the script runtime during a run only): a Series created by the
190
+ * script gets a slot, and toArray() reuses the values of the previous run up to the first bar that changed.
191
+ * @internal
192
+ */
193
+ export interface SeriesRunHooks {
194
+ created(series: Series): void;
195
+ /** The values of the previous run (indexes below `from` are kept; the array is reused), or null to compute every bar */
196
+ prefix(series: Series, bars: readonly Bar[]): { values: number[]; from: number } | null;
197
+ computed(series: Series, values: number[]): void;
198
+ }
199
+
200
+ let runHooks: SeriesRunHooks | null = null;
201
+
202
+ /** @internal */
203
+ export function setSeriesRunHooks(hooks: SeriesRunHooks | null): void {
204
+ runHooks = hooks;
205
+ }
206
+
188
207
  export class Series {
189
208
  private extractor: SeriesExtractor;
190
209
  private dataSource: BarData;
@@ -207,6 +226,7 @@ export class Series {
207
226
  // Support both Bar[] and BarData for backward compatibility
208
227
  this.dataSource = data instanceof BarData ? data : new BarData(data);
209
228
  this.extractor = extractor;
229
+ runHooks?.created(this);
210
230
  }
211
231
 
212
232
  /**
@@ -568,8 +588,20 @@ export class Series {
568
588
 
569
589
  // Recompute and update cache
570
590
  const bars = this.dataSource.bars;
571
- this.cached = bars.map((bar, i) => this.extractor(bar, i, bars));
591
+ const prefix = runHooks?.prefix(this, bars) ?? null;
592
+ if (prefix) {
593
+ // the run's own array of the previous run: its first values are kept, the newest computed in place
594
+ const n = bars.length;
595
+ const values = prefix.values;
596
+ const from = Math.min(prefix.from, n);
597
+ values.length = n;
598
+ for (let i = from; i < n; i++) values[i] = this.extractor(bars[i]!, i, bars);
599
+ this.cached = values;
600
+ } else {
601
+ this.cached = bars.map((bar, i) => this.extractor(bar, i, bars));
602
+ }
572
603
  this.cachedVersion = this.dataSource.version;
604
+ runHooks?.computed(this, this.cached);
573
605
  return this.cached;
574
606
  }
575
607
 
@@ -0,0 +1,279 @@
1
+ /**
2
+ * The variables of the script that an eachBar() callback changes outside itself (#196): an incremental run cannot put
3
+ * them back to their value at the last confirmed bar, so a script with such a write is calculated in full.
4
+ *
5
+ * Read from the callback's source text (`fn.toString()`), with a tokenizer (strings, template literals, comments and
6
+ * regular expressions skipped). A write is an assignment (`x = `, `x += `, `x++`...) or a change of a member
7
+ * (`x.y = `, `x[i] = `, `x.push(...)` and the other mutating methods) whose root name is not declared inside the
8
+ * callback. The `.value` of a persist() box (`dir.value = 1`) is not a write. Conservative: a name declared anywhere
9
+ * inside the callback counts as its own (a shadowed outer write is missed); functions called by the callback are not
10
+ * read.
11
+ *
12
+ * @internal
13
+ */
14
+
15
+ const MUTATORS = new Set([
16
+ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse', 'fill', 'copyWithin',
17
+ 'set', 'delete', 'clear', 'add',
18
+ ]);
19
+
20
+ const KEYWORDS = new Set([
21
+ 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'export',
22
+ 'extends', 'finally', 'for', 'function', 'if', 'import', 'in', 'instanceof', 'let', 'new', 'return', 'super',
23
+ 'switch', 'this', 'throw', 'try', 'typeof', 'var', 'void', 'while', 'with', 'yield', 'await', 'of', 'true', 'false',
24
+ 'null', 'undefined', 'async', 'static', 'get',
25
+ ]);
26
+
27
+ type Token = { kind: 'id' | 'punct' | 'num' | 'str'; text: string };
28
+
29
+ /** Tokens of a JavaScript source: names, numbers, punctuators; strings, template literals, comments and regexes skipped. */
30
+ function tokenize(src: string): Token[] {
31
+ const out: Token[] = [];
32
+ let i = 0;
33
+ const n = src.length;
34
+ const regexAllowed = (): boolean => {
35
+ const last = out[out.length - 1];
36
+ if (!last) return true;
37
+ if (last.kind === 'num' || last.kind === 'str') return false;
38
+ if (last.kind === 'id') return KEYWORDS.has(last.text) && !['this', 'super', 'true', 'false', 'null', 'undefined'].includes(last.text);
39
+ return ![')', ']', '}'].includes(last.text);
40
+ };
41
+ while (i < n) {
42
+ const ch = src[i]!;
43
+ if (/\s/.test(ch)) {
44
+ i++;
45
+ } else if (ch === '/' && src[i + 1] === '/') {
46
+ while (i < n && src[i] !== '\n') i++;
47
+ } else if (ch === '/' && src[i + 1] === '*') {
48
+ i = src.indexOf('*/', i + 2);
49
+ i = i < 0 ? n : i + 2;
50
+ } else if (ch === '"' || ch === "'") {
51
+ i++;
52
+ while (i < n && src[i] !== ch) i += src[i] === '\\' ? 2 : 1;
53
+ i++;
54
+ out.push({ kind: 'str', text: '' });
55
+ } else if (ch === '`') {
56
+ // a template literal: its ${...} parts are tokenized as code
57
+ i++;
58
+ let depth = 0;
59
+ const inner: string[] = [];
60
+ let part = '';
61
+ while (i < n) {
62
+ if (depth === 0 && src[i] === '\\') {
63
+ i += 2;
64
+ continue;
65
+ }
66
+ if (depth === 0 && src[i] === '`') break;
67
+ if (depth === 0 && src[i] === '$' && src[i + 1] === '{') {
68
+ depth = 1;
69
+ i += 2;
70
+ continue;
71
+ }
72
+ if (depth > 0) {
73
+ if (src[i] === '{') depth++;
74
+ if (src[i] === '}' && --depth === 0) {
75
+ inner.push(part);
76
+ part = '';
77
+ i++;
78
+ continue;
79
+ }
80
+ part += src[i];
81
+ }
82
+ i++;
83
+ }
84
+ i++;
85
+ out.push({ kind: 'str', text: '' });
86
+ for (const code of inner) {
87
+ out.push({ kind: 'punct', text: '(' });
88
+ out.push(...tokenize(code));
89
+ out.push({ kind: 'punct', text: ')' });
90
+ }
91
+ } else if (ch === '/' && regexAllowed()) {
92
+ i++;
93
+ let inClass = false;
94
+ while (i < n && (src[i] !== '/' || inClass)) {
95
+ if (src[i] === '\\') i++;
96
+ else if (src[i] === '[') inClass = true;
97
+ else if (src[i] === ']') inClass = false;
98
+ i++;
99
+ }
100
+ i++;
101
+ while (i < n && /[a-z]/i.test(src[i]!)) i++;
102
+ out.push({ kind: 'str', text: '' });
103
+ } else if (/[A-Za-z_$]/.test(ch)) {
104
+ let j = i + 1;
105
+ while (j < n && /[\w$]/.test(src[j]!)) j++;
106
+ out.push({ kind: 'id', text: src.slice(i, j) });
107
+ i = j;
108
+ } else if (/[0-9]/.test(ch) || (ch === '.' && /[0-9]/.test(src[i + 1] ?? ''))) {
109
+ let j = i + 1;
110
+ while (j < n && /[\w.]/.test(src[j]!)) j++;
111
+ out.push({ kind: 'num', text: src.slice(i, j) });
112
+ i = j;
113
+ } else {
114
+ const three = src.slice(i, i + 4);
115
+ const op = ['>>>=', '...', '===', '!==', '**=', '<<=', '>>=', '&&=', '||=', '??=', '>>>', '=>', '==', '!=', '<=', '>=',
116
+ '&&', '||', '??', '?.', '++', '--', '+=', '-=', '*=', '/=', '%=', '&=', '|=', '^=', '**', '<<', '>>']
117
+ .find((o) => three.startsWith(o));
118
+ const text = op ?? ch;
119
+ out.push({ kind: 'punct', text });
120
+ i += text.length;
121
+ }
122
+ }
123
+ return out;
124
+ }
125
+
126
+ const ASSIGN = new Set(['=', '+=', '-=', '*=', '/=', '%=', '**=', '<<=', '>>=', '>>>=', '&=', '|=', '^=', '&&=', '||=', '??=']);
127
+
128
+ /** Names declared inside the tokens: let / const / var / function / class / catch, and parameters of functions. */
129
+ function declaredNames(t: Token[]): Set<string> {
130
+ const names = new Set<string>();
131
+ const addUntil = (start: number, stop: (tok: Token, depth: number) => boolean): void => {
132
+ let depth = 0;
133
+ for (let k = start; k < t.length; k++) {
134
+ const tok = t[k]!;
135
+ if (tok.kind === 'punct' && ['(', '[', '{'].includes(tok.text)) depth++;
136
+ if (tok.kind === 'punct' && [')', ']', '}'].includes(tok.text)) {
137
+ if (depth === 0) return;
138
+ depth--;
139
+ }
140
+ if (stop(tok, depth)) return;
141
+ // a default value or a computed key is not a name: skip to the next , at this depth
142
+ if (tok.kind === 'id' && !KEYWORDS.has(tok.text) && t[k - 1]?.text !== '.' && t[k + 1]?.text !== ':') names.add(tok.text);
143
+ }
144
+ };
145
+ for (let k = 0; k < t.length; k++) {
146
+ const tok = t[k]!;
147
+ if (tok.kind !== 'id') continue;
148
+ if (tok.text === 'let' || tok.text === 'const' || tok.text === 'var') {
149
+ // up to the end of the declaration: an = at depth 0 ends a name, a , starts the next one
150
+ let depth = 0;
151
+ let naming = true;
152
+ for (let j = k + 1; j < t.length; j++) {
153
+ const x = t[j]!;
154
+ if (x.kind === 'punct' && ['(', '[', '{'].includes(x.text)) depth++;
155
+ else if (x.kind === 'punct' && [')', ']', '}'].includes(x.text)) {
156
+ if (depth === 0) break;
157
+ depth--;
158
+ } else if (depth === 0 && x.text === ';') break;
159
+ else if (depth === 0 && x.text === '=') naming = false;
160
+ else if (depth === 0 && x.text === ',') naming = true;
161
+ else if (depth === 0 && (x.text === 'of' || x.text === 'in')) break;
162
+ if (naming && x.kind === 'id' && !KEYWORDS.has(x.text) && t[j + 1]?.text !== ':') names.add(x.text);
163
+ if (!naming && depth === 0 && x.kind === 'punct' && x.text === '=>' ) break;
164
+ }
165
+ } else if ((tok.text === 'function' || tok.text === 'class') && t[k + 1]?.kind === 'id') {
166
+ names.add(t[k + 1]!.text);
167
+ } else if (tok.text === 'catch' && t[k + 1]?.text === '(') {
168
+ addUntil(k + 2, () => false);
169
+ }
170
+ }
171
+ // parameters: ( ... ) => or function name ( ... ), and a single name before =>
172
+ for (let k = 0; k < t.length; k++) {
173
+ const tok = t[k]!;
174
+ if (tok.text === '=>' && t[k - 1]?.kind === 'id') names.add(t[k - 1]!.text);
175
+ if (tok.text === '=>' && t[k - 1]?.text === ')') {
176
+ let depth = 0;
177
+ let j = k - 1;
178
+ for (; j >= 0; j--) {
179
+ if (t[j]!.text === ')') depth++;
180
+ else if (t[j]!.text === '(' && --depth === 0) break;
181
+ }
182
+ addUntil(j + 1, () => false);
183
+ }
184
+ if (tok.text === 'function') {
185
+ let j = k + 1;
186
+ if (t[j]?.kind === 'id') j++;
187
+ if (t[j]?.text === '(') addUntil(j + 1, () => false);
188
+ }
189
+ }
190
+ return names;
191
+ }
192
+
193
+ /** The names outside the function source `src` that it assigns or changes (empty: none found). */
194
+ export function outerWrites(src: string): string[] {
195
+ const t = tokenize(src);
196
+ const inside = declaredNames(t);
197
+ const found = new Set<string>();
198
+ for (let k = 0; k < t.length; k++) {
199
+ const tok = t[k]!;
200
+ if (tok.kind !== 'id' || KEYWORDS.has(tok.text) || inside.has(tok.text)) continue;
201
+ const before = t[k - 1];
202
+ if (before && (before.text === '.' || before.text === '?.')) continue; // a member, not a root name
203
+ if (t[k + 1]?.text === ':' && (before?.text === '{' || before?.text === ',')) continue; // an object key
204
+ // the member chain after the name: .a.b / [x] / ?.a
205
+ let j = k + 1;
206
+ let members = 0;
207
+ let firstMember = '';
208
+ let lastMember = '';
209
+ const memberList: string[] = [];
210
+ while (j < t.length) {
211
+ if ((t[j]!.text === '.' || t[j]!.text === '?.') && t[j + 1]?.kind === 'id') {
212
+ lastMember = t[j + 1]!.text;
213
+ memberList.push(lastMember);
214
+ if (members === 0) firstMember = lastMember;
215
+ j += 2;
216
+ members++;
217
+ } else if (t[j]!.text === '[') {
218
+ if (members === 0) firstMember = '[]';
219
+ let depth = 0;
220
+ for (; j < t.length; j++) {
221
+ if (t[j]!.text === '[') depth++;
222
+ else if (t[j]!.text === ']' && --depth === 0) break;
223
+ }
224
+ j++;
225
+ members++;
226
+ lastMember = '[]';
227
+ memberList.push('[]');
228
+ } else break;
229
+ }
230
+ const next = t[j];
231
+ // a call of a PineScript namespace (label.delete(l), array.push(zones, x); also through a module object of compiled
232
+ // code, script_1.label.delete(l)): not a change of the namespace; array / map / matrix functions change their first
233
+ // argument
234
+ const ns = members === 1 ? tok.text : members >= 2 ? memberList[members - 2]! : '';
235
+ if (next?.text === '(' && PINE_NAMESPACES.has(ns) && (members === 1 || members >= 2)) {
236
+ if (NAMESPACES.has(ns) && !READS.has(lastMember)) {
237
+ const arg = t[j + 1];
238
+ if (arg?.kind === 'id' && !inside.has(arg.text) && !KEYWORDS.has(arg.text)) {
239
+ const box = t[j + 2]?.text === '.' && t[j + 3]?.text === 'value';
240
+ if (!box) found.add(arg.text);
241
+ }
242
+ }
243
+ continue;
244
+ }
245
+ // the content of a persist() box (dir.value = 1, zones.value.push(x)) is put back by the runtime
246
+ if (firstMember === 'value') continue;
247
+ const written =
248
+ (next && ASSIGN.has(next.text)) ||
249
+ (next && (next.text === '++' || next.text === '--')) ||
250
+ before?.text === '++' ||
251
+ before?.text === '--' ||
252
+ (members > 0 && MUTATORS.has(lastMember) && next?.text === '(');
253
+ if (written) found.add(tok.text);
254
+ }
255
+ return [...found];
256
+ }
257
+
258
+ /** Namespaces of the PineScript API (their functions do not change the namespace object) */
259
+ const PINE_NAMESPACES = new Set([
260
+ 'array', 'matrix', 'map', 'label', 'line', 'box', 'table', 'polyline', 'linefill', 'chart', 'str', 'math', 'ta', 'color',
261
+ 'request', 'strategy', 'input', 'timeframe', 'syminfo', 'barstate', 'session', 'callsite', 'taCore', 'taStep',
262
+ 'compare', 'plot', 'time', 'text', 'ticker', 'runtime', 'log', 'alert', 'chartPoint',
263
+ ]);
264
+
265
+ /** PineScript namespaces whose functions change their first argument */
266
+ const NAMESPACES = new Set(['array', 'matrix', 'map']);
267
+
268
+ /** Functions of those namespaces that only read their first argument */
269
+ const READS = new Set([
270
+ 'get', 'size', 'includes', 'indexof', 'lastindexof', 'sum', 'avg', 'max', 'min', 'median', 'mode', 'stdev',
271
+ 'variance', 'range', 'first', 'last', 'slice', 'copy', 'join', 'every', 'some', 'abs', 'binary_search',
272
+ 'binary_search_leftmost', 'binary_search_rightmost', 'covariance', 'percentile_linear_interpolation',
273
+ 'percentile_nearest_rank', 'percentrank', 'standardize', 'sort_indices', 'from', 'new', 'new_float', 'new_int',
274
+ 'new_bool', 'new_string', 'new_color', 'new_line', 'new_label', 'new_box', 'new_table', 'new_linefill',
275
+ 'contains', 'keys', 'values', 'rows', 'columns', 'elements_count', 'row', 'col', 'det', 'inv', 'pinv', 'rank',
276
+ 'trace', 'transpose', 'mult', 'diff', 'pow', 'eigenvalues', 'eigenvectors', 'kron', 'is_square', 'is_zero',
277
+ 'is_binary', 'is_symmetric', 'is_antisymmetric', 'is_diagonal', 'is_antidiagonal', 'is_identity', 'is_triangular',
278
+ 'is_stochastic',
279
+ ]);
@@ -29,7 +29,9 @@ import type * as S from './index.js';
29
29
 
30
30
  declare global {
31
31
  const executeIntrabar: typeof S.executeIntrabar;
32
+ const createScriptRun: typeof S.createScriptRun;
32
33
  const varip: typeof S.varip;
34
+ const persist: typeof S.persist;
33
35
  const indicator: typeof S.indicator;
34
36
  const fixnan: typeof S.fixnan;
35
37
  const fill: typeof S.fill;
@@ -0,0 +1,246 @@
1
+ /**
2
+ * State of an incremental script run (#196, createScriptRun).
3
+ *
4
+ * A run executes the script body again on each update, but what the body creates (Series, ta.* calls, eachBar()
5
+ * blocks, plots, persist() boxes) is matched by creation order with the previous run, and keeps the values of the bars
6
+ * before the first bar to calculate (`from`, the forming bar of the previous run). Only the bars from `from` on are
7
+ * calculated:
8
+ * - a Series: its values before `from` are those of the previous run, the others are computed
9
+ * - a ta.* call with a {@link taStep} machine: the machine holds the state of the last confirmed bar and steps the newest
10
+ * bars only
11
+ * - an eachBar() block: its callback runs from `from` on, its persist() boxes and history buffers put back to their
12
+ * state at the end of the last confirmed bar
13
+ * - a plot: the points of the bars before `from` are kept
14
+ *
15
+ * A feature that is not resumed (drawings, other symbols, strategies, varip, values that depend on the bar count)
16
+ * calls {@link nonIncremental}: a recorded (full) run marks the run so that the next updates are full runs, a resumed
17
+ * run stops ({@link ResumeAborted}) and the host runs it in full.
18
+ *
19
+ * @internal
20
+ */
21
+ import { Series, setSeriesRunHooks, type SeriesRunHooks } from '../runtime/series.js';
22
+ import type { Bar } from '../types/index.js';
23
+ import type { BarStep } from '../ta/step.js';
24
+ import { isDrawingObject, setDrawingRunHooks, type DrawingCheckpoint, type DrawingKind, type DrawingRunHooks } from '../drawing/registry.js';
25
+
26
+ /** A resumed run met a feature it does not resume: the update is calculated by a full run. */
27
+ export class ResumeAborted extends Error {
28
+ constructor(readonly reason: string) {
29
+ super(`incremental run stopped: ${reason}`);
30
+ }
31
+ }
32
+
33
+ /** History buffer state of one source of an eachBar() block (RE10008). */
34
+ export interface BufferState {
35
+ size: number;
36
+ previous: number;
37
+ barMax: number;
38
+ }
39
+
40
+ /** State of an eachBar() block at the end of the last confirmed bar. */
41
+ export interface BlockCheckpoint {
42
+ /** Values of the persist() boxes the block owns, by box slot */
43
+ boxes: Map<number, unknown>;
44
+ /** History buffers by source key (Series slot, or the Series of the chart) */
45
+ buffers: Map<unknown, BufferState>;
46
+ pendingError: { bar: number; barsBack: number } | null;
47
+ /** The drawing registry and its objects (the block that draws puts it back) */
48
+ drawings: DrawingCheckpoint | null;
49
+ /** State the block keeps besides the script's (the strategy engine of strategy.eachBar()) */
50
+ extra?: unknown;
51
+ }
52
+
53
+ export interface BlockMemory {
54
+ out: number[];
55
+ checkpoint: BlockCheckpoint;
56
+ }
57
+
58
+ /** A ta.* call with a machine: its machines (state of the last confirmed bar) and output values. */
59
+ export interface TaMemory {
60
+ kind: string;
61
+ machine: BarStep<unknown[], unknown>;
62
+ outs: number[][];
63
+ }
64
+
65
+ /** A plot's points and, for each bar j, the number of points before it. */
66
+ export interface PlotMemory {
67
+ data: Array<{ time: number; value: number; color?: string }>;
68
+ pos: number[];
69
+ /** Offset and colour kind of the plot: the points are kept only for the same */
70
+ sig: string;
71
+ }
72
+
73
+ /** What a run keeps for the next update. */
74
+ export interface RunMemory {
75
+ /** Bars of that run */
76
+ n: number;
77
+ /** Values of the Series the script created, by slot */
78
+ series: Array<number[] | undefined>;
79
+ /** Values of the Series that live across runs (the chart's open, close, bar_index...) */
80
+ kept: WeakMap<Series, number[]>;
81
+ ta: Array<TaMemory | undefined>;
82
+ blocks: Array<BlockMemory | undefined>;
83
+ plots: Array<PlotMemory | undefined>;
84
+ /** Block slot that owns each persist() box */
85
+ boxOwner: Array<number | undefined>;
86
+ /** Drawing objects created in the script body (outside the callbacks), by creation order */
87
+ bodyDrawings: Array<{ kind: DrawingKind; obj: object } | undefined>;
88
+ /** The eachBar() block that uses the drawings (one per script), undefined when none */
89
+ drawingBlock: number | undefined;
90
+ }
91
+
92
+ export function emptyMemory(n: number): RunMemory {
93
+ return { n, series: [], kept: new WeakMap(), ta: [], blocks: [], plots: [], boxOwner: [], bodyDrawings: [], drawingBlock: undefined };
94
+ }
95
+
96
+ export interface ActiveRun {
97
+ mode: 'record' | 'resume';
98
+ /** First bar calculated (0 when recording) */
99
+ from: number;
100
+ bars: readonly Bar[];
101
+ prev: RunMemory | null;
102
+ next: RunMemory;
103
+ seriesSlot: number;
104
+ taSlot: number;
105
+ blockSlot: number;
106
+ plotSlot: number;
107
+ boxSlot: number;
108
+ drawSlot: number;
109
+ /** The eachBar() block running (its slot), -1 outside */
110
+ block: number;
111
+ /** Getters and setters of the persist() boxes of this run, by slot */
112
+ boxes: Array<{ get(): unknown; set(v: unknown): void }>;
113
+ /** Why the next updates are full runs (null: they can be resumed) */
114
+ blocked: string | null;
115
+ }
116
+
117
+ /** The incremental run being executed (null outside createScriptRun or in a plain executeScript). */
118
+ export let active: ActiveRun | null = null;
119
+
120
+ const SLOT = Symbol('series slot');
121
+
122
+ /** Slot of a Series created by the script in this run, or undefined (a chart Series, or one made inside eachBar) */
123
+ export function slotOf(series: Series): number | undefined {
124
+ return (series as unknown as Record<symbol, number | undefined>)[SLOT];
125
+ }
126
+
127
+ const hooks: SeriesRunHooks = {
128
+ created(series) {
129
+ const run = active;
130
+ // A Series made in an eachBar() callback is made again on each bar: it is not matched with the previous run.
131
+ if (!run || run.block >= 0) return;
132
+ (series as unknown as Record<symbol, number>)[SLOT] = run.seriesSlot++;
133
+ },
134
+ prefix(series, bars) {
135
+ const run = active;
136
+ if (!run || run.mode !== 'resume' || bars !== run.bars || !run.prev) return null;
137
+ const slot = slotOf(series);
138
+ const values = slot !== undefined ? run.prev.series[slot] : run.prev.kept.get(series);
139
+ return values && values.length >= run.from ? { values, from: run.from } : null;
140
+ },
141
+ computed(series, values) {
142
+ const run = active;
143
+ if (!run || run.block >= 0) return;
144
+ const slot = slotOf(series);
145
+ if (slot !== undefined) run.next.series[slot] = values;
146
+ else run.next.kept.set(series, values);
147
+ },
148
+ };
149
+
150
+ /**
151
+ * Drawings in an incremental run: one eachBar() block uses them (its checkpoint holds the registry and the state of
152
+ * the objects); the objects created in the script body before the blocks are the same objects on each run (matched by
153
+ * creation order), set again to their new state. Drawings used by two blocks, or in the body after a block, are not
154
+ * resumed.
155
+ */
156
+ const drawingHooks: DrawingRunHooks = {
157
+ access() {
158
+ const run = active;
159
+ if (!run) return;
160
+ if (run.block < 0) {
161
+ if (run.blockSlot > 0) nonIncremental('drawings in the script body after an eachBar() block');
162
+ return;
163
+ }
164
+ if (run.next.drawingBlock === undefined) run.next.drawingBlock = run.block;
165
+ else if (run.next.drawingBlock !== run.block) nonIncremental('drawings in two eachBar() blocks');
166
+ },
167
+ reuse(kind, obj) {
168
+ const run = active;
169
+ if (!run || run.block >= 0) return null;
170
+ const slot = run.drawSlot++;
171
+ if (run.mode === 'record') {
172
+ run.next.bodyDrawings[slot] = { kind, obj };
173
+ return null;
174
+ }
175
+ const old = run.prev?.bodyDrawings[slot];
176
+ if (!old || old.kind !== kind) nonIncremental('a new drawing in the script body');
177
+ run.next.bodyDrawings[slot] = old;
178
+ return old!.obj;
179
+ },
180
+ };
181
+
182
+ /** Starts an incremental run (the script body runs next); returns the run to give to {@link endRun}. */
183
+ export function beginRun(run: ActiveRun): ActiveRun | null {
184
+ const outer = active;
185
+ active = run;
186
+ setSeriesRunHooks(hooks);
187
+ setDrawingRunHooks(drawingHooks);
188
+ return outer;
189
+ }
190
+
191
+ /** Ends the run started by {@link beginRun}, putting back the outer one (a nested run) or none. */
192
+ export function endRun(outer: ActiveRun | null): void {
193
+ active = outer;
194
+ setSeriesRunHooks(outer ? hooks : null);
195
+ setDrawingRunHooks(outer ? drawingHooks : null);
196
+ }
197
+
198
+ /** The script body has run: the run builds its outputs (they read the drawings without being part of the script). */
199
+ export function bodyDone(): void {
200
+ setDrawingRunHooks(null);
201
+ }
202
+
203
+ /** No incremental run inside (a nested executeScript, e.g. other symbols): the outer one is put back by endRun(). */
204
+ export function suspendRun(): ActiveRun | null {
205
+ const outer = active;
206
+ active = null;
207
+ setSeriesRunHooks(null);
208
+ setDrawingRunHooks(null);
209
+ return outer;
210
+ }
211
+
212
+ /**
213
+ * A copy of a persist() value for a checkpoint: the forming bar may change an array or an object in place after it was
214
+ * taken. Plain data is copied (structuredClone); a value that cannot be copied (a function, a class instance such as
215
+ * a drawing) is kept as it is and marks the run as not resumable.
216
+ */
217
+ export function copyValue(value: unknown): unknown {
218
+ // a drawing object is shared: the checkpoint of the registry puts its state back
219
+ if (isDrawingObject(value)) return value;
220
+ if (value === null || typeof value !== 'object') {
221
+ if (typeof value === 'function') nonIncremental('a function in persist()');
222
+ return value;
223
+ }
224
+ if (Array.isArray(value)) return value.map(copyValue);
225
+ if (value instanceof Map) return new Map([...value].map(([k, v]) => [copyValue(k), copyValue(v)]));
226
+ if (value instanceof Set) return new Set([...value].map(copyValue));
227
+ const proto = Object.getPrototypeOf(value);
228
+ if (proto !== Object.prototype && proto !== null) {
229
+ nonIncremental('a class instance in persist()');
230
+ return value;
231
+ }
232
+ const out: Record<string, unknown> = {};
233
+ for (const [k, v] of Object.entries(value)) out[k] = copyValue(v);
234
+ return out;
235
+ }
236
+
237
+ /**
238
+ * A feature an incremental run does not resume: a recorded run keeps its result (it is a full run) and marks the next
239
+ * updates as full runs; a resumed run stops.
240
+ */
241
+ export function nonIncremental(reason: string): void {
242
+ const run = active;
243
+ if (!run) return;
244
+ if (run.mode === 'resume') throw new ResumeAborted(reason);
245
+ run.blocked ??= reason;
246
+ }