@invinite-org/chartlang-compiler 1.2.1 → 1.4.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 (64) hide show
  1. package/CHANGELOG.md +310 -0
  2. package/dist/analysis/extractDependencyGraph.d.ts.map +1 -1
  3. package/dist/analysis/extractDependencyGraph.js +9 -1
  4. package/dist/analysis/extractDependencyGraph.js.map +1 -1
  5. package/dist/analysis/extractInputs.d.ts.map +1 -1
  6. package/dist/analysis/extractInputs.js +2 -0
  7. package/dist/analysis/extractInputs.js.map +1 -1
  8. package/dist/analysis/extractMaxLookback.d.ts +2 -1
  9. package/dist/analysis/extractMaxLookback.d.ts.map +1 -1
  10. package/dist/analysis/extractMaxLookback.js +90 -6
  11. package/dist/analysis/extractMaxLookback.js.map +1 -1
  12. package/dist/analysis/extractRequestedIntervals.d.ts +63 -1
  13. package/dist/analysis/extractRequestedIntervals.d.ts.map +1 -1
  14. package/dist/analysis/extractRequestedIntervals.js +245 -29
  15. package/dist/analysis/extractRequestedIntervals.js.map +1 -1
  16. package/dist/analysis/forbiddenConstructs.d.ts.map +1 -1
  17. package/dist/analysis/forbiddenConstructs.js +2 -41
  18. package/dist/analysis/forbiddenConstructs.js.map +1 -1
  19. package/dist/analysis/index.d.ts +4 -1
  20. package/dist/analysis/index.d.ts.map +1 -1
  21. package/dist/analysis/index.js +3 -1
  22. package/dist/analysis/index.js.map +1 -1
  23. package/dist/analysis/loopBounds.d.ts +91 -0
  24. package/dist/analysis/loopBounds.d.ts.map +1 -0
  25. package/dist/analysis/loopBounds.js +132 -0
  26. package/dist/analysis/loopBounds.js.map +1 -0
  27. package/dist/analysis/resolveIndexBound.d.ts +73 -0
  28. package/dist/analysis/resolveIndexBound.d.ts.map +1 -0
  29. package/dist/analysis/resolveIndexBound.js +336 -0
  30. package/dist/analysis/resolveIndexBound.js.map +1 -0
  31. package/dist/analysis/stateArrayCapacity.d.ts +58 -0
  32. package/dist/analysis/stateArrayCapacity.d.ts.map +1 -0
  33. package/dist/analysis/stateArrayCapacity.js +108 -0
  34. package/dist/analysis/stateArrayCapacity.js.map +1 -0
  35. package/dist/analysis/validateSecurityExpr.d.ts +25 -0
  36. package/dist/analysis/validateSecurityExpr.d.ts.map +1 -0
  37. package/dist/analysis/validateSecurityExpr.js +154 -0
  38. package/dist/analysis/validateSecurityExpr.js.map +1 -0
  39. package/dist/api.d.ts.map +1 -1
  40. package/dist/api.js +22 -3
  41. package/dist/api.js.map +1 -1
  42. package/dist/diagnostics.d.ts +8 -2
  43. package/dist/diagnostics.d.ts.map +1 -1
  44. package/dist/diagnostics.js.map +1 -1
  45. package/dist/manifest.d.ts +3 -1
  46. package/dist/manifest.d.ts.map +1 -1
  47. package/dist/manifest.js +11 -0
  48. package/dist/manifest.js.map +1 -1
  49. package/dist/program.d.ts.map +1 -1
  50. package/dist/program.js +148 -15
  51. package/dist/program.js.map +1 -1
  52. package/dist/transformers/callsiteIdInjection.d.ts +21 -0
  53. package/dist/transformers/callsiteIdInjection.d.ts.map +1 -1
  54. package/dist/transformers/callsiteIdInjection.js +34 -4
  55. package/dist/transformers/callsiteIdInjection.js.map +1 -1
  56. package/dist/transformers/plotKindFromCallsite.d.ts +3 -0
  57. package/dist/transformers/plotKindFromCallsite.d.ts.map +1 -1
  58. package/dist/transformers/plotKindFromCallsite.js +7 -0
  59. package/dist/transformers/plotKindFromCallsite.js.map +1 -1
  60. package/dist/transformers/resolveCallee.d.ts +21 -0
  61. package/dist/transformers/resolveCallee.d.ts.map +1 -1
  62. package/dist/transformers/resolveCallee.js +14 -1
  63. package/dist/transformers/resolveCallee.js.map +1 -1
  64. package/package.json +2 -2
