@rangular-framework/cli 0.0.0-stage → 1.0.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 (36) hide show
  1. package/dist/cli/src/cli.js +1217 -0
  2. package/dist/compiler/src/catalog.js +198 -0
  3. package/dist/compiler/src/class/formInit.js +370 -0
  4. package/dist/compiler/src/class/parseComponent.js +430 -0
  5. package/dist/compiler/src/class/parseDirective.js +227 -0
  6. package/dist/compiler/src/class/parseRoutes.js +163 -0
  7. package/dist/compiler/src/codegen/generate.js +3466 -0
  8. package/dist/compiler/src/codegen/methods.js +975 -0
  9. package/dist/compiler/src/codegen/sourceMap.js +77 -0
  10. package/dist/compiler/src/compile.js +775 -0
  11. package/dist/compiler/src/diagnostics.js +113 -0
  12. package/dist/compiler/src/doctor.js +144 -0
  13. package/dist/compiler/src/fix.js +44 -0
  14. package/dist/compiler/src/index.js +38 -0
  15. package/dist/compiler/src/preview/renderPreview.js +7158 -0
  16. package/dist/compiler/src/preview/styleSnapshot.js +268 -0
  17. package/dist/compiler/src/propTable.js +107 -0
  18. package/dist/compiler/src/style/css.js +161 -0
  19. package/dist/compiler/src/template/ast.js +19 -0
  20. package/dist/compiler/src/template/evaluate.js +151 -0
  21. package/dist/compiler/src/template/expr.js +360 -0
  22. package/dist/compiler/src/template/forms.js +80 -0
  23. package/dist/compiler/src/template/literal.js +248 -0
  24. package/dist/compiler/src/template/parser.js +230 -0
  25. package/dist/compiler/src/template/pipes.js +225 -0
  26. package/dist/compiler/src/template/printAst.js +38 -0
  27. package/dist/compiler/src/template/structural.js +51 -0
  28. package/dist/runtime/src/index.js +1197 -0
  29. package/dist/ui/src/chart.js +196 -0
  30. package/dist/ui/src/datetime.js +240 -0
  31. package/dist/ui/src/icons.js +310 -0
  32. package/dist/ui/src/mask.js +103 -0
  33. package/dist/ui/src/palette.js +141 -0
  34. package/dist/ui/src/tokens.js +173 -0
  35. package/package.json +28 -4
  36. package/README.md +0 -3
