fg-dynamic-component 3.0.0 → 5.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fg-dynamic-component",
3
- "version": "3.0.0",
3
+ "version": "5.0.0",
4
4
  "author": "Francesco Guagnano <guagnanofrancesco11@gmail.com>",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -18,8 +18,10 @@
18
18
  "life-cycle"
19
19
  ],
20
20
  "peerDependencies": {
21
- "@angular/common": "22.1.6",
22
- "@angular/core": "22.1.6"
21
+ "@angular/common": "^22.2.3",
22
+ "@angular/core": "^22.2.3",
23
+ "@angular/forms": "^22.2.3",
24
+ "rxjs": "^7.8.0"
23
25
  },
24
26
  "sideEffects": false,
25
27
  "module": "fesm2022/fg-dynamic-component.mjs",
@@ -1,14 +1,104 @@
1
1
  import * as i0 from "@angular/core";
2
2
  import { InputSignal, ModelSignal, OnChanges, OnDestroy, Signal, SimpleChanges, Type } from "@angular/core";
3
3
  import { FormGroup } from "@angular/forms";
4
+ /**
5
+ * Small, allowlisted expression interpreter used for the `$vm` / `$event` binding
6
+ * feature of `FGDynamicComponent`.
7
+ *
8
+ * This intentionally does NOT use `eval`, `new Function`, or any other
9
+ * string-to-code primitive. Only the following constructs are supported:
10
+ *
11
+ * - literals (string, number, boolean, null, undefined, NaN, Infinity)
12
+ * - identifiers from the provided variables (`$vm`, `$event`, arrow parameters)
13
+ * - member access: `a.b`, `a['b']`, optional chaining `a?.b`
14
+ * - calls: `$vm()`, `$vm.update(fn)`, `$event.value`
15
+ * - unary: `!`, `-`, `+`, `typeof`
16
+ * - binary/logical/ternary operators
17
+ * - array and object literals, including spread
18
+ * - expression-bodied arrow functions (and arrow blocks containing `return`)
19
+ *
20
+ * Assignments, `new`, `this`, globals (e.g. `window`, `fetch`), template
21
+ * literals and regular-expression literals are rejected. Prototype-related
22
+ * property names are blocked at every access.
23
+ *
24
+ * Expressions are also treated as a capability boundary: browser host objects
25
+ * (DOM nodes, events, `window`, `document`, storage, …) are never readable and
26
+ * methods can only be invoked through an allowlist. This prevents an expression
27
+ * from escaping through `$event`/`$vm` values that happen to reference the DOM.
28
+ */
29
+ /**
30
+ * A single method capability granted to expressions.
31
+ *
32
+ * `receiver` defaults to `'root'`, which only permits the call on the `$vm`
33
+ * capability or on the value returned by `$vm()`. Granting a method name to
34
+ * every reachable object (`'any'`) is only safe for fully trusted view models;
35
+ * `on` pins the capability to one object identity.
36
+ */
37
+ interface FGDynamicAllowedMethod {
38
+ name: string;
39
+ receiver?: 'root' | 'any';
40
+ on?: object;
41
+ }
4
42
  export type FGDynamicType = Type<unknown> | Promise<Type<unknown>> | (() => Promise<Type<unknown>>);
5
43
  export interface IFGDynamicItem {
6
44
  type?: string | FGDynamicType;
7
- inputs?: Record<string, string | unknown>;
45
+ inputs?: Record<string, unknown>;
8
46
  outputs?: Record<string, string | Function>;
9
- attributes?: Record<string, string | unknown>;
47
+ attributes?: Record<string, unknown>;
10
48
  items?: IFGDynamicItem[];
11
49
  }
