@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,1197 @@
1
+ "use strict";
2
+ /**
3
+ * @rangular-framework/runtime, small pure-TypeScript helpers for generated apps.
4
+ * EventEmitter (for @Output), the signals core (signal, computed,
5
+ * effect, untracked and the SignalRenderTracker React bridge), a DI Container,
6
+ * the ReactiveService base class generated services extend (Stage 3),
7
+ * HttpClient over fetch, returning real RxJS Observables (Stage 3;
8
+ * the RxJS adoption replaced the old Observable-lite shape, so every
9
+ * stream this package hands out takes the full operator library),
10
+ * and the forms core (Stage 8): Validators, FormControl and FormGroup, mirroring
11
+ * @angular/forms semantics (Stage 8), and the routing core (Stage 9):
12
+ * matchRoute, RgNavigator, Router and ActivatedRoute, mirroring
13
+ * @angular/router, and the snackbar service (Stage 10): SnackBar and
14
+ * SnackBarRef, mirroring @angular/material's MatSnackBar. No react or
15
+ * react-native imports live in this file: generated components bridge
16
+ * services to React themselves (useSyncExternalStore over
17
+ * __subscribe / __getVersion), so this package stays environment-free
18
+ * and unit-testable.
19
+ */
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.SnackBar = exports.SnackBarRef = exports.ActivatedRoute = exports.Router = exports.RgNavigator = exports.FormBuilder = exports.FormArray = exports.FormGroup = exports.FormControl = exports.Validators = exports.Container = exports.HttpClient = exports.ReactiveService = exports.SignalRenderTracker = exports.EventEmitter = void 0;
22
+ exports.signal = signal;
23
+ exports.computed = computed;
24
+ exports.flushEffects = flushEffects;
25
+ exports.beginEffectScope = beginEffectScope;
26
+ exports.endEffectScope = endEffectScope;
27
+ exports.effect = effect;
28
+ exports.untracked = untracked;
29
+ exports.pipe = pipe;
30
+ exports.validateValue = validateValue;
31
+ exports.normalizeRoutePath = normalizeRoutePath;
32
+ exports.matchRoute = matchRoute;
33
+ const rxjs_1 = require("rxjs");
34
+ const rxjs_2 = require("rxjs");
35
+ /**
36
+ * An output emitter, as in Angular: an EventEmitter IS a Subject, so
37
+ * it can be subscribed, piped and composed like any other stream
38
+ * (the RxJS adoption made this literally true; before it, the class
39
+ * was a small listener set shaped like one). `emit` is the Angular
40
+ * spelling of `next`. `on` and `off` stay as the framework's older
41
+ * convenience pair: `on` subscribes and returns an unsubscribe
42
+ * function, `off` removes a listener registered through `on`.
43
+ */
44
+ class EventEmitter extends rxjs_1.Subject {
45
+ tracked = new Map();
46
+ /** Subscribe; returns an unsubscribe function. */
47
+ on(listener) {
48
+ const sub = this.subscribe(listener);
49
+ this.tracked.set(listener, sub);
50
+ return () => this.off(listener);
51
+ }
52
+ off(listener) {
53
+ this.tracked.get(listener)?.unsubscribe();
54
+ this.tracked.delete(listener);
55
+ }
56
+ emit(value) {
57
+ this.next(value);
58
+ }
59
+ get listenerCount() {
60
+ return this.observers.length;
61
+ }
62
+ }
63
+ exports.EventEmitter = EventEmitter;
64
+ let activeConsumer = null;
65
+ let computedDepth = 0;
66
+ function trackRead(producer) {
67
+ if (!activeConsumer)
68
+ return;
69
+ activeConsumer.producers.set(producer, producer.version);
70
+ producer.consumers.add(activeConsumer);
71
+ }
72
+ function detachConsumer(consumer) {
73
+ for (const producer of consumer.producers.keys())
74
+ producer.consumers.delete(consumer);
75
+ consumer.producers.clear();
76
+ }
77
+ function notifyConsumers(producer) {
78
+ for (const consumer of [...producer.consumers])
79
+ consumer.onProducerChanged();
80
+ }
81
+ class SignalNode {
82
+ version = 0;
83
+ consumers = new Set();
84
+ value;
85
+ equal;
86
+ constructor(initial, equal) {
87
+ this.value = initial;
88
+ this.equal = equal;
89
+ }
90
+ }
91
+ /** Create a writable signal holding `initial`, as in Angular. */
92
+ function signal(initial, options) {
93
+ const node = new SignalNode(initial, options?.equal ?? Object.is);
94
+ let readonlyView;
95
+ const read = (() => {
96
+ trackRead(node);
97
+ return node.value;
98
+ });
99
+ read.set = (value) => {
100
+ if (computedDepth > 0) {
101
+ throw new Error('Writing to a signal is not allowed inside a computed value; move the write into a method or an effect.');
102
+ }
103
+ if (node.equal(node.value, value))
104
+ return;
105
+ node.value = value;
106
+ node.version++;
107
+ notifyConsumers(node);
108
+ };
109
+ read.update = (fn) => {
110
+ read.set(fn(node.value));
111
+ };
112
+ read.asReadonly = () => {
113
+ if (!readonlyView) {
114
+ readonlyView = (() => {
115
+ trackRead(node);
116
+ return node.value;
117
+ });
118
+ }
119
+ return readonlyView;
120
+ };
121
+ return read;
122
+ }
123
+ class ComputedNode {
124
+ version = 0;
125
+ consumers = new Set();
126
+ producers = new Map();
127
+ value;
128
+ hasValue = false;
129
+ stale = true;
130
+ fn;
131
+ equal;
132
+ constructor(fn, equal) {
133
+ this.fn = fn;
134
+ this.equal = equal;
135
+ }
136
+ onProducerChanged() {
137
+ if (this.stale)
138
+ return;
139
+ this.stale = true;
140
+ notifyConsumers(this);
141
+ }
142
+ refreshIfStale() {
143
+ if (this.stale)
144
+ this.refresh();
145
+ }
146
+ read() {
147
+ if (this.stale || !this.hasValue)
148
+ this.refresh();
149
+ trackRead(this);
150
+ return this.value;
151
+ }
152
+ refresh() {
153
+ if (this.hasValue) {
154
+ let changed = false;
155
+ for (const [producer, seen] of this.producers) {
156
+ if (producer instanceof ComputedNode)
157
+ producer.refreshIfStale();
158
+ if (producer.version !== seen) {
159
+ changed = true;
160
+ break;
161
+ }
162
+ }
163
+ if (!changed) {
164
+ this.stale = false;
165
+ return;
166
+ }
167
+ }
168
+ detachConsumer(this);
169
+ const prev = activeConsumer;
170
+ activeConsumer = this;
171
+ computedDepth++;
172
+ let next;
173
+ try {
174
+ next = this.fn();
175
+ }
176
+ finally {
177
+ computedDepth--;
178
+ activeConsumer = prev;
179
+ }
180
+ const valueChanged = !this.hasValue || !this.equal(this.value, next);
181
+ this.value = next;
182
+ this.hasValue = true;
183
+ this.stale = false;
184
+ if (valueChanged)
185
+ this.version++;
186
+ }
187
+ }
188
+ /**
189
+ * Create a computed value, as in Angular: lazy (nothing runs until the
190
+ * first read), cached (a read with unchanged inputs returns the cached
191
+ * value), and tracked (the inputs are whatever the function read last).
192
+ */
193
+ function computed(fn, options) {
194
+ const node = new ComputedNode(fn, options?.equal ?? Object.is);
195
+ return (() => node.read());
196
+ }
197
+ const pendingEffects = new Set();
198
+ let effectFlushQueued = false;
199
+ function queueEffectFlush() {
200
+ if (effectFlushQueued)
201
+ return;
202
+ effectFlushQueued = true;
203
+ queueMicrotask(() => {
204
+ effectFlushQueued = false;
205
+ flushEffects();
206
+ });
207
+ }
208
+ /** Run every queued effect now, including any those runs queue. */
209
+ function flushEffects() {
210
+ for (let guard = 0; pendingEffects.size > 0 && guard < 100; guard++) {
211
+ const batch = [...pendingEffects];
212
+ pendingEffects.clear();
213
+ for (const node of batch)
214
+ node.run();
215
+ }
216
+ pendingEffects.clear();
217
+ }
218
+ const effectScopeStack = [];
219
+ /**
220
+ * Generated components open an effect scope around their mount effect:
221
+ * every effect created while a scope is open joins it, and the cleanup
222
+ * the matching end call returns destroys them all (the component
223
+ * unmount path).
224
+ */
225
+ function beginEffectScope() {
226
+ effectScopeStack.push(new Set());
227
+ }
228
+ function endEffectScope() {
229
+ const scope = effectScopeStack.pop();
230
+ return () => {
231
+ if (scope)
232
+ for (const node of [...scope])
233
+ node.destroy();
234
+ };
235
+ }
236
+ class EffectNode {
237
+ producers = new Map();
238
+ cleanups = [];
239
+ destroyed = false;
240
+ queued = false;
241
+ scope;
242
+ fn;
243
+ constructor(fn) {
244
+ this.fn = fn;
245
+ }
246
+ onProducerChanged() {
247
+ if (this.destroyed || this.queued)
248
+ return;
249
+ this.queued = true;
250
+ pendingEffects.add(this);
251
+ queueEffectFlush();
252
+ }
253
+ joinScope(scope) {
254
+ this.scope = scope;
255
+ }
256
+ run() {
257
+ this.queued = false;
258
+ if (this.destroyed)
259
+ return;
260
+ this.runCleanups();
261
+ detachConsumer(this);
262
+ const prev = activeConsumer;
263
+ activeConsumer = this;
264
+ try {
265
+ this.fn((cleanup) => { this.cleanups.push(cleanup); });
266
+ }
267
+ finally {
268
+ activeConsumer = prev;
269
+ }
270
+ }
271
+ destroy() {
272
+ if (this.destroyed)
273
+ return;
274
+ this.destroyed = true;
275
+ pendingEffects.delete(this);
276
+ if (this.scope)
277
+ this.scope.delete(this);
278
+ this.runCleanups();
279
+ detachConsumer(this);
280
+ }
281
+ runCleanups() {
282
+ const cleanups = this.cleanups;
283
+ this.cleanups = [];
284
+ for (const cleanup of cleanups)
285
+ cleanup();
286
+ }
287
+ }
288
+ /**
289
+ * Create an effect, as in Angular: the function runs once at creation
290
+ * and re-runs whenever a signal or computed it read changes. The
291
+ * function receives onCleanup to register teardown that runs before
292
+ * each re-run and at destroy. Effects created inside a component's
293
+ * mount scope are destroyed with the component.
294
+ */
295
+ function effect(fn) {
296
+ const node = new EffectNode(fn);
297
+ const scope = effectScopeStack[effectScopeStack.length - 1];
298
+ if (scope) {
299
+ scope.add(node);
300
+ node.joinScope(scope);
301
+ }
302
+ node.run();
303
+ return { destroy: () => { node.destroy(); } };
304
+ }
305
+ /** Run `fn` with dependency tracking suspended, as in Angular. */
306
+ function untracked(fn) {
307
+ const prev = activeConsumer;
308
+ activeConsumer = null;
309
+ try {
310
+ return fn();
311
+ }
312
+ finally {
313
+ activeConsumer = prev;
314
+ }
315
+ }
316
+ /**
317
+ * The React bridge for generated components: a tracker is the consumer
318
+ * for one component's render. Codegen opens it (begin) just before the
319
+ * returned view is evaluated and closes it (end) right after, so every
320
+ * signal read by the view, including reads inside methods the view
321
+ * calls, subscribes exactly this component. A later write to any of
322
+ * those signals calls onChange once, and the next render re-tracks
323
+ * from scratch, so a component follows the signals its current view
324
+ * actually reads.
325
+ */
326
+ class SignalRenderTracker {
327
+ producers = new Map();
328
+ rendering = false;
329
+ disposed = false;
330
+ prevConsumer = null;
331
+ onChange;
332
+ constructor(onChange) {
333
+ this.onChange = onChange;
334
+ }
335
+ begin() {
336
+ detachConsumer(this);
337
+ this.rendering = true;
338
+ this.prevConsumer = activeConsumer;
339
+ activeConsumer = this;
340
+ }
341
+ end() {
342
+ activeConsumer = this.prevConsumer;
343
+ this.prevConsumer = null;
344
+ this.rendering = false;
345
+ }
346
+ onProducerChanged() {
347
+ if (!this.rendering && !this.disposed)
348
+ this.onChange();
349
+ }
350
+ dispose() {
351
+ this.disposed = true;
352
+ detachConsumer(this);
353
+ }
354
+ }
355
+ exports.SignalRenderTracker = SignalRenderTracker;
356
+ /**
357
+ * Pipe helper referenced by generated code for `expr | pipeName` template
358
+ * expressions: the full Stage 12 built-in set (uppercase, lowercase,
359
+ * titlecase, json, date, number, percent, currency, slice, keyvalue,
360
+ * async). The semantics are the compiler's canonical ones
361
+ * (packages/compiler/src/template/pipes.ts); a parity test runs one
362
+ * case table through both. Unknown pipes return the value unchanged:
363
+ * generated code only reaches this helper for pipes the compiler has
364
+ * already validated, so an unknown name here means a hand-edited file.
365
+ *
366
+ * The `async` case is only a fallback: codegen replaces every
367
+ * template `| async` with a live subscription hook, so this helper
368
+ * sees an observable only from hand-written calls. Its behaviour is
369
+ * the pure snapshot: subscribe, keep what arrives synchronously,
370
+ * unsubscribe, return the latest value (null before any emission).
371
+ */
372
+ function pipe(name, value, ...args) {
373
+ switch (name) {
374
+ case 'uppercase': return typeof value === 'string' ? value.toUpperCase() : value;
375
+ case 'lowercase': return typeof value === 'string' ? value.toLowerCase() : value;
376
+ case 'titlecase':
377
+ return typeof value === 'string'
378
+ ? value.replace(/\w\S*/g, (w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
379
+ : value;
380
+ case 'json': return JSON.stringify(value);
381
+ case 'date': return pipeDate(value, args[0]);
382
+ case 'number':
383
+ return typeof value === 'number'
384
+ ? formatPipeNumber(value, parsePipeDigits(args[0], { minInt: 1, minFrac: 0, maxFrac: 3 }))
385
+ : value;
386
+ case 'percent':
387
+ return typeof value === 'number'
388
+ ? formatPipeNumber(value * 100, parsePipeDigits(args[0], { minInt: 1, minFrac: 0, maxFrac: 3 })) + '%'
389
+ : value;
390
+ case 'currency': return pipeCurrency(value, args);
391
+ case 'slice': {
392
+ if (typeof value !== 'string' && !Array.isArray(value))
393
+ return value;
394
+ const start = typeof args[0] === 'number' ? args[0] : 0;
395
+ const end = typeof args[1] === 'number' ? args[1] : undefined;
396
+ return value.slice(start, end);
397
+ }
398
+ case 'keyvalue': {
399
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
400
+ return value;
401
+ const rec = value;
402
+ return Object.keys(rec)
403
+ .map((key) => ({ key, value: rec[key] }))
404
+ .sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
405
+ }
406
+ case 'async': return pipeAsyncSnapshot(value);
407
+ default: throw new Error(`Unknown pipe '${name}'`);
408
+ }
409
+ }
410
+ function parsePipeDigits(info, fallback) {
411
+ if (typeof info !== 'string')
412
+ return fallback;
413
+ const m = /^(\d+)\.(\d+)-(\d+)$/.exec(info.trim());
414
+ if (!m)
415
+ return fallback;
416
+ const parsed = { minInt: Number(m[1]), minFrac: Number(m[2]), maxFrac: Number(m[3]) };
417
+ return parsed.maxFrac < parsed.minFrac ? fallback : parsed;
418
+ }
419
+ function formatPipeNumber(value, digits) {
420
+ if (!Number.isFinite(value))
421
+ return String(value);
422
+ const negative = value < 0;
423
+ const fixed = Math.abs(value).toFixed(digits.maxFrac);
424
+ const dot = fixed.indexOf('.');
425
+ let intPart = dot >= 0 ? fixed.slice(0, dot) : fixed;
426
+ let fracPart = dot >= 0 ? fixed.slice(dot + 1) : '';
427
+ while (fracPart.length > digits.minFrac && fracPart.endsWith('0'))
428
+ fracPart = fracPart.slice(0, -1);
429
+ while (fracPart.length < digits.minFrac)
430
+ fracPart += '0';
431
+ while (intPart.length < digits.minInt)
432
+ intPart = '0' + intPart;
433
+ const grouped = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
434
+ return (negative ? '-' : '') + grouped + (fracPart ? '.' + fracPart : '');
435
+ }
436
+ const PIPE_MONTH_SHORT = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
437
+ const PIPE_DATE_FORMATS = {
438
+ shortDate: 'M/d/yy',
439
+ mediumDate: 'MMM d, yyyy',
440
+ shortTime: 'h:mm a',
441
+ medium: 'MMM d, yyyy, h:mm:ss a',
442
+ short: 'M/d/yy, h:mm a',
443
+ };
444
+ function pipeDate(value, formatArg) {
445
+ let d;
446
+ if (value instanceof Date)
447
+ d = Number.isNaN(value.getTime()) ? undefined : value;
448
+ else if (typeof value === 'number' && Number.isFinite(value))
449
+ d = new Date(value);
450
+ else if (typeof value === 'string' && value.trim() !== '') {
451
+ const parsed = new Date(value);
452
+ d = Number.isNaN(parsed.getTime()) ? undefined : parsed;
453
+ }
454
+ if (!d)
455
+ return value;
456
+ const named = typeof formatArg === 'string' ? formatArg : 'mediumDate';
457
+ const format = PIPE_DATE_FORMATS[named] ?? named;
458
+ const pad = (n) => String(n).padStart(2, '0');
459
+ const hours = d.getHours();
460
+ const hour12 = hours % 12 === 0 ? 12 : hours % 12;
461
+ const tokens = [
462
+ ['yyyy', String(d.getFullYear())],
463
+ ['MMM', PIPE_MONTH_SHORT[d.getMonth()]],
464
+ ['yy', pad(d.getFullYear() % 100)],
465
+ ['MM', pad(d.getMonth() + 1)],
466
+ ['dd', pad(d.getDate())],
467
+ ['HH', pad(hours)],
468
+ ['hh', pad(hour12)],
469
+ ['mm', pad(d.getMinutes())],
470
+ ['ss', pad(d.getSeconds())],
471
+ ['M', String(d.getMonth() + 1)],
472
+ ['d', String(d.getDate())],
473
+ ['H', String(hours)],
474
+ ['h', String(hour12)],
475
+ ['a', hours < 12 ? 'AM' : 'PM'],
476
+ ];
477
+ let out = '';
478
+ let i = 0;
479
+ while (i < format.length) {
480
+ const hit = tokens.find(([tok]) => format.startsWith(tok, i));
481
+ if (hit) {
482
+ out += hit[1];
483
+ i += hit[0].length;
484
+ }
485
+ else {
486
+ out += format[i];
487
+ i++;
488
+ }
489
+ }
490
+ return out;
491
+ }
492
+ const PIPE_CURRENCY_SYMBOLS = {
493
+ USD: '$', EUR: '€', GBP: '£', INR: '₹', NPR: 'Rs',
494
+ };
495
+ function pipeCurrency(value, args) {
496
+ if (typeof value !== 'number')
497
+ return value;
498
+ const code = typeof args[0] === 'string' && args[0] !== '' ? args[0] : 'USD';
499
+ const display = typeof args[1] === 'string' ? args[1] : 'symbol';
500
+ const digits = parsePipeDigits(args[2], { minInt: 1, minFrac: 2, maxFrac: 2 });
501
+ const symbol = display === 'code' ? undefined : PIPE_CURRENCY_SYMBOLS[code];
502
+ const formatted = formatPipeNumber(Math.abs(value), digits);
503
+ const sign = value < 0 ? '-' : '';
504
+ return symbol !== undefined ? `${sign}${symbol}${formatted}` : `${sign}${code} ${formatted}`;
505
+ }
506
+ function pipeAsyncSnapshot(value) {
507
+ if (value === null || value === undefined)
508
+ return null;
509
+ const sub = value;
510
+ if (typeof sub.subscribe !== 'function')
511
+ return value;
512
+ let latest = null;
513
+ try {
514
+ const handle = sub.subscribe((v) => { latest = v; });
515
+ if (handle && typeof handle.unsubscribe === 'function')
516
+ handle.unsubscribe();
517
+ }
518
+ catch {
519
+ return latest;
520
+ }
521
+ return latest;
522
+ }
523
+ /**
524
+ * Base class for generated services (Stage 3, M6).
525
+ *
526
+ * A service's state is plain class fields. Whenever a translated service
527
+ * method assigns a field, the codegen appends `this.__notify()`; subscribed
528
+ * components re-render. Generated components subscribe with React's
529
+ * useSyncExternalStore over __subscribe/__getVersion, the version counter
530
+ * is the snapshot, so every notification produces a new snapshot value.
531
+ */
532
+ class ReactiveService {
533
+ __listeners = new Set();
534
+ __version = 0;
535
+ /** Bump the version and notify every subscribed component. */
536
+ __notify() {
537
+ this.__version++;
538
+ for (const listener of [...this.__listeners])
539
+ listener();
540
+ }
541
+ /** Subscribe to changes; returns an unsubscribe function. */
542
+ __subscribe(listener) {
543
+ this.__listeners.add(listener);
544
+ return () => { this.__listeners.delete(listener); };
545
+ }
546
+ /** Monotonic snapshot for useSyncExternalStore. */
547
+ __getVersion() {
548
+ return this.__version;
549
+ }
550
+ }
551
+ exports.ReactiveService = ReactiveService;
552
+ /**
553
+ * Angular-shaped HttpClient over fetch (Stage 3, M6). Registered in the
554
+ * generated app's container under its own class token, so components inject
555
+ * it exactly like a service: `constructor(private http: HttpClient)`.
556
+ * Responses are parsed as JSON (Angular's default responseType). The four
557
+ * verbs share one request path: get and delete send no body, post and put
558
+ * send theirs as JSON (the verbs joined in 0.6.5, for lesson 63's examples).
559
+ */
560
+ class HttpClient {
561
+ fetchImpl;
562
+ constructor(fetchImpl = (url, init) => fetch(url, init)) {
563
+ this.fetchImpl = fetchImpl;
564
+ }
565
+ get(url) {
566
+ return this.request('GET', url);
567
+ }
568
+ post(url, body) {
569
+ return this.request('POST', url, body);
570
+ }
571
+ put(url, body) {
572
+ return this.request('PUT', url, body);
573
+ }
574
+ delete(url) {
575
+ return this.request('DELETE', url);
576
+ }
577
+ request(method, url, body) {
578
+ const fetchImpl = this.fetchImpl;
579
+ return new rxjs_1.Observable((subscriber) => {
580
+ let cancelled = false;
581
+ const init = body === undefined
582
+ ? { method }
583
+ : { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) };
584
+ fetchImpl(url, init)
585
+ .then((res) => res.json())
586
+ .then((data) => {
587
+ if (cancelled)
588
+ return;
589
+ subscriber.next(data);
590
+ subscriber.complete();
591
+ })
592
+ .catch((err) => { if (!cancelled)
593
+ subscriber.error(err); });
594
+ return () => { cancelled = true; };
595
+ });
596
+ }
597
+ }
598
+ exports.HttpClient = HttpClient;
599
+ /**
600
+ * A tiny dependency-injection registry. Generated apps register providers
601
+ * under a token and components resolve them with get(). A later stage bridges
602
+ * this to React Context; the registry semantics stay the same.
603
+ */
604
+ class Container {
605
+ providers = new Map();
606
+ register(token, instance) {
607
+ this.providers.set(token, instance);
608
+ return this;
609
+ }
610
+ has(token) {
611
+ return this.providers.has(token);
612
+ }
613
+ get(token) {
614
+ if (!this.providers.has(token)) {
615
+ const name = typeof token === 'function' ? token.name : String(token);
616
+ throw new Error(`Rangular DI: no provider registered for token '${name}'`);
617
+ }
618
+ return this.providers.get(token);
619
+ }
620
+ }
621
+ exports.Container = Container;
622
+ function isEmptyValue(value) {
623
+ return value === null || value === undefined || value === ''
624
+ || (Array.isArray(value) && value.length === 0);
625
+ }
626
+ function valueLength(value) {
627
+ if (typeof value === 'string' || Array.isArray(value))
628
+ return value.length;
629
+ return String(value).length;
630
+ }
631
+ // Angular's own email check is a very long RFC regex; this is the same
632
+ // shape (local part, @, dotted domain, a TLD of at least two letters),
633
+ // kept readable on purpose.
634
+ const EMAIL_RE = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}$/;
635
+ /** Anchor a string pattern the way Angular does: ^ at the start, $ at the end. */
636
+ function anchorPattern(pattern) {
637
+ let out = pattern;
638
+ if (!out.startsWith('^'))
639
+ out = `^${out}`;
640
+ if (!out.endsWith('$'))
641
+ out = `${out}$`;
642
+ return out;
643
+ }
644
+ exports.Validators = {
645
+ required(value) {
646
+ return isEmptyValue(value) ? { required: true } : null;
647
+ },
648
+ minLength(requiredLength) {
649
+ return (value) => {
650
+ if (isEmptyValue(value))
651
+ return null;
652
+ const actualLength = valueLength(value);
653
+ return actualLength < requiredLength
654
+ ? { minlength: { requiredLength, actualLength } }
655
+ : null;
656
+ };
657
+ },
658
+ maxLength(requiredLength) {
659
+ return (value) => {
660
+ if (isEmptyValue(value))
661
+ return null;
662
+ const actualLength = valueLength(value);
663
+ return actualLength > requiredLength
664
+ ? { maxlength: { requiredLength, actualLength } }
665
+ : null;
666
+ };
667
+ },
668
+ email(value) {
669
+ if (isEmptyValue(value))
670
+ return null;
671
+ return EMAIL_RE.test(String(value)) ? null : { email: true };
672
+ },
673
+ pattern(p) {
674
+ const requiredPattern = typeof p === 'string' ? anchorPattern(p) : p.source;
675
+ const regex = typeof p === 'string' ? new RegExp(requiredPattern) : p;
676
+ return (value) => {
677
+ if (isEmptyValue(value))
678
+ return null;
679
+ return regex.test(String(value))
680
+ ? null
681
+ : { pattern: { requiredPattern, actualValue: value } };
682
+ };
683
+ },
684
+ };
685
+ /** Run validators in order and merge their error objects; null when all pass. */
686
+ function validateValue(value, validators) {
687
+ let merged = null;
688
+ for (const validator of validators) {
689
+ const errors = validator(value);
690
+ if (errors)
691
+ merged = { ...(merged ?? {}), ...errors };
692
+ }
693
+ return merged;
694
+ }
695
+ /**
696
+ * One reactive form control (Stage 8). Holds a value, validates it on
697
+ * construction and on every setValue, tracks touched/dirty the way
698
+ * Angular does, and exposes valueChanges as a real RxJS Observable
699
+ * fed by a Subject the control owns.
700
+ */
701
+ class FormControl {
702
+ value;
703
+ errors = null;
704
+ touched = false;
705
+ dirty = false;
706
+ valueChanges;
707
+ validators;
708
+ changes = new rxjs_1.Subject();
709
+ constructor(initialValue = null, validators) {
710
+ this.value = initialValue;
711
+ this.validators = validators == null ? [] : Array.isArray(validators) ? [...validators] : [validators];
712
+ this.valueChanges = this.changes.asObservable();
713
+ this.revalidate();
714
+ }
715
+ get valid() { return this.errors === null; }
716
+ get invalid() { return this.errors !== null; }
717
+ get pristine() { return !this.dirty; }
718
+ get untouched() { return !this.touched; }
719
+ setValue(value) {
720
+ this.value = value;
721
+ this.dirty = true;
722
+ this.revalidate();
723
+ this.changes.next(value);
724
+ }
725
+ patchValue(value) { this.setValue(value); }
726
+ markAsTouched() { this.touched = true; }
727
+ markAllAsTouched() { this.touched = true; }
728
+ markAsDirty() { this.dirty = true; }
729
+ revalidate() {
730
+ this.errors = validateValue(this.value, this.validators);
731
+ }
732
+ }
733
+ exports.FormControl = FormControl;
734
+ /** Write a value into any form node, recursing into containers. */
735
+ function setNodeValue(node, value) {
736
+ if (node instanceof FormControl)
737
+ node.setValue(value);
738
+ else if (node instanceof FormGroup)
739
+ node.setValue(value);
740
+ else
741
+ node.setValue(value);
742
+ }
743
+ /** Write a partial value into any form node, recursing into containers. */
744
+ function patchNodeValue(node, value) {
745
+ if (node instanceof FormControl)
746
+ node.patchValue(value);
747
+ else if (node instanceof FormGroup)
748
+ node.patchValue(value);
749
+ else
750
+ node.patchValue(value);
751
+ }
752
+ /**
753
+ * A named set of form nodes (Stage 8; tree nodes since the forms
754
+ * completion pass). The group's value is the plain object of child
755
+ * values (a FormArray child contributes an array, a nested FormGroup
756
+ * an object); the group is valid exactly when every child is valid.
757
+ * There are no group-level validators in this version, so the group's
758
+ * own errors are always null, as in Angular when no group validator
759
+ * is registered. The group's valueChanges emits its value whenever
760
+ * any descendant control changes.
761
+ */
762
+ class FormGroup {
763
+ controls;
764
+ valueChanges;
765
+ constructor(controls) {
766
+ this.controls = controls;
767
+ this.valueChanges = (0, rxjs_2.merge)(...Object.values(this.controls).map((child) => child.valueChanges)).pipe((0, rxjs_2.map)(() => this.value));
768
+ }
769
+ get(name) {
770
+ return this.controls[name];
771
+ }
772
+ get value() {
773
+ const out = {};
774
+ for (const [name, child] of Object.entries(this.controls))
775
+ out[name] = child.value;
776
+ return out;
777
+ }
778
+ get valid() {
779
+ return Object.values(this.controls).every((c) => c.valid);
780
+ }
781
+ get invalid() { return !this.valid; }
782
+ get errors() { return null; }
783
+ get touched() {
784
+ return Object.values(this.controls).some((c) => c.touched);
785
+ }
786
+ get dirty() {
787
+ return Object.values(this.controls).some((c) => c.dirty);
788
+ }
789
+ markAllAsTouched() {
790
+ for (const child of Object.values(this.controls))
791
+ child.markAllAsTouched();
792
+ }
793
+ /** Set every child from a complete value object, as in Angular. */
794
+ setValue(value) {
795
+ for (const name of Object.keys(this.controls)) {
796
+ if (!(name in value))
797
+ throw new Error(`FormGroup.setValue: no value given for control '${name}'`);
798
+ }
799
+ for (const [name, v] of Object.entries(value)) {
800
+ const child = this.controls[name];
801
+ if (!child)
802
+ throw new Error(`FormGroup.setValue: no control named '${name}'`);
803
+ setNodeValue(child, v);
804
+ }
805
+ }
806
+ /** Set the children named in a partial value object, as in Angular. */
807
+ patchValue(value) {
808
+ for (const [name, v] of Object.entries(value)) {
809
+ const child = this.controls[name];
810
+ if (child)
811
+ patchNodeValue(child, v);
812
+ }
813
+ }
814
+ }
815
+ exports.FormGroup = FormGroup;
816
+ /**
817
+ * An ordered list of form nodes (forms completion pass): the dynamic
818
+ * side of reactive forms, for rows the user can add and remove. The
819
+ * array's value is the array of child values; it is valid exactly
820
+ * when every child is valid. Its valueChanges emits whenever a child
821
+ * changes and whenever the structure changes (push, insert, removeAt,
822
+ * clear), so a component subscribed once stays live across edits.
823
+ * There are no array-level validators in this version, so the array's
824
+ * own errors are always null.
825
+ */
826
+ class FormArray {
827
+ controls;
828
+ valueChanges;
829
+ changes = new rxjs_1.Subject();
830
+ childSubs = new Map();
831
+ constructor(controls = []) {
832
+ this.controls = [...controls];
833
+ this.valueChanges = this.changes.asObservable();
834
+ for (const child of this.controls)
835
+ this.watch(child);
836
+ }
837
+ watch(child) {
838
+ this.childSubs.set(child, child.valueChanges.subscribe(() => this.emit()));
839
+ }
840
+ unwatch(child) {
841
+ this.childSubs.get(child)?.unsubscribe();
842
+ this.childSubs.delete(child);
843
+ }
844
+ emit() {
845
+ this.changes.next(this.value);
846
+ }
847
+ get length() { return this.controls.length; }
848
+ at(index) {
849
+ return this.controls[index];
850
+ }
851
+ push(control) {
852
+ this.controls.push(control);
853
+ this.watch(control);
854
+ this.emit();
855
+ }
856
+ insert(index, control) {
857
+ this.controls.splice(index, 0, control);
858
+ this.watch(control);
859
+ this.emit();
860
+ }
861
+ removeAt(index) {
862
+ const removed = this.controls.splice(index, 1)[0];
863
+ if (removed)
864
+ this.unwatch(removed);
865
+ this.emit();
866
+ }
867
+ clear() {
868
+ for (const child of this.controls)
869
+ this.unwatch(child);
870
+ this.controls.length = 0;
871
+ this.emit();
872
+ }
873
+ get value() {
874
+ return this.controls.map((c) => c.value);
875
+ }
876
+ get valid() {
877
+ return this.controls.every((c) => c.valid);
878
+ }
879
+ get invalid() { return !this.valid; }
880
+ get errors() { return null; }
881
+ get touched() {
882
+ return this.controls.some((c) => c.touched);
883
+ }
884
+ get dirty() {
885
+ return this.controls.some((c) => c.dirty);
886
+ }
887
+ markAllAsTouched() {
888
+ for (const child of this.controls)
889
+ child.markAllAsTouched();
890
+ }
891
+ /** Set every child from a complete array of values, as in Angular. */
892
+ setValue(values) {
893
+ if (values.length !== this.controls.length) {
894
+ throw new Error(`FormArray.setValue: expected ${this.controls.length} values, got ${values.length}`);
895
+ }
896
+ this.controls.forEach((child, i) => setNodeValue(child, values[i]));
897
+ }
898
+ /** Set the first children from a partial array of values. */
899
+ patchValue(values) {
900
+ values.forEach((v, i) => {
901
+ if (i < this.controls.length)
902
+ patchNodeValue(this.controls[i], v);
903
+ });
904
+ }
905
+ }
906
+ exports.FormArray = FormArray;
907
+ /**
908
+ * The config-object factory for form trees (forms completion pass),
909
+ * Angular's convenience over the classes above. An injected built-in,
910
+ * like HttpClient: constructor(private fb: FormBuilder). Each config
911
+ * entry becomes a node: a FormControl, FormGroup or FormArray instance
912
+ * is used as-is; a tuple [initialValue, validators] becomes a
913
+ * FormControl with those validators; any other value becomes a
914
+ * FormControl holding it. A tuple's third element (Angular's async
915
+ * validators) is ignored: there are no async validators in this
916
+ * version.
917
+ */
918
+ class FormBuilder {
919
+ group(config) {
920
+ const controls = {};
921
+ for (const [name, entry] of Object.entries(config))
922
+ controls[name] = this.coerce(entry);
923
+ return new FormGroup(controls);
924
+ }
925
+ control(initialValue = null, validators) {
926
+ return new FormControl(initialValue, validators);
927
+ }
928
+ array(entries = []) {
929
+ return new FormArray(entries.map((entry) => this.coerce(entry)));
930
+ }
931
+ coerce(entry) {
932
+ if (entry instanceof FormControl || entry instanceof FormGroup || entry instanceof FormArray)
933
+ return entry;
934
+ if (Array.isArray(entry)) {
935
+ const validators = entry.length > 1 ? entry[1] : undefined;
936
+ return new FormControl(entry.length ? entry[0] : null, validators);
937
+ }
938
+ return new FormControl(entry ?? null);
939
+ }
940
+ }
941
+ exports.FormBuilder = FormBuilder;
942
+ /** Normalise a path: split on '/', drop empty segments, rejoin. */
943
+ function normalizeRoutePath(raw) {
944
+ return raw.split('/').filter((s) => s.length > 0).join('/');
945
+ }
946
+ function segmentsOf(path) {
947
+ const normalized = normalizeRoutePath(path);
948
+ return normalized === '' ? [] : normalized.split('/');
949
+ }
950
+ /** Match one pattern against one concrete path; params or null. */
951
+ function matchSegments(pattern, path) {
952
+ if (pattern === '**')
953
+ return {};
954
+ const want = segmentsOf(pattern);
955
+ const got = segmentsOf(path);
956
+ if (want.length !== got.length)
957
+ return null;
958
+ const params = {};
959
+ for (let i = 0; i < want.length; i++) {
960
+ if (want[i].startsWith(':'))
961
+ params[want[i].slice(1)] = got[i];
962
+ else if (want[i] !== got[i])
963
+ return null;
964
+ }
965
+ return params;
966
+ }
967
+ /**
968
+ * Match a path against a route table, following redirects. Returns the
969
+ * final match, or null when nothing matches (no entry and no wildcard).
970
+ */
971
+ function matchRoute(routes, rawPath) {
972
+ let current = normalizeRoutePath(rawPath);
973
+ const seen = new Set();
974
+ for (let hop = 0; hop <= 10; hop++) {
975
+ let hit = null;
976
+ for (const def of routes) {
977
+ const params = matchSegments(def.path, current);
978
+ if (params) {
979
+ hit = { def, params };
980
+ break;
981
+ }
982
+ }
983
+ if (!hit)
984
+ return null;
985
+ if (hit.def.redirectTo === undefined) {
986
+ return { path: current, params: hit.params, routePath: hit.def.path };
987
+ }
988
+ if (seen.has(current))
989
+ return null;
990
+ seen.add(current);
991
+ current = normalizeRoutePath(hit.def.redirectTo);
992
+ }
993
+ return null;
994
+ }
995
+ /**
996
+ * The navigation stack of a generated app (Stage 9). One instance lives
997
+ * at module level in the generated file; the root component subscribes
998
+ * and re-renders the outlet whenever the top entry changes. The stack
999
+ * always holds at least the initial entry (the match for the empty
1000
+ * path, redirects followed), so `current` is always defined and
1001
+ * `back()` at depth 1 is a no-op that returns false.
1002
+ */
1003
+ class RgNavigator {
1004
+ routes;
1005
+ entries;
1006
+ listeners = new Set();
1007
+ constructor(routes) {
1008
+ this.routes = routes;
1009
+ const initial = matchRoute(routes, '');
1010
+ this.entries = [initial ?? { path: '', params: {}, routePath: '' }];
1011
+ }
1012
+ /** The entry on top of the stack: what the outlet renders. */
1013
+ get current() {
1014
+ return this.entries[this.entries.length - 1];
1015
+ }
1016
+ /** Stack depth; the app can go back exactly when this is above 1. */
1017
+ get depth() {
1018
+ return this.entries.length;
1019
+ }
1020
+ /** Push a new entry; false (and no change) when no route matches. */
1021
+ navigate(rawPath) {
1022
+ const match = matchRoute(this.routes, rawPath);
1023
+ if (!match)
1024
+ return false;
1025
+ this.entries.push(match);
1026
+ this.emit();
1027
+ return true;
1028
+ }
1029
+ /** Pop back to the previous entry; false at the root of the stack. */
1030
+ back() {
1031
+ if (this.entries.length <= 1)
1032
+ return false;
1033
+ this.entries.pop();
1034
+ this.emit();
1035
+ return true;
1036
+ }
1037
+ /** Subscribe to navigation changes; returns an unsubscribe function. */
1038
+ subscribe(listener) {
1039
+ this.listeners.add(listener);
1040
+ return () => { this.listeners.delete(listener); };
1041
+ }
1042
+ emit() {
1043
+ for (const listener of [...this.listeners])
1044
+ listener();
1045
+ }
1046
+ }
1047
+ exports.RgNavigator = RgNavigator;
1048
+ /**
1049
+ * The injectable Angular authors navigate with (Stage 9). Generated
1050
+ * components receive the one instance bound to the app's navigator.
1051
+ *
1052
+ * `navigate(commands)` joins the command segments with '/': numbers
1053
+ * are stringified, and slashes at segment edges mean nothing, so
1054
+ * `navigate(['/mail', 3])` and `navigate(['mail', '3'])` both land on
1055
+ * 'mail/3'. In v1 commands always resolve from the app root; Angular's
1056
+ * relative-to-current-route navigation is not in this version.
1057
+ */
1058
+ class Router {
1059
+ navigator;
1060
+ constructor(navigator) {
1061
+ this.navigator = navigator;
1062
+ }
1063
+ navigate(commands) {
1064
+ return this.navigator.navigate(commands.map((c) => String(c)).join('/'));
1065
+ }
1066
+ navigateByUrl(url) {
1067
+ return this.navigator.navigate(url);
1068
+ }
1069
+ }
1070
+ exports.Router = Router;
1071
+ /**
1072
+ * The injectable that carries the current route's parameters into a
1073
+ * route component (Stage 9). The outlet creates one instance per mount
1074
+ * from the current navigation entry and passes it to the component.
1075
+ *
1076
+ * `snapshot.params` is the plain params object. `paramMap` is a real
1077
+ * RxJS Observable fed by a BehaviorSubject: it emits the current
1078
+ * params on subscribe and, while subscribed, again whenever the
1079
+ * navigator's current entry changes.
1080
+ * In v1 the generated outlet remounts a route component when the path
1081
+ * changes (it keys the component by the concrete path), so a component
1082
+ * normally sees exactly one emission per mount; the snapshot is the
1083
+ * primary surface, exactly the pattern Angular's own docs teach first.
1084
+ */
1085
+ class ActivatedRoute {
1086
+ initialParams;
1087
+ navigatorRef;
1088
+ paramMap;
1089
+ paramsChanges;
1090
+ constructor(initialParams, navigatorRef) {
1091
+ this.initialParams = initialParams;
1092
+ this.navigatorRef = navigatorRef;
1093
+ this.paramsChanges = new rxjs_1.BehaviorSubject(initialParams);
1094
+ if (this.navigatorRef) {
1095
+ const nav = this.navigatorRef;
1096
+ nav.subscribe(() => this.paramsChanges.next(nav.current.params));
1097
+ }
1098
+ this.paramMap = this.paramsChanges.asObservable();
1099
+ }
1100
+ /**
1101
+ * The current parameters, read live: with a navigator attached the
1102
+ * snapshot reflects the latest navigation (Angular refreshes the
1103
+ * snapshot on each activation the same way); without one it is the
1104
+ * fixed set the instance was constructed with.
1105
+ */
1106
+ get snapshot() {
1107
+ return { params: this.navigatorRef ? this.navigatorRef.current.params : this.initialParams };
1108
+ }
1109
+ }
1110
+ exports.ActivatedRoute = ActivatedRoute;
1111
+ /**
1112
+ * The handle `SnackBar.open` returns, mirroring MatSnackBarRef.
1113
+ * `onAction(callback)` registers what runs when the bar's action is
1114
+ * pressed (the Undo pattern); `dismiss()` closes the bar early.
1115
+ */
1116
+ class SnackBarRef {
1117
+ bar;
1118
+ actionCallbacks = [];
1119
+ constructor(bar) {
1120
+ this.bar = bar;
1121
+ }
1122
+ onAction(callback) {
1123
+ this.actionCallbacks.push(callback);
1124
+ }
1125
+ dismiss() {
1126
+ this.bar.dismiss();
1127
+ }
1128
+ /** Fired by the owning SnackBar when the action is pressed. Hosts never call this. */
1129
+ __fireAction() {
1130
+ for (const callback of [...this.actionCallbacks])
1131
+ callback();
1132
+ }
1133
+ }
1134
+ exports.SnackBarRef = SnackBarRef;
1135
+ class SnackBar {
1136
+ state = null;
1137
+ currentRef = null;
1138
+ listeners = new Set();
1139
+ timer;
1140
+ /** The bar currently showing, or null. The generated host renders this. */
1141
+ get current() {
1142
+ return this.state;
1143
+ }
1144
+ /** Subscribe to open/dismiss changes; returns an unsubscribe function. */
1145
+ subscribe(listener) {
1146
+ this.listeners.add(listener);
1147
+ return () => { this.listeners.delete(listener); };
1148
+ }
1149
+ /**
1150
+ * Open a bar, replacing any bar currently showing (its action
1151
+ * callbacks do not fire). Returns the bar's ref.
1152
+ */
1153
+ open(message, actionLabel, durationMs = 4000) {
1154
+ this.clearTimer();
1155
+ const ref = new SnackBarRef(this);
1156
+ this.currentRef = ref;
1157
+ this.state = { message, actionLabel, durationMs };
1158
+ if (typeof setTimeout === 'function' && durationMs > 0) {
1159
+ this.timer = setTimeout(() => this.dismiss(), durationMs);
1160
+ // In Node (tests, tooling) a pending auto-dismiss must not hold
1161
+ // the process open; in React Native the timer has no unref.
1162
+ this.timer.unref?.();
1163
+ }
1164
+ this.emit();
1165
+ return ref;
1166
+ }
1167
+ /** Close the current bar without firing its action callbacks. */
1168
+ dismiss() {
1169
+ if (this.state === null)
1170
+ return;
1171
+ this.clearTimer();
1172
+ this.state = null;
1173
+ this.currentRef = null;
1174
+ this.emit();
1175
+ }
1176
+ /**
1177
+ * The action was pressed: the bar dismisses and the current ref's
1178
+ * onAction callbacks fire, in that order. Called by the generated
1179
+ * snackbar host; authors use SnackBarRef.onAction instead.
1180
+ */
1181
+ pressAction() {
1182
+ const ref = this.currentRef;
1183
+ this.dismiss();
1184
+ ref?.__fireAction();
1185
+ }
1186
+ clearTimer() {
1187
+ if (this.timer !== undefined && typeof clearTimeout === 'function') {
1188
+ clearTimeout(this.timer);
1189
+ }
1190
+ this.timer = undefined;
1191
+ }
1192
+ emit() {
1193
+ for (const listener of [...this.listeners])
1194
+ listener();
1195
+ }
1196
+ }
1197
+ exports.SnackBar = SnackBar;