@@ -0,0 +1,198 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.findRepoRoot = findRepoRoot;
37
+ exports.parsePrimitives = parsePrimitives;
38
+ exports.buildCatalog = buildCatalog;
39
+ exports.renderCatalogMarkdown = renderCatalogMarkdown;
40
+ const fs = __importStar(require("node:fs"));
41
+ const path = __importStar(require("node:path"));
42
+ const ts = __importStar(require("typescript"));
43
+ const diagnostics_1 = require("./diagnostics");
44
+ const generate_1 = require("./codegen/generate");
45
+ const tokens_1 = require("../../ui/src/tokens");
46
+ const icons_1 = require("../../ui/src/icons");
47
+ /** Walk up from a start directory until packages/ui/src/primitives.tsx is found. */
48
+ function findRepoRoot(startDir) {
49
+ let dir = path.resolve(startDir);
50
+ for (let i = 0; i < 8; i++) {
51
+ if (fs.existsSync(path.join(dir, 'packages', 'ui', 'src', 'primitives.tsx')))
52
+ return dir;
53
+ const parent = path.dirname(dir);
54
+ if (parent === dir)
55
+ return undefined;
56
+ dir = parent;
57
+ }
58
+ return undefined;
59
+ }
60
+ function parsePrimitives(source, fileName = 'primitives.tsx') {
61
+ const sf = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
62
+ const primitives = [];
63
+ const visit = (node) => {
64
+ if (ts.isFunctionDeclaration(node) && node.name && /^Rg[A-Z]/.test(node.name.text)
65
+ && node.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)) {
66
+ const param = node.parameters[0];
67
+ const props = [];
68
+ if (param) {
69
+ const typeText = param.type ? param.type.getText(sf) : 'any';
70
+ if (ts.isObjectBindingPattern(param.name)) {
71
+ for (const el of param.name.elements) {
72
+ // A renamed destructure (`{ theme: mode }`) declares the
73
+ // prop `theme` and binds it locally as `mode`; the catalog
74
+ // lists the prop name callers actually pass, which is the
75
+ // propertyName when one is written.
76
+ const propName = el.propertyName ? el.propertyName.getText(sf) : el.name.getText(sf);
77
+ props.push({ name: propName, type: typeText });
78
+ }
79
+ }
80
+ }
81
+ primitives.push({ name: node.name.text, props });
82
+ }
83
+ ts.forEachChild(node, visit);
84
+ };
85
+ visit(sf);
86
+ return primitives;
87
+ }
88
+ function buildCatalog(options = {}) {
89
+ let primitives = [];
90
+ let version = '0.0.0';
91
+ const primPath = options.primitivesPath
92
+ ?? (() => {
93
+ const root = findRepoRoot(options.fromDir ?? __dirname);
94
+ return root ? path.join(root, 'packages', 'ui', 'src', 'primitives.tsx') : undefined;
95
+ })();
96
+ if (primPath && fs.existsSync(primPath)) {
97
+ primitives = parsePrimitives(fs.readFileSync(primPath, 'utf8'), path.basename(primPath));
98
+ const root = findRepoRoot(path.dirname(primPath));
99
+ if (root) {
100
+ try {
101
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
102
+ if (typeof pkg.version === 'string')
103
+ version = pkg.version;
104
+ }
105
+ catch { /* version stays 0.0.0 */ }
106
+ }
107
+ }
108
+ const tags = Object.entries(generate_1.TAG_MAP).map(([tag, m]) => ({
109
+ tag,
110
+ component: m.component,
111
+ from: m.fromUi ? '@rangular-framework/ui' : 'react-native',
112
+ ...(m.variant ? { variant: m.variant } : {}),
113
+ }));
114
+ const events = Object.entries(generate_1.EVENT_PROPS).map(([event, rnProp]) => ({ event, rnProp }));
115
+ events.push({
116
+ event: 'input',
117
+ rnProp: 'onChangeText',
118
+ note: 'On <input> only; on any other tag (input) maps to onInput and the compiler notes it has no standard RN prop.',
119
+ });
120
+ return {
121
+ name: 'rangular-framework',
122
+ version,
123
+ tags,
124
+ events,
125
+ primitives,
126
+ icons: [...icons_1.ICON_NAMES],
127
+ tokens: { spacing: tokens_1.spacing, spacingScale: tokens_1.spacingScale, radius: tokens_1.radius, radiusScale: tokens_1.radiusScale, typeScale: tokens_1.typeScale, colours: tokens_1.colours, elevation: tokens_1.elevation, themes: tokens_1.themes },
128
+ diagnostics: Object.entries(diagnostics_1.DIAGNOSTIC_CODES).map(([code, meaning]) => ({ code, meaning })),
129
+ };
130
+ }
131
+ function renderCatalogMarkdown(catalog) {
132
+ const lines = [];
133
+ lines.push('# Rangular catalog');
134
+ lines.push('');
135
+ lines.push(`Generated by \`rg catalog\` from the compiler, UI primitives and tokens, do not edit by hand. Version ${catalog.version}.`);
136
+ lines.push('');
137
+ lines.push('## Template tags');
138
+ lines.push('');
139
+ lines.push('| Tag | Generates | From | Text variant |');
140
+ lines.push('|---|---|---|---|');
141
+ for (const t of catalog.tags) {
142
+ lines.push(`| \`<${t.tag}>\` | \`${t.component}\` | ${t.from} | ${t.variant ?? '-'} |`);
143
+ }
144
+ lines.push('');
145
+ lines.push('Any other Capitalised or dashed tag is treated as an app component and passed through; any other lowercase tag warns (GEN_UNKNOWN_TAG) and becomes <View>.');
146
+ lines.push('');
147
+ lines.push('## Events');
148
+ lines.push('');
149
+ lines.push('| Template event | React Native prop |');
150
+ lines.push('|---|---|');
151
+ for (const e of catalog.events) {
152
+ lines.push(`| \`(${e.event})\` | \`${e.rnProp}\`${e.note ? `, ${e.note}` : ''} |`);
153
+ }
154
+ lines.push('');
155
+ lines.push('Any other (event) maps to on<Event> with a compiler comment that it has no standard RN prop.');
156
+ lines.push('');
157
+ lines.push('## Primitives and their props');
158
+ lines.push('');
159
+ lines.push('Props are parsed from `packages/ui/src/primitives.tsx`; the primitives are shipped source typed `any`, so every prop type is `any` today.');
160
+ lines.push('');
161
+ for (const p of catalog.primitives) {
162
+ lines.push(`### ${p.name}`);
163
+ lines.push('');
164
+ if (!p.props.length)
165
+ lines.push('No props.');
166
+ for (const prop of p.props)
167
+ lines.push(`- \`${prop.name}\`: ${prop.type}`);
168
+ lines.push('');
169
+ }
170
+ lines.push('## Icons');
171
+ lines.push('');
172
+ lines.push(`Icons live in \`packages/ui/src/icons.ts\` as SVG path data (24 by 24 viewBox). \`<icon name="...">\` draws one of these ${catalog.icons.length} names; any other name is a GEN_ICON_UNKNOWN error whose JSON form carries this same list in \`validIcons\`.`);
173
+ lines.push('');
174
+ for (const name of catalog.icons)
175
+ lines.push(`- \`${name}\``);
176
+ lines.push('');
177
+ lines.push('## Design tokens');
178
+ lines.push('');
179
+ lines.push(`- Spacing scale: ${catalog.tokens.spacingScale.join(', ')} (keys: ${Object.keys(catalog.tokens.spacing).join(', ')})`);
180
+ lines.push(`- Radius scale: ${catalog.tokens.radiusScale.join(', ')} (keys: ${Object.keys(catalog.tokens.radius).join(', ')}; full = 9999)`);
181
+ lines.push(`- Type scale: ${Object.entries(catalog.tokens.typeScale).map(([k, v]) => `${k} ${v.fontSize}/${v.lineHeight} w${v.fontWeight}`).join(' · ')}`);
182
+ lines.push(`- Colour roles (same roles in light and dark): ${Object.keys(catalog.tokens.colours.light).join(', ')}`);
183
+ lines.push(`- Elevation presets: ${Object.entries(catalog.tokens.elevation).map(([k, v]) => `${k} (elevation ${v.elevation})`).join(', ')}`);
184
+ lines.push(`- Theming: \`<screen theme="dark">\` compiles to \`<RgScreen theme="dark">\`; primitives read the active theme from context (RgThemeProvider / useRgTheme in @rangular-framework/ui) and default to light. CSS spacing/radius/font-size values snap to the scales above (STYLE_OFF_SCALE).`);
185
+ lines.push('');
186
+ lines.push('Full token values (both colour modes, the light and dark theme objects, elevation presets) are in catalog.json.');
187
+ lines.push('');
188
+ lines.push('## Diagnostic codes');
189
+ lines.push('');
190
+ lines.push('| Code | Meaning |');
191
+ lines.push('|---|---|');
192
+ for (const d of catalog.diagnostics)
193
+ lines.push(`| ${d.code} | ${d.meaning} |`);
194
+ lines.push('');
195
+ lines.push('Diagnostics also carry a `fix:` suggestion in human output and in `rg build --json`.');
196
+ lines.push('');
197
+ return lines.join('\n');
198
+ }
@@ -0,0 +1,370 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.isFormInitializer = isFormInitializer;
37
+ exports.signalKindOf = signalKindOf;
38
+ exports.isSignalInitializer = isSignalInitializer;
39
+ exports.isStreamInitializer = isStreamInitializer;
40
+ exports.builderDepsOf = builderDepsOf;
41
+ exports.formFieldKind = formFieldKind;
42
+ exports.rewriteBuilderInitializer = rewriteBuilderInitializer;
43
+ exports.analyzeFormInitializer = analyzeFormInitializer;
44
+ exports.evaluateFormInitializer = evaluateFormInitializer;
45
+ const ts = __importStar(require("typescript"));
46
+ const index_1 = require("../../../runtime/src/index");
47
+ const FORM_NEW_RE = /^\s*new\s+(FormGroup|FormControl|FormArray)\s*\(/;
48
+ const FORM_BUILDER_RE = /^\s*this\.([A-Za-z_$][\w$]*)\.(group|control|array)\s*\(/;
49
+ /**
50
+ * True for field initializers that build a form tree: a `new
51
+ * FormGroup/FormControl/FormArray(...)`, or a call on a FormBuilder
52
+ * constructor dep (`this.fb.group(...)`) when the dep name is in
53
+ * builderDeps.
54
+ */
55
+ function isFormInitializer(initializer, builderDeps) {
56
+ if (!initializer)
57
+ return false;
58
+ if (FORM_NEW_RE.test(initializer))
59
+ return true;
60
+ const m = FORM_BUILDER_RE.exec(initializer);
61
+ return !!m && !!builderDeps && builderDeps.has(m[1]);
62
+ }
63
+ const SIGNAL_CALL_RE = /^\s*(signal|computed)\s*(<[^>]*>)?\s*\(/;
64
+ /**
65
+ * The kind of a signal field initializer (signals adoption): a field
66
+ * initialised with `signal(...)` or `computed(...)` from
67
+ * '@angular/core'. Like a subject field, a signal field is one stable
68
+ * instance for the component's whole life: codegen holds it in a ref,
69
+ * because a signal recreated per render would lose its value and
70
+ * orphan every reader. In a service the same initializer is a plain
71
+ * class field, emitted verbatim.
72
+ */
73
+ function signalKindOf(initializer) {
74
+ if (!initializer)
75
+ return undefined;
76
+ const m = SIGNAL_CALL_RE.exec(initializer);
77
+ return m ? m[1] : undefined;
78
+ }
79
+ function isSignalInitializer(initializer) {
80
+ return signalKindOf(initializer) !== undefined;
81
+ }
82
+ const STREAM_NEW_RE = /^\s*new\s+(Subject|BehaviorSubject|ReplaySubject|AsyncSubject)\s*(<[^>]*>)?\s*\(/;
83
+ /**
84
+ * True when a field initializer constructs an RxJS subject (RxJS
85
+ * adoption). Like a form field, a subject field is one stable
86
+ * instance for the component's whole life: codegen holds it in a
87
+ * ref, because a subject recreated per render would orphan every
88
+ * subscriber of the previous instance.
89
+ */
90
+ function isStreamInitializer(initializer) {
91
+ if (!initializer)
92
+ return false;
93
+ return STREAM_NEW_RE.test(initializer);
94
+ }
95
+ /** The FormBuilder constructor dep names of a host component or service. */
96
+ function builderDepsOf(host) {
97
+ return new Set((host.constructorDeps ?? [])
98
+ .filter((d) => d.typeName === 'FormBuilder')
99
+ .map((d) => d.propertyName));
100
+ }
101
+ /** Parse `const __x = <initializer>;` and return its top-level expression. */
102
+ function topExpression(initializer) {
103
+ const sf = ts.createSourceFile('form-init.ts', `const __x = ${initializer};`, ts.ScriptTarget.Latest,
104
+ /* setParentNodes */ true);
105
+ let found;
106
+ const visit = (node) => {
107
+ if (found)
108
+ return;
109
+ if (ts.isVariableDeclaration(node) && node.initializer) {
110
+ found = node.initializer;
111
+ return;
112
+ }
113
+ ts.forEachChild(node, visit);
114
+ };
115
+ visit(sf);
116
+ return found;
117
+ }
118
+ /** The builder call parts of `this.<dep>.<method>(...)`, when it is one. */
119
+ function builderCallOf(node) {
120
+ if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression))
121
+ return undefined;
122
+ const target = node.expression.expression;
123
+ if (!ts.isPropertyAccessExpression(target) || target.expression.kind !== ts.SyntaxKind.ThisKeyword)
124
+ return undefined;
125
+ const method = node.expression.name.text;
126
+ if (method !== 'group' && method !== 'control' && method !== 'array')
127
+ return undefined;
128
+ return { dep: target.name.text, method, args: node.arguments };
129
+ }
130
+ /** The kind one config entry builds, from its shape alone. */
131
+ function kindOfEntry(node) {
132
+ if (ts.isNewExpression(node) && ts.isIdentifier(node.expression)) {
133
+ if (node.expression.text === 'FormGroup')
134
+ return 'group';
135
+ if (node.expression.text === 'FormArray')
136
+ return 'array';
137
+ return 'control';
138
+ }
139
+ const call = builderCallOf(node);
140
+ if (call)
141
+ return call.method === 'group' ? 'group' : call.method === 'array' ? 'array' : 'control';
142
+ return 'control';
143
+ }
144
+ function kindsOfConfig(config) {
145
+ const controlNames = [];
146
+ const controlKinds = {};
147
+ if (config && ts.isObjectLiteralExpression(config)) {
148
+ for (const prop of config.properties) {
149
+ if (ts.isPropertyAssignment(prop)) {
150
+ const name = prop.name.getText().replace(/^['"]|['"]$/g, '');
151
+ controlNames.push(name);
152
+ controlKinds[name] = kindOfEntry(prop.initializer);
153
+ }
154
+ }
155
+ }
156
+ return { controlNames, controlKinds };
157
+ }
158
+ /** Kind and group control names from the initializer's shape alone. */
159
+ function formFieldKind(initializer, builderDeps) {
160
+ const expr = topExpression(initializer);
161
+ if (!expr)
162
+ return { kind: 'control', controlNames: [], controlKinds: {} };
163
+ if (ts.isNewExpression(expr) && ts.isIdentifier(expr.expression)) {
164
+ if (expr.expression.text === 'FormGroup') {
165
+ return { kind: 'group', ...kindsOfConfig(expr.arguments?.[0]) };
166
+ }
167
+ if (expr.expression.text === 'FormArray')
168
+ return { kind: 'array', controlNames: [], controlKinds: {} };
169
+ return { kind: 'control', controlNames: [], controlKinds: {} };
170
+ }
171
+ const call = builderCallOf(expr);
172
+ if (call && builderDeps && builderDeps.has(call.dep)) {
173
+ if (call.method === 'group') {
174
+ return { kind: 'group', ...kindsOfConfig(call.args[0]), builderDep: call.dep };
175
+ }
176
+ return { kind: call.method === 'array' ? 'array' : 'control', controlNames: [], controlKinds: {}, builderDep: call.dep };
177
+ }
178
+ return { kind: 'control', controlNames: [], controlKinds: {} };
179
+ }
180
+ class Unsupported extends Error {
181
+ }
182
+ function evalLiteral(node) {
183
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))
184
+ return node.text;
185
+ if (ts.isNumericLiteral(node))
186
+ return Number(node.text);
187
+ if (node.kind === ts.SyntaxKind.TrueKeyword)
188
+ return true;
189
+ if (node.kind === ts.SyntaxKind.FalseKeyword)
190
+ return false;
191
+ if (node.kind === ts.SyntaxKind.NullKeyword)
192
+ return null;
193
+ if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.MinusToken) {
194
+ const inner = evalLiteral(node.operand);
195
+ if (typeof inner === 'number')
196
+ return -inner;
197
+ }
198
+ throw new Unsupported(`a ${ts.SyntaxKind[node.kind]} is not a literal value`);
199
+ }
200
+ /** `Validators.required` and friends, as member or call expressions. */
201
+ function evalValidator(node) {
202
+ if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression)
203
+ && node.expression.text === 'Validators') {
204
+ if (node.name.text === 'required')
205
+ return index_1.Validators.required;
206
+ if (node.name.text === 'email')
207
+ return index_1.Validators.email;
208
+ throw new Unsupported(`Validators.${node.name.text} is used as a value but takes an argument`);
209
+ }
210
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)
211
+ && ts.isIdentifier(node.expression.expression)
212
+ && node.expression.expression.text === 'Validators') {
213
+ const name = node.expression.name.text;
214
+ const arg = node.arguments[0] ? evalLiteral(node.arguments[0]) : undefined;
215
+ if (name === 'minLength' && typeof arg === 'number')
216
+ return index_1.Validators.minLength(arg);
217
+ if (name === 'maxLength' && typeof arg === 'number')
218
+ return index_1.Validators.maxLength(arg);
219
+ if (name === 'pattern' && typeof arg === 'string')
220
+ return index_1.Validators.pattern(arg);
221
+ throw new Unsupported(`Validators.${name}(...) is outside the supported subset`);
222
+ }
223
+ throw new Unsupported('validators must be Validators references or calls');
224
+ }
225
+ function evalValidators(node) {
226
+ if (!node)
227
+ return [];
228
+ if (ts.isArrayLiteralExpression(node))
229
+ return node.elements.map(evalValidator);
230
+ return [evalValidator(node)];
231
+ }
232
+ /** One builder config entry: a node expression, a tuple, or a literal. */
233
+ function evalBuilderEntry(node) {
234
+ if (ts.isArrayLiteralExpression(node)) {
235
+ const initial = node.elements[0] ? evalLiteral(node.elements[0]) : null;
236
+ return new index_1.FormControl(initial, evalValidators(node.elements[1]));
237
+ }
238
+ if (ts.isNewExpression(node) || ts.isCallExpression(node))
239
+ return evalFormNode(node);
240
+ return new index_1.FormControl(evalLiteral(node));
241
+ }
242
+ function evalFormNode(node) {
243
+ if (ts.isNewExpression(node) && ts.isIdentifier(node.expression)) {
244
+ if (node.expression.text === 'FormControl') {
245
+ const args = node.arguments ?? [];
246
+ const initial = args[0] ? evalLiteral(args[0]) : null;
247
+ return new index_1.FormControl(initial, evalValidators(args[1]));
248
+ }
249
+ if (node.expression.text === 'FormGroup') {
250
+ const config = node.arguments?.[0];
251
+ if (!config || !ts.isObjectLiteralExpression(config)) {
252
+ throw new Unsupported('a FormGroup config must be an object literal of form nodes');
253
+ }
254
+ const controls = {};
255
+ for (const prop of config.properties) {
256
+ if (!ts.isPropertyAssignment(prop)) {
257
+ throw new Unsupported('FormGroup entries must be name: <form node> pairs');
258
+ }
259
+ const name = prop.name.getText().replace(/^['"]|['"]$/g, '');
260
+ controls[name] = evalFormNode(prop.initializer);
261
+ }
262
+ return new index_1.FormGroup(controls);
263
+ }
264
+ if (node.expression.text === 'FormArray') {
265
+ const list = node.arguments?.[0];
266
+ if (!list || !ts.isArrayLiteralExpression(list)) {
267
+ throw new Unsupported('a FormArray argument must be an array literal of form nodes');
268
+ }
269
+ return new index_1.FormArray(list.elements.map(evalFormNode));
270
+ }
271
+ throw new Unsupported(`new ${node.expression.text}(...) is not a form class`);
272
+ }
273
+ const call = builderCallOf(node);
274
+ if (call) {
275
+ if (call.method === 'control') {
276
+ const initial = call.args[0] ? evalLiteral(call.args[0]) : null;
277
+ return new index_1.FormControl(initial, evalValidators(call.args[1]));
278
+ }
279
+ if (call.method === 'group') {
280
+ const config = call.args[0];
281
+ if (!config || !ts.isObjectLiteralExpression(config)) {
282
+ throw new Unsupported('a builder group config must be an object literal');
283
+ }
284
+ const controls = {};
285
+ for (const prop of config.properties) {
286
+ if (!ts.isPropertyAssignment(prop)) {
287
+ throw new Unsupported('builder group entries must be name: <entry> pairs');
288
+ }
289
+ const name = prop.name.getText().replace(/^['"]|['"]$/g, '');
290
+ controls[name] = evalBuilderEntry(prop.initializer);
291
+ }
292
+ return new index_1.FormGroup(controls);
293
+ }
294
+ const list = call.args[0];
295
+ if (!list || !ts.isArrayLiteralExpression(list)) {
296
+ throw new Unsupported('a builder array argument must be an array literal');
297
+ }
298
+ return new index_1.FormArray(list.elements.map(evalBuilderEntry));
299
+ }
300
+ throw new Unsupported('expected new FormControl(...), new FormGroup(...), new FormArray(...) or a FormBuilder call');
301
+ }
302
+ /**
303
+ * Rewrite the `this.<dep>` roots of a builder initializer to the bare
304
+ * dep name, for generated code: the generated component holds the
305
+ * injected FormBuilder in a local of the dep's own name, so
306
+ * `this.fb.group(...)` becomes `fb.group(...)`, nested builder calls
307
+ * included. Spans come from the TypeScript AST, so the text of a
308
+ * string literal in the config is never touched.
309
+ */
310
+ function rewriteBuilderInitializer(initializer, dep) {
311
+ const prefix = 'const __x = ';
312
+ const sf = ts.createSourceFile('form-init.ts', `${prefix}${initializer};`, ts.ScriptTarget.Latest,
313
+ /* setParentNodes */ true);
314
+ const spans = [];
315
+ const visit = (node) => {
316
+ if (ts.isPropertyAccessExpression(node)
317
+ && node.expression.kind === ts.SyntaxKind.ThisKeyword
318
+ && node.name.text === dep) {
319
+ spans.push({ start: node.getStart() - prefix.length, end: node.name.getEnd() - prefix.length });
320
+ return;
321
+ }
322
+ ts.forEachChild(node, visit);
323
+ };
324
+ visit(sf);
325
+ let out = initializer;
326
+ for (const span of spans.sort((a, b) => b.start - a.start)) {
327
+ out = out.slice(0, span.start) + dep + out.slice(span.end);
328
+ }
329
+ return out;
330
+ }
331
+ /**
332
+ * Analyse one form field initializer: its kind, its group control
333
+ * names and kinds, and whether the preview can evaluate it.
334
+ * builderDeps names the component's FormBuilder constructor deps, so
335
+ * `this.fb.group(...)` initializers are recognised as builder calls.
336
+ */
337
+ function analyzeFormInitializer(initializer, builderDeps) {
338
+ const { kind, controlNames, controlKinds, builderDep } = formFieldKind(initializer, builderDeps);
339
+ const expr = topExpression(initializer);
340
+ if (!expr)
341
+ return { kind, controlNames, controlKinds, supported: false, reason: 'the initializer could not be parsed', builderDep };
342
+ try {
343
+ evalFormNode(expr);
344
+ return { kind, controlNames, controlKinds, supported: true, builderDep };
345
+ }
346
+ catch (e) {
347
+ return {
348
+ kind, controlNames, controlKinds, supported: false,
349
+ reason: e instanceof Unsupported ? e.message : 'the initializer could not be evaluated',
350
+ builderDep,
351
+ };
352
+ }
353
+ }
354
+ /**
355
+ * Build the real runtime instance for a form field initializer, for
356
+ * the preview's server-side paint. Fails with { ok: false } on the
357
+ * same shapes analyzeFormInitializer reports as unsupported.
358
+ */
359
+ function evaluateFormInitializer(initializer, builderDeps) {
360
+ const expr = topExpression(initializer);
361
+ if (!expr)
362
+ return { ok: false, reason: 'the initializer could not be parsed' };
363
+ try {
364
+ void builderDeps;
365
+ return { ok: true, value: evalFormNode(expr) };
366
+ }
367
+ catch (e) {
368
+ return { ok: false, reason: e instanceof Unsupported ? e.message : 'the initializer could not be evaluated' };
369
+ }
370
+ }