pine2profit 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +243 -2
  2. package/build/.gitkeep +0 -0
  3. package/build/index.cjs +1152 -0
  4. package/build/index.mjs +1142 -0
  5. package/build/modules/frontend/build/.nojekyll +0 -0
  6. package/build/modules/frontend/build/404/index.html +1 -0
  7. package/build/modules/frontend/build/404.html +1 -0
  8. package/build/modules/frontend/build/_next/static/chunks/11.78c5bec5897e1148.js +1 -0
  9. package/build/modules/frontend/build/_next/static/chunks/195.64632be71175c993.js +63 -0
  10. package/build/modules/frontend/build/_next/static/chunks/204.008bcbcf48844ee2.js +1 -0
  11. package/build/modules/frontend/build/_next/static/chunks/255-da04dc9178303a31.js +1 -0
  12. package/build/modules/frontend/build/_next/static/chunks/2738385b.306f7750ad5b8be4.js +372 -0
  13. package/build/modules/frontend/build/_next/static/chunks/338-31711140cb6d61e5.js +1 -0
  14. package/build/modules/frontend/build/_next/static/chunks/4bd1b696-c023c6e3521b1417.js +1 -0
  15. package/build/modules/frontend/build/_next/static/chunks/50e49f97.75feacc2b3cc7709.js +433 -0
  16. package/build/modules/frontend/build/_next/static/chunks/554.dd4ac9a0aff9b782.js +1 -0
  17. package/build/modules/frontend/build/_next/static/chunks/570-33c81efca66c4bc9.js +3 -0
  18. package/build/modules/frontend/build/_next/static/chunks/5957d0c3.7b96612772854e2d.js +2 -0
  19. package/build/modules/frontend/build/_next/static/chunks/619-f09bc47e24909021.js +1 -0
  20. package/build/modules/frontend/build/_next/static/chunks/7589b812.60f2b16513f3aa42.js +1 -0
  21. package/build/modules/frontend/build/_next/static/chunks/771.5c62ba94f930669e.js +1 -0
  22. package/build/modules/frontend/build/_next/static/chunks/796.4b04b2b64c066b03.js +1 -0
  23. package/build/modules/frontend/build/_next/static/chunks/897-b727cc7229802490.js +1 -0
  24. package/build/modules/frontend/build/_next/static/chunks/app/_not-found/page-b6d9300903c2ab41.js +1 -0
  25. package/build/modules/frontend/build/_next/static/chunks/app/layout-0da8bd54f47c9e1b.js +1 -0
  26. package/build/modules/frontend/build/_next/static/chunks/app/page-7ab911a70ef48cfe.js +1 -0
  27. package/build/modules/frontend/build/_next/static/chunks/app/run/page-42836fc705c46a59.js +1 -0
  28. package/build/modules/frontend/build/_next/static/chunks/c525c9ef.018edb9552a70fc2.js +143 -0
  29. package/build/modules/frontend/build/_next/static/chunks/e1865c21-8d63eb0f5b25cb0c.js +1 -0
  30. package/build/modules/frontend/build/_next/static/chunks/framework-28b60818f5cffd83.js +1 -0
  31. package/build/modules/frontend/build/_next/static/chunks/main-45ecedd1f28e3a74.js +1 -0
  32. package/build/modules/frontend/build/_next/static/chunks/main-app-4ff0bbe1b367fcb5.js +1 -0
  33. package/build/modules/frontend/build/_next/static/chunks/pages/_app-7d307437aca18ad4.js +1 -0
  34. package/build/modules/frontend/build/_next/static/chunks/pages/_error-cb2a52f75f2162e2.js +1 -0
  35. package/build/modules/frontend/build/_next/static/chunks/polyfills-42372ed130431b0a.js +1 -0
  36. package/build/modules/frontend/build/_next/static/chunks/webpack-bb5ccf34ea47f1d7.js +1 -0
  37. package/build/modules/frontend/build/_next/static/css/91363587ff8467b5.css +1 -0
  38. package/build/modules/frontend/build/_next/static/media/29b98dbfba401fa9-s.p.woff2 +0 -0
  39. package/build/modules/frontend/build/_next/static/media/313510e2713fb214-s.p.woff2 +0 -0
  40. package/build/modules/frontend/build/_next/static/media/558ca1a6aa3cb55e-s.p.woff2 +0 -0
  41. package/build/modules/frontend/build/_next/static/media/64d784ea54a4acde-s.woff2 +0 -0
  42. package/build/modules/frontend/build/_next/static/media/6d831b18ae5b01dc-s.woff2 +0 -0
  43. package/build/modules/frontend/build/_next/static/media/8048a25e80cc4179-s.woff2 +0 -0
  44. package/build/modules/frontend/build/_next/static/media/851c4691abdf3def-s.woff2 +0 -0
  45. package/build/modules/frontend/build/_next/static/media/87bc17f7c8b98e48-s.woff2 +0 -0
  46. package/build/modules/frontend/build/_next/static/media/982ceffe7b733b3b-s.p.woff2 +0 -0
  47. package/build/modules/frontend/build/_next/static/media/a6c19694cd327cd4-s.woff2 +0 -0
  48. package/build/modules/frontend/build/_next/static/media/a8a8dd7277bab4cf-s.woff2 +0 -0
  49. package/build/modules/frontend/build/_next/static/media/ac0e76ddaeeb7981-s.woff2 +0 -0
  50. package/build/modules/frontend/build/_next/static/media/b8bfb68ab9ab617c-s.woff2 +0 -0
  51. package/build/modules/frontend/build/_next/static/media/d76fe899475ae4d7-s.woff2 +0 -0
  52. package/build/modules/frontend/build/_next/static/media/e546cf32c9d4702c-s.woff2 +0 -0
  53. package/build/modules/frontend/build/_next/static/media/edc640959b0c7826-s.woff2 +0 -0
  54. package/build/modules/frontend/build/_next/static/media/ff71da380fbe67dd-s.woff2 +0 -0
  55. package/build/modules/frontend/build/_next/static/vHsenj52Jy0T31oXW8dJX/_buildManifest.js +1 -0
  56. package/build/modules/frontend/build/_next/static/vHsenj52Jy0T31oXW8dJX/_ssgManifest.js +1 -0
  57. package/build/modules/frontend/build/icon.svg +1 -0
  58. package/build/modules/frontend/build/index.html +1 -0
  59. package/build/modules/frontend/build/index.txt +23 -0
  60. package/build/modules/frontend/build/run/index.html +1 -0
  61. package/build/modules/frontend/build/run/index.txt +23 -0
  62. package/package.json +93 -4
  63. package/types.d.ts +124 -0