50
+ /**
51
+ * Controls what expressions may do. By default expressions are read-only and
52
+ * can only call native built-ins and `$vm()`; custom view-model methods and
53
+ * view-model mutation require an explicit opt-in.
54
+ */
55
+ export interface IFGDynamicExpressionPolicy {
56
+ /** Allow calling any method reachable from the view model. Defaults to `false`. */
57
+ allowCustomMethods?: boolean;
58
+ /**
59
+ * Methods that may be called when `allowCustomMethods` is `false`.
60
+ * String entries are scoped to `$vm` and the value returned by `$vm()`;
61
+ * use `{ name, receiver: 'any' }` or `{ name, on }` to grant a nested method.
62
+ */
63
+ allowedMethods?: readonly (string | FGDynamicAllowedMethod)[];
64
+ /** Expose `$vm.set` and `$vm.update`. Defaults to `false`. */
65
+ allowViewModelMutation?: boolean;
66
+ }
67
+ /**
68
+ * Controls how the dynamic component interacts with the host `FormGroup`.
69
+ * By default pre-existing controls and nested groups are not reused.
70
+ */
71
+ export interface IFGDynamicFormPolicy {
72
+ /** Reuse controls/groups that already exist in the supplied `FormGroup`. */
73
+ allowExistingControls?: boolean;
74
+ /** Optional allowlist of form control names (the evaluated `attributes.name`). */
75
+ allowedControlNames?: readonly string[];
76
+ }
77
+ /**
78
+ * Controls which component `type` values are accepted.
79
+ * Promise/loader values are rejected unless explicitly enabled.
80
+ */
81
+ export interface IFGDynamicTypePolicy {
82
+ /** Allow promise-returning and function loader `type` values. Defaults to `false`. */
83
+ allowFunctionTypes?: boolean;
84
+ /** Require an explicit scoped registry instead of the global default. */
85
+ requireScopedRegistry?: boolean;
86
+ }
87
+ /**
88
+ * Controls which DOM attributes may be applied. `strict` is intended for
89
+ * untrusted configurations and disables UI-redress/DOM-clobbering attributes.
90
+ */
91
+ export interface IFGDynamicAttributePolicy {
92
+ /** Disallow `id`, `class`, `for`, `href` and `src`. Defaults to `false`. */
93
+ strict?: boolean;
94
+ /**
95
+ * Allow `href`/`src` to point at other origins (including protocol-relative
96
+ * URLs). Defaults to `false`: relative and same-origin URLs only, so an
97
+ * untrusted configuration cannot exfiltrate view-model data by rendering a
98
+ * request to an attacker-controlled host.
99
+ */
100
+ allowExternalUrls?: boolean;
101
+ }
12
102
  /**
13
103
  * A scoped component registry. Backed by a `Map`, so lookups never walk the
14
104
  * prototype chain and names such as `__proto__` or `constructor` are ordinary keys.
@@ -52,38 +142,95 @@ export declare class FGDynamicComponent implements OnChanges, OnDestroy {
52
142
  viewModel: ModelSignal<unknown>;
53
143
  formGroup: InputSignal<FormGroup>;
54
144
  registry: InputSignal<FGDynamicRegistry>;
145
+ expressionPolicy: InputSignal<IFGDynamicExpressionPolicy>;
146
+ formControlPolicy: InputSignal<IFGDynamicFormPolicy>;
147
+ typePolicy: InputSignal<IFGDynamicTypePolicy>;
148
+ attributePolicy: InputSignal<IFGDynamicAttributePolicy>;
149
+ /** Current nesting depth; used to bound recursive configurations. */
150
+ depth: InputSignal<number>;
151
+ /**
152
+ * Cached structural validation for the current configuration. Both
153
+ * `ngOnChanges` and `items` read this computed, so the tree is validated
154
+ * once per signal change rather than twice.
155
+ */
156
+ private readonly _configurationIsValid;
55
157
  /**
56
- * Validated child items. Invalid entries are ignored and the list is capped
57
- * to avoid pathological configurations blocking the renderer.
158
+ * Child items, capped to avoid pathological configurations blocking the
159
+ * renderer. Non-object entries are ignored. Structural limits (depth, node
160
+ * count, cycles) are enforced by `_configurationIsValid`.
58
161
  */
59
162
  protected readonly items: Signal<readonly IFGDynamicItem[]>;
60
163
  private _viewContainerRef;
61
164
  private _dynamicItems;
62
- private _componentRef;
165
+ private _componentRef?;
63
166
  private _renderer;
64
167
  private _outputsSubscriptions;
65
168
  private _currentOutputsConfig?;