@@ -0,0 +1,154 @@
1
+ // Copyright (c) 2026 Invinite. Licensed under the MIT License.
2
+ // See the LICENSE file in the repo root for full license text.
3
+ import ts from "typescript";
4
+ import { createDiagnostic } from "../diagnostics.js";
5
+ import { resolveCoreSymbolName } from "../transformers/resolveCallee.js";
6
+ /**
7
+ * Validate that a `request.security({ interval }, (bar) => …)` expression
8
+ * callback references only its `bar` parameter (and locals derived from it),
9
+ * the ambient `ta` namespace, `inputs`, safe `Math.*` globals, and literal
10
+ * constants. Any other free identifier is a captured outer binding — it would
11
+ * smuggle the main-timeline clock into the higher-timeframe expression — and
12
+ * is rejected with `request-security-expr-captures-local`.
13
+ *
14
+ * Function / arrow expressions nested deeper inside the callback are out of
15
+ * the v1 subset and rejected too (keeps the expression unit flat), as is a
16
+ * `this` reference. Parameter default initialisers are walked alongside the
17
+ * body so a default that captures an outer binding is flagged too.
18
+ *
19
+ * @since 0.7
20
+ * @stable
21
+ * @example
22
+ * // Inside extractRequestAnalysis, once per expression callsite:
23
+ * // validateSecurityExpr(callback, checker, diagnostics, sourcePath);
24
+ * const fn: typeof validateSecurityExpr = validateSecurityExpr;
25
+ * void fn;
26
+ */
27
+ export function validateSecurityExpr(callback, checker, diagnostics, sourcePath) {
28
+ const sourceFile = callback.getSourceFile();
29
+ const bound = collectBoundNames(callback);
30
+ const visit = (node) => {
31
+ // Nested functions/arrows are out of the flat v1 subset.
32
+ if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) {
33
+ diagnostics.push(createDiagnostic({
34
+ severity: "error",
35
+ code: "request-security-expr-captures-local",
36
+ message: "A request.security expression callback may not contain a nested function. Keep the expression flat.",
37
+ file: sourcePath,
38
+ node,
39
+ sourceFile,
40
+ }));
41
+ return;
42
+ }
43
+ // `this` is not a value the flat expression subset may read — in a
44
+ // function-expression callback it would be `undefined` under the
45
+ // module's strict mode and throw at runtime.
46
+ if (node.kind === ts.SyntaxKind.ThisKeyword) {
47
+ diagnostics.push(createDiagnostic({
48
+ severity: "error",
49
+ code: "request-security-expr-captures-local",
50
+ message: "A request.security expression callback may not use `this`.",
51
+ file: sourcePath,
52
+ node,
53
+ sourceFile,
54
+ }));
55
+ return;
56
+ }
57
+ if (ts.isIdentifier(node) && isFreeReference(node)) {
58
+ if (!isAllowedReference(node, bound, checker)) {
59
+ diagnostics.push(createDiagnostic({
60
+ severity: "error",
61
+ code: "request-security-expr-captures-local",
62
+ message: `A request.security expression callback may not capture the outer binding \`${node.text}\`. Inline it as a literal or read it from \`inputs\`.`,
63
+ file: sourcePath,
64
+ node,
65
+ sourceFile,
66
+ }));
67
+ }
68
+ }
69
+ ts.forEachChild(node, visit);
70
+ };
71
+ // A parameter default (`(bar = outer) => …`) is a value read of whatever it
72
+ // initialises to, so it must be checked for captures alongside the body.
73
+ for (const parameter of callback.parameters) {
74
+ if (parameter.initializer !== undefined)
75
+ visit(parameter.initializer);
76
+ }
77
+ visit(callback.body);
78
+ }
79
+ /**
80
+ * Collect every name bound *inside* the callback: the parameter identifiers
81
+ * plus any `const` / `let` / `var` declared in the body. A binding's
82
+ * initialiser is still walked by the caller, so an initialiser that captures
83
+ * an outer name is still flagged.
84
+ */
85
+ function collectBoundNames(callback) {
86
+ const names = new Set();
87
+ for (const parameter of callback.parameters) {
88
+ addBindingNames(parameter.name, names);
89
+ }
90
+ const visit = (node) => {
91
+ if (ts.isVariableDeclaration(node)) {
92
+ addBindingNames(node.name, names);
93
+ }
94
+ ts.forEachChild(node, visit);
95
+ };
96
+ visit(callback.body);
97
+ return names;
98
+ }
99
+ function addBindingNames(name, into) {
100
+ if (ts.isIdentifier(name)) {
101
+ into.add(name.text);
102
+ return;
103
+ }
104
+ for (const element of name.elements) {
105
+ if (ts.isBindingElement(element))
106
+ addBindingNames(element.name, into);
107
+ }
108
+ }
109
+ /**
110
+ * Whether an identifier is a *free reference* — an actual value read, not a
111
+ * property name (`bar.close` → `close`), a property-assignment key, or a
112
+ * binding/declaration name (handled by `collectBoundNames`).
113
+ *
114
+ * A shorthand property (`{ offset }`) is deliberately NOT excluded: the
115
+ * identifier there is both the key and the value read, so `{ outerLength }`
116
+ * inside an opts object must still be checked against the allowed subset.
117
+ */
118
+ function isFreeReference(node) {
119
+ const parent = node.parent;
120
+ if (ts.isPropertyAccessExpression(parent) && parent.name === node)
121
+ return false;
122
+ if (ts.isPropertyAssignment(parent) && parent.name === node)
123
+ return false;
124
+ if (ts.isBindingElement(parent) && parent.propertyName === node)
125
+ return false;
126
+ if (ts.isVariableDeclaration(parent) && parent.name === node)
127
+ return false;
128
+ return true;
129
+ }
130
+ /**
131
+ * Pure value globals that carry no main-timeline data and are morally literals.
132
+ * They cannot smuggle the outer clock in, so they are allowed alongside `Math`.
133
+ * Genuinely hostile globals (`Date`, `fetch`, …) are rejected separately by the
134
+ * file-level `forbiddenConstructs` pass, which also covers the inline callback.
135
+ */
136
+ const SAFE_VALUE_GLOBALS = new Set(["undefined", "NaN", "Infinity"]);
137
+ /**
138
+ * Whether a free identifier is in the allowed subset: a name bound inside the
139
+ * callback (`bar` + locals), a {@link SAFE_VALUE_GLOBALS} constant, the ambient
140
+ * `ta` / `inputs` namespaces, or the `Math` global (individual hostile members
141
+ * such as `Math.random` are rejected by the separate hostile-global pass, not
142
+ * here).
143
+ */
144
+ function isAllowedReference(node, bound, checker) {
145
+ if (bound.has(node.text))
146
+ return true;
147
+ if (node.text === "Math")
148
+ return true;
149
+ if (SAFE_VALUE_GLOBALS.has(node.text))
150
+ return true;
151
+ const canonical = resolveCoreSymbolName(checker, node);
152
+ return canonical === "ta" || canonical === "inputs";
153
+ }
154
+ //# sourceMappingURL=validateSecurityExpr.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validateSecurityExpr.js","sourceRoot":"","sources":["../../src/analysis/validateSecurityExpr.ts"],"names":[],"mappings":"AAAA,+DAA+D;AAC/D,+DAA+D;AAE/D,OAAO,EAAE,MAAM,YAAY,CAAC;AAE5B,OAAO,EAA0B,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC7E,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAEzE;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,UAAU,oBAAoB,CAChC,QAAkD,EAClD,OAAuB,EACvB,WAAgC,EAChC,UAAkB;IAElB,MAAM,UAAU,GAAG,Q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cesContent":["// Copyright (c) 2026 Invinite. Licensed under the MIT License.\n// See the LICENSE file in the repo root for full license text.\n\nimport ts from \"typescript\";\n\nimport { type CompileDiagnostic, createDiagnostic } from \"../diagnostics.js\";\nimport { resolveCoreSymbolName } from \"../transformers/resolveCallee.js\";\n\n/**\n * Validate that a `request.security({ interval }, (bar) => …)` expression\n * callback references only its `bar` parameter (and locals derived from it),\n * the ambient `ta` namespace, `inputs`, safe `Math.*` globals, and literal\n * constants. Any other free identifier is a captured outer binding — it would\n * smuggle the main-timeline clock into the higher-timeframe expression — and\n * is rejected with `request-security-expr-captures-local`.\n *\n * Function / arrow expressions nested deeper inside the callback are out of\n * the v1 subset and rejected too (keeps the expression unit flat), as is a\n * `this` reference. Parameter default initialisers are walked alongside the\n * body so a default that captures an outer binding is flagged too.\n *\n * @since 0.7\n * @stable\n * @example\n * // Inside extractRequestAnalysis, once per expression callsite:\n * // validateSecurityExpr(callback, checker, diagnostics, sourcePath);\n * const fn: typeof validateSecurityExpr = validateSecurityExpr;\n * void fn;\n */\nexport function validateSecurityExpr(\n callback: ts.ArrowFunction | ts.FunctionExpression,\n checker: ts.TypeChecker,\n diagnostics: CompileDiagnostic[],\n sourcePath: string,\n): void {\n const sourceFile = callback.getSourceFile();\n const bound = collectBoundNames(callback);\n\n const visit = (node: ts.Node): void => {\n // Nested functions/arrows are out of the flat v1 subset.\n if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) {\n diagnostics.push(\n createDiagnostic({\n severity: \"error\",\n code: \"request-security-expr-captures-local\",\n message:\n \"A request.security expression callback may not contain a nested function. Keep the expression flat.\",\n file: sourcePath,\n node,\n sourceFile,\n }),\n );\n return;\n }\n // `this` is not a value the flat expression subset may read — in a\n // function-expression callback it would be `undefined` under the\n // module's strict mode and throw at runtime.\n if (node.kind === ts.SyntaxKind.ThisKeyword) {\n diagnostics.push(\n createDiagnostic({\n severity: \"error\",\n code: \"request-security-expr-captures-local\",\n message: \"A request.security expression callback may not use `this`.\",\n file: sourcePath,\n node,\n sourceFile,\n }),\n );\n return;\n }\n if (ts.isIdentifier(node) && isFreeReference(node)) {\n if (!isAllowedReference(node, bound, checker)) {\n diagnostics.push(\n createDiagnostic({\n severity: \"error\",\n code: \"request-security-expr-captures-local\",\n message: `A request.security expression callback may not capture the outer binding \\`${node.text}\\`. Inline it as a literal or read it from \\`inputs\\`.`,\n file: sourcePath,\n node,\n sourceFile,\n }),\n );\n }\n }\n ts.forEachChild(node, visit);\n };\n\n // A parameter default (`(bar = outer) => …`) is a value read of whatever it\n // initialises to, so it must be checked for captures alongside the body.\n for (const parameter of callback.parameters) {\n if (parameter.initializer !== undefined) visit(parameter.initializer);\n }\n visit(callback.body);\n}\n\n/**\n * Collect every name bound *inside* the callback: the parameter identifiers\n * plus any `const` / `let` / `var` declared in the body. A binding's\n * initialiser is still walked by the caller, so an initialiser that captures\n * an outer name is still flagged.\n */\nfunction collectBoundNames(\n callback: ts.ArrowFunction | ts.FunctionExpression,\n): ReadonlySet<string> {\n const names = new Set<string>();\n for (const parameter of callback.parameters) {\n addBindingNames(parameter.name, names);\n }\n const visit = (node: ts.Node): void => {\n if (ts.isVariableDeclaration(node)) {\n addBindingNames(node.name, names);\n }\n ts.forEachChild(node, visit);\n };\n visit(callback.body);\n return names;\n}\n\nfunction addBindingNames(name: ts.BindingName, into: Set<string>): void {\n if (ts.isIdentifier(name)) {\n into.add(name.text);\n return;\n }\n for (const element of name.elements) {\n if (ts.isBindingElement(element)) addBindingNames(element.name, into);\n }\n}\n\n/**\n * Whether an identifier is a *free reference* — an actual value read, not a\n * property name (`bar.close` → `close`), a property-assignment key, or a\n * binding/declaration name (handled by `collectBoundNames`).\n *\n * A shorthand property (`{ offset }`) is deliberately NOT excluded: the\n * identifier there is both the key and the value read, so `{ outerLength }`\n * inside an opts object must still be checked against the allowed subset.\n */\nfunction isFreeReference(node: ts.Identifier): boolean {\n const parent = node.parent;\n if (ts.isPropertyAccessExpression(parent) && parent.name === node) return false;\n if (ts.isPropertyAssignment(parent) && parent.name === node) return false;\n if (ts.isBindingElement(parent) && parent.propertyName === node) return false;\n if (ts.isVariableDeclaration(parent) && parent.name === node) return false;\n return true;\n}\n\n/**\n * Pure value globals that carry no main-timeline data and are morally literals.\n * They cannot smuggle the outer clock in, so they are allowed alongside `Math`.\n * Genuinely hostile globals (`Date`, `fetch`, …) are rejected separately by the\n * file-level `forbiddenConstructs` pass, which also covers the inline callback.\n */\nconst SAFE_VALUE_GLOBALS: ReadonlySet<string> = new Set([\"undefined\", \"NaN\", \"Infinity\"]);\n\n/**\n * Whether a free identifier is in the allowed subset: a name bound inside the\n * callback (`bar` + locals), a {@link SAFE_VALUE_GLOBALS} constant, the ambient\n * `ta` / `inputs` namespaces, or the `Math` global (individual hostile members\n * such as `Math.random` are rejected by the separate hostile-global pass, not\n * here).\n */\nfunction isAllowedReference(\n node: ts.Identifier,\n bound: ReadonlySet<string>,\n checker: ts.TypeChecker,\n): boolean {\n if (bound.has(node.text)) return true;\n if (node.text === \"Math\") return true;\n if (SAFE_VALUE_GLOBALS.has(node.text)) return true;\n const canonical = resolveCoreSymbolName(checker, node);\n return canonical === \"ta\" || canonical === \"inputs\";\n}\n"]}
package/dist/api.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAER,kBAAkB,EAGlB,cAAc,EACjB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,MAAM,YAAY,CAAC;AAiB5B,OAAO,EAGH,KAAK,wBAAwB,EAEhC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAQ1D;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,MAAM,0BAA0B,GAAG,QAAQ,CAAC;IAC9C,UAAU,EAAE,MAAM,CAAC;IACnB,iBAAiB,CAAC,EAAE,aAAa,CAAC,kBAAkB,CAAC,CA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,WAAW,EAAE,aAAa,CAAC,iBAAiB,CAAC;CAU5D;AAOD;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC,CAkJ3F;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAcjF;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,kBAAkB,GAAG,OAAO,CAAC,cAAc,CAAC,CAiCjG;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CA+BvE;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,cAAc,CAChC,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,cAAc,GACrB,OAAO,CAAC,aAAa,CAAC,cAAc,CAAC,CAAC,CA0BxC"}
package/dist/api.js CHANGED
@@ -5,7 +5,7 @@ import { readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
5
5
  import { dirname, isAbsolute, join, relative, resolve as resolvePath } from "node:path";
6
6
  import { STATEFUL_PRIMITIVES_BY_NAME } from "@invinite-org/chartlang-core";
7
7
  import ts from "typescript";
8
- import { extractAlertConditions, extractCapabilities, extractDependencyGraph, extractInputs, extractMaxLookback, extractRequestedIntervals, extractRequiresIntervals, runForbiddenConstructs, runStatefulCallInLoop, runStructuralChecks, validateLowerTfIntervals, } from "./analysis/index.js";
8
+ import { extractAlertConditions, extractCapabilities, extractDependencyGraph, extractInputs, extractMaxLookback, extractRequestAnalysis, extractRequiresIntervals, runForbiddenConstructs, runStateArrayCapacity, runStatefulCallInLoop, runStructuralChecks, validateLowerTfIntervals, } from "./analysis/index.js";
9
9
  import { bundleModule, formatDependenciesAssignment, formatManifestAssignment } from "./bundle.js";
10
10
  import { createProducerResolver, } from "./dependency/index.js";
11
11
  import { mapTsDiagnostic } from "./diagnostics.js";
@@ -46,6 +46,7 @@ export function transformAndAnalyse(source, opts) {
46
46
  const structural = runStructuralChecks(sourceFile, checker, sourcePath);
47
47
  const forbidden = runForbiddenConstructs(sourceFile, sourcePath);
48
48
  const statefulInLoop = runStatefulCallInLoop(sourceFile, checker, sourcePath, STATEFUL_PRIMITIVES_BY_NAME);
49
+ const stateArrayCapacity = runStateArrayCapacity(sourceFile, checker, sourcePath);
49
50
  // PLAN §5.2 step 1: the pipeline starts with tsc programmatic-API
50
51
  // typechecking against `@invinite-org/chartlang-core`'s ambient
51
52
  // declarations. Surface every semantic error coming from the
@@ -77,6 +78,7 @@ export function transformAndAnalyse(source, opts) {
77
78
  ...structural.diagnostics,
78
79
  ...forbidden,
79
80
  ...statefulInLoop,
81
+ ...stateArrayCapacity,
80
82
  ...depGraph.diagnostics,
81
83
  ];
82
84
  const hasError = earlyDiagnostics.some((d) => d.severity === "error");
@@ -127,7 +129,8 @@ export function transformAndAnalyse(source, opts) {
127
129
  const fileCapabilities = extractCapabilities(sourceFile, checker, structural.kind);
128
130
  const fileLookback = extractMaxLookback(sourceFile, checker, sourcePath);
129
131
  const fileInputs = extractInputs(sourceFile, checker, sourcePath);
130
- const fileRequestedIntervalsFromCalls = extractRequestedIntervals(sourceFile, checker, fileInputs.inputs, intervalDiagnostics, sourcePath);
132
+ const fileRequestAnalysis = extractRequestAnalysis(sourceFile, checker, fileInputs.inputs, intervalDiagnostics, sourcePath, true);
133
+ const fileRequestedIntervalsFromCalls = fileRequestAnalysis.intervals;
131
134
  const fileRequiresIntervals = extractRequiresIntervals(sourceFile, checker, intervalDiagnostics, sourcePath);
132
135
  const fileRequestedIntervals = Array.from(new Set([...fileRequestedIntervalsFromCalls, ...fileRequiresIntervals])).sort();
133
136
  const namedManifests = [];
@@ -163,6 +166,12 @@ export function transformAndAnalyse(source, opts) {
163
166
  : { dependencies: defaultDependencies }),
164
167
  ...(defaultOutputs === undefined ? {} : { outputs: defaultOutputs }),
165
168
  ...(plotSlots.length === 0 ? {} : { plots: plotSlots }),
169
+ ...(fileRequestAnalysis.securityExpressions.length === 0
170
+ ? {}
171
+ : { securityExpressions: fileRequestAnalysis.securityExpressions }),
172
+ ...(fileRequestAnalysis.feeds.length === 0
173
+ ? {}
174
+ : { requestedFeeds: fileRequestAnalysis.feeds }),
166
175
  });
167
176
  const allDiagnostics = [
168
177
  ...earlyDiagnostics,
@@ -187,7 +196,8 @@ function buildDrawnManifest(drawn, depGraph, sourceFile, checker, sourcePath, ki
187
196
  const capabilities = extractCapabilities(sourceFile, checker, kind, scope);
188
197
  const lookback = extractMaxLookback(sourceFile, checker, sourcePath, scope);
189
198
  const inputs = extractInputs(sourceFile, checker, sourcePath, scope);
190
- const requestedFromCalls = extractRequestedIntervals(sourceFile, checker, inputs.inputs, intervalDiagnostics, sourcePath);
199
+ const requestAnalysis = extractRequestAnalysis(sourceFile, checker, inputs.inputs, intervalDiagnostics, sourcePath);
200
+ const requestedFromCalls = requestAnalysis.intervals;
191
201
  const requiresIntervalsScoped = extractRequiresIntervals(sourceFile, checker, intervalDiagnostics, sourcePath);
192
202
  const requestedIntervals = Array.from(new Set([...requestedFromCalls, ...requiresIntervalsScoped])).sort();
193
203
  const dependencies = buildDependencyDeclarations(drawn, depGraph, sourcePath);
@@ -213,6 +223,15 @@ function buildDrawnManifest(drawn, depGraph, sourceFile, checker, sourcePath, ki
213
223
  ...(dependencies === undefined || dependencies.length === 0 ? {} : { dependencies }),
214
224
  ...(outputs === undefined ? {} : { outputs }),
215
225
  ...(plotSlots === undefined || plotSlots.length === 0 ? {} : { plots: plotSlots }),
226
+ // Mirror `plots` scoping: the flat security-expression list and the
227
+ // requested-feeds list attach to the default manifest only (the call
228
+ // that also receives `plotSlots`).
229
+ ...(plotSlots === undefined || requestAnalysis.securityExpressions.length === 0
230
+ ? {}
231
+ : { securityExpressions: requestAnalysis.securityExpressions }),
232
+ ...(plotSlots === undefined || requestAnalysis.feeds.length === 0
233
+ ? {}
234
+ : { requestedFeeds: requestAnalysis.feeds }),
216
235
  exportName: drawn.exportName,
217
236
  isDrawn: true,
218
237
  ...(siblings !== undefined && siblings.length > 0 ? { siblings } : {}),
package/dist/api.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"api.js","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA,+DAA+D;AAC/D,+DAA+D;AAE/D,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAChF,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,WAAW,CAAC;AACxF,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAQ3E,OAAO,EAAE,MAAM,YAAY,CAAC;AAG5B,OAAO,EACH,sBAAsB,EACtB,mBAAmB,EACnB,sBAAsB,EACtB,aAAa,EACb,kBAAkB,EAClB,yBAAyB,EACzB,wBAAwB,EACxB,sBAAsB,EACtB,qBAAqB,EACrB,mBAAmB,EACnB,wBAAwB,GAC3B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,YAAY,EAAE,4BAA4B,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AACnG,OAAO,EAIH,sBAAsB,GACzB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAC9C,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,iBAAiB,EAAE,MAAM,uCAAuC,CAAC;AAC1E,OAAO,EAAE,0BAA0B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AAC,OAAO,CAAC,CAAC;QACzD,sBAAsB;QACtB,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;YACzB,OAAO,IAAI,CAAC;QAChB,CAAC;QACD,oBAAoB;QACpB,MAAM,OAAO,GAAG,QAAQ,CAAC,OAAO,IAAI,EAAE,CAAC;QACvC,OAAO,MAAM,CAAC,MAAM,CAAC;YACjB,IAAI,EAAE,QAAQ,CAAC,IAAI;YACnB,OAAO,EAAE,MAAM,CAAC,MAAM,CAClB,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CACtE;YACD,MAAM,EAAE,MAAM,CAAC,WAAW,CACtB,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,UAAU,CAAC,EAAE,EAAE,CAAC;gBACvD,GAAG;gBACH,UAAqB;aACxB,CAAC,CACL;SACJ,CAAC,CAAC;IACP,CAAC,CAAC;AACN,CAAC","sourcesContent":["// Copyright (c) 2026 Invinite. Licensed under the MIT License.\n// See the LICENSE file in the repo root for full license text.\n\nimport { randomBytes } from \"node:crypto\";\nimport { readFile, readdir, rename, unlink, writeFile } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, relative, resolve as resolvePath } from \"node:path\";\nimport { STATEFUL_PRIMITIVES_BY_NAME } from \"@invinite-org/chartlang-core\";\nimport type {\n DependencyDeclaration,\n IntervalDescriptor,\n OutputDeclaration,\n PlotSlotDescriptor,\n ScriptManifest,\n} from \"@invinite-org/chartlang-core\";\nimport ts from \"typescript\";\n\nimport type { DepGraph, DrawnScript } from \"./analysis/extractDependencyGraph.js\";\nimport {\n extractAlertConditions,\n extractCapabilities,\n extractDependencyGraph,\n extractInputs,\n extractMaxLookback,\n extractRequestedIntervals,\n extractRequiresIntervals,\n runForbiddenConstructs,\n runStatefulCallInLoop,\n runStructuralChecks,\n validateLowerTfIntervals,\n} from \"./analysis/index.js\";\nimport { bundleModule, formatDependenciesAssignment, formatManifestAssignment } from \"./bundle.js\";\nimport {\n type CompiledProducerArtefacts,\n type ProducerCompiled,\n type ResolveCrossFileProducer,\n createProducerResolver,\n} from \"./dependency/index.js\";\nimport type { CompileDiagnostic } from \"./diagnostics.js\";\nimport { mapTsDiagnostic } from \"./diagnostics.js\";\nimport { buildManifest } from \"./manifest.js\";\nimport { createProgramForSource } from \"./program.js\";\nimport { injectCallsiteIds } from \"./transformers/callsiteIdInjection.js\";\nimport { rewriteDependencyAccessors } from \"./transformers/rewriteDependencyAccessors.js\";\nimport { emitTypes } from \"./typesEmit.js\";\n\n/**\n * Options accepted by `transformAndAnalyse`. `sourcePath` is the\n * package-relative POSIX path baked into every callsite id; the compiler\n * does not read any other file. `declaredIntervals` is the host-supplied\n * `Capabilities.intervals` set used by the `lower-tf-not-lower` validation —\n * when omitted the lower-timeframe ordering check is skipped.\n *\n * `resolveProducer` is the sync §22.10 indicator-composition snapshot\n * lookup; `compile` builds this from the pre-resolved cross-file\n * `ProducerCompiled` snapshots before invoking the transform pass. When\n * omitted (e.g. direct unit-test calls), cross-file dep edges resolve to\n * `null` and the analysis pass treats them as unresolvable.\n *\n * @since 0.1\n * @example\n * const opts: TransformAndAnalyseOptions = { sourcePath: \"demo.chart.ts\" };\n */\nexport type TransformAndAnalyseOptions = Readonly<{\n sourcePath: string;\n declaredIntervals?: ReadonlyArray<IntervalDescriptor>;\n resolveProducer?: (\n moduleSpecifier: string,\n exportName: string,\n ) => Readonly<{\n readonly name: string;\n readonly outputs: ReadonlyArray<{ readonly title: string; readonly kind: string }>;\n readonly inputs: Readonly<Record<string, unknown>>;\n }> | null;\n}>;\n\n/**\n * Result of `transformAndAnalyse`. `transformed` is the AST after callsite\n * ids have been injected; `manifest` is the recursively-frozen\n * `ScriptManifest`; `diagnostics` is the flat list of every diagnostic\n * emitted by any pass (errors abort the rewrite, warnings flow through).\n *\n * `siblings` is populated only for §22.10 multi-export indicator-composition\n * files (files with more than one drawn `defineIndicator(...)` binding) —\n * it carries every named-export manifest in source order. Single-script\n * files omit the field entirely so existing snapshot assertions stay\n * byte-identical.\n *\n * @since 0.1\n * @example\n * // const { transformed, manifest, diagnostics } =\n * // transformAndAnalyse(src, { sourcePath: \"demo.chart.ts\" });\n * const shape: { transformed: unknown; manifest: unknown; diagnostics: unknown } = {\n * transformed: null,\n * manifest: null,\n * diagnostics: [],\n * };\n * void shape;\n */\nexport type TransformAndAnalyseResult = Readonly<{\n transformed: ts.SourceFile;\n manifest: ScriptManifest;\n diagnostics: ReadonlyArray<CompileDiagnostic>;\n siblings?: ReadonlyArray<ScriptManifest>;\n}>;\n\n/**\n * Run the Phase-1 compiler pipeline against an in-memory script source.\n * Builds a TypeScript program, runs the structural / forbidden-construct /\n * stateful-call-in-loop checks, rewrites stateful calls with callsite ids,\n * and extracts the manifest's `capabilities` / `maxLookback` /\n * `seriesCapacities` / `inputs` fields.\n *\n * Error-severity diagnostics short-circuit the transform: the function\n * returns the original `sourceFile` and a placeholder manifest so callers\n * can still surface the errors uniformly. The public `compile` /\n * `compileFile` / `compileProject` wrappers above turn those error\n * diagnostics into a `CompileError` throw.\n *\n * @since 0.1\n * @example\n * // const result = transformAndAnalyse(\n * // 'export default defineIndicator({ name: \"x\", apiVersion: 1, compute: () => {} });',\n * // { sourcePath: \"demo.chart.ts\" },\n * // );\n * const fn: typeof transformAndAnalyse = transformAndAnalyse;\n * void fn;\n */\nexport function transformAndAnalyse(\n source: string,\n opts: TransformAndAnalyseOptions,\n): TransformAndAnalyseResult {\n const sourcePath = opts.sourcePath;\n const chartImports = preScanChartImports(source, sourcePath);\n const { program, sourceFile, checker } = createProgramForSource(source, {\n sourcePath,\n chartImports,\n });\n\n const structural = runStructuralChecks(sourceFile, checker, sourcePath);\n const forbidden = runForbiddenConstructs(sourceFile, sourcePath);\n const statefulInLoop = runStatefulCallInLoop(\n sourceFile,\n checker,\n sourcePath,\n STATEFUL_PRIMITIVES_BY_NAME,\n );\n // PLAN §5.2 step 1: the pipeline starts with tsc programmatic-API\n // typechecking against `@invinite-org/chartlang-core`'s ambient\n // declarations. Surface every semantic error coming from the\n // user's source file under the stable `type-error` code. Shim\n // diagnostics are dropped — they always come from the synthetic\n // core.d.ts and would only ever signal a chartlang-side bug.\n const semanticDiagnostics: CompileDiagnostic[] = program\n .getSemanticDiagnostics(sourceFile)\n .filter((d) => d.file?.fileName === sourceFile.fileName)\n .map((d) => mapTsDiagnostic(d, sourcePath));\n\n const depGraph: DepGraph = extractDependencyGraph(\n sourceFile,\n checker,\n sourcePath,\n structural.bindings,\n opts.resolveProducer === undefined\n ? () => null\n : (modSpec, expName) => {\n const snap = opts.resolveProducer?.(modSpec, expName);\n /* v8 ignore next */\n if (snap === undefined || snap === null) return null;\n return Object.freeze({\n name: snap.name,\n outputs: Object.freeze(\n snap.outputs.map((o) =>\n Object.freeze({\n title: o.title,\n kind: o.kind as \"series-number\",\n }),\n ),\n ),\n inputs: snap.inputs,\n });\n },\n );\n\n const earlyDiagnostics: CompileDiagnostic[] = [\n ...semanticDiagnostics,\n ...structural.diagnostics,\n ...forbidden,\n ...statefulInLoop,\n ...depGraph.diagnostics,\n ];\n const hasError = earlyDiagnostics.some((d) => d.severity === \"error\");\n if (hasError) {\n return Object.freeze({\n transformed: sourceFile,\n manifest: buildManifest({\n name: structural.name,\n kind: structural.kind,\n capabilities: [\"indicators\"],\n requestedIntervals: [],\n userPickableInterval: false,\n seriesCapacities: {},\n maxLookback: 0,\n inputs: {},\n ...structural.overrides,\n }),\n diagnostics: Object.freeze(earlyDiagnostics.slice()),\n });\n }\n\n const rewrite = rewriteDependencyAccessors(sourceFile, depGraph, sourcePath);\n const rewrittenSource = rewrite.transformed;\n const plotSlots: PlotSlotDescriptor[] = [];\n const injection = injectCallsiteIds(rewrittenSource, checker, {\n sourcePath,\n statefulByName: STATEFUL_PRIMITIVES_BY_NAME,\n plotSlots,\n });\n const alertConditions = extractAlertConditions(sourceFile, checker, sourcePath);\n const intervalDiagnostics: CompileDiagnostic[] = [];\n const lowerTfDiagnostics = validateLowerTfIntervals(\n sourceFile,\n checker,\n sourcePath,\n opts.declaredIntervals ?? [],\n );\n const { requiresIntervals: structuralRequiresIntervals, ...structuralOverrides } =\n structural.overrides;\n void structuralRequiresIntervals;\n\n // The structural pass guarantees a single default-export drawn\n // entry before we reach this code (errors short-circuit above);\n // we surface the default here for manifest assembly.\n const defaultDrawn = depGraph.drawn.find((d) => d.exportName === \"default\");\n /* v8 ignore start */\n if (defaultDrawn === undefined) {\n // The structural pass guarantees a default-export drawn entry\n // before we reach this code (errors short-circuit above).\n throw new Error(\"internal: depGraph.drawn missing default entry\");\n }\n /* v8 ignore stop */\n\n const isMultiExport = depGraph.drawn.length > 1;\n\n // File-level extractions (single-export back-compat path) — full source\n // walk so existing single-script manifests stay byte-identical.\n const fileCapabilities = extractCapabilities(sourceFile, checker, structural.kind);\n const fileLookback = extractMaxLookback(sourceFile, checker, sourcePath);\n const fileInputs = extractInputs(sourceFile, checker, sourcePath);\n const fileRequestedIntervalsFromCalls = extractRequestedIntervals(\n sourceFile,\n checker,\n fileInputs.inputs,\n intervalDiagnostics,\n sourcePath,\n );\n const fileRequiresIntervals = extractRequiresIntervals(\n sourceFile,\n checker,\n intervalDiagnostics,\n sourcePath,\n );\n const fileRequestedIntervals = Array.from(\n new Set([...fileRequestedIntervalsFromCalls, ...fileRequiresIntervals]),\n ).sort();\n\n const namedManifests: ScriptManifest[] = [];\n if (isMultiExport) {\n for (const drawn of depGraph.drawn) {\n if (drawn.exportName === \"default\") continue;\n namedManifests.push(\n buildDrawnManifest(\n drawn,\n depGraph,\n sourceFile,\n checker,\n sourcePath,\n structural.kind,\n structuralOverrides,\n alertConditions.alertConditions,\n ),\n );\n }\n }\n\n const defaultDependencies = buildDependencyDeclarations(defaultDrawn, depGraph, sourcePath);\n const defaultOutputs = defaultDrawn.outputs.length === 0 ? undefined : defaultDrawn.outputs;\n\n const manifest = isMultiExport\n ? buildDrawnManifest(\n defaultDrawn,\n depGraph,\n sourceFile,\n checker,\n sourcePath,\n structural.kind,\n structuralOverrides,\n alertConditions.alertConditions,\n namedManifests,\n plotSlots,\n )\n : buildManifest({\n name: structural.name,\n kind: structural.kind,\n capabilities: fileCapabilities,\n requestedIntervals: fileRequestedIntervals,\n userPickableInterval: fileInputs.userPickableInterval,\n seriesCapacities: fileLookback.seriesCapacities,\n maxLookback: fileLookback.maxLookback,\n inputs: fileInputs.inputs,\n ...structuralOverrides,\n ...(fileRequiresIntervals.length === 0\n ? {}\n : { requiresIntervals: fileRequiresIntervals }),\n ...(alertConditions.alertConditions.length === 0\n ? {}\n : { alertConditions: alertConditions.alertConditions }),\n ...(defaultDependencies === undefined || defaultDependencies.length === 0\n ? {}\n : { dependencies: defaultDependencies }),\n ...(defaultOutputs === undefined ? {} : { outputs: defaultOutputs }),\n ...(plotSlots.length === 0 ? {} : { plots: plotSlots }),\n });\n\n const allDiagnostics: CompileDiagnostic[] = [\n ...earlyDiagnostics,\n ...injection.diagnostics,\n ...rewrite.diagnostics,\n ...fileLookback.diagnostics,\n ...fileInputs.diagnostics,\n ...alertConditions.diagnostics,\n ...intervalDiagnostics,\n ...lowerTfDiagnostics,\n ];\n\n return Object.freeze({\n transformed: injection.transformed,\n manifest,\n diagnostics: Object.freeze(allDiagnostics.slice()),\n ...(isMultiExport ? { siblings: Object.freeze(namedManifests.slice()) } : {}),\n });\n}\n\nfunction buildDrawnManifest(\n drawn: DrawnScript,\n depGraph: DepGraph,\n sourceFile: ts.SourceFile,\n checker: ts.TypeChecker,\n sourcePath: string,\n kind: \"indicator\" | \"drawing\" | \"alert\" | \"alertCondition\",\n structuralOverrides: Omit<\n ReturnType<typeof runStructuralChecks>[\"overrides\"],\n \"requiresIntervals\"\n >,\n sharedAlertConditions: ReturnType<typeof extractAlertConditions>[\"alertConditions\"],\n siblings?: ReadonlyArray<ScriptManifest>,\n plotSlots?: ReadonlyArray<PlotSlotDescriptor>,\n): ScriptManifest {\n const intervalDiagnostics: CompileDiagnostic[] = [];\n const scope = drawn.defineCall;\n const capabilities = extractCapabilities(sourceFile, checker, kind, scope);\n const lookback = extractMaxLookback(sourceFile, checker, sourcePath, scope);\n const inputs = extractInputs(sourceFile, checker, sourcePath, scope);\n const requestedFromCalls = extractRequestedIntervals(\n sourceFile,\n checker,\n inputs.inputs,\n intervalDiagnostics,\n sourcePath,\n );\n const requiresIntervalsScoped = extractRequiresIntervals(\n sourceFile,\n checker,\n intervalDiagnostics,\n sourcePath,\n );\n const requestedIntervals = Array.from(\n new Set([...requestedFromCalls, ...requiresIntervalsScoped]),\n ).sort();\n const dependencies = buildDependencyDeclarations(drawn, depGraph, sourcePath);\n const outputs = drawn.outputs.length === 0 ? undefined : drawn.outputs;\n const isDefault = drawn.exportName === \"default\";\n const nameForManifest = isDefault ? readDefineCallName(drawn.defineCall) : drawn.bindingName;\n\n return buildManifest({\n name: nameForManifest,\n kind,\n capabilities,\n requestedIntervals,\n userPickableInterval: inputs.userPickableInterval,\n seriesCapacities: lookback.seriesCapacities,\n maxLookback: lookback.maxLookback,\n inputs: inputs.inputs,\n ...structuralOverrides,\n /* v8 ignore start */\n ...(requiresIntervalsScoped.length === 0\n ? {}\n : { requiresIntervals: requiresIntervalsScoped }),\n ...(sharedAlertConditions.length === 0 ? {} : { alertConditions: sharedAlertConditions }),\n /* v8 ignore stop */\n ...(dependencies === undefined || dependencies.length === 0 ? {} : { dependencies }),\n ...(outputs === undefined ? {} : { outputs }),\n ...(plotSlots === undefined || plotSlots.length === 0 ? {} : { plots: plotSlots }),\n exportName: drawn.exportName,\n isDrawn: true,\n ...(siblings !== undefined && siblings.length > 0 ? { siblings } : {}),\n });\n}\n\nfunction readDefineCallName(defineCall: ts.CallExpression): string {\n const arg = defineCall.arguments[0];\n /* v8 ignore next 3 */\n if (arg === undefined || !ts.isObjectLiteralExpression(arg)) {\n return \"\";\n }\n for (const property of arg.properties) {\n /* v8 ignore next */\n if (!ts.isPropertyAssignment(property)) continue;\n const name = property.name;\n /* v8 ignore next */\n if (!ts.isIdentifier(name) || name.text !== \"name\") continue;\n const initializer = property.initializer;\n if (ts.isStringLiteral(initializer)) return initializer.text;\n /* v8 ignore next */\n }\n /* v8 ignore next 2 */\n return \"\";\n}\n\n/**\n * Options accepted by `compile`. `apiVersion` is the frozen language\n * version this compiler implements. Passing `apiVersion: 1` is an explicit\n * acknowledgement of that contract; the type stays the literal `1` so a\n * future `apiVersion: 2` compiler is a type-level break. See\n * `docs/spec/versioning.md`. `sourcePath` overrides the file-system-derived\n * path used in callsite ids; `sourcemap`, `minify`, and `target` mirror the\n * bundler's flags. `declaredIntervals` is the adapter's\n * `Capabilities.intervals` set — when supplied, `request.lowerTf` literals\n * are validated against the smallest declared main interval\n * (`lower-tf-not-lower`).\n *\n * @since 0.1\n * @example\n * const opts: CompileOptions = { apiVersion: 1, sourcePath: \"demo.chart.ts\" };\n * void opts;\n */\nexport type CompileOptions = Readonly<{\n apiVersion: 1;\n sourcePath?: string;\n sourcemap?: boolean | \"inline\" | \"external\";\n minify?: boolean;\n target?: \"es2022\";\n declaredIntervals?: ReadonlyArray<IntervalDescriptor>;\n /**\n * Cross-file `.chart.ts` resolver. When undefined, `compile` builds\n * a default per-call resolver rooted at the file's directory.\n * `compileProject` shares one resolver across every file so the\n * inline-once invariant holds (a producer referenced by N consumers\n * compiles exactly once per project compile).\n *\n * @since 0.7\n */\n resolveProducer?: ResolveCrossFileProducer;\n /**\n * Absolute path the cross-file resolver should treat as the project\n * root. Defaults to the directory of `sourcePath`'s absolute\n * resolution. Imports resolving outside this tree return `null`.\n *\n * @since 0.7\n */\n rootDir?: string;\n /**\n * Bare specifier → self-contained ESM source map the bundler resolves\n * in-memory instead of from disk. Lets a host run `compile` where the\n * workspace `@invinite-org/chartlang-*` packages are not installed as\n * resolvable node_modules — e.g. a bundled serverless function, where\n * the packages were inlined into the host bundle rather than shipped\n * to the function filesystem. Each value must have no remaining bare\n * imports (pre-bundle the package before passing it).\n *\n * @since 1.1\n */\n inMemoryModules?: Readonly<Record<string, string>>;\n}>;\n\n/**\n * Options accepted by `compileFile`. Extends `CompileOptions` with a `write`\n * toggle that, when `false`, skips the sibling-file writes and returns the\n * triple in memory only.\n *\n * @since 0.1\n * @example\n * const opts: CompileFileOptions = { apiVersion: 1, write: false };\n * void opts;\n */\nexport type CompileFileOptions = CompileOptions &\n Readonly<{\n write?: boolean;\n }>;\n\n/**\n * Frozen result of a single script compilation. `moduleSource` is the bundled\n * ESM string (with the `export const __manifest = …;` tail appended);\n * `sourcemap` is present when the caller asked for an external map;\n * `manifest` is the recursively-frozen `ScriptManifest`; `types` is the\n * `.d.ts` sibling source.\n *\n * @since 0.1\n * @example\n * // const result: CompiledScript = await compile(src, { apiVersion: 1 });\n * const shape: CompiledScript = {} as CompiledScript;\n * void shape;\n */\nexport type CompiledScript = Readonly<{\n moduleSource: string;\n sourcemap?: string;\n manifest: ScriptManifest;\n types: string;\n}>;\n\n/**\n * Error thrown by `compile` / `compileFile` / `compileProject` when any\n * compilation produces an error-severity diagnostic. Carries the full\n * frozen diagnostic array on `err.diagnostics`; the message starts with the\n * first diagnostic's `code: message (file:line:column)` so console output\n * stays compact.\n *\n * @since 0.1\n * @example\n * // try { await compile(badSrc, { apiVersion: 1 }); }\n * // catch (err) { if (err instanceof CompileError) console.error(err.diagnostics); }\n * const E: typeof CompileError = CompileError;\n * void E;\n */\nexport class CompileError extends Error {\n readonly diagnostics: ReadonlyArray<CompileDiagnostic>;\n\n constructor(diagnostics: ReadonlyArray<CompileDiagnostic>) {\n const first = diagnostics[0];\n const message =\n first === undefined\n ? \"Compilation failed\"\n : `${first.code}: ${first.message} (${first.file}:${first.line}:${first.column})`;\n super(message);\n this.name = \"CompileError\";\n this.diagnostics = diagnostics;\n }\n}\n\nconst PRINTER = ts.createPrinter({\n removeComments: false,\n newLine: ts.NewLineKind.LineFeed,\n});\n\n/**\n * Compile a script source into a frozen `CompiledScript` triple. Runs\n * `transformAndAnalyse`, throws `CompileError` on any error diagnostic,\n * prints the transformed AST, drives esbuild to ESM, appends the\n * `__manifest` assignment, and emits the `.d.ts` sibling.\n *\n * @since 0.1\n * @example\n * // const result = await compile(emaCrossSource, {\n * // apiVersion: 1,\n * // sourcePath: \"ema-cross.chart.ts\",\n * // });\n * const fn: typeof compile = compile;\n * void fn;\n */\nexport async function compile(source: string, opts: CompileOptions): Promise<CompiledScript> {\n const sourcePath = opts.sourcePath ?? \"script.chart.ts\";\n const resolveProducer = opts.resolveProducer ?? createDefaultProducerResolver(sourcePath, opts);\n\n // Pre-scan the consumer's source for `import X from \"./Y.chart\"`\n // statements + resolve them in parallel. Each producer's resolved\n // snapshot feeds the sync lookup passed to `transformAndAnalyse`;\n // the same snapshots become the bundler's `inlinedProducers`.\n const preScan = preScanChartImports(source, sourcePath);\n const resolved = await Promise.all(\n preScan.map(async (specifier) => {\n const compiled = await resolveProducer(specifier, sourcePath);\n return { specifier, compiled };\n }),\n );\n const resolvedBySpecifier = new Map<string, ProducerCompiled | null>();\n for (const entry of resolved) {\n resolvedBySpecifier.set(entry.specifier, entry.compiled);\n }\n\n const transformOpts: TransformAndAnalyseOptions = {\n sourcePath,\n /* v8 ignore next 3 */\n ...(opts.declaredIntervals === undefined\n ? {}\n : { declaredIntervals: opts.declaredIntervals }),\n resolveProducer: (modSpec, expName) => {\n const compiled = resolvedBySpecifier.get(modSpec);\n /* v8 ignore next 3 */\n if (compiled === undefined || compiled === null) {\n return null;\n }\n const manifest = compiled.drawnByExportName.get(expName);\n /* v8 ignore next 3 */\n if (manifest === undefined) {\n return null;\n }\n /* v8 ignore next */\n const outputs = manifest.outputs ?? [];\n return Object.freeze({\n name: manifest.name,\n outputs: Object.freeze(\n outputs.map((o) => Object.freeze({ title: o.title, kind: o.kind })),\n ),\n inputs: Object.fromEntries(\n Object.entries(manifest.inputs).map(([key, descriptor]) => [\n key,\n descriptor as unknown,\n ]),\n ),\n });\n },\n };\n const result = transformAndAnalyse(source, transformOpts);\n\n const errors = result.diagnostics.filter((d) => d.severity === \"error\");\n if (errors.length > 0) {\n throw new CompileError(Object.freeze(errors.slice()));\n }\n\n const printedSource = PRINTER.printFile(result.transformed);\n const sourcemap = opts.sourcemap ?? false;\n // Walk every direct dep's transitive producer tree to build a\n // topologically-ordered list (leaves first). Dedup by hash so a\n // producer reached via two paths inlines exactly once.\n const orderedProducers: ProducerCompiled[] = [];\n const seenHashes = new Set<string>();\n const collectTransitive = (p: ProducerCompiled): void => {\n if (seenHashes.has(p.hash)) return;\n for (const nested of p.transitiveProducers) collectTransitive(nested);\n seenHashes.add(p.hash);\n orderedProducers.push(p);\n };\n for (const { compiled } of resolved) {\n /* v8 ignore next */\n if (compiled === null) continue;\n collectTransitive(compiled);\n }\n // Lower each cross-file `import <name> from \"./X.chart\"` line in\n // the consumer's source to `const <name> = __producer_<hash>__default;`\n // so the inlined producer's local binding feeds the rest of the\n // consumer's body. Imports of non-resolved producers stay as-is so\n // esbuild surfaces the unresolved-import error.\n const specifierToHash = new Map<string, string>();\n for (const entry of resolved) {\n /* v8 ignore next */\n if (entry.compiled === null) continue;\n specifierToHash.set(entry.specifier, entry.compiled.hash);\n }\n const consumerSourceWithRewrittenImports = rewriteConsumerChartImports(\n printedSource,\n specifierToHash,\n );\n // §22.10 indicator-composition: when the default manifest declares\n // private deps, append a hidden `export const __dependencies = [...]`\n // BEFORE handing the source to esbuild so the bundler sees every\n // alias binding referenced from the export graph. Pre-bundle inclusion\n // is load-bearing — appending after `bundleModule` would let esbuild's\n // tree-shaker drop aliases declared via `const trend = baseTrend;`\n // (cross-file aliases reduce to a bare reference after the §22.10\n // `withInputs` chain rewrite, which esbuild treats as side-effect-free\n // and DCE-eligible).\n const defaultDeps = result.manifest.dependencies ?? [];\n const depsAssignment = formatDependenciesAssignment(\n defaultDeps.map((d) => ({\n localId: d.localId,\n bindingExpression: d.localId,\n ...(Object.keys(d.effectiveInputs).length === 0\n ? {}\n : { effectiveInputs: d.effectiveInputs }),\n })),\n );\n const transformedSource = `${consumerSourceWithRewrittenImports}\\n${depsAssignment}`;\n const inlinedProducers = orderedProducers.map((p) => ({\n hash: p.hash,\n rewrittenSource: p.rewrittenSource,\n }));\n const bundle = await bundleModule({\n transformedSource,\n sourcePath,\n sourcemap,\n minify: opts.minify ?? false,\n ...(inlinedProducers.length === 0 ? {} : { inlinedProducers }),\n ...(opts.inMemoryModules === undefined ? {} : { inMemoryModules: opts.inMemoryModules }),\n });\n\n const sidecar: ScriptManifest | ReadonlyArray<ScriptManifest> =\n result.siblings === undefined\n ? result.manifest\n : Object.freeze([result.manifest, ...result.siblings]);\n const moduleSource = `${bundle.moduleSource}${formatManifestAssignment(sidecar)}`;\n const types = emitTypes({ manifest: sidecar, sourcePath });\n\n if (bundle.sourcemap !== undefined) {\n return Object.freeze({\n moduleSource,\n sourcemap: bundle.sourcemap,\n manifest: result.manifest,\n types,\n });\n }\n return Object.freeze({\n moduleSource,\n manifest: result.manifest,\n types,\n });\n}\n\n/**\n * Write a file atomically — render to a `<target>.tmp.<rand>` sibling first,\n * then `rename` into place. On any error during write or rename, the temp\n * file is unlinked so the caller never sees a half-written artefact.\n *\n * @since 0.1\n * @example\n * // await writeAtomic(\"/tmp/foo.txt\", \"hello\");\n * const fn: typeof writeAtomic = writeAtomic;\n * void fn;\n */\nexport async function writeAtomic(target: string, contents: string): Promise<void> {\n const suffix = randomBytes(8).toString(\"hex\");\n const tmp = `${target}.tmp.${suffix}`;\n try {\n await writeFile(tmp, contents, \"utf8\");\n await rename(tmp, target);\n } catch (err) {\n try {\n await unlink(tmp);\n } catch {\n // Best-effort cleanup; the rename failure is the real error.\n }\n throw err;\n }\n}\n\n/**\n * Read a `.chart.ts` file from disk, compile it, and (when `write !== false`)\n * emit the three sibling files atomically — `<base>.chart.js`,\n * `<base>.chart.manifest.json`, `<base>.chart.d.ts`, plus\n * `<base>.chart.js.map` when `sourcemap` is external.\n *\n * @since 0.1\n * @example\n * // const result = await compileFile(\"./demo.chart.ts\", { apiVersion: 1 });\n * const fn: typeof compileFile = compileFile;\n * void fn;\n */\nexport async function compileFile(path: string, opts: CompileFileOptions): Promise<CompiledScript> {\n const absolute = isAbsolute(path) ? path : resolvePath(process.cwd(), path);\n const source = await readFile(absolute, \"utf8\");\n const sourcePath = opts.sourcePath ?? toPosixRelative(process.cwd(), absolute);\n\n const compileOpts: CompileOptions = stripWriteFlag({ ...opts, sourcePath });\n const result = await compile(source, compileOpts);\n\n if (opts.write === false) {\n return result;\n }\n\n const base = absolute.replace(/\\.chart\\.ts$/, \"\");\n const jsPath = `${base}.chart.js`;\n const manifestPath = `${base}.chart.manifest.json`;\n const dtsPath = `${base}.chart.d.ts`;\n\n const sidecar: ScriptManifest | ReadonlyArray<ScriptManifest> =\n result.manifest.siblings === undefined\n ? result.manifest\n : Object.freeze([result.manifest, ...result.manifest.siblings]);\n\n await writeAtomic(jsPath, result.moduleSource);\n await writeAtomic(manifestPath, JSON.stringify(sidecar, null, 4));\n await writeAtomic(dtsPath, result.types);\n if (\n (opts.sourcemap === true || opts.sourcemap === \"external\") &&\n result.sourcemap !== undefined\n ) {\n await writeAtomic(`${jsPath}.map`, result.sourcemap);\n }\n\n return result;\n}\n\n/**\n * Walk `rootDir` recursively and return every `*.chart.ts` file's absolute\n * path. Skips `node_modules` and `dist` subtrees. The walker is iterative to\n * stay portable across Node 20.1 → 20.x.\n *\n * @since 0.1\n * @example\n * // const files = await walkChartFiles(\"./examples/scripts\");\n * const fn: typeof walkChartFiles = walkChartFiles;\n * void fn;\n */\nexport async function walkChartFiles(rootDir: string): Promise<string[]> {\n const absolute = isAbsolute(rootDir) ? rootDir : resolvePath(process.cwd(), rootDir);\n const out: string[] = [];\n const queue: string[] = [absolute];\n\n for (;;) {\n const current = queue.shift();\n if (current === undefined) break;\n\n let entries: Awaited<ReturnType<typeof readDirEntries>>;\n try {\n entries = await readDirEntries(current);\n } catch {\n continue;\n }\n\n for (const entry of entries) {\n if (entry.name === \"node_modules\" || entry.name === \"dist\") continue;\n const full = join(current, entry.name);\n if (entry.isDirectory) {\n queue.push(full);\n continue;\n }\n if (entry.isFile && full.endsWith(\".chart.ts\")) {\n out.push(full);\n }\n }\n }\n\n out.sort();\n return out;\n}\n\n/**\n * Discover every `*.chart.ts` under `rootDir` and compile each in parallel.\n * Results are returned in deterministic (path-sorted) order so callers can\n * snapshot the array safely. Compilation runs in memory only — the CLI\n * (Phase-1 Task 11) loops `compileFile` when it needs sibling files on disk.\n *\n * @since 0.1\n * @example\n * // const all = await compileProject(\"./examples/scripts\", { apiVersion: 1 });\n * const fn: typeof compileProject = compileProject;\n * void fn;\n */\nexport async function compileProject(\n rootDir: string,\n opts: CompileOptions,\n): Promise<ReadonlyArray<CompiledScript>> {\n const files = await walkChartFiles(rootDir);\n let absoluteRoot: string;\n if (isAbsolute(rootDir)) {\n absoluteRoot = rootDir;\n /* v8 ignore next 3 */\n } else {\n absoluteRoot = resolvePath(process.cwd(), rootDir);\n }\n const sharedResolver: ResolveCrossFileProducer =\n opts.resolveProducer ??\n createProducerResolver({ rootDir: absoluteRoot }, (source, producerSourcePath) =>\n compileProducerArtefacts(source, producerSourcePath, sharedResolver),\n );\n const compiled = await Promise.all(\n files.map((file) =>\n compileFile(file, {\n ...opts,\n write: false,\n sourcePath: toPosixRelative(process.cwd(), file),\n resolveProducer: sharedResolver,\n rootDir: absoluteRoot,\n }),\n ),\n );\n return Object.freeze(compiled);\n}\n\nfunction toPosixRelative(cwd: string, absolute: string): string {\n return relative(cwd, absolute).replace(/\\\\/g, \"/\");\n}\n\ntype DirEntry = Readonly<{ name: string; isDirectory: boolean; isFile: boolean }>;\n\nasync function readDirEntries(dir: string): Promise<DirEntry[]> {\n const raw = await readdir(dir, { withFileTypes: true });\n return raw.map((entry) =>\n Object.freeze({\n name: entry.name,\n isDirectory: entry.isDirectory(),\n isFile: entry.isFile(),\n }),\n );\n}\n\nfunction buildDependencyDeclarations(\n drawn: DrawnScript,\n depGraph: DepGraph,\n sourcePath: string,\n): ReadonlyArray<DependencyDeclaration> {\n if (drawn.consumes.length === 0) return Object.freeze([]);\n const declarations: DependencyDeclaration[] = [];\n for (const consume of drawn.consumes) {\n declarations.push(buildOneDependencyDeclaration(consume, depGraph, sourcePath));\n }\n return Object.freeze(declarations);\n}\n\nfunction buildOneDependencyDeclaration(\n consume: DrawnScript[\"consumes\"][number],\n depGraph: DepGraph,\n sourcePath: string,\n): DependencyDeclaration {\n const ref = consume.producerRef;\n const outputsCopy = consume.outputs.map(\n (o): OutputDeclaration => Object.freeze({ title: o.title, kind: o.kind }),\n );\n /* v8 ignore next */\n if (ref.kind !== \"same-file\") return buildCrossFileDeclaration(consume, ref, outputsCopy);\n const isDrawn = depGraph.drawn.some(\n (d) => d.bindingName === ref.bindingName && d.exportName !== \"default\",\n );\n const exportName =\n depGraph.drawn.find((d) => d.bindingName === ref.bindingName)?.exportName ??\n ref.bindingName;\n return Object.freeze({\n localId: consume.localId,\n producerName: ref.bindingName,\n producerSourcePath: sourcePath,\n producerExportName: exportName,\n effectiveInputs: Object.freeze({ ...consume.effectiveInputs }),\n outputs: Object.freeze(outputsCopy),\n isDrawn,\n });\n}\n\n/* v8 ignore start */\nfunction buildCrossFileDeclaration(\n consume: DrawnScript[\"consumes\"][number],\n ref: Extract<DrawnScript[\"consumes\"][number][\"producerRef\"], { kind: \"cross-file\" }>,\n outputsCopy: ReadonlyArray<OutputDeclaration>,\n): DependencyDeclaration {\n return Object.freeze({\n localId: consume.localId,\n producerName: ref.exportName,\n producerSourcePath: ref.sourcePath,\n producerExportName: ref.exportName,\n effectiveInputs: Object.freeze({ ...consume.effectiveInputs }),\n outputs: Object.freeze(outputsCopy),\n isDrawn: false,\n });\n}\n/* v8 ignore stop */\n\nfunction stripWriteFlag(opts: CompileFileOptions): CompileOptions {\n const {\n apiVersion,\n sourcePath,\n sourcemap,\n minify,\n target,\n declaredIntervals,\n resolveProducer,\n rootDir,\n } = opts;\n const out: { -readonly [K in keyof CompileOptions]: CompileOptions[K] } = { apiVersion };\n if (sourcePath !== undefined) out.sourcePath = sourcePath;\n if (sourcemap !== undefined) out.sourcemap = sourcemap;\n if (minify !== undefined) out.minify = minify;\n if (target !== undefined) out.target = target;\n if (declaredIntervals !== undefined) out.declaredIntervals = declaredIntervals;\n if (resolveProducer !== undefined) out.resolveProducer = resolveProducer;\n if (rootDir !== undefined) out.rootDir = rootDir;\n return out;\n}\n\n/**\n * Lower each cross-file `import <name> from \"./X.chart\"` line in the\n * consumer's printed TS source to `const <name> = __producer_<hash>__default;`\n * so the inlined producer's local binding wires into the consumer's body.\n * Imports of unresolved specifiers (no entry in `specifierToHash`) stay\n * as-is so esbuild surfaces the resolution failure.\n *\n * Phase 1 only supports the default-import form — named imports remain\n * untouched and will be addressed when same-file named-export composition\n * crosses file boundaries.\n *\n * @since 0.7\n */\nfunction rewriteConsumerChartImports(\n source: string,\n specifierToHash: ReadonlyMap<string, string>,\n): string {\n if (specifierToHash.size === 0) return source;\n return source.replace(\n /^\\s*import\\s+([A-Za-z_$][A-Za-z0-9_$]*)\\s+from\\s+(['\"])([^'\"]+)\\2;\\s*$/gm,\n (match, name: string, _quote: string, specifier: string) => {\n const hash = specifierToHash.get(specifier);\n /* v8 ignore next */\n if (hash === undefined) return match;\n return `const ${name} = __producer_${hash}__default;`;\n },\n );\n}\n\n/**\n * Pre-scan a `.chart.ts` source for `.chart.ts` / `.chart` import\n * specifiers using a one-pass AST walk. Returns a deduplicated array of\n * specifiers in source-declaration order. The list feeds `compile`'s\n * async resolver before `transformAndAnalyse` runs so the analysis pass\n * can resolve cross-file producer snapshots synchronously.\n *\n * @since 0.7\n */\nfunction preScanChartImports(source: string, sourcePath: string): ReadonlyArray<string> {\n const sourceFile = ts.createSourceFile(\n sourcePath,\n source,\n ts.ScriptTarget.ES2022,\n true,\n ts.ScriptKind.TS,\n );\n const specifiers: string[] = [];\n const seen = new Set<string>();\n for (const statement of sourceFile.statements) {\n if (!ts.isImportDeclaration(statement)) continue;\n const specifier = statement.moduleSpecifier;\n /* v8 ignore next 3 */\n if (!ts.isStringLiteral(specifier)) {\n continue;\n }\n const text = specifier.text;\n if (!text.endsWith(\".chart\") && !text.endsWith(\".chart.ts\")) continue;\n /* v8 ignore next 3 */\n if (seen.has(text)) {\n continue;\n }\n seen.add(text);\n specifiers.push(text);\n }\n return Object.freeze(specifiers);\n}\n\n/**\n * Build a per-`compile` cross-file resolver rooted at the consumer's\n * directory. `compileProject` overrides this by sharing a single\n * resolver across every file so the inline-once invariant holds.\n *\n * @since 0.7\n */\nfunction createDefaultProducerResolver(\n sourcePath: string,\n opts: CompileOptions,\n): ResolveCrossFileProducer {\n let absSourcePath: string;\n /* v8 ignore next 3 */\n if (isAbsolute(sourcePath)) {\n absSourcePath = sourcePath;\n } else {\n absSourcePath = resolvePath(process.cwd(), sourcePath);\n }\n const rootDir = opts.rootDir ?? dirname(absSourcePath);\n const resolver: ResolveCrossFileProducer = createProducerResolver(\n { rootDir },\n (source, producerSourcePath) =>\n compileProducerArtefacts(source, producerSourcePath, resolver),\n );\n return resolver;\n}\n\n/**\n * Compile one producer file for the resolver. Pre-scans its imports,\n * resolves them recursively (so transitive producers populate the\n * cache before we hand control back), runs the producer's own\n * `compile` + `transformAndAnalyse`, and returns the artefacts the\n * resolver wraps into a {@link ProducerCompiled} snapshot.\n *\n * @since 0.7\n */\nasync function compileProducerArtefacts(\n source: string,\n producerSourcePath: string,\n resolver: ResolveCrossFileProducer,\n): Promise<CompiledProducerArtefacts | null> {\n try {\n // Pre-resolve the producer's own cross-file deps so the\n // recursive `compile` can pull the matching snapshot from the\n // shared resolver's cache instead of compiling twice.\n const preScan = preScanChartImports(source, producerSourcePath);\n const nested = await Promise.all(\n preScan.map(async (specifier) => ({\n specifier,\n compiled: await resolver(specifier, producerSourcePath),\n })),\n );\n const result = await compile(source, {\n apiVersion: 1,\n sourcePath: producerSourcePath,\n resolveProducer: resolver,\n });\n const transformAndAnalyseResult = transformAndAnalyse(source, {\n sourcePath: producerSourcePath,\n resolveProducer: buildSyncSnapshotResolver(nested),\n });\n const transformedSource = PRINTER.printFile(transformAndAnalyseResult.transformed);\n const transitiveProducers: ProducerCompiled[] = [];\n const specifierToHash = new Map<string, string>();\n for (const { specifier, compiled } of nested) {\n /* v8 ignore next */\n if (compiled === null) continue;\n transitiveProducers.push(compiled);\n specifierToHash.set(specifier, compiled.hash);\n }\n let siblings: ReadonlyArray<ScriptManifest>;\n if (transformAndAnalyseResult.siblings === undefined) {\n siblings = Object.freeze([]);\n /* v8 ignore next 3 */\n } else {\n siblings = transformAndAnalyseResult.siblings;\n }\n return Object.freeze({\n moduleSource: result.moduleSource,\n transformedSource,\n manifest: result.manifest,\n siblings,\n transitiveProducers: Object.freeze(transitiveProducers),\n specifierToHash,\n });\n /* v8 ignore next 3 */\n } catch {\n return null;\n }\n}\n\n/**\n * Build a sync snapshot resolver from a pre-resolved list of cross-file\n * producers. Returns the producer manifest's `ProducerSnapshot` shape\n * `transformAndAnalyse` calls when walking consumer-side\n * `<binding>.output(\"title\")` references.\n */\nfunction buildSyncSnapshotResolver(\n nested: ReadonlyArray<{ specifier: string; compiled: ProducerCompiled | null }>,\n): NonNullable<TransformAndAnalyseOptions[\"resolveProducer\"]> {\n const bySpecifier = new Map<string, ProducerCompiled>();\n for (const entry of nested) {\n if (entry.compiled !== null) bySpecifier.set(entry.specifier, entry.compiled);\n }\n return (modSpec, expName) => {\n const compiled = bySpecifier.get(modSpec);\n /* v8 ignore next 3 */\n if (compiled === undefined) {\n return null;\n }\n const manifest = compiled.drawnByExportName.get(expName);\n /* v8 ignore next 3 */\n if (manifest === undefined) {\n return null;\n }\n /* v8 ignore next */\n const outputs = manifest.outputs ?? [];\n return Object.freeze({\n name: manifest.name,\n outputs: Object.freeze(\n outputs.map((o) => Object.freeze({ title: o.title, kind: o.kind })),\n ),\n inputs: Object.fromEntries(\n Object.entries(manifest.inputs).map(([key, descriptor]) => [\n key,\n descriptor as unknown,\n ]),\n ),\n });\n };\n}\n"]}
1
+ {"version":3,"file":"api.js","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA,+DAA+D;AAC/D,+DAA+D;AAE/D,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAChF,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,WAAW,CAAC;AACxF,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAQ3E,OAAO,EAAE,MAAM,YAAY,CAAC;AAG5B,OAAO,EACH,sBAAsB,EACtB,mBAAmB,EACnB,sBAAsB,EACtB,aAAa,EACb,kBAAkB,EAClB,sBAAsB,EACtB,wBAAwB,EACxB,sBAAsB,EACtB,qBAAqB,EACrB,qBAAqB,EACrB,mBAAmB,EACnB,wBAAwB,GAC3B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,YAAY,EAAE,4BAA4B,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AACnG,OAAO,EAIH,sBAAsB,GACzB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAC9C,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,iBAAiB,EAAE,MAAM,uCAAuC,CAAC;AAC1E,OAAO,EAAE,0BAA0B,EAAE,MAAM,8CAA8C,CAAC;AAC1F,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AA8D3C;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,UAAU,mBAAmB,CAC/B,MA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AAC,IAAI,EAAE,CAAC,CAAC,CACtE;YACD,MAAM,EAAE,MAAM,CAAC,WAAW,CACtB,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,UAAU,CAAC,EAAE,EAAE,CAAC;gBACvD,GAAG;gBACH,UAAqB;aACxB,CAAC,CACL;SACJ,CAAC,CAAC;IACP,CAAC,CAAC;AACN,CAAC","sourcesContent":["// Copyright (c) 2026 Invinite. Licensed under the MIT License.\n// See the LICENSE file in the repo root for full license text.\n\nimport { randomBytes } from \"node:crypto\";\nimport { readFile, readdir, rename, unlink, writeFile } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, relative, resolve as resolvePath } from \"node:path\";\nimport { STATEFUL_PRIMITIVES_BY_NAME } from \"@invinite-org/chartlang-core\";\nimport type {\n DependencyDeclaration,\n IntervalDescriptor,\n OutputDeclaration,\n PlotSlotDescriptor,\n ScriptManifest,\n} from \"@invinite-org/chartlang-core\";\nimport ts from \"typescript\";\n\nimport type { DepGraph, DrawnScript } from \"./analysis/extractDependencyGraph.js\";\nimport {\n extractAlertConditions,\n extractCapabilities,\n extractDependencyGraph,\n extractInputs,\n extractMaxLookback,\n extractRequestAnalysis,\n extractRequiresIntervals,\n runForbiddenConstructs,\n runStateArrayCapacity,\n runStatefulCallInLoop,\n runStructuralChecks,\n validateLowerTfIntervals,\n} from \"./analysis/index.js\";\nimport { bundleModule, formatDependenciesAssignment, formatManifestAssignment } from \"./bundle.js\";\nimport {\n type CompiledProducerArtefacts,\n type ProducerCompiled,\n type ResolveCrossFileProducer,\n createProducerResolver,\n} from \"./dependency/index.js\";\nimport type { CompileDiagnostic } from \"./diagnostics.js\";\nimport { mapTsDiagnostic } from \"./diagnostics.js\";\nimport { buildManifest } from \"./manifest.js\";\nimport { createProgramForSource } from \"./program.js\";\nimport { injectCallsiteIds } from \"./transformers/callsiteIdInjection.js\";\nimport { rewriteDependencyAccessors } from \"./transformers/rewriteDependencyAccessors.js\";\nimport { emitTypes } from \"./typesEmit.js\";\n\n/**\n * Options accepted by `transformAndAnalyse`. `sourcePath` is the\n * package-relative POSIX path baked into every callsite id; the compiler\n * does not read any other file. `declaredIntervals` is the host-supplied\n * `Capabilities.intervals` set used by the `lower-tf-not-lower` validation —\n * when omitted the lower-timeframe ordering check is skipped.\n *\n * `resolveProducer` is the sync §22.10 indicator-composition snapshot\n * lookup; `compile` builds this from the pre-resolved cross-file\n * `ProducerCompiled` snapshots before invoking the transform pass. When\n * omitted (e.g. direct unit-test calls), cross-file dep edges resolve to\n * `null` and the analysis pass treats them as unresolvable.\n *\n * @since 0.1\n * @example\n * const opts: TransformAndAnalyseOptions = { sourcePath: \"demo.chart.ts\" };\n */\nexport type TransformAndAnalyseOptions = Readonly<{\n sourcePath: string;\n declaredIntervals?: ReadonlyArray<IntervalDescriptor>;\n resolveProducer?: (\n moduleSpecifier: string,\n exportName: string,\n ) => Readonly<{\n readonly name: string;\n readonly outputs: ReadonlyArray<{ readonly title: string; readonly kind: string }>;\n readonly inputs: Readonly<Record<string, unknown>>;\n }> | null;\n}>;\n\n/**\n * Result of `transformAndAnalyse`. `transformed` is the AST after callsite\n * ids have been injected; `manifest` is the recursively-frozen\n * `ScriptManifest`; `diagnostics` is the flat list of every diagnostic\n * emitted by any pass (errors abort the rewrite, warnings flow through).\n *\n * `siblings` is populated only for §22.10 multi-export indicator-composition\n * files (files with more than one drawn `defineIndicator(...)` binding) —\n * it carries every named-export manifest in source order. Single-script\n * files omit the field entirely so existing snapshot assertions stay\n * byte-identical.\n *\n * @since 0.1\n * @example\n * // const { transformed, manifest, diagnostics } =\n * // transformAndAnalyse(src, { sourcePath: \"demo.chart.ts\" });\n * const shape: { transformed: unknown; manifest: unknown; diagnostics: unknown } = {\n * transformed: null,\n * manifest: null,\n * diagnostics: [],\n * };\n * void shape;\n */\nexport type TransformAndAnalyseResult = Readonly<{\n transformed: ts.SourceFile;\n manifest: ScriptManifest;\n diagnostics: ReadonlyArray<CompileDiagnostic>;\n siblings?: ReadonlyArray<ScriptManifest>;\n}>;\n\n/**\n * Run the Phase-1 compiler pipeline against an in-memory script source.\n * Builds a TypeScript program, runs the structural / forbidden-construct /\n * stateful-call-in-loop checks, rewrites stateful calls with callsite ids,\n * and extracts the manifest's `capabilities` / `maxLookback` /\n * `seriesCapacities` / `inputs` fields.\n *\n * Error-severity diagnostics short-circuit the transform: the function\n * returns the original `sourceFile` and a placeholder manifest so callers\n * can still surface the errors uniformly. The public `compile` /\n * `compileFile` / `compileProject` wrappers above turn those error\n * diagnostics into a `CompileError` throw.\n *\n * @since 0.1\n * @example\n * // const result = transformAndAnalyse(\n * // 'export default defineIndicator({ name: \"x\", apiVersion: 1, compute: () => {} });',\n * // { sourcePath: \"demo.chart.ts\" },\n * // );\n * const fn: typeof transformAndAnalyse = transformAndAnalyse;\n * void fn;\n */\nexport function transformAndAnalyse(\n source: string,\n opts: TransformAndAnalyseOptions,\n): TransformAndAnalyseResult {\n const sourcePath = opts.sourcePath;\n const chartImports = preScanChartImports(source, sourcePath);\n const { program, sourceFile, checker } = createProgramForSource(source, {\n sourcePath,\n chartImports,\n });\n\n const structural = runStructuralChecks(sourceFile, checker, sourcePath);\n const forbidden = runForbiddenConstructs(sourceFile, sourcePath);\n const statefulInLoop = runStatefulCallInLoop(\n sourceFile,\n checker,\n sourcePath,\n STATEFUL_PRIMITIVES_BY_NAME,\n );\n const stateArrayCapacity = runStateArrayCapacity(sourceFile, checker, sourcePath);\n // PLAN §5.2 step 1: the pipeline starts with tsc programmatic-API\n // typechecking against `@invinite-org/chartlang-core`'s ambient\n // declarations. Surface every semantic error coming from the\n // user's source file under the stable `type-error` code. Shim\n // diagnostics are dropped — they always come from the synthetic\n // core.d.ts and would only ever signal a chartlang-side bug.\n const semanticDiagnostics: CompileDiagnostic[] = program\n .getSemanticDiagnostics(sourceFile)\n .filter((d) => d.file?.fileName === sourceFile.fileName)\n .map((d) => mapTsDiagnostic(d, sourcePath));\n\n const depGraph: DepGraph = extractDependencyGraph(\n sourceFile,\n checker,\n sourcePath,\n structural.bindings,\n opts.resolveProducer === undefined\n ? () => null\n : (modSpec, expName) => {\n const snap = opts.resolveProducer?.(modSpec, expName);\n /* v8 ignore next */\n if (snap === undefined || snap === null) return null;\n return Object.freeze({\n name: snap.name,\n outputs: Object.freeze(\n snap.outputs.map((o) =>\n Object.freeze({\n title: o.title,\n kind: o.kind as \"series-number\",\n }),\n ),\n ),\n inputs: snap.inputs,\n });\n },\n );\n\n const earlyDiagnostics: CompileDiagnostic[] = [\n ...semanticDiagnostics,\n ...structural.diagnostics,\n ...forbidden,\n ...statefulInLoop,\n ...stateArrayCapacity,\n ...depGraph.diagnostics,\n ];\n const hasError = earlyDiagnostics.some((d) => d.severity === \"error\");\n if (hasError) {\n return Object.freeze({\n transformed: sourceFile,\n manifest: buildManifest({\n name: structural.name,\n kind: structural.kind,\n capabilities: [\"indicators\"],\n requestedIntervals: [],\n userPickableInterval: false,\n seriesCapacities: {},\n maxLookback: 0,\n inputs: {},\n ...structural.overrides,\n }),\n diagnostics: Object.freeze(earlyDiagnostics.slice()),\n });\n }\n\n const rewrite = rewriteDependencyAccessors(sourceFile, depGraph, sourcePath);\n const rewrittenSource = rewrite.transformed;\n const plotSlots: PlotSlotDescriptor[] = [];\n const injection = injectCallsiteIds(rewrittenSource, checker, {\n sourcePath,\n statefulByName: STATEFUL_PRIMITIVES_BY_NAME,\n plotSlots,\n });\n const alertConditions = extractAlertConditions(sourceFile, checker, sourcePath);\n const intervalDiagnostics: CompileDiagnostic[] = [];\n const lowerTfDiagnostics = validateLowerTfIntervals(\n sourceFile,\n checker,\n sourcePath,\n opts.declaredIntervals ?? [],\n );\n const { requiresIntervals: structuralRequiresIntervals, ...structuralOverrides } =\n structural.overrides;\n void structuralRequiresIntervals;\n\n // The structural pass guarantees a single default-export drawn\n // entry before we reach this code (errors short-circuit above);\n // we surface the default here for manifest assembly.\n const defaultDrawn = depGraph.drawn.find((d) => d.exportName === \"default\");\n /* v8 ignore start */\n if (defaultDrawn === undefined) {\n // The structural pass guarantees a default-export drawn entry\n // before we reach this code (errors short-circuit above).\n throw new Error(\"internal: depGraph.drawn missing default entry\");\n }\n /* v8 ignore stop */\n\n const isMultiExport = depGraph.drawn.length > 1;\n\n // File-level extractions (single-export back-compat path) — full source\n // walk so existing single-script manifests stay byte-identical.\n const fileCapabilities = extractCapabilities(sourceFile, checker, structural.kind);\n const fileLookback = extractMaxLookback(sourceFile, checker, sourcePath);\n const fileInputs = extractInputs(sourceFile, checker, sourcePath);\n const fileRequestAnalysis = extractRequestAnalysis(\n sourceFile,\n checker,\n fileInputs.inputs,\n intervalDiagnostics,\n sourcePath,\n true,\n );\n const fileRequestedIntervalsFromCalls = fileRequestAnalysis.intervals;\n const fileRequiresIntervals = extractRequiresIntervals(\n sourceFile,\n checker,\n intervalDiagnostics,\n sourcePath,\n );\n const fileRequestedIntervals = Array.from(\n new Set([...fileRequestedIntervalsFromCalls, ...fileRequiresIntervals]),\n ).sort();\n\n const namedManifests: ScriptManifest[] = [];\n if (isMultiExport) {\n for (const drawn of depGraph.drawn) {\n if (drawn.exportName === \"default\") continue;\n namedManifests.push(\n buildDrawnManifest(\n drawn,\n depGraph,\n sourceFile,\n checker,\n sourcePath,\n structural.kind,\n structuralOverrides,\n alertConditions.alertConditions,\n ),\n );\n }\n }\n\n const defaultDependencies = buildDependencyDeclarations(defaultDrawn, depGraph, sourcePath);\n const defaultOutputs = defaultDrawn.outputs.length === 0 ? undefined : defaultDrawn.outputs;\n\n const manifest = isMultiExport\n ? buildDrawnManifest(\n defaultDrawn,\n depGraph,\n sourceFile,\n checker,\n sourcePath,\n structural.kind,\n structuralOverrides,\n alertConditions.alertConditions,\n namedManifests,\n plotSlots,\n )\n : buildManifest({\n name: structural.name,\n kind: structural.kind,\n capabilities: fileCapabilities,\n requestedIntervals: fileRequestedIntervals,\n userPickableInterval: fileInputs.userPickableInterval,\n seriesCapacities: fileLookback.seriesCapacities,\n maxLookback: fileLookback.maxLookback,\n inputs: fileInputs.inputs,\n ...structuralOverrides,\n ...(fileRequiresIntervals.length === 0\n ? {}\n : { requiresIntervals: fileRequiresIntervals }),\n ...(alertConditions.alertConditions.length === 0\n ? {}\n : { alertConditions: alertConditions.alertConditions }),\n ...(defaultDependencies === undefined || defaultDependencies.length === 0\n ? {}\n : { dependencies: defaultDependencies }),\n ...(defaultOutputs === undefined ? {} : { outputs: defaultOutputs }),\n ...(plotSlots.length === 0 ? {} : { plots: plotSlots }),\n ...(fileRequestAnalysis.securityExpressions.length === 0\n ? {}\n : { securityExpressions: fileRequestAnalysis.securityExpressions }),\n ...(fileRequestAnalysis.feeds.length === 0\n ? {}\n : { requestedFeeds: fileRequestAnalysis.feeds }),\n });\n\n const allDiagnostics: CompileDiagnostic[] = [\n ...earlyDiagnostics,\n ...injection.diagnostics,\n ...rewrite.diagnostics,\n ...fileLookback.diagnostics,\n ...fileInputs.diagnostics,\n ...alertConditions.diagnostics,\n ...intervalDiagnostics,\n ...lowerTfDiagnostics,\n ];\n\n return Object.freeze({\n transformed: injection.transformed,\n manifest,\n diagnostics: Object.freeze(allDiagnostics.slice()),\n ...(isMultiExport ? { siblings: Object.freeze(namedManifests.slice()) } : {}),\n });\n}\n\nfunction buildDrawnManifest(\n drawn: DrawnScript,\n depGraph: DepGraph,\n sourceFile: ts.SourceFile,\n checker: ts.TypeChecker,\n sourcePath: string,\n kind: \"indicator\" | \"drawing\" | \"alert\" | \"alertCondition\",\n structuralOverrides: Omit<\n ReturnType<typeof runStructuralChecks>[\"overrides\"],\n \"requiresIntervals\"\n >,\n sharedAlertConditions: ReturnType<typeof extractAlertConditions>[\"alertConditions\"],\n siblings?: ReadonlyArray<ScriptManifest>,\n plotSlots?: ReadonlyArray<PlotSlotDescriptor>,\n): ScriptManifest {\n const intervalDiagnostics: CompileDiagnostic[] = [];\n const scope = drawn.defineCall;\n const capabilities = extractCapabilities(sourceFile, checker, kind, scope);\n const lookback = extractMaxLookback(sourceFile, checker, sourcePath, scope);\n const inputs = extractInputs(sourceFile, checker, sourcePath, scope);\n const requestAnalysis = extractRequestAnalysis(\n sourceFile,\n checker,\n inputs.inputs,\n intervalDiagnostics,\n sourcePath,\n );\n const requestedFromCalls = requestAnalysis.intervals;\n const requiresIntervalsScoped = extractRequiresIntervals(\n sourceFile,\n checker,\n intervalDiagnostics,\n sourcePath,\n );\n const requestedIntervals = Array.from(\n new Set([...requestedFromCalls, ...requiresIntervalsScoped]),\n ).sort();\n const dependencies = buildDependencyDeclarations(drawn, depGraph, sourcePath);\n const outputs = drawn.outputs.length === 0 ? undefined : drawn.outputs;\n const isDefault = drawn.exportName === \"default\";\n const nameForManifest = isDefault ? readDefineCallName(drawn.defineCall) : drawn.bindingName;\n\n return buildManifest({\n name: nameForManifest,\n kind,\n capabilities,\n requestedIntervals,\n userPickableInterval: inputs.userPickableInterval,\n seriesCapacities: lookback.seriesCapacities,\n maxLookback: lookback.maxLookback,\n inputs: inputs.inputs,\n ...structuralOverrides,\n /* v8 ignore start */\n ...(requiresIntervalsScoped.length === 0\n ? {}\n : { requiresIntervals: requiresIntervalsScoped }),\n ...(sharedAlertConditions.length === 0 ? {} : { alertConditions: sharedAlertConditions }),\n /* v8 ignore stop */\n ...(dependencies === undefined || dependencies.length === 0 ? {} : { dependencies }),\n ...(outputs === undefined ? {} : { outputs }),\n ...(plotSlots === undefined || plotSlots.length === 0 ? {} : { plots: plotSlots }),\n // Mirror `plots` scoping: the flat security-expression list and the\n // requested-feeds list attach to the default manifest only (the call\n // that also receives `plotSlots`).\n ...(plotSlots === undefined || requestAnalysis.securityExpressions.length === 0\n ? {}\n : { securityExpressions: requestAnalysis.securityExpressions }),\n ...(plotSlots === undefined || requestAnalysis.feeds.length === 0\n ? {}\n : { requestedFeeds: requestAnalysis.feeds }),\n exportName: drawn.exportName,\n isDrawn: true,\n ...(siblings !== undefined && siblings.length > 0 ? { siblings } : {}),\n });\n}\n\nfunction readDefineCallName(defineCall: ts.CallExpression): string {\n const arg = defineCall.arguments[0];\n /* v8 ignore next 3 */\n if (arg === undefined || !ts.isObjectLiteralExpression(arg)) {\n return \"\";\n }\n for (const property of arg.properties) {\n /* v8 ignore next */\n if (!ts.isPropertyAssignment(property)) continue;\n const name = property.name;\n /* v8 ignore next */\n if (!ts.isIdentifier(name) || name.text !== \"name\") continue;\n const initializer = property.initializer;\n if (ts.isStringLiteral(initializer)) return initializer.text;\n /* v8 ignore next */\n }\n /* v8 ignore next 2 */\n return \"\";\n}\n\n/**\n * Options accepted by `compile`. `apiVersion` is the frozen language\n * version this compiler implements. Passing `apiVersion: 1` is an explicit\n * acknowledgement of that contract; the type stays the literal `1` so a\n * future `apiVersion: 2` compiler is a type-level break. See\n * `docs/spec/versioning.md`. `sourcePath` overrides the file-system-derived\n * path used in callsite ids; `sourcemap`, `minify`, and `target` mirror the\n * bundler's flags. `declaredIntervals` is the adapter's\n * `Capabilities.intervals` set — when supplied, `request.lowerTf` literals\n * are validated against the smallest declared main interval\n * (`lower-tf-not-lower`).\n *\n * @since 0.1\n * @example\n * const opts: CompileOptions = { apiVersion: 1, sourcePath: \"demo.chart.ts\" };\n * void opts;\n */\nexport type CompileOptions = Readonly<{\n apiVersion: 1;\n sourcePath?: string;\n sourcemap?: boolean | \"inline\" | \"external\";\n minify?: boolean;\n target?: \"es2022\";\n declaredIntervals?: ReadonlyArray<IntervalDescriptor>;\n /**\n * Cross-file `.chart.ts` resolver. When undefined, `compile` builds\n * a default per-call resolver rooted at the file's directory.\n * `compileProject` shares one resolver across every file so the\n * inline-once invariant holds (a producer referenced by N consumers\n * compiles exactly once per project compile).\n *\n * @since 0.7\n */\n resolveProducer?: ResolveCrossFileProducer;\n /**\n * Absolute path the cross-file resolver should treat as the project\n * root. Defaults to the directory of `sourcePath`'s absolute\n * resolution. Imports resolving outside this tree return `null`.\n *\n * @since 0.7\n */\n rootDir?: string;\n /**\n * Bare specifier → self-contained ESM source map the bundler resolves\n * in-memory instead of from disk. Lets a host run `compile` where the\n * workspace `@invinite-org/chartlang-*` packages are not installed as\n * resolvable node_modules — e.g. a bundled serverless function, where\n * the packages were inlined into the host bundle rather than shipped\n * to the function filesystem. Each value must have no remaining bare\n * imports (pre-bundle the package before passing it).\n *\n * @since 1.1\n */\n inMemoryModules?: Readonly<Record<string, string>>;\n}>;\n\n/**\n * Options accepted by `compileFile`. Extends `CompileOptions` with a `write`\n * toggle that, when `false`, skips the sibling-file writes and returns the\n * triple in memory only.\n *\n * @since 0.1\n * @example\n * const opts: CompileFileOptions = { apiVersion: 1, write: false };\n * void opts;\n */\nexport type CompileFileOptions = CompileOptions &\n Readonly<{\n write?: boolean;\n }>;\n\n/**\n * Frozen result of a single script compilation. `moduleSource` is the bundled\n * ESM string (with the `export const __manifest = …;` tail appended);\n * `sourcemap` is present when the caller asked for an external map;\n * `manifest` is the recursively-frozen `ScriptManifest`; `types` is the\n * `.d.ts` sibling source.\n *\n * @since 0.1\n * @example\n * // const result: CompiledScript = await compile(src, { apiVersion: 1 });\n * const shape: CompiledScript = {} as CompiledScript;\n * void shape;\n */\nexport type CompiledScript = Readonly<{\n moduleSource: string;\n sourcemap?: string;\n manifest: ScriptManifest;\n types: string;\n}>;\n\n/**\n * Error thrown by `compile` / `compileFile` / `compileProject` when any\n * compilation produces an error-severity diagnostic. Carries the full\n * frozen diagnostic array on `err.diagnostics`; the message starts with the\n * first diagnostic's `code: message (file:line:column)` so console output\n * stays compact.\n *\n * @since 0.1\n * @example\n * // try { await compile(badSrc, { apiVersion: 1 }); }\n * // catch (err) { if (err instanceof CompileError) console.error(err.diagnostics); }\n * const E: typeof CompileError = CompileError;\n * void E;\n */\nexport class CompileError extends Error {\n readonly diagnostics: ReadonlyArray<CompileDiagnostic>;\n\n constructor(diagnostics: ReadonlyArray<CompileDiagnostic>) {\n const first = diagnostics[0];\n const message =\n first === undefined\n ? \"Compilation failed\"\n : `${first.code}: ${first.message} (${first.file}:${first.line}:${first.column})`;\n super(message);\n this.name = \"CompileError\";\n this.diagnostics = diagnostics;\n }\n}\n\nconst PRINTER = ts.createPrinter({\n removeComments: false,\n newLine: ts.NewLineKind.LineFeed,\n});\n\n/**\n * Compile a script source into a frozen `CompiledScript` triple. Runs\n * `transformAndAnalyse`, throws `CompileError` on any error diagnostic,\n * prints the transformed AST, drives esbuild to ESM, appends the\n * `__manifest` assignment, and emits the `.d.ts` sibling.\n *\n * @since 0.1\n * @example\n * // const result = await compile(emaCrossSource, {\n * // apiVersion: 1,\n * // sourcePath: \"ema-cross.chart.ts\",\n * // });\n * const fn: typeof compile = compile;\n * void fn;\n */\nexport async function compile(source: string, opts: CompileOptions): Promise<CompiledScript> {\n const sourcePath = opts.sourcePath ?? \"script.chart.ts\";\n const resolveProducer = opts.resolveProducer ?? createDefaultProducerResolver(sourcePath, opts);\n\n // Pre-scan the consumer's source for `import X from \"./Y.chart\"`\n // statements + resolve them in parallel. Each producer's resolved\n // snapshot feeds the sync lookup passed to `transformAndAnalyse`;\n // the same snapshots become the bundler's `inlinedProducers`.\n const preScan = preScanChartImports(source, sourcePath);\n const resolved = await Promise.all(\n preScan.map(async (specifier) => {\n const compiled = await resolveProducer(specifier, sourcePath);\n return { specifier, compiled };\n }),\n );\n const resolvedBySpecifier = new Map<string, ProducerCompiled | null>();\n for (const entry of resolved) {\n resolvedBySpecifier.set(entry.specifier, entry.compiled);\n }\n\n const transformOpts: TransformAndAnalyseOptions = {\n sourcePath,\n /* v8 ignore next 3 */\n ...(opts.declaredIntervals === undefined\n ? {}\n : { declaredIntervals: opts.declaredIntervals }),\n resolveProducer: (modSpec, expName) => {\n const compiled = resolvedBySpecifier.get(modSpec);\n /* v8 ignore next 3 */\n if (compiled === undefined || compiled === null) {\n return null;\n }\n const manifest = compiled.drawnByExportName.get(expName);\n /* v8 ignore next 3 */\n if (manifest === undefined) {\n return null;\n }\n /* v8 ignore next */\n const outputs = manifest.outputs ?? [];\n return Object.freeze({\n name: manifest.name,\n outputs: Object.freeze(\n outputs.map((o) => Object.freeze({ title: o.title, kind: o.kind })),\n ),\n inputs: Object.fromEntries(\n Object.entries(manifest.inputs).map(([key, descriptor]) => [\n key,\n descriptor as unknown,\n ]),\n ),\n });\n },\n };\n const result = transformAndAnalyse(source, transformOpts);\n\n const errors = result.diagnostics.filter((d) => d.severity === \"error\");\n if (errors.length > 0) {\n throw new CompileError(Object.freeze(errors.slice()));\n }\n\n const printedSource = PRINTER.printFile(result.transformed);\n const sourcemap = opts.sourcemap ?? false;\n // Walk every direct dep's transitive producer tree to build a\n // topologically-ordered list (leaves first). Dedup by hash so a\n // producer reached via two paths inlines exactly once.\n const orderedProducers: ProducerCompiled[] = [];\n const seenHashes = new Set<string>();\n const collectTransitive = (p: ProducerCompiled): void => {\n if (seenHashes.has(p.hash)) return;\n for (const nested of p.transitiveProducers) collectTransitive(nested);\n seenHashes.add(p.hash);\n orderedProducers.push(p);\n };\n for (const { compiled } of resolved) {\n /* v8 ignore next */\n if (compiled === null) continue;\n collectTransitive(compiled);\n }\n // Lower each cross-file `import <name> from \"./X.chart\"` line in\n // the consumer's source to `const <name> = __producer_<hash>__default;`\n // so the inlined producer's local binding feeds the rest of the\n // consumer's body. Imports of non-resolved producers stay as-is so\n // esbuild surfaces the unresolved-import error.\n const specifierToHash = new Map<string, string>();\n for (const entry of resolved) {\n /* v8 ignore next */\n if (entry.compiled === null) continue;\n specifierToHash.set(entry.specifier, entry.compiled.hash);\n }\n const consumerSourceWithRewrittenImports = rewriteConsumerChartImports(\n printedSource,\n specifierToHash,\n );\n // §22.10 indicator-composition: when the default manifest declares\n // private deps, append a hidden `export const __dependencies = [...]`\n // BEFORE handing the source to esbuild so the bundler sees every\n // alias binding referenced from the export graph. Pre-bundle inclusion\n // is load-bearing — appending after `bundleModule` would let esbuild's\n // tree-shaker drop aliases declared via `const trend = baseTrend;`\n // (cross-file aliases reduce to a bare reference after the §22.10\n // `withInputs` chain rewrite, which esbuild treats as side-effect-free\n // and DCE-eligible).\n const defaultDeps = result.manifest.dependencies ?? [];\n const depsAssignment = formatDependenciesAssignment(\n defaultDeps.map((d) => ({\n localId: d.localId,\n bindingExpression: d.localId,\n ...(Object.keys(d.effectiveInputs).length === 0\n ? {}\n : { effectiveInputs: d.effectiveInputs }),\n })),\n );\n const transformedSource = `${consumerSourceWithRewrittenImports}\\n${depsAssignment}`;\n const inlinedProducers = orderedProducers.map((p) => ({\n hash: p.hash,\n rewrittenSource: p.rewrittenSource,\n }));\n const bundle = await bundleModule({\n transformedSource,\n sourcePath,\n sourcemap,\n minify: opts.minify ?? false,\n ...(inlinedProducers.length === 0 ? {} : { inlinedProducers }),\n ...(opts.inMemoryModules === undefined ? {} : { inMemoryModules: opts.inMemoryModules }),\n });\n\n const sidecar: ScriptManifest | ReadonlyArray<ScriptManifest> =\n result.siblings === undefined\n ? result.manifest\n : Object.freeze([result.manifest, ...result.siblings]);\n const moduleSource = `${bundle.moduleSource}${formatManifestAssignment(sidecar)}`;\n const types = emitTypes({ manifest: sidecar, sourcePath });\n\n if (bundle.sourcemap !== undefined) {\n return Object.freeze({\n moduleSource,\n sourcemap: bundle.sourcemap,\n manifest: result.manifest,\n types,\n });\n }\n return Object.freeze({\n moduleSource,\n manifest: result.manifest,\n types,\n });\n}\n\n/**\n * Write a file atomically — render to a `<target>.tmp.<rand>` sibling first,\n * then `rename` into place. On any error during write or rename, the temp\n * file is unlinked so the caller never sees a half-written artefact.\n *\n * @since 0.1\n * @example\n * // await writeAtomic(\"/tmp/foo.txt\", \"hello\");\n * const fn: typeof writeAtomic = writeAtomic;\n * void fn;\n */\nexport async function writeAtomic(target: string, contents: string): Promise<void> {\n const suffix = randomBytes(8).toString(\"hex\");\n const tmp = `${target}.tmp.${suffix}`;\n try {\n await writeFile(tmp, contents, \"utf8\");\n await rename(tmp, target);\n } catch (err) {\n try {\n await unlink(tmp);\n } catch {\n // Best-effort cleanup; the rename failure is the real error.\n }\n throw err;\n }\n}\n\n/**\n * Read a `.chart.ts` file from disk, compile it, and (when `write !== false`)\n * emit the three sibling files atomically — `<base>.chart.js`,\n * `<base>.chart.manifest.json`, `<base>.chart.d.ts`, plus\n * `<base>.chart.js.map` when `sourcemap` is external.\n *\n * @since 0.1\n * @example\n * // const result = await compileFile(\"./demo.chart.ts\", { apiVersion: 1 });\n * const fn: typeof compileFile = compileFile;\n * void fn;\n */\nexport async function compileFile(path: string, opts: CompileFileOptions): Promise<CompiledScript> {\n const absolute = isAbsolute(path) ? path : resolvePath(process.cwd(), path);\n const source = await readFile(absolute, \"utf8\");\n const sourcePath = opts.sourcePath ?? toPosixRelative(process.cwd(), absolute);\n\n const compileOpts: CompileOptions = stripWriteFlag({ ...opts, sourcePath });\n const result = await compile(source, compileOpts);\n\n if (opts.write === false) {\n return result;\n }\n\n const base = absolute.replace(/\\.chart\\.ts$/, \"\");\n const jsPath = `${base}.chart.js`;\n const manifestPath = `${base}.chart.manifest.json`;\n const dtsPath = `${base}.chart.d.ts`;\n\n const sidecar: ScriptManifest | ReadonlyArray<ScriptManifest> =\n result.manifest.siblings === undefined\n ? result.manifest\n : Object.freeze([result.manifest, ...result.manifest.siblings]);\n\n await writeAtomic(jsPath, result.moduleSource);\n await writeAtomic(manifestPath, JSON.stringify(sidecar, null, 4));\n await writeAtomic(dtsPath, result.types);\n if (\n (opts.sourcemap === true || opts.sourcemap === \"external\") &&\n result.sourcemap !== undefined\n ) {\n await writeAtomic(`${jsPath}.map`, result.sourcemap);\n }\n\n return result;\n}\n\n/**\n * Walk `rootDir` recursively and return every `*.chart.ts` file's absolute\n * path. Skips `node_modules` and `dist` subtrees. The walker is iterative to\n * stay portable across Node 20.1 → 20.x.\n *\n * @since 0.1\n * @example\n * // const files = await walkChartFiles(\"./examples/scripts\");\n * const fn: typeof walkChartFiles = walkChartFiles;\n * void fn;\n */\nexport async function walkChartFiles(rootDir: string): Promise<string[]> {\n const absolute = isAbsolute(rootDir) ? rootDir : resolvePath(process.cwd(), rootDir);\n const out: string[] = [];\n const queue: string[] = [absolute];\n\n for (;;) {\n const current = queue.shift();\n if (current === undefined) break;\n\n let entries: Awaited<ReturnType<typeof readDirEntries>>;\n try {\n entries = await readDirEntries(current);\n } catch {\n continue;\n }\n\n for (const entry of entries) {\n if (entry.name === \"node_modules\" || entry.name === \"dist\") continue;\n const full = join(current, entry.name);\n if (entry.isDirectory) {\n queue.push(full);\n continue;\n }\n if (entry.isFile && full.endsWith(\".chart.ts\")) {\n out.push(full);\n }\n }\n }\n\n out.sort();\n return out;\n}\n\n/**\n * Discover every `*.chart.ts` under `rootDir` and compile each in parallel.\n * Results are returned in deterministic (path-sorted) order so callers can\n * snapshot the array safely. Compilation runs in memory only — the CLI\n * (Phase-1 Task 11) loops `compileFile` when it needs sibling files on disk.\n *\n * @since 0.1\n * @example\n * // const all = await compileProject(\"./examples/scripts\", { apiVersion: 1 });\n * const fn: typeof compileProject = compileProject;\n * void fn;\n */\nexport async function compileProject(\n rootDir: string,\n opts: CompileOptions,\n): Promise<ReadonlyArray<CompiledScript>> {\n const files = await walkChartFiles(rootDir);\n let absoluteRoot: string;\n if (isAbsolute(rootDir)) {\n absoluteRoot = rootDir;\n /* v8 ignore next 3 */\n } else {\n absoluteRoot = resolvePath(process.cwd(), rootDir);\n }\n const sharedResolver: ResolveCrossFileProducer =\n opts.resolveProducer ??\n createProducerResolver({ rootDir: absoluteRoot }, (source, producerSourcePath) =>\n compileProducerArtefacts(source, producerSourcePath, sharedResolver),\n );\n const compiled = await Promise.all(\n files.map((file) =>\n compileFile(file, {\n ...opts,\n write: false,\n sourcePath: toPosixRelative(process.cwd(), file),\n resolveProducer: sharedResolver,\n rootDir: absoluteRoot,\n }),\n ),\n );\n return Object.freeze(compiled);\n}\n\nfunction toPosixRelative(cwd: string, absolute: string): string {\n return relative(cwd, absolute).replace(/\\\\/g, \"/\");\n}\n\ntype DirEntry = Readonly<{ name: string; isDirectory: boolean; isFile: boolean }>;\n\nasync function readDirEntries(dir: string): Promise<DirEntry[]> {\n const raw = await readdir(dir, { withFileTypes: true });\n return raw.map((entry) =>\n Object.freeze({\n name: entry.name,\n isDirectory: entry.isDirectory(),\n isFile: entry.isFile(),\n }),\n );\n}\n\nfunction buildDependencyDeclarations(\n drawn: DrawnScript,\n depGraph: DepGraph,\n sourcePath: string,\n): ReadonlyArray<DependencyDeclaration> {\n if (drawn.consumes.length === 0) return Object.freeze([]);\n const declarations: DependencyDeclaration[] = [];\n for (const consume of drawn.consumes) {\n declarations.push(buildOneDependencyDeclaration(consume, depGraph, sourcePath));\n }\n return Object.freeze(declarations);\n}\n\nfunction buildOneDependencyDeclaration(\n consume: DrawnScript[\"consumes\"][number],\n depGraph: DepGraph,\n sourcePath: string,\n): DependencyDeclaration {\n const ref = consume.producerRef;\n const outputsCopy = consume.outputs.map(\n (o): OutputDeclaration => Object.freeze({ title: o.title, kind: o.kind }),\n );\n /* v8 ignore next */\n if (ref.kind !== \"same-file\") return buildCrossFileDeclaration(consume, ref, outputsCopy);\n const isDrawn = depGraph.drawn.some(\n (d) => d.bindingName === ref.bindingName && d.exportName !== \"default\",\n );\n const exportName =\n depGraph.drawn.find((d) => d.bindingName === ref.bindingName)?.exportName ??\n ref.bindingName;\n return Object.freeze({\n localId: consume.localId,\n producerName: ref.bindingName,\n producerSourcePath: sourcePath,\n producerExportName: exportName,\n effectiveInputs: Object.freeze({ ...consume.effectiveInputs }),\n outputs: Object.freeze(outputsCopy),\n isDrawn,\n });\n}\n\n/* v8 ignore start */\nfunction buildCrossFileDeclaration(\n consume: DrawnScript[\"consumes\"][number],\n ref: Extract<DrawnScript[\"consumes\"][number][\"producerRef\"], { kind: \"cross-file\" }>,\n outputsCopy: ReadonlyArray<OutputDeclaration>,\n): DependencyDeclaration {\n return Object.freeze({\n localId: consume.localId,\n producerName: ref.exportName,\n producerSourcePath: ref.sourcePath,\n producerExportName: ref.exportName,\n effectiveInputs: Object.freeze({ ...consume.effectiveInputs }),\n outputs: Object.freeze(outputsCopy),\n isDrawn: false,\n });\n}\n/* v8 ignore stop */\n\nfunction stripWriteFlag(opts: CompileFileOptions): CompileOptions {\n const {\n apiVersion,\n sourcePath,\n sourcemap,\n minify,\n target,\n declaredIntervals,\n resolveProducer,\n rootDir,\n } = opts;\n const out: { -readonly [K in keyof CompileOptions]: CompileOptions[K] } = { apiVersion };\n if (sourcePath !== undefined) out.sourcePath = sourcePath;\n if (sourcemap !== undefined) out.sourcemap = sourcemap;\n if (minify !== undefined) out.minify = minify;\n if (target !== undefined) out.target = target;\n if (declaredIntervals !== undefined) out.declaredIntervals = declaredIntervals;\n if (resolveProducer !== undefined) out.resolveProducer = resolveProducer;\n if (rootDir !== undefined) out.rootDir = rootDir;\n return out;\n}\n\n/**\n * Lower each cross-file `import <name> from \"./X.chart\"` line in the\n * consumer's printed TS source to `const <name> = __producer_<hash>__default;`\n * so the inlined producer's local binding wires into the consumer's body.\n * Imports of unresolved specifiers (no entry in `specifierToHash`) stay\n * as-is so esbuild surfaces the resolution failure.\n *\n * Phase 1 only supports the default-import form — named imports remain\n * untouched and will be addressed when same-file named-export composition\n * crosses file boundaries.\n *\n * @since 0.7\n */\nfunction rewriteConsumerChartImports(\n source: string,\n specifierToHash: ReadonlyMap<string, string>,\n): string {\n if (specifierToHash.size === 0) return source;\n return source.replace(\n /^\\s*import\\s+([A-Za-z_$][A-Za-z0-9_$]*)\\s+from\\s+(['\"])([^'\"]+)\\2;\\s*$/gm,\n (match, name: string, _quote: string, specifier: string) => {\n const hash = specifierToHash.get(specifier);\n /* v8 ignore next */\n if (hash === undefined) return match;\n return `const ${name} = __producer_${hash}__default;`;\n },\n );\n}\n\n/**\n * Pre-scan a `.chart.ts` source for `.chart.ts` / `.chart` import\n * specifiers using a one-pass AST walk. Returns a deduplicated array of\n * specifiers in source-declaration order. The list feeds `compile`'s\n * async resolver before `transformAndAnalyse` runs so the analysis pass\n * can resolve cross-file producer snapshots synchronously.\n *\n * @since 0.7\n */\nfunction preScanChartImports(source: string, sourcePath: string): ReadonlyArray<string> {\n const sourceFile = ts.createSourceFile(\n sourcePath,\n source,\n ts.ScriptTarget.ES2022,\n true,\n ts.ScriptKind.TS,\n );\n const specifiers: string[] = [];\n const seen = new Set<string>();\n for (const statement of sourceFile.statements) {\n if (!ts.isImportDeclaration(statement)) continue;\n const specifier = statement.moduleSpecifier;\n /* v8 ignore next 3 */\n if (!ts.isStringLiteral(specifier)) {\n continue;\n }\n const text = specifier.text;\n if (!text.endsWith(\".chart\") && !text.endsWith(\".chart.ts\")) continue;\n /* v8 ignore next 3 */\n if (seen.has(text)) {\n continue;\n }\n seen.add(text);\n specifiers.push(text);\n }\n return Object.freeze(specifiers);\n}\n\n/**\n * Build a per-`compile` cross-file resolver rooted at the consumer's\n * directory. `compileProject` overrides this by sharing a single\n * resolver across every file so the inline-once invariant holds.\n *\n * @since 0.7\n */\nfunction createDefaultProducerResolver(\n sourcePath: string,\n opts: CompileOptions,\n): ResolveCrossFileProducer {\n let absSourcePath: string;\n /* v8 ignore next 3 */\n if (isAbsolute(sourcePath)) {\n absSourcePath = sourcePath;\n } else {\n absSourcePath = resolvePath(process.cwd(), sourcePath);\n }\n const rootDir = opts.rootDir ?? dirname(absSourcePath);\n const resolver: ResolveCrossFileProducer = createProducerResolver(\n { rootDir },\n (source, producerSourcePath) =>\n compileProducerArtefacts(source, producerSourcePath, resolver),\n );\n return resolver;\n}\n\n/**\n * Compile one producer file for the resolver. Pre-scans its imports,\n * resolves them recursively (so transitive producers populate the\n * cache before we hand control back), runs the producer's own\n * `compile` + `transformAndAnalyse`, and returns the artefacts the\n * resolver wraps into a {@link ProducerCompiled} snapshot.\n *\n * @since 0.7\n */\nasync function compileProducerArtefacts(\n source: string,\n producerSourcePath: string,\n resolver: ResolveCrossFileProducer,\n): Promise<CompiledProducerArtefacts | null> {\n try {\n // Pre-resolve the producer's own cross-file deps so the\n // recursive `compile` can pull the matching snapshot from the\n // shared resolver's cache instead of compiling twice.\n const preScan = preScanChartImports(source, producerSourcePath);\n const nested = await Promise.all(\n preScan.map(async (specifier) => ({\n specifier,\n compiled: await resolver(specifier, producerSourcePath),\n })),\n );\n const result = await compile(source, {\n apiVersion: 1,\n sourcePath: producerSourcePath,\n resolveProducer: resolver,\n });\n const transformAndAnalyseResult = transformAndAnalyse(source, {\n sourcePath: producerSourcePath,\n resolveProducer: buildSyncSnapshotResolver(nested),\n });\n const transformedSource = PRINTER.printFile(transformAndAnalyseResult.transformed);\n const transitiveProducers: ProducerCompiled[] = [];\n const specifierToHash = new Map<string, string>();\n for (const { specifier, compiled } of nested) {\n /* v8 ignore next */\n if (compiled === null) continue;\n transitiveProducers.push(compiled);\n specifierToHash.set(specifier, compiled.hash);\n }\n let siblings: ReadonlyArray<ScriptManifest>;\n if (transformAndAnalyseResult.siblings === undefined) {\n siblings = Object.freeze([]);\n /* v8 ignore next 3 */\n } else {\n siblings = transformAndAnalyseResult.siblings;\n }\n return Object.freeze({\n moduleSource: result.moduleSource,\n transformedSource,\n manifest: result.manifest,\n siblings,\n transitiveProducers: Object.freeze(transitiveProducers),\n specifierToHash,\n });\n /* v8 ignore next 3 */\n } catch {\n return null;\n }\n}\n\n/**\n * Build a sync snapshot resolver from a pre-resolved list of cross-file\n * producers. Returns the producer manifest's `ProducerSnapshot` shape\n * `transformAndAnalyse` calls when walking consumer-side\n * `<binding>.output(\"title\")` references.\n */\nfunction buildSyncSnapshotResolver(\n nested: ReadonlyArray<{ specifier: string; compiled: ProducerCompiled | null }>,\n): NonNullable<TransformAndAnalyseOptions[\"resolveProducer\"]> {\n const bySpecifier = new Map<string, ProducerCompiled>();\n for (const entry of nested) {\n if (entry.compiled !== null) bySpecifier.set(entry.specifier, entry.compiled);\n }\n return (modSpec, expName) => {\n const compiled = bySpecifier.get(modSpec);\n /* v8 ignore next 3 */\n if (compiled === undefined) {\n return null;\n }\n const manifest = compiled.drawnByExportName.get(expName);\n /* v8 ignore next 3 */\n if (manifest === undefined) {\n return null;\n }\n /* v8 ignore next */\n const outputs = manifest.outputs ?? [];\n return Object.freeze({\n name: manifest.name,\n outputs: Object.freeze(\n outputs.map((o) => Object.freeze({ title: o.title, kind: o.kind })),\n ),\n inputs: Object.fromEntries(\n Object.entries(manifest.inputs).map(([key, descriptor]) => [\n key,\n descriptor as unknown,\n ]),\n ),\n });\n };\n}\n"]}