@@ -0,0 +1,1152 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ var functoolsKit = require('functools-kit');
5
+ var util = require('util');
6
+ var url = require('url');
7
+ var fs = require('fs');
8
+ var path = require('path');
9
+ var http = require('http');
10
+ var micro = require('micro');
11
+ var Router = require('router');
12
+ var finalhandler = require('finalhandler');
13
+ var serveHandler = require('serve-handler');
14
+ var mime = require('mime-types');
15
+ var promises = require('fs/promises');
16
+ var diKit = require('di-kit');
17
+ var readline = require('readline');
18
+ var module$1 = require('module');
19
+
20
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
21
+ const getArgs = functoolsKit.singleshot(() => {
22
+ const { values, positionals } = util.parseArgs({
23
+ args: process.argv.slice(2),
24
+ options: {
25
+ port: {
26
+ type: "string",
27
+ default: "",
28
+ },
29
+ host: {
30
+ type: "string",
31
+ default: "",
32
+ },
33
+ check: {
34
+ type: "boolean",
35
+ default: false,
36
+ },
37
+ help: {
38
+ type: "boolean",
39
+ default: false,
40
+ },
41
+ version: {
42
+ type: "boolean",
43
+ default: false,
44
+ },
45
+ },
46
+ strict: false,
47
+ allowPositionals: true,
48
+ });
49
+ return {
50
+ values,
51
+ positionals,
52
+ };
53
+ });
54
+
55
+ /** True when this bundle is the script node was started with (bin / `node build/index.mjs`), not an import. */
56
+ const getEntry = (metaUrl) => {
57
+ if (!process.argv[1]) {
58
+ return false;
59
+ }
60
+ try {
61
+ const metaPath = url.fileURLToPath(metaUrl);
62
+ const realArgv = fs.realpathSync(process.argv[1]);
63
+ return path.resolve(realArgv) === path.resolve(metaPath);
64
+ }
65
+ catch {
66
+ return false;
67
+ }
68
+ };
69
+
70
+ const HELP_TEXT = `
71
+ Usage:
72
+ npx pine2profit <dir> [flags]
73
+
74
+ <dir> Folder that contains data/ (required)
75
+
76
+ Flags:
77
+
78
+ --port <number> HTTP port (default: CC_WWWROOT_PORT or 60050)
79
+ --host <string> Bind address (default: CC_WWWROOT_HOST or 0.0.0.0)
80
+ --check Validate <dir>/data and exit: 0 when there are no errors, 1 otherwise.
81
+ The server is not started. The same check runs before every start.
82
+ --help Print this help message
83
+ --version Print the version
84
+
85
+ What the server does:
86
+
87
+ GET / The dashboard bundled with this package (modules/frontend, static export)
88
+ GET /data/<file> <dir>/data/<file> as is, Cache-Control: no-store, 404 when the file is missing
89
+
90
+ Nothing else: no API, no POST. The site on GitHub Pages makes exactly the same requests
91
+ for the same relative paths, so a data folder that works here works there unchanged.
92
+
93
+ The data folder (<dir>/data/), flat, no subfolders:
94
+
95
+ index_1.jsonl, index_2.jsonl, ... The list: one JSON object per line, about 1000 lines per file
96
+ <id>_messages.json The agent's text for one script
97
+ <id>_candles.json Bars, trades and equity for the chart
98
+ <id>_pinescript.json The author's script and the trade rule (optional)
99
+
100
+ <id> is a slug matching [a-z0-9-]+ and every file of that script starts with it.
101
+
102
+ index_N.jsonl (one line per script):
103
+
104
+ The site reads index_1, then index_2, ... and stops at the first 404. A later line with the
105
+ same "id" replaces the earlier one, so append updates to the last file instead of rewriting
106
+ old ones. Required: id, title, kind, verdict, updated. Leave a field out when it is null.
107
+ Dollars are integers on a notional $10,000 account.
108
+
109
+ {
110
+ "id": string, slug, prefix of the other files of this script
111
+ "title": string,
112
+ "kind": "indicator" | "strategy",
113
+ "subcategory": string, optional; any key — the list builds its filter chips from the
114
+ values it sees. Keys with a label on the site:
115
+ indicator: trend oscillator volatility volume structure signals
116
+ strategy: trend-following mean-reversion breakout grid-dca
117
+ pattern-event composite
118
+ "usable": boolean, optional; false = no signal is final at bar close: the page says
119
+ "not tradeable", shows no rule and no money numbers
120
+ "verdict": "YES" | "NO" | "UNKNOWN",
121
+ "main": number, optional; 12 months via alerts, $
122
+ "paper": number, optional; paper journal since cycleStart, $
123
+ "paperTrades": number, optional
124
+ "expected": [number, number], optional; expected per month on $10,000: [low, high]
125
+ "iterations": number, optional (default 1)
126
+ "updated": "YYYY-MM-DD",
127
+ "market": string, optional; "BTCUSDT"
128
+ "timeframe": string, optional; "1h"
129
+ "license": string, optional
130
+ "author": string, optional
131
+ "tvUrl": string, optional; link under the author's name
132
+ "cycleStart": "YYYY-MM-DD", optional; drawn on the chart and on the P&L line
133
+ "percentile": number, optional; the rule's percentile against random entries
134
+ "reason": string optional; one sentence under the verdict
135
+ }
136
+
137
+ Example line (one line in the file, no line breaks inside):
138
+
139
+ {"id":"sma-cross-20-50","title":"SMA Cross 20/50","kind":"strategy","subcategory":"trend-following","verdict":"NO","main":-2465,"paper":461,"paperTrades":3,"expected":[-599,181],"iterations":3,"updated":"2026-11-26","market":"BTCUSDT","timeframe":"1h","license":"MPL-2.0","author":"example_author","tvUrl":"https://www.tradingview.com/script/EXAMPLE02/","cycleStart":"2026-11-12","percentile":59,"reason":"12 months −$2,465; only 4/10 markets positive; not better than random entries (59th percentile)"}
140
+
141
+ A script that is not tradeable:
142
+
143
+ {"id":"volume-pressure","title":"Volume Pressure Delta","kind":"indicator","subcategory":"volume","usable":false,"verdict":"NO","iterations":1,"updated":"2026-11-26","market":"BTCUSDT","timeframe":"1h","reason":"not tradeable: the signal depends on realtime tick data (varip)"}
144
+
145
+ <id>_messages.json:
146
+
147
+ {
148
+ "head": { the same fields as this script's line in index_N.jsonl, same values;
149
+ "id": string, the page reads the header from here when opened by a direct link
150
+ "title": string, /run/?id=<id> without going through the list
151
+ "kind": "indicator" | "strategy",
152
+ "subcategory": string, optional
153
+ "usable": boolean, optional
154
+ "verdict": "YES" | "NO" | "UNKNOWN",
155
+ "main": number, optional
156
+ "paper": number, optional
157
+ "paperTrades": number, optional
158
+ "expected": [number, number], optional
159
+ "iterations": number, optional
160
+ "updated": "YYYY-MM-DD",
161
+ "market": string, optional
162
+ "timeframe": string, optional
163
+ "license": string, optional
164
+ "author": string, optional
165
+ "tvUrl": string, optional
166
+ "cycleStart": "YYYY-MM-DD", optional
167
+ "percentile": number, optional
168
+ "reason": string optional
169
+ },
170
+ "groups": [ { "code": string, "title": string } ], the left navigation, in this order
171
+ "messages": [
172
+ {
173
+ "code": string, optional; "A0", "C7", "E1", "RISK2" — shown on the block and in the navigation
174
+ "group": string, optional; navigation group; default: the leading letters of "code"
175
+ "title": string,
176
+ "md": string, markdown
177
+ "iteration": number, optional; messages with the same value in a row form a dated section
178
+ "date": "YYYY-MM-DD" optional; shown next to the section title
179
+ }
180
+ ]
181
+ }
182
+
183
+ Messages render in file order, nothing is deduplicated: put in the file what the page should show.
184
+ A message belongs to the group whose code equals its "group", or the leading letters of its "code"
185
+ (A0 -> A, RISK2 -> RISK). A group that appears in messages but not in "groups" shows its code as
186
+ the title; a group without messages is dropped. Inside a group the navigation items are the message
187
+ codes, or the iteration numbers when every message of the group carries "iteration". Messages
188
+ without "iteration" go under "Analysis".
189
+
190
+ Chart references inside "md" become buttons that frame the chart:
191
+
192
+ [[t:2026-11-12T14:00Z]] a bar
193
+ [[t:2026-11-12T14:00Z@41820]] a bar and a price
194
+ [[range:2026-11-01T00:00Z..2026-11-08T00:00Z]] a segment, both edges marked
195
+ [[trade:12]] a trade from <id>_candles.json
196
+ [see the breakout](ref:range:2026-11-01T00:00Z..2026-11-08T00:00Z) the same, as a link
197
+
198
+ Example:
199
+
200
+ {
201
+ "head": {"id":"sma-cross-20-50","title":"SMA Cross 20/50","kind":"strategy","subcategory":"trend-following","verdict":"NO","main":-2465,"paper":461,"paperTrades":3,"expected":[-599,181],"iterations":3,"updated":"2026-11-26","market":"BTCUSDT","timeframe":"1h","cycleStart":"2026-11-12","percentile":59,"reason":"12 months −$2,465; not better than random entries"},
202
+ "groups": [
203
+ { "code": "A", "title": "What it is" },
204
+ { "code": "C", "title": "Money" },
205
+ { "code": "E", "title": "Iterations" }
206
+ ],
207
+ "messages": [
208
+ { "code": "A0", "title": "How to run it", "md": "Run it on **1h**. A typical trade: [[trade:137]]." },
209
+ { "code": "C2", "title": "The last 12 months", "md": "Window [[range:2025-11-12T00:00Z..2026-11-12T00:00Z]]: 97 trades, -$2,465." },
210
+ { "code": "E1", "title": "What happened since the previous iteration?", "md": "Three paper trades, +$461.", "iteration": 3, "date": "2026-11-26" },
211
+ { "code": "E1", "title": "What happened since the previous iteration?", "md": "First week on paper.", "iteration": 2, "date": "2026-11-19" }
212
+ ]
213
+ }
214
+
215
+ <id>_candles.json:
216
+
217
+ {
218
+ "timeframe": string, optional; "1h" (falls back to the index line)
219
+ "bars": [ { "time": ms, "open": number, "high": number, "low": number, "close": number, "volume": number } ],
220
+ "trades": [ { "id": number, "side": "long" | "short", "open_time": ms, "open_price": number,
221
+ "close_time": ms | null, "close_price": number | null, "pnl_usd": number } ], optional
222
+ "equity": [ { "time": ms, "backtest_usd": number | null, "paper_usd": number | null } ] optional
223
+ }
224
+
225
+ "bars" feed the chart; "trades" label and frame [[trade:N]]; "equity" draws the P&L line
226
+ (no line without it). No file at all: "no candles for this script", the text still renders.
227
+
228
+ Example:
229
+
230
+ {
231
+ "timeframe": "1h",
232
+ "bars": [
233
+ { "time": 1732665600000, "open": 62000, "high": 62000, "low": 61498.5, "close": 61498.5, "volume": 377 },
234
+ { "time": 1732669200000, "open": 61498.5, "high": 61553.9, "low": 61201.0, "close": 61340.2, "volume": 412 }
235
+ ],
236
+ "trades": [
237
+ { "id": 1, "side": "long", "open_time": 1732928400000, "open_price": 61642.5, "close_time": 1732996800000, "close_price": 60510.8, "pnl_usd": -195.58 }
238
+ ],
239
+ "equity": [
240
+ { "time": 1732665600000, "backtest_usd": 0, "paper_usd": null },
241
+ { "time": 1732996800000, "backtest_usd": -195.58, "paper_usd": null }
242
+ ]
243
+ }
244
+
245
+ <id>_pinescript.json (optional):
246
+
247
+ {
248
+ "source": string, the author's script: shown read-only and run on the chart
249
+ "rule": string optional; the agent's trade rule as a Pine strategy() — its fills
250
+ become the trade markers on the chart
251
+ }
252
+
253
+ No file: no code panel. No "rule": the chart runs the author's script only.
254
+
255
+ Example:
256
+
257
+ {
258
+ "source": "//@version=5\\nindicator(\\"EMA Ribbon\\", overlay=true)\\nplot(ta.ema(close, 20))\\nplot(ta.ema(close, 50))",
259
+ "rule": "//@version=5\\nstrategy(\\"EMA Ribbon rule\\", overlay=true, initial_capital=10000)\\nif ta.crossover(ta.ema(close, 20), ta.ema(close, 50))\\n strategy.entry(\\"Long\\", strategy.long)\\nif ta.crossunder(ta.ema(close, 20), ta.ema(close, 50))\\n strategy.close(\\"Long\\")"
260
+ }
261
+
262
+ Startup check:
263
+
264
+ Before listening, the folder is validated. A single error refuses to start (exit code 1);
265
+ warnings are printed and the server starts anyway. \`npx pine2profit <dir> --check\` runs the
266
+ same validation and exits without starting the server, for the agent to call after every
267
+ write. What is checked:
268
+
269
+ data/ exists; index_1.jsonl exists (an empty file is fine); index files are numbered without gaps
270
+ every index line is JSON with the fields above: required ones present, types and values right,
271
+ no unknown fields (a typo such as "tv_url" is reported together with the right name)
272
+ every script in the index has <id>_messages.json and <id>_candles.json; <id>_pinescript.json is optional
273
+ <id>_messages.json: "head" equals the index line, "groups" and "messages" have the right shape,
274
+ every [[t:...]], [[range:...]], [[trade:N]] and (ref:...) points at a real date, range or trade
275
+ <id>_candles.json: "bars" not empty and numeric with growing time and high >= low, trade ids unique
276
+ warnings only: files for ids that are not in the index, files the site never reads, a missing "head"
277
+
278
+ A minimal data folder:
279
+
280
+ <dir>/data/index_1.jsonl
281
+ <dir>/data/sma-cross-20-50_messages.json
282
+ <dir>/data/sma-cross-20-50_candles.json
283
+ <dir>/data/sma-cross-20-50_pinescript.json
284
+
285
+ Environment variables:
286
+
287
+ CC_WWWROOT_HOST Bind address (default: 0.0.0.0)
288
+ CC_WWWROOT_PORT Port (default: 60050)
289
+ CC_DATA_PATH Folder that contains data/ for serve() called from code without a path;
290
+ the CLI always takes <dir> from the command line
291
+
292
+ Examples:
293
+
294
+ npx pine2profit .
295
+ npx pine2profit . --check
296
+ npx pine2profit ./project --port 8080
297
+ npx pine2profit /var/agent/project --host 127.0.0.1 --port 60050
298
+ `.trimStart();
299
+ const main$1 = () => {
300
+ if (!getEntry((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)))) {
301
+ return;
302
+ }
303
+ const { values } = getArgs();
304
+ if (!values.help) {
305
+ return;
306
+ }
307
+ process.stdout.write(`pine2profit ${"0.1.0"}\n\n`);
308
+ process.stdout.write(HELP_TEXT);
309
+ process.exit(0);
310
+ };
311
+ main$1();
312
+
313
+ const GLOBAL_CONFIG = {
314
+ CC_WWWROOT_PATH: "",
315
+ CC_WWWROOT_HOST: "",
316
+ CC_WWWROOT_PORT: 0,
317
+ CC_DATA_PATH: "",
318
+ };
319
+ Object.freeze({ ...GLOBAL_CONFIG });
320
+ const getConfig = () => {
321
+ const config = {
322
+ CC_WWWROOT_PATH: process.env.CC_WWWROOT_PATH || "",
323
+ CC_WWWROOT_HOST: process.env.CC_WWWROOT_HOST || "0.0.0.0",
324
+ CC_WWWROOT_PORT: parseInt(process.env.CC_WWWROOT_PORT) || 60050,
325
+ CC_DATA_PATH: process.env.CC_DATA_PATH || "",
326
+ };
327
+ if (GLOBAL_CONFIG.CC_WWWROOT_PATH) {
328
+ config.CC_WWWROOT_PATH = GLOBAL_CONFIG.CC_WWWROOT_PATH;
329
+ }
330
+ if (GLOBAL_CONFIG.CC_WWWROOT_HOST) {
331
+ config.CC_WWWROOT_HOST = GLOBAL_CONFIG.CC_WWWROOT_HOST;
332
+ }
333
+ if (GLOBAL_CONFIG.CC_WWWROOT_PORT) {
334
+ config.CC_WWWROOT_PORT = GLOBAL_CONFIG.CC_WWWROOT_PORT;
335
+ }
336
+ if (GLOBAL_CONFIG.CC_DATA_PATH) {
337
+ config.CC_DATA_PATH = GLOBAL_CONFIG.CC_DATA_PATH;
338
+ }
339
+ return config;
340
+ };
341
+ const setConfig = (config) => {
342
+ Object.assign(GLOBAL_CONFIG, config);
343
+ };
344
+
345
+ /** Project root passed to serve(); data files are served from <root>/data. */
346
+ const serveSubject = new functoolsKit.BehaviorSubject();
347
+
348
+ const NOOP_LOGGER = {
349
+ log() {
350
+ },
351
+ debug() {
352
+ },
353
+ info() {
354
+ },
355
+ warn() {
356
+ },
357
+ };
358
+ /** A failing custom logger is reported once per call on stderr and never escapes into the caller. */
359
+ const guard = (fn) => {
360
+ try {
361
+ fn();
362
+ }
363
+ catch (error) {
364
+ console.error("pine2profit logger failed:", error);
365
+ }
366
+ };
367
+ class LoggerService {
368
+ constructor() {
369
+ this._commonLogger = NOOP_LOGGER;
370
+ this.log = (topic, ...args) => {
371
+ guard(() => this._commonLogger.log(topic, ...args));
372
+ };
373
+ this.debug = (topic, ...args) => {
374
+ guard(() => this._commonLogger.debug(topic, ...args));
375
+ };
376
+ this.info = (topic, ...args) => {
377
+ guard(() => this._commonLogger.info(topic, ...args));
378
+ };
379
+ this.warn = (topic, ...args) => {
380
+ guard(() => this._commonLogger.warn(topic, ...args));
381
+ };
382
+ this.setLogger = (logger) => {
383
+ this._commonLogger = logger;
384
+ };
385
+ }
386
+ }
387
+
388
+ const { provide, inject, init, override } = diKit.createActivator("pine2profit");
389
+
390
+ const baseServices$1 = {
391
+ loggerService: Symbol("loggerService"),
392
+ };
393
+ const viewServices$1 = {
394
+ dataViewService: Symbol("dataViewService"),
395
+ };
396
+ const validationServices$1 = {
397
+ dataValidationService: Symbol("dataValidationService"),
398
+ };
399
+ const TYPES = {
400
+ ...baseServices$1,
401
+ ...viewServices$1,
402
+ ...validationServices$1,
403
+ };
404
+
405
+ const DATA_DIR$1 = "data";
406
+ const isInside = (root, target) => target === root || target.startsWith(root + path.sep);
407
+ /** Drops empty, "." and ".." segments so a request can never climb above the root. */
408
+ const normalizeSegments = (relPath) => relPath.split(/[\\/]+/).filter((segment) => segment && segment !== "." && segment !== "..");
409
+ class DataViewService {
410
+ constructor() {
411
+ this.loggerService = inject(TYPES.loggerService);
412
+ /** <root>/data; serve() resolves root once (its cwd argument, else CC_DATA_PATH, else process.cwd()). */
413
+ this.getRoot = () => {
414
+ return path.resolve(serveSubject.data || process.cwd(), DATA_DIR$1);
415
+ };
416
+ /**
417
+ * Absolute path of a file inside the data root, or null when the request points
418
+ * outside of it: checked on the lexical path and again on the real path, so a
419
+ * symlink inside data/ cannot lead out either.
420
+ */
421
+ this.resolve = async (relPath) => {
422
+ this.loggerService.log("dataViewService resolve", { relPath });
423
+ const root = this.getRoot();
424
+ const absPath = path.resolve(root, ...normalizeSegments(relPath));
425
+ if (!isInside(root, absPath)) {
426
+ return null;
427
+ }
428
+ try {
429
+ const realRoot = await promises.realpath(root);
430
+ const realPath = await promises.realpath(absPath);
431
+ return isInside(realRoot, realPath) ? realPath : null;
432
+ }
433
+ catch {
434
+ return null;
435
+ }
436
+ };
437
+ /**
438
+ * Opens a file for streaming. The handle is opened first and the size read from it, so the
439
+ * Content-Length matches the bytes the stream will deliver even if the agent replaces the
440
+ * file (rename) meanwhile; the stream closes the handle when it ends or fails.
441
+ */
442
+ this.open = async (relPath) => {
443
+ this.loggerService.log("dataViewService open", { relPath });
444
+ const filePath = await this.resolve(relPath);
445
+ if (!filePath) {
446
+ return null;
447
+ }
448
+ let handle;
449
+ try {
450
+ handle = await promises.open(filePath, "r");
451
+ }
452
+ catch {
453
+ return null;
454
+ }
455
+ const fileStat = await handle.stat();
456
+ if (!fileStat.isFile()) {
457
+ await handle.close();
458
+ return null;
459
+ }
460
+ return { path: filePath, size: fileStat.size, stream: handle.createReadStream() };
461
+ };
462
+ }
463
+ }
464
+
465
+ const DATA_DIR = "data";
466
+ const SLUG = /^[a-z0-9-]+$/;
467
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
468
+ const INDEX_FILE = /^index_(\d+)\.jsonl$/;
469
+ const SCRIPT_FILE = /^([a-z0-9-]+)_(messages|candles|pinescript)\.json$/;
470
+ const CHART_REF = /\[\[(t|range|trade):([^\]]+)\]\]|\]\(ref:(t|range|trade):([^)]+)\)/g;
471
+ const INDEX_LINE = {
472
+ id: { type: "slug", required: true },
473
+ title: { type: "string", required: true },
474
+ kind: { type: "enum", values: ["indicator", "strategy"], required: true },
475
+ subcategory: { type: "string" },
476
+ usable: { type: "boolean" },
477
+ verdict: { type: "enum", values: ["YES", "NO", "UNKNOWN"], required: true },
478
+ main: { type: "number" },
479
+ paper: { type: "number" },
480
+ paperTrades: { type: "integer" },
481
+ expected: { type: "tuple2" },
482
+ iterations: { type: "integer" },
483
+ updated: { type: "date", required: true },
484
+ market: { type: "string" },
485
+ timeframe: { type: "string" },
486
+ license: { type: "string" },
487
+ author: { type: "string" },
488
+ tvUrl: { type: "string" },
489
+ cycleStart: { type: "date" },
490
+ percentile: { type: "number" },
491
+ reason: { type: "string" },
492
+ };
493
+ const MESSAGES_FILE = {
494
+ head: { type: "object" },
495
+ groups: { type: "array" },
496
+ messages: { type: "array", required: true },
497
+ };
498
+ const GROUP = {
499
+ code: { type: "string", required: true },
500
+ title: { type: "string", required: true },
501
+ };
502
+ const MESSAGE = {
503
+ code: { type: "string" },
504
+ group: { type: "string" },
505
+ title: { type: "string", required: true },
506
+ md: { type: "string", required: true },
507
+ iteration: { type: "integer" },
508
+ date: { type: "date" },
509
+ };
510
+ const CANDLES_FILE = {
511
+ timeframe: { type: "string" },
512
+ bars: { type: "array", required: true },
513
+ trades: { type: "array" },
514
+ equity: { type: "array" },
515
+ };
516
+ const BAR = {
517
+ time: { type: "number", required: true },
518
+ open: { type: "number", required: true },
519
+ high: { type: "number", required: true },
520
+ low: { type: "number", required: true },
521
+ close: { type: "number", required: true },
522
+ volume: { type: "number", required: true },
523
+ };
524
+ const TRADE = {
525
+ id: { type: "integer", required: true },
526
+ iteration: { type: "integer" },
527
+ side: { type: "enum", values: ["long", "short"], required: true },
528
+ open_time: { type: "number", required: true },
529
+ open_price: { type: "number", required: true },
530
+ close_time: { type: "number", nullable: true },
531
+ close_price: { type: "number", nullable: true },
532
+ pnl_usd: { type: "number", required: true },
533
+ };
534
+ const EQUITY = {
535
+ time: { type: "number", required: true },
536
+ backtest_usd: { type: "number", nullable: true },
537
+ paper_usd: { type: "number", nullable: true },
538
+ };
539
+ const PINESCRIPT_FILE = {
540
+ source: { type: "string", required: true },
541
+ rule: { type: "string" },
542
+ };
543
+ const isPlainObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
544
+ const describe = (v) => {
545
+ if (v === null)
546
+ return "null";
547
+ if (Array.isArray(v))
548
+ return "an array";
549
+ if (typeof v === "string")
550
+ return `"${v.length > 40 ? v.slice(0, 40) + "…" : v}"`;
551
+ return typeof v === "object" ? "an object" : String(v);
552
+ };
553
+ const typeError = (rule, v) => {
554
+ switch (rule.type) {
555
+ case "string": return typeof v === "string" ? null : `must be a string, got ${describe(v)}`;
556
+ case "number": return typeof v === "number" && Number.isFinite(v) ? null : `must be a number, got ${describe(v)}`;
557
+ case "integer": return Number.isInteger(v) ? null : `must be an integer, got ${describe(v)}`;
558
+ case "boolean": return typeof v === "boolean" ? null : `must be true or false, got ${describe(v)}`;
559
+ case "date": return typeof v === "string" && DATE.test(v) && !Number.isNaN(Date.parse(v)) ? null : `must be a date YYYY-MM-DD, got ${describe(v)}`;
560
+ case "slug": return typeof v === "string" && SLUG.test(v) ? null : `must be a slug [a-z0-9-]+, got ${describe(v)}`;
561
+ case "enum": return typeof v === "string" && rule.values.includes(v) ? null : `must be one of ${rule.values.join(", ")}, got ${describe(v)}`;
562
+ case "tuple2": return Array.isArray(v) && v.length === 2 && v.every((x) => typeof x === "number" && Number.isFinite(x)) ? null : `must be [low, high] with two numbers, got ${describe(v)}`;
563
+ case "array": return Array.isArray(v) ? null : `must be an array, got ${describe(v)}`;
564
+ case "object": return isPlainObject(v) ? null : `must be an object, got ${describe(v)}`;
565
+ }
566
+ };
567
+ /** Key order and formatting do not matter when comparing head with the index line. */
568
+ const canonical = (v) => isPlainObject(v)
569
+ ? `{${Object.keys(v).filter((k) => v[k] !== null && v[k] !== undefined).sort().map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`).join(",")}}`
570
+ : JSON.stringify(v);
571
+ const error = (file, message, where = {}) => ({ level: "error", file, message, ...where });
572
+ const warning = (file, message, where = {}) => ({ level: "warning", file, message, ...where });
573
+ /** The shape of a JSON value against a schema; pure and small, so a plain array is returned. */
574
+ const checkObject = (value, schema, where) => {
575
+ const issues = [];
576
+ const at = () => ({ line: where.line, at: where.at });
577
+ if (!isPlainObject(value)) {
578
+ issues.push(error(where.file, `must be an object, got ${describe(value)}`, at()));
579
+ return { ok: false, issues };
580
+ }
581
+ for (const [key, rule] of Object.entries(schema)) {
582
+ const v = value[key];
583
+ if (v === undefined || (v === null && !rule.nullable)) {
584
+ if (rule.required)
585
+ issues.push(error(where.file, v === null ? `"${key}" is required and must not be null` : `"${key}" is required`, at()));
586
+ continue;
587
+ }
588
+ if (v === null)
589
+ continue;
590
+ const problem = typeError(rule, v);
591
+ if (problem) {
592
+ issues.push(error(where.file, `"${key}" ${problem}`, at()));
593
+ continue;
594
+ }
595
+ if (rule.required && rule.type === "string" && !v.trim()) {
596
+ issues.push(error(where.file, `"${key}" must not be empty`, at()));
597
+ }
598
+ }
599
+ const norm = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
600
+ for (const key of Object.keys(value)) {
601
+ if (key in schema)
602
+ continue;
603
+ const hit = Object.keys(schema).find((k) => norm(k) === norm(key));
604
+ issues.push(error(where.file, `unknown field "${key}"${hit ? ` (did you mean "${hit}"?)` : ""}`, at()));
605
+ }
606
+ return { ok: !issues.length, issues };
607
+ };
608
+ /** [[t:…]], [[range:…]], [[trade:N]] and [text](ref:…) must point at something the chart can show. */
609
+ function* checkRefs(md, where, tradeIds) {
610
+ for (const m of md.matchAll(CHART_REF)) {
611
+ const kind = m[1] ?? m[3];
612
+ const body = (m[2] ?? m[4]).trim();
613
+ const ref = m[0];
614
+ const at = { at: where.at };
615
+ if (kind === "t") {
616
+ const [ts, price] = body.split("@");
617
+ if (Number.isNaN(Date.parse(ts)))
618
+ yield error(where.file, `${ref}: not a date (ISO 8601 expected)`, at);
619
+ if (price !== undefined && !Number.isFinite(Number(price)))
620
+ yield error(where.file, `${ref}: the price after @ is not a number`, at);
621
+ }
622
+ else if (kind === "range") {
623
+ const [a, b] = body.split("..");
624
+ const from = Date.parse(a), to = Date.parse(b ?? "");
625
+ if (Number.isNaN(from) || Number.isNaN(to))
626
+ yield error(where.file, `${ref}: expected two ISO 8601 dates joined with ".."`, at);
627
+ else if (from >= to)
628
+ yield error(where.file, `${ref}: the range ends before it starts`, at);
629
+ }
630
+ else {
631
+ const n = Number(body);
632
+ if (!Number.isInteger(n))
633
+ yield error(where.file, `${ref}: expected a trade id (integer)`, at);
634
+ else if (tradeIds && !tradeIds.has(n))
635
+ yield error(where.file, `${ref}: no trade with id ${n} in the candles file`, at);
636
+ }
637
+ }
638
+ }
639
+ /**
640
+ * Validates <root>/data against the contract and yields every problem the moment it is found:
641
+ * the index files are read line by line, the files of each script one script at a time, so memory
642
+ * holds one document at once whatever the size of the folder. The generator's return value is
643
+ * the summary (counts) once everything has been yielded.
644
+ */
645
+ class DataValidationService {
646
+ constructor() {
647
+ this.loggerService = inject(TYPES.loggerService);
648
+ this.validate = async function* (root) {
649
+ this.loggerService.log("dataValidationService validate", { root });
650
+ const dir = path.resolve(root, DATA_DIR);
651
+ const rel = (name) => path.join(DATA_DIR, name);
652
+ const summary = { root, scripts: 0, chunks: 0, errors: 0, warnings: 0 };
653
+ const count = (issue) => {
654
+ if (issue.level === "error")
655
+ summary.errors += 1;
656
+ else
657
+ summary.warnings += 1;
658
+ return issue;
659
+ };
660
+ // the folder
661
+ let dirStat;
662
+ try {
663
+ dirStat = await promises.stat(dir);
664
+ }
665
+ catch {
666
+ yield count(error(DATA_DIR, `folder not found: ${dir}`));
667
+ return summary;
668
+ }
669
+ if (!dirStat.isDirectory()) {
670
+ yield count(error(DATA_DIR, `is not a folder: ${dir}`));
671
+ return summary;
672
+ }
673
+ const names = (await promises.readdir(dir)).filter((n) => !n.startsWith("."));
674
+ const present = new Set(names);
675
+ // index chunks: index_1 … index_N without gaps
676
+ const chunks = names
677
+ .map((n) => ({ name: n, n: Number(INDEX_FILE.exec(n)?.[1]) }))
678
+ .filter((c) => Number.isInteger(c.n) && c.n >= 1)
679
+ .sort((a, b) => a.n - b.n);
680
+ summary.chunks = chunks.length;
681
+ if (!chunks.length) {
682
+ yield count(error(rel("index_1.jsonl"), "not found: the list is read from data/index_1.jsonl (an empty file is fine)"));
683
+ }
684
+ for (let i = 0; i < chunks.length; i += 1) {
685
+ const expected = i + 1;
686
+ if (chunks[i].n !== expected) {
687
+ yield count(error(rel(`index_${expected}.jsonl`), `missing: the site stops at the first missing index file, so index_${chunks[i].n}.jsonl and later are never read`));
688
+ break;
689
+ }
690
+ }
691
+ // index lines, streamed; only the raw text of the last line per id is kept
692
+ const rows = new Map();
693
+ for (const chunk of chunks) {
694
+ const file = rel(chunk.name);
695
+ const lines = readline.createInterface({ input: fs.createReadStream(path.join(dir, chunk.name), "utf8"), crlfDelay: Infinity });
696
+ let line = 0;
697
+ for await (const raw of lines) {
698
+ line += 1;
699
+ const l = raw.trim();
700
+ if (!l)
701
+ continue;
702
+ let obj;
703
+ try {
704
+ obj = JSON.parse(l);
705
+ }
706
+ catch (e) {
707
+ yield count(error(file, `not valid JSON: ${e.message}`, { line }));
708
+ continue;
709
+ }
710
+ const check = checkObject(obj, INDEX_LINE, { file, line });
711
+ for (const issue of check.issues)
712
+ yield count(issue);
713
+ if (check.ok)
714
+ rows.set(obj.id, l);
715
+ }
716
+ }
717
+ summary.scripts = rows.size;
718
+ // every script's files, one script at a time
719
+ const known = new Set();
720
+ for (const [id, raw] of rows) {
721
+ const row = JSON.parse(raw);
722
+ const messagesName = `${id}_messages.json`;
723
+ const candlesName = `${id}_candles.json`;
724
+ const pinescriptName = `${id}_pinescript.json`;
725
+ known.add(messagesName);
726
+ known.add(candlesName);
727
+ known.add(pinescriptName);
728
+ let tradeIds = null;
729
+ for await (const item of this.checkCandles(dir, rel(candlesName), present.has(candlesName))) {
730
+ if (item instanceof Set)
731
+ tradeIds = item;
732
+ else
733
+ yield count(item);
734
+ }
735
+ for await (const issue of this.checkMessages(dir, rel(messagesName), present.has(messagesName), id, row, tradeIds))
736
+ yield count(issue);
737
+ if (present.has(pinescriptName)) {
738
+ const doc = await this.readJson(dir, pinescriptName);
739
+ if (doc.issue)
740
+ yield count(doc.issue);
741
+ else
742
+ for (const issue of checkObject(doc.value, PINESCRIPT_FILE, { file: rel(pinescriptName) }).issues)
743
+ yield count(issue);
744
+ }
745
+ }
746
+ // files nobody asked for
747
+ for (const name of names) {
748
+ if (INDEX_FILE.test(name) || known.has(name))
749
+ continue;
750
+ const m = SCRIPT_FILE.exec(name);
751
+ yield count(m
752
+ ? warning(rel(name), `no index line with id "${m[1]}": the file is never shown`)
753
+ : warning(rel(name), "unexpected file: the site only reads index_N.jsonl and <id>_messages|candles|pinescript.json"));
754
+ }
755
+ return summary;
756
+ };
757
+ this.readJson = async (dir, name) => {
758
+ const text = await promises.readFile(path.join(dir, name), "utf8");
759
+ try {
760
+ return { value: JSON.parse(text) };
761
+ }
762
+ catch (e) {
763
+ return { issue: error(path.join(DATA_DIR, name), `not valid JSON: ${e.message}`) };
764
+ }
765
+ };
766
+ /** Yields issues, and the set of trade ids as the last item when the file is usable. */
767
+ this.checkCandles = async function* (dir, file, exists) {
768
+ if (!exists) {
769
+ yield error(file, "not found: every script needs its candles file (bars for the chart)");
770
+ return;
771
+ }
772
+ const doc = await this.readJson(dir, path.basename(file));
773
+ if (doc.issue) {
774
+ yield doc.issue;
775
+ return;
776
+ }
777
+ const top = checkObject(doc.value, CANDLES_FILE, { file });
778
+ yield* top.issues;
779
+ if (!top.ok)
780
+ return;
781
+ const d = doc.value;
782
+ if (!d.bars.length)
783
+ yield error(file, '"bars" must not be empty', { at: "bars" });
784
+ let prev = -Infinity;
785
+ for (let i = 0; i < d.bars.length; i += 1) {
786
+ const check = checkObject(d.bars[i], BAR, { file, at: `bars[${i}]` });
787
+ yield* check.issues;
788
+ if (!check.ok)
789
+ continue;
790
+ const b = d.bars[i];
791
+ if (b.time <= prev)
792
+ yield error(file, `"time" must grow from bar to bar (got ${b.time} after ${prev})`, { at: `bars[${i}]` });
793
+ if (b.high < b.low)
794
+ yield error(file, `"high" is below "low"`, { at: `bars[${i}]` });
795
+ prev = b.time;
796
+ }
797
+ const tradeIds = new Set();
798
+ const trades = d.trades ?? [];
799
+ for (let i = 0; i < trades.length; i += 1) {
800
+ const check = checkObject(trades[i], TRADE, { file, at: `trades[${i}]` });
801
+ yield* check.issues;
802
+ if (!check.ok)
803
+ continue;
804
+ const t = trades[i];
805
+ if (tradeIds.has(t.id))
806
+ yield error(file, `"id" ${t.id} is used twice`, { at: `trades[${i}]` });
807
+ tradeIds.add(t.id);
808
+ if (t.close_time != null && t.close_time < t.open_time)
809
+ yield error(file, `"close_time" is before "open_time"`, { at: `trades[${i}]` });
810
+ }
811
+ const equity = d.equity ?? [];
812
+ for (let i = 0; i < equity.length; i += 1)
813
+ yield* checkObject(equity[i], EQUITY, { file, at: `equity[${i}]` }).issues;
814
+ if (d.equity && d.equity.length === 1)
815
+ yield warning(file, '"equity" has a single point: the P&L line needs at least two', { at: "equity" });
816
+ yield tradeIds;
817
+ };
818
+ this.checkMessages = async function* (dir, file, exists, id, row, tradeIds) {
819
+ if (!exists) {
820
+ yield error(file, "not found: every script needs its messages file (the report text)");
821
+ return;
822
+ }
823
+ const doc = await this.readJson(dir, path.basename(file));
824
+ if (doc.issue) {
825
+ yield doc.issue;
826
+ return;
827
+ }
828
+ const top = checkObject(doc.value, MESSAGES_FILE, { file });
829
+ yield* top.issues;
830
+ if (!top.ok)
831
+ return;
832
+ const d = doc.value;
833
+ if (d.head !== undefined) {
834
+ const check = checkObject(d.head, INDEX_LINE, { file, at: "head" });
835
+ yield* check.issues;
836
+ if (check.ok) {
837
+ if (d.head.id !== id)
838
+ yield error(file, `"id" is "${d.head.id}" but the file belongs to "${id}"`, { at: "head" });
839
+ else if (canonical(d.head) !== canonical(row)) {
840
+ const diff = [...new Set([...Object.keys(d.head), ...Object.keys(row)])].filter((k) => canonical(d.head[k]) !== canonical(row[k]));
841
+ yield error(file, `differs from the index line in ${diff.map((k) => `"${k}"`).join(", ")}: copy the index line as is`, { at: "head" });
842
+ }
843
+ }
844
+ }
845
+ else {
846
+ yield warning(file, `"head" is missing: a direct link to /run/?id=${id} has to scan the index first`);
847
+ }
848
+ const groups = d.groups ?? [];
849
+ for (let i = 0; i < groups.length; i += 1)
850
+ yield* checkObject(groups[i], GROUP, { file, at: `groups[${i}]` }).issues;
851
+ if (!d.messages.length)
852
+ yield warning(file, '"messages" is empty: the page shows no text', { at: "messages" });
853
+ for (let i = 0; i < d.messages.length; i += 1) {
854
+ const check = checkObject(d.messages[i], MESSAGE, { file, at: `messages[${i}]` });
855
+ yield* check.issues;
856
+ if (!check.ok)
857
+ continue;
858
+ yield* checkRefs(d.messages[i].md, { file, at: `messages[${i}].md` }, tradeIds);
859
+ }
860
+ };
861
+ }
862
+ }
863
+
864
+ {
865
+ provide(TYPES.loggerService, () => new LoggerService());
866
+ }
867
+ {
868
+ provide(TYPES.dataViewService, () => new DataViewService());
869
+ }
870
+ {
871
+ provide(TYPES.dataValidationService, () => new DataValidationService());
872
+ }
873
+
874
+ const baseServices = {
875
+ loggerService: inject(TYPES.loggerService),
876
+ };
877
+ const viewServices = {
878
+ dataViewService: inject(TYPES.dataViewService),
879
+ };
880
+ const validationServices = {
881
+ dataValidationService: inject(TYPES.dataValidationService),
882
+ };
883
+ const ioc = {
884
+ ...baseServices,
885
+ ...viewServices,
886
+ ...validationServices,
887
+ };
888
+ init();
889
+
890
+ const router$2 = Router({
891
+ params: true,
892
+ });
893
+ const DEFAULT_MIME = "application/octet-stream";
894
+ const MIME_OVERRIDES = {
895
+ ".json": "application/json; charset=utf-8",
896
+ ".jsonl": "application/x-ndjson; charset=utf-8",
897
+ };
898
+ router$2.get("/data/:filePath(*)", async (req, res) => {
899
+ try {
900
+ const { filePath } = req.params;
901
+ const file = await ioc.dataViewService.open(filePath);
902
+ if (!file) {
903
+ ioc.loggerService.log("/data not found", {
904
+ request: { filePath },
905
+ });
906
+ return await micro.send(res, 404, {
907
+ status: "error",
908
+ error: `file not found filePath=${filePath}`,
909
+ });
910
+ }
911
+ const ext = path.extname(file.path).toLowerCase();
912
+ const mimeType = MIME_OVERRIDES[ext] ?? (mime.lookup(file.path) || DEFAULT_MIME);
913
+ // A read error (the agent deleted or truncated the file mid-stream) must not become an
914
+ // uncaught exception: answer 500 while the headers are still ours, otherwise cut the connection
915
+ // so the browser sees a failed request instead of a short body.
916
+ file.stream.on("error", (error) => {
917
+ ioc.loggerService.log("/data stream error", {
918
+ request: { filePath },
919
+ error: functoolsKit.errorData(error),
920
+ });
921
+ if (res.headersSent) {
922
+ res.destroy(error);
923
+ return;
924
+ }
925
+ micro.send(res, 500, {
926
+ status: "error",
927
+ error: functoolsKit.getErrorMessage(error),
928
+ });
929
+ });
930
+ res.on("close", () => {
931
+ file.stream.destroy();
932
+ });
933
+ res.setHeader("Content-Type", mimeType);
934
+ res.setHeader("Content-Length", file.size);
935
+ // the agent rewrites these files between runs; never let the browser keep a stale copy
936
+ res.setHeader("Cache-Control", "no-store");
937
+ ioc.loggerService.log("/data ok", {
938
+ request: { filePath },
939
+ result: { path: file.path, mime: mimeType, size: file.size },
940
+ });
941
+ return await micro.send(res, 200, file.stream);
942
+ }
943
+ catch (error) {
944
+ ioc.loggerService.log("/data error", {
945
+ error: functoolsKit.errorData(error),
946
+ });
947
+ return await micro.send(res, 500, {
948
+ status: "error",
949
+ error: functoolsKit.getErrorMessage(error),
950
+ });
951
+ }
952
+ });
953
+
954
+ const require$1 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
955
+ /**
956
+ * Static root of the dashboard: <package>/build/modules/frontend/build.
957
+ * Resolved against the installed package (self-reference via package.json "exports"),
958
+ * so it works from any cwd. Override with CC_WWWROOT_PATH or setConfig().
959
+ */
960
+ function getPublicPath() {
961
+ const modulePath = require$1.resolve("pine2profit");
962
+ const basePath = path.dirname(modulePath);
963
+ return path.join(basePath, "./modules/frontend/build");
964
+ }
965
+
966
+ const router = Router({
967
+ params: true,
968
+ });
969
+ // The agent's files: GET /data/<file> -> <root>/data/<file>. The same relative
970
+ // paths the site requests on GitHub Pages, so nothing differs between the two.
971
+ router.all("/data/*", (req, res) => {
972
+ return router$2(req, res, finalhandler(req, res));
973
+ });
974
+ // Next.js static export (modules/frontend, output: "export", trailingSlash: true):
975
+ // /run/?id=x -> run/index.html, 404.html is picked up by serve-handler.
976
+ router.get("/*", (req, res) => {
977
+ const { CC_WWWROOT_PATH } = getConfig();
978
+ return serveHandler(req, res, {
979
+ public: CC_WWWROOT_PATH || getPublicPath(),
980
+ });
981
+ });
982
+ var router$1 = micro.serve(async (req, res) => {
983
+ res.setHeader("Access-Control-Allow-Origin", "*");
984
+ res.setHeader("Access-Control-Allow-Headers", "*");
985
+ res.setHeader("Access-Control-Allow-Credentials", "true");
986
+ res.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
987
+ return router(req, res, finalhandler(req, res));
988
+ });
989
+
990
+ const METHOD_NAME_SERVE = "serve.serve";
991
+ const METHOD_NAME_GET_ROUTER = "serve.getRouter";
992
+ const MAX_CONNECTIONS = 1000;
993
+ const SOCKET_TIMEOUT = 60 * 10 * 1000;
994
+ const serveInternal = functoolsKit.singleshot((host = getConfig().CC_WWWROOT_HOST, port = getConfig().CC_WWWROOT_PORT, callback) => {
995
+ const server = new http.Server(router$1);
996
+ server.listen(port, host).addListener("listening", () => {
997
+ console.log(`Listening on http://${host}:${port}`);
998
+ callback && callback();
999
+ });
1000
+ server.addListener("error", (err) => {
1001
+ console.error("Server error:", err);
1002
+ // The server never came up: reset the singleshot, otherwise a retry of serve()
1003
+ // would hand back this dead instance and nobody would try the port again.
1004
+ if (!server.listening) {
1005
+ serveInternal.clear();
1006
+ }
1007
+ callback && callback(err);
1008
+ });
1009
+ server.maxConnections = MAX_CONNECTIONS;
1010
+ server.setTimeout(SOCKET_TIMEOUT);
1011
+ return () => {
1012
+ server.close();
1013
+ serveInternal.clear();
1014
+ };
1015
+ });
1016
+ /**
1017
+ * Starts the server. `cwd` is the project root whose data/ folder is served: the argument wins,
1018
+ * then the CC_DATA_PATH environment variable, then process.cwd().
1019
+ */
1020
+ function serve(host, port, cwd, callback) {
1021
+ const root = cwd || getConfig().CC_DATA_PATH || process.cwd();
1022
+ ioc.loggerService.log(METHOD_NAME_SERVE, {
1023
+ host,
1024
+ port,
1025
+ root,
1026
+ });
1027
+ serveSubject.next(root);
1028
+ return serveInternal(host, port, callback);
1029
+ }
1030
+ function getRouter() {
1031
+ ioc.loggerService.log(METHOD_NAME_GET_ROUTER);
1032
+ return router$1;
1033
+ }
1034
+
1035
+ const METHOD_NAME_VALIDATE = "validate.validate";
1036
+ /**
1037
+ * Checks <root>/data against the contract. Yields each problem as soon as it is found; the
1038
+ * generator's return value is the summary. Consume it with `for await`, or step with next()
1039
+ * when the summary is needed:
1040
+ * const it = validate(root); let r; while (!(r = await it.next()).done) report(r.value); const summary = r.value;
1041
+ */
1042
+ function validate(root) {
1043
+ ioc.loggerService.log(METHOD_NAME_VALIDATE, { root });
1044
+ return ioc.dataValidationService.validate(root);
1045
+ }
1046
+
1047
+ const MAX_ISSUES_SHOWN = 50;
1048
+ const NO_DIR_TEXT = `
1049
+ Example:
1050
+
1051
+ npx pine2profit --help
1052
+ npx pine2profit <dir>
1053
+ `.trimStart();
1054
+ const formatIssue = (issue) => {
1055
+ const where = `${issue.file}${issue.line ? `:${issue.line}` : ""}${issue.at ? ` ${issue.at}` : ""}`;
1056
+ return `${issue.level.padEnd(8)} ${where}\n ${issue.message}`;
1057
+ };
1058
+ const main = async () => {
1059
+ if (!getEntry((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)))) {
1060
+ return;
1061
+ }
1062
+ const { values, positionals } = getArgs();
1063
+ if (values.help) {
1064
+ return;
1065
+ }
1066
+ if (values.version) {
1067
+ process.stdout.write(`${"0.1.0"}\n`);
1068
+ process.exit(0);
1069
+ }
1070
+ const [dir = null] = positionals;
1071
+ if (!dir) {
1072
+ process.stdout.write(`pine2profit ${"0.1.0"}\n`);
1073
+ process.stdout.write("\n");
1074
+ process.stdout.write(`The folder that contains data/ is required. Run with --help to see how to build it.\n`);
1075
+ process.stdout.write("\n");
1076
+ process.stdout.write(NO_DIR_TEXT);
1077
+ process.exit(1);
1078
+ }
1079
+ const root = path.resolve(String(dir));
1080
+ setConfig({ CC_DATA_PATH: root });
1081
+ if (values.port) {
1082
+ const port = Number(values.port);
1083
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
1084
+ console.error(`--port must be an integer between 1 and 65535, got "${values.port}"`);
1085
+ process.exit(1);
1086
+ }
1087
+ setConfig({ CC_WWWROOT_PORT: port });
1088
+ }
1089
+ if (values.host) {
1090
+ setConfig({ CC_WWWROOT_HOST: String(values.host) });
1091
+ }
1092
+ // The data folder is checked on every start and a single error refuses to start: the agent
1093
+ // must never be left looking at a page that silently shows something wrong. Problems are
1094
+ // printed as they are found; the folder is read one file at a time.
1095
+ const check = validate(root);
1096
+ let shown = 0;
1097
+ let summary;
1098
+ for (;;) {
1099
+ const step = await check.next();
1100
+ if (step.done) {
1101
+ summary = step.value;
1102
+ break;
1103
+ }
1104
+ const issue = step.value;
1105
+ if (shown < MAX_ISSUES_SHOWN) {
1106
+ (issue.level === "error" ? console.error : console.warn)(formatIssue(issue));
1107
+ }
1108
+ else if (shown === MAX_ISSUES_SHOWN) {
1109
+ console.error("… more problems follow, only the first ones are shown");
1110
+ }
1111
+ shown += 1;
1112
+ }
1113
+ const dataDir = path.join(root, "data");
1114
+ const counts = `${summary.scripts} script${summary.scripts === 1 ? "" : "s"} in ${summary.chunks} index file${summary.chunks === 1 ? "" : "s"}${summary.warnings ? `, ${summary.warnings} warning${summary.warnings === 1 ? "" : "s"}` : ""}`;
1115
+ if (summary.errors) {
1116
+ console.error(`\n${summary.errors} error${summary.errors === 1 ? "" : "s"} in ${dataDir}: ${values.check ? "the folder is not valid" : "refusing to start"}. Run with --help for the data contract.`);
1117
+ process.exit(1);
1118
+ }
1119
+ if (values.check) {
1120
+ // --check: the same validation as before every start, without starting the server
1121
+ console.log(`${dataDir}: no errors, ${counts}`);
1122
+ process.exit(0);
1123
+ }
1124
+ console.log(`data: ${counts}`);
1125
+ const { CC_WWWROOT_HOST, CC_WWWROOT_PORT } = getConfig();
1126
+ const unServer = serve(CC_WWWROOT_HOST, CC_WWWROOT_PORT, root, (error) => {
1127
+ if (error) {
1128
+ process.exit(1);
1129
+ }
1130
+ console.log(`Serving ${path.join(root, "data")} at http://localhost:${CC_WWWROOT_PORT}/data/`);
1131
+ });
1132
+ const beforeExit = () => {
1133
+ process.off("SIGINT", beforeExit);
1134
+ unServer();
1135
+ process.exit(0);
1136
+ };
1137
+ process.on("SIGINT", beforeExit);
1138
+ };
1139
+ main();
1140
+
1141
+ const setLogger = (logger) => {
1142
+ ioc.loggerService.setLogger(logger);
1143
+ };
1144
+
1145
+ exports.getConfig = getConfig;
1146
+ exports.getPublicPath = getPublicPath;
1147
+ exports.getRouter = getRouter;
1148
+ exports.lib = ioc;
1149
+ exports.serve = serve;
1150
+ exports.setConfig = setConfig;
1151
+ exports.setLogger = setLogger;
1152
+ exports.validate = validate;