66
- private _formControl;
67
- private _formControlDirective;
68
- private _formControlSubscription;
169
+ private _formControl?;
170
+ private _formControlDirective?;
171
+ private _formControlSubscription?;
69
172
  private _managedValidatorFns;
70
- private _component;
173
+ private _component?;
71
174
  private _injector;
72
175
  private _ngOnChangesCounter;
73
- private _lastProjectedItemsSignature;
176
+ private _destroyed;
177
+ private _lastProjectedItemsSignature?;
178
+ /** Group that literally contains the current control (may be a nested group). */
179
+ private _formControlContainer?;
180
+ /** Literal key of the control inside `_formControlContainer`. */
181
+ private _formControlKey?;
182
+ /** True only when this component created (and may therefore remove) the control. */
183
+ private _ownsFormControl;
184
+ /** Intermediate groups created while wiring a dotted control name. */
185
+ private _createdFormGroups;
186
+ /** Form wiring currently attached to the rendered component, used to detect rebinds. */
187
+ private _wiredFormGroup?;
188
+ private _wiredControlName?;
189
+ /** `allowExistingControls` value used for the active wiring. */
190
+ private _wiredAllowExistingControls?;
191
+ /** Last value written to the control, used to avoid feedback loops when syncing the model. */
192
+ private _hasSyncedControlValue;
193
+ private _lastSyncedControlValue;
194
+ /** Disabled state managed by this component, so it can be restored when `disabled` disappears. */
195
+ private _disabledManaged;
196
+ private _disabledBeforeManagement?;
197
+ /** Attribute names currently applied to the dynamic element. */
198
+ private _appliedAttributes;
199
+ /** Input names currently set on the dynamic component. */
200
+ private _appliedInputs;
74
201
  /**
75
202
  * A callback method that is invoked immediately after the default change
76
203
  * detector has checked data-bound properties if at least one has changed,
77
204
  * and before the view and content children are checked.
78
205
  */
79
206
  ngOnChanges(changes?: SimpleChanges): Promise<void>;
207
+ /**
208
+ * Destroys the rendered component when it no longer has a resolvable type.
209
+ * Ignored when a newer `ngOnChanges` generation has started.
210
+ */
211
+ private clearResolvedComponent;
212
+ /**
213
+ * Validates the whole configuration subtree before rendering. Rejects
214
+ * excessive depth, node count, key counts, oversized keys and cycles.
215
+ * The check is iterative so a hostile configuration cannot overflow the
216
+ * JavaScript stack during validation itself.
217
+ */
218
+ private validateConfiguration;
219
+ private collectConfigurationStats;
80
220
  /**
81
221
  * A method to lazy-load a component.
82
222
  */
83
223
  private loadComponentAsync;
224
+ private isPromiseLike;
84
225
  private resolveCandidate;
85
226
  private toComponentType;
86
227
  private isAngularComponentType;
228
+ /**
229
+ * Function loaders and thenables execute host code, so they are only
230
+ * accepted when the host opts in. Angular component classes stay allowed.
231
+ */
232
+ private isCandidateAllowed;
233
+ private isUsingGlobalRegistry;
87
234
  private getRegistry;
88
235
  /**
89
236
  * Instantiates a single component and inserts its host view into this container.
@@ -91,15 +238,66 @@ export declare class FGDynamicComponent implements OnChanges, OnDestroy {
91
238
  private createComponent;
92
239
  /**
93
240
  * Register handlers for those events by subscribing to an instance.
241
+ * Supports both `EventEmitter` (`@Output`) and signal outputs created with `output()`.
94
242
  */
95
243
  private handleOutputs;
244
+ private isOutputEmitter;
96
245
  private handleOutputsIfChanged;
97
246
  /**
98
- * Construct a FormControl with an initial value.
247
+ * Evaluates the configured `attributes.name` into a safe control path.
248
+ * Returns `undefined` when the view model or name is not available yet, so
249
+ * the wiring is retried on the next change.
250
+ */
251
+ private resolveFormControlName;
252
+ /**
253
+ * Recreates the dynamic component when the `formGroup`, the evaluated
254
+ * control name or the availability of the view model changed.
255
+ */
256
+ private rewireFormIfNeeded;
257
+ /**
258
+ * Constructs (or reuses) the form control and attaches it to the rendered
259
+ * component. Dotted names are represented as nested `FormGroup`s so that
260
+ * `formGroup.get('data.firstName')` works and no key contains a dot.
261
+ */
262
+ private wireFormControl;
263
+ /**
264
+ * Walks/creates the nested `FormGroup`s required by a dotted control path.
265
+ * Created groups are tracked so they can be removed again on cleanup.
99
266
  */
100
- private createFormControl;
267
+ private ensureFormGroupPath;
101
268
  /**
102
- * Disables/enables the control.
269
+ * Keeps the view model in sync with the control value. Used for both newly
270
+ * created and reused controls.
271
+ */
272
+ private bindFormControlValueChanges;
273
+ /**
274
+ * Clones only the containers along `path`, sharing every other subtree.
275
+ * Accessor properties are preserved without being invoked.
276
+ */
277
+ private cloneAlongPathForMutation;
278
+ /** Shallow-copies own descriptors without invoking getters. */
279
+ private cloneContainerShallow;
280
+ /**
281
+ * Reflects external view-model changes into the control. Values written by
282
+ * the control itself are skipped to avoid clobbering user input.
283
+ */
284
+ private syncFormControlFromViewModel;
285
+ /** Bounded structural comparison used to detect real view-model changes. */
286
+ private valuesEqual;
287
+ /**
288
+ * Removes created intermediate groups that are detached or still empty.
289
+ * Used after a failed wiring attempt and during cleanup.
290
+ */
291
+ private pruneCreatedFormGroups;
292
+ private setControlDisabled;
293
+ /**
294
+ * Restores the disabled state a control had before this component managed
295
+ * it (important for pre-existing/reused controls and removed `disabled` keys).
296
+ */
297
+ private restoreManagedDisabledState;
298
+ /**
299
+ * Disables/enables the control, normalizing boolean-ish values, and restores
300
+ * the previous state when the `disabled` key is removed.
103
301
  */
104
302
  private setFormControlStatus;
105
303
  /**
@@ -112,8 +310,15 @@ export declare class FGDynamicComponent implements OnChanges, OnDestroy {
112
310
  */
113
311
  private createPatternValidator;
114
312
  /**
115
- * Heuristic check for regular expressions with nested/ambiguous quantifiers
116
- * (e.g. `(a+)+`, `(a*)*`, `(\d+){2,}`) that can cause exponential backtracking.
313
+ * Conservative scanner for regular expressions with nested/ambiguous
314
+ * quantifiers (e.g. `(a+)+`, `(\d+(?:\d+)?)+`, `(a*)*`, `(\d+){2,}`) and
315
+ * quantified alternations (e.g. `(a|aa)+`, `(\w|\d)+`) that can cause
316
+ * exponential backtracking.
317
+ *
318
+ * Groups are tracked with an explicit stack, so nested groups and optional
319
+ * inner quantifiers are detected instead of relying on a single regex.
320
+ * This is still a heuristic: it errs on the side of rejecting ambiguous
321
+ * constructs rather than allowing a catastrophic pattern through.
117
322
  */
118
323
  private isUnsafeRegex;
119
324
  /**
@@ -126,8 +331,20 @@ export declare class FGDynamicComponent implements OnChanges, OnDestroy {
126
331
  * `constructor`), which protects both the view model and `FormGroup`.
127
332
  */
128
333
  private parsePath;
334
+ /**
335
+ * Strictly parses `a.b`, `a[0]`, `a['b']` and `a["b"]`. Unbalanced brackets,
336
+ * empty segments and stray characters are rejected instead of being silently
337
+ * ignored.
338
+ */
339
+ private parseStringPath;
129
340
  private isSafePath;
130
341
  private defineOwn;
342
+ /**
343
+ * Only plain objects and arrays may be traversed/written by form
344
+ * synchronization. This prevents writes into class instances, services and
345
+ * DOM objects referenced by the view model.
346
+ */
347
+ private isMutableContainer;
131
348
  /**
132
349
  * Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.
133
350
  * Only own properties are read; prototype-chain reads are blocked.
@@ -147,7 +364,8 @@ export declare class FGDynamicComponent implements OnChanges, OnDestroy {
147
364
  */
148
365
  private setModelPropertyValue;
149
366
  /**
150
- * Updates specified input names to new values.
367
+ * Updates specified input names to new values and resets inputs that were
368
+ * removed from the configuration.
151
369
  */
152
370
  private setInputs;
153
371
  /**
@@ -157,6 +375,9 @@ export declare class FGDynamicComponent implements OnChanges, OnDestroy {
157
375
  * namespaced attributes, `style`/`srcdoc`/`formaction` and unsafe URL
158
376
  * schemes are never applied. Non-primitive values are ignored so that
159
377
  * configuration data cannot invoke `toString()`/`toJSON()` hooks.
378
+ *
379
+ * Attributes removed from the configuration (or set to a false boolean /
380
+ * `null`) are removed from the element.
160
381
  */
161
382
  private setAttributes;
162
383
  private isAllowedAttribute;
@@ -166,14 +387,38 @@ export declare class FGDynamicComponent implements OnChanges, OnDestroy {
166
387
  */
167
388
  private attributeValueToString;
168
389
  private isSafeUrl;
390
+ private allowsExternalUrls;
391
+ /**
392
+ * Resolves `value` against the document base URL and compares origins. In a
393
+ * non-browser environment absolute URLs are treated as external.
394
+ */
395
+ private isSameOriginUrl;
396
+ /**
397
+ * Evaluates a configured attribute value and reports whether it is an
398
+ * expression that could not be evaluated because its context was missing.
399
+ */
400
+ private evaluateAttribute;
401
+ /**
402
+ * True when a string expression was returned verbatim because its `$vm` or
403
+ * `$event` context was not available. Such values must not be treated as
404
+ * literal booleans/attributes/control names.
405
+ */
406
+ private isUnresolvedExpression;
407
+ /**
408
+ * Normalizes boolean-ish configuration values. `false`, `'false'`, `0`,
409
+ * `'0'`, `''`, `null` and `undefined` are false; everything else is true.
410
+ */
411
+ private toBoolean;
169
412
  /**
170
413
  * Evaluates an expression with a small, allowlisted interpreter. No `eval`,
171
414
  * `Function` or other string-to-code primitive is used.
172
415
  * @param value The expression or literal value.
173
- * @param vmParam The view model (signal or plain value).
416
+ * @param viewModelValue The resolved view model value.
174
417
  * @param eventParam The event payload.
418
+ * @param hasEventContext Whether an event is currently being handled. This
419
+ * distinguishes "no event" from an output that emitted `null`/`undefined`.
175
420
  * @returns Evaluated expression, `undefined` when the expression is rejected,
176
- * or the original value when it is a literal.
421
+ * or the original value when it is a literal/unresolved expression.
177
422
  */
178
423
  private evaluateExpression;
179
424
  private getViewModelValue;
@@ -210,7 +455,33 @@ export declare class FGDynamicComponent implements OnChanges, OnDestroy {
210
455
  "required": false;
211
456
  "isSignal": true;
212
457
  };
458
+ "expressionPolicy": {
459
+ "alias": "expressionPolicy";
460
+ "required": false;
461
+ "isSignal": true;
462
+ };
463
+ "formControlPolicy": {
464
+ "alias": "formControlPolicy";
465
+ "required": false;
466
+ "isSignal": true;
467
+ };
468
+ "typePolicy": {
469
+ "alias": "typePolicy";
470
+ "required": false;
471
+ "isSignal": true;
472
+ };
473
+ "attributePolicy": {
474
+ "alias": "attributePolicy";
475
+ "required": false;
476
+ "isSignal": true;
477
+ };
478
+ "depth": {
479
+ "alias": "depth";
480
+ "required": false;
481
+ "isSignal": true;
482
+ };
213
483
  }, {
214
484
  "viewModel": "viewModelChange";
215
485
  }, never, never, true, never>;
216
- }
486
+ }
487
+ export type { FGDynamicAllowedMethod };