fg-dynamic-component 2.0.0 → 3.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.
@@ -1,465 +1,1678 @@
1
- import * as i0 from '@angular/core';
2
- import { input, model, viewChild, ViewContainerRef, viewChildren, ElementRef, inject, Renderer2, Injector, EventEmitter, ChangeDetectionStrategy, Component } from '@angular/core';
3
- import { FormControlDirective, NgControl, FormControl, Validators, NG_VALUE_ACCESSOR } from '@angular/forms';
4
-
5
- /**
6
- * Declare components to dynamically load in static and/or dynamic way using the FGDynamicService.
7
- */
8
- class FGDynamicService {
9
- static { this._components = {}; }
10
- static registerComponent(name, type) {
11
- if (name && type) {
12
- FGDynamicService._components[name] = type;
13
- }
14
- }
15
- static getComponent(name) {
16
- return FGDynamicService._components[name];
17
- }
1
+ import * as i0 from "@angular/core";
2
+ import { ChangeDetectionStrategy, Component, ElementRef, EventEmitter, Injector, Renderer2, ViewContainerRef, computed, inject, input, isDevMode, model, viewChild, viewChildren } from "@angular/core";
3
+ import { FormControl, FormControlDirective, NG_VALUE_ACCESSOR, NgControl, Validators } from "@angular/forms";
4
+ const MAX_SOURCE_LENGTH = 2e3;
5
+ const MAX_TOKENS = 4e3;
6
+ const MAX_PARSE_DEPTH = 80;
7
+ const MAX_EVALUATION_STEPS = 2e4;
8
+ const MAX_EVALUATION_DEPTH = 80;
9
+ const FORBIDDEN_PROPERTIES = /* @__PURE__ */ new Set([
10
+ "__proto__",
11
+ "prototype",
12
+ "constructor",
13
+ "caller",
14
+ "callee",
15
+ "arguments",
16
+ "__defineGetter__",
17
+ "__defineSetter__",
18
+ "__lookupGetter__",
19
+ "__lookupSetter__"
20
+ ]);
21
+ const PUNCTUATORS = [
22
+ "===",
23
+ "!==",
24
+ "**",
25
+ "==",
26
+ "!=",
27
+ "<=",
28
+ ">=",
29
+ "&&",
30
+ "||",
31
+ "??",
32
+ "?.",
33
+ "...",
34
+ "=>",
35
+ "+",
36
+ "-",
37
+ "*",
38
+ "/",
39
+ "%",
40
+ "<",
41
+ ">",
42
+ "!",
43
+ "?",
44
+ ":",
45
+ ".",
46
+ ",",
47
+ "(",
48
+ ")",
49
+ "[",
50
+ "]",
51
+ "{",
52
+ "}",
53
+ ";"
54
+ ];
55
+ var FGDynamicExpressionError = class extends Error {
56
+ constructor(message) {
57
+ super(message);
58
+ this.name = "FGDynamicExpressionError";
59
+ }
60
+ };
61
+ function fail(message) {
62
+ throw new FGDynamicExpressionError(message);
18
63
  }
19
- /**
20
- * Create a standalone signals based dynamic components tree through a JSON configuration with full
21
- * life-cycle support for inputs, outputs, attributes, reactive forms and expressions binding evaluation.
22
- */
23
- class FGDynamicComponent {
24
- constructor() {
25
- this.configuration = input.required(/* @ts-ignore */
26
- ...(ngDevMode ? [{ debugName: "configuration" }] : /* istanbul ignore next */ []));
27
- this.viewModel = model(/* @ts-ignore */
28
- ...(ngDevMode ? [undefined, { debugName: "viewModel" }] : /* istanbul ignore next */ []));
29
- this.formGroup = input(/* @ts-ignore */
30
- ...(ngDevMode ? [undefined, { debugName: "formGroup" }] : /* istanbul ignore next */ []));
31
- this._viewContainerRef = viewChild.required('viewContainer', { ...(ngDevMode ? { debugName: "_viewContainerRef" } : /* istanbul ignore next */ {}), read: ViewContainerRef });
32
- this._dynamicItems = viewChildren('dynamicItem', { ...(ngDevMode ? { debugName: "_dynamicItems" } : /* istanbul ignore next */ {}), read: ElementRef });
33
- this._renderer = inject(Renderer2);
34
- this._outputsSubscriptions = [];
35
- this._managedValidatorFns = [];
36
- this._injector = inject(Injector);
37
- }
38
- /**
39
- * A callback method that is invoked immediately after the default change
40
- * detector has checked data-bound properties if at least one has changed,
41
- * and before the view and content children are checked.
42
- */
43
- async ngOnChanges() {
44
- try {
45
- // Lazy-load a component.
46
- await this.loadComponentAsync();
47
- // Instantiates a single component and inserts its host view into this container.
48
- this.createComponent();
49
- // Updates specified input names to new values.
50
- this.setInputs();
51
- // Disables/enables the control.
52
- this.setFormControlStatus();
53
- // Add synchronous validators to this control.
54
- this.setFormControlValidators();
55
- // Set attribute values for an element in the DOM.
56
- this.setAttributes();
57
- }
58
- catch (error) {
59
- console.error('[fg-dynamic] Error during component initialization:', error);
60
- }
61
- }
62
- /**
63
- * A method to lazy-load a component.
64
- */
65
- async loadComponentAsync() {
66
- const configurationType = this.configuration().type;
67
- if (configurationType != null) {
68
- const requestedType = typeof configurationType === 'string'
69
- ? FGDynamicService.getComponent(configurationType)
70
- : configurationType;
71
- if (requestedType == null) {
72
- return;
73
- }
74
- let resolvedType;
75
- if (typeof requestedType === 'function') {
76
- // Try to invoke as a lazy loader function: () => Promise<Type<unknown>>
77
- try {
78
- const result = requestedType();
79
- resolvedType = result instanceof Promise ? await result : result;
80
- }
81
- catch {
82
- // Not a lazy loader function, treat it as a direct Type
83
- resolvedType = requestedType;
84
- }
85
- }
86
- else if (requestedType instanceof Promise) {
87
- resolvedType = await requestedType;
88
- }
89
- else {
90
- resolvedType = requestedType;
91
- }
92
- // Only re-assign when the resolved type actually changed, so that subsequent
93
- // input/attribute updates don't tear down the already-instantiated component.
94
- if (this._component !== resolvedType) {
95
- this._component = resolvedType;
96
- }
97
- }
98
- }
99
- /**
100
- * Instantiates a single component and inserts its host view into this container.
101
- */
102
- createComponent() {
103
- // If the component type changed, clean up and recreate it.
104
- if (this._componentRef && this._component !== this._componentRef.componentType) {
105
- this.cleanup();
106
- }
107
- if (this._component && !this._componentRef && this._viewContainerRef() && !this._formControlDirective) {
108
- let injector;
109
- if (this.formGroup() && this.configuration()?.attributes && this.configuration().attributes['name'] && typeof (this.evaluateExpression(this.configuration().attributes['name'], this.viewModel)) === 'string' && this.viewModel() != null) {
110
- // Synchronizes a standalone FormControl instance to a form control element.
111
- this._formControlDirective = new FormControlDirective(null, null, null, null);
112
- // Creates a new injector instance that provides one or more dependencies, according to a given type or types of StaticProvider.
113
- injector = Injector.create({
114
- providers: [{
115
- provide: NgControl,
116
- useValue: this._formControlDirective
117
- }],
118
- parent: this._injector
119
- });
120
- }
121
- // Instantiates a single component and inserts its host view into this container.
122
- this._componentRef = this._viewContainerRef().createComponent(this._component, {
123
- projectableNodes: this._dynamicItems()?.length > 0 ? [this._dynamicItems().map((e) => e.nativeElement)] : undefined,
124
- injector: injector
125
- });
126
- // When a view uses the ChangeDetectionStrategy#OnPush (checkOnce) change detection strategy, explicitly marks the view as changed so that it can be checked again.
127
- // Components are normally marked as dirty (in need of rerendering) when inputs have changed or events have fired in the view.
128
- // Call this method to ensure that a component is checked even if these triggers have not occurred.
129
- if (this._componentRef?.changeDetectorRef) {
130
- this._componentRef.changeDetectorRef.markForCheck();
131
- }
132
- // Register handlers for those events by subscribing to an instance.
133
- this.handleOutputs();
134
- // Construct a FormControl with an initial value.
135
- this.createFormControl();
136
- }
137
- }
138
- /**
139
- * Register handlers for those events by subscribing to an instance.
140
- */
141
- handleOutputs() {
142
- if (this.configuration()?.outputs && Object.keys(this.configuration().outputs).length > 0 && this._componentRef?.instance) {
143
- for (const outputName in this.configuration().outputs) {
144
- if (this._componentRef.instance[outputName] instanceof EventEmitter) {
145
- this._outputsSubscriptions.push(this._componentRef.instance[outputName].subscribe(($event) => {
146
- // Evaluates JavaScript code and executes it.
147
- const result = this.evaluateExpression(this.configuration().outputs[outputName], this.viewModel, $event);
148
- if (result instanceof Function) {
149
- // Executes a function.
150
- result($event);
151
- }
152
- }));
153
- }
154
- }
155
- }
156
- }
157
- /**
158
- * Construct a FormControl with an initial value.
159
- */
160
- createFormControl() {
161
- if (this.formGroup() && this.configuration()?.attributes && this.configuration().attributes['name'] && this.viewModel() != null) {
162
- // Evaluates JavaScript code and executes it.
163
- const name = this.evaluateExpression(this.configuration().attributes['name'], this.viewModel);
164
- if (typeof (name) === 'string') {
165
- // Construct a FormControl with an initial value.
166
- this._formControl = new FormControl(this.getModelPropertyValue(this.viewModel(), name, null));
167
- // Add a control to this group. In a strongly-typed group, the control must be in the group's type (possibly as an optional key).
168
- // If a control with a given name already exists, it would not be replaced with a new one.
169
- // If you want to replace an existing control, use the FormGroup#setControl setControl method instead.
170
- // This method also updates the value and validity of the control.
171
- this.formGroup().addControl(name, this._formControl);
172
- // A multicasting observable that emits an event every time the value of the control changes, in the UI or programmatically.
173
- this._formControlSubscription = this._formControl.valueChanges.subscribe((value) => {
174
- // Creates a deep clone of an object, falling back to a JSON round-trip
175
- // when the view model contains non-cloneable values (functions, DOM nodes, ...).
176
- let viewModel;
177
- try {
178
- viewModel = structuredClone(this.viewModel());
179
- }
180
- catch {
181
- viewModel = JSON.parse(JSON.stringify(this.viewModel()));
182
- }
183
- // Sets the value at path of object.
184
- // If a portion of path doesn't exist, it's created.
185
- // Arrays are created for missing index properties while objects are created for all other missing properties.
186
- // This method mutates object.
187
- this.setModelPropertyValue(viewModel, name, value);
188
- // Directly set the signal to a new value, and notify any dependents.
189
- this.viewModel.set(viewModel);
190
- });
191
- // Synchronizes a standalone FormControl instance to a form control element.
192
- this.attachFormControlDirective();
193
- }
194
- }
195
- }
196
- /**
197
- * Disables/enables the control.
198
- */
199
- setFormControlStatus() {
200
- if (this._formControl && this.configuration().attributes && this.configuration().attributes['disabled'] != null) {
201
- // Evaluates JavaScript code and executes it.
202
- const isDisabled = this.evaluateExpression(this.configuration().attributes['disabled'], this.viewModel);
203
- if (typeof (isDisabled) === 'boolean' && ((isDisabled && this._formControl.enabled) || (!isDisabled && this._formControl.disabled))) {
204
- if (isDisabled) {
205
- // Disables the control.
206
- this._formControl.disable({
207
- onlySelf: true,
208
- emitEvent: false
209
- });
210
- }
211
- else {
212
- // Enables the control.
213
- this._formControl.enable({
214
- onlySelf: true,
215
- emitEvent: false
216
- });
217
- }
218
- }
219
- }
220
- }
221
- /**
222
- * Add synchronous validators to this control.
223
- */
224
- setFormControlValidators() {
225
- if (!this._formControl) {
226
- return;
227
- }
228
- // Always remove previously managed validators, even when the current
229
- // configuration has no validator-bearing attributes.
230
- if (this._managedValidatorFns.length > 0) {
231
- this._formControl.removeValidators(this._managedValidatorFns);
232
- this._managedValidatorFns = [];
233
- this._formControl.updateValueAndValidity({
234
- onlySelf: true,
235
- emitEvent: false
236
- });
237
- }
238
- if (this.configuration()?.attributes && Object.keys(this.configuration().attributes).length > 0 && this._componentRef?.location?.nativeElement) {
239
- const validators = [];
240
- // Validator that requires the control's value to be greater than or equal to the provided number.
241
- const min = this.evaluateExpression(this.configuration().attributes['min'], this.viewModel);
242
- if (typeof (min) === 'number' && min.toString() !== this._componentRef.location.nativeElement.getAttribute('min')) {
243
- validators.push(Validators.min(min));
244
- }
245
- // Validator that requires the control's value to be less than or equal to the provided number.
246
- const max = this.evaluateExpression(this.configuration().attributes['max'], this.viewModel);
247
- if (typeof (max) === 'number' && max.toString() !== this._componentRef.location.nativeElement.getAttribute('max')) {
248
- validators.push(Validators.max(max));
249
- }
250
- // Validator that requires the control have a non-empty value.
251
- const required = this.evaluateExpression(this.configuration().attributes['required'], this.viewModel);
252
- if (required === true && required.toString() !== this._componentRef.location.nativeElement.getAttribute('required')) {
253
- validators.push(Validators.required);
254
- }
255
- // Validator that requires the control's value pass an email validation test.
256
- const email = this.evaluateExpression(this.configuration().attributes['email'], this.viewModel);
257
- if (email === true && email.toString() !== this._componentRef.location.nativeElement.getAttribute('email')) {
258
- validators.push(Validators.email);
259
- }
260
- // Validator that requires the length of the control's value to be less than or equal to the provided maximum length.
261
- const maxLength = this.evaluateExpression(this.configuration().attributes['maxlength'], this.viewModel);
262
- if (maxLength >= 0 && maxLength.toString() !== this._componentRef.location.nativeElement.getAttribute('maxlength')) {
263
- validators.push(Validators.maxLength(maxLength));
264
- }
265
- // Validator that requires the length of the control's value to be greater than or equal to the provided minimum length.
266
- const minLength = this.evaluateExpression(this.configuration().attributes['minlength'], this.viewModel);
267
- if (minLength >= 0 && minLength.toString() !== this._componentRef.location.nativeElement.getAttribute('minlength')) {
268
- validators.push(Validators.minLength(minLength));
269
- }
270
- // Validator that requires the control's value to match a regex pattern.
271
- const pattern = this.evaluateExpression(this.configuration().attributes['pattern'], this.viewModel);
272
- if (typeof (pattern) === 'string' && pattern !== this._componentRef.location.nativeElement.getAttribute('pattern')) {
273
- validators.push(Validators.pattern(pattern));
274
- }
275
- // Track and add the newly built managed validators.
276
- this._managedValidatorFns = validators;
277
- this._formControl.addValidators(this._managedValidatorFns);
278
- // Recalculates the value and validation status of the control whenever the
279
- // managed validator set changes (including when it becomes empty).
280
- this._formControl.updateValueAndValidity({
281
- onlySelf: true,
282
- emitEvent: false
283
- });
284
- }
285
- }
286
- /**
287
- * Synchronizes a standalone FormControl instance to a form control element.
288
- */
289
- attachFormControlDirective() {
290
- if (this._formControlDirective && this._componentRef?.injector && this._formControl) {
291
- const valueAccessors = this._componentRef.injector.get(NG_VALUE_ACCESSOR, null);
292
- this._formControlDirective.valueAccessor = Array.isArray(valueAccessors) && valueAccessors.length > 0 ? valueAccessors[0] : null;
293
- this._formControlDirective.form = this._formControl;
294
- // A callback method that is invoked immediately after the default change detector has checked data-bound properties if at least one has changed, and before the view and content children are checked.
295
- this._formControlDirective.ngOnChanges({
296
- form: {
297
- firstChange: true,
298
- currentValue: this._formControl,
299
- previousValue: undefined,
300
- isFirstChange: () => true
301
- }
302
- });
303
- }
304
- }
305
- /**
306
- * Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.
307
- * @param model The object.
308
- * @param property The path.
309
- * @param defaultValue The resolved value.
310
- */
311
- getModelPropertyValue(model, property, defaultValue) {
312
- // If path is not defined or it has false value
313
- if (!property) {
314
- return undefined;
315
- }
316
- // Check if path is string or array. Regex : ensure that we do not have '.' and brackets.
317
- const pathArray = Array.isArray(property) ? property : property.match(/([^[.\]])+/g);
318
- // Find value
319
- const result = pathArray.reduce((prevObj, key) => prevObj && prevObj[key], model);
320
- // If found value is undefined return default value; otherwise return the value
321
- return result != null ? result : defaultValue;
322
- }
323
- /**
324
- * Sets the value at path of object. If a portion of path doesn't exist, it's created.
325
- * Arrays are created for missing index properties while objects are created for all other missing properties.
326
- * This method mutates object.
327
- * @param model The object.
328
- * @param property The path.
329
- * @param value The value.
330
- */
331
- setModelPropertyValue(model, property, value) {
332
- const pathArray = Array.isArray(property) ? property : property.match(/([^[.\]])+/g);
333
- pathArray.reduce((acc, key, i) => {
334
- if (acc[key] === undefined) {
335
- acc[key] = {};
336
- }
337
- if (i === pathArray.length - 1) {
338
- acc[key] = value;
339
- }
340
- return acc[key];
341
- }, model);
342
- }
343
- /**
344
- * Updates specified input names to new values.
345
- */
346
- setInputs() {
347
- if (this.configuration()?.inputs && Object.keys(this.configuration().inputs).length > 0 && this._componentRef) {
348
- for (const inputName in this.configuration().inputs) {
349
- // Updates a specified input name to a new value.
350
- // Using this method will properly mark for check component using the OnPush change detection strategy.
351
- // It will also assure that the OnChanges lifecycle hook runs when a dynamically created component is change-detected.
352
- this._componentRef.setInput(inputName, this.evaluateExpression(this.configuration().inputs[inputName], this.viewModel));
353
- }
354
- }
355
- }
356
- /**
357
- * Set attribute values for an element in the DOM.
358
- */
359
- setAttributes() {
360
- if (this.configuration()?.attributes && Object.keys(this.configuration().attributes).length > 0 && this._componentRef?.location?.nativeElement) {
361
- for (const attributeName in this.configuration().attributes) {
362
- // Evaluates JavaScript code and executes it.
363
- const value = this.evaluateExpression(this.configuration().attributes[attributeName], this.viewModel);
364
- // Convert non-string values to their string form; null/undefined mean "remove the attribute".
365
- const stringValue = value != null ? String(value) : null;
366
- // Returns element's first attribute whose qualified name is qualifiedName, and null if there is no such attribute otherwise.
367
- if (stringValue !== this._componentRef.location.nativeElement.getAttribute(attributeName)) {
368
- // Implement this callback to set an attribute value for an element in the DOM.
369
- if (stringValue != null) {
370
- this._renderer.setAttribute(this._componentRef.location.nativeElement, attributeName, stringValue);
371
- }
372
- else {
373
- this._renderer.removeAttribute(this._componentRef.location.nativeElement, attributeName);
374
- }
375
- }
376
- }
377
- }
378
- }
379
- /**
380
- * Evaluates JavaScript code and executes it.
381
- * @param value The JavaScript code.
382
- * @param $vm The view model.
383
- * @param $event The event.
384
- * @returns Evaluated expression.
385
- */
386
- evaluateExpression(value, $vm, $event) {
387
- if (typeof (value) === 'string' && ((value.includes('$vm') && $vm != null && $vm() != null) || (value.includes('$event') && $event != null))) {
388
- // NOTE: This uses eval() by design to support expression binding via the $vm and $event placeholders.
389
- // Only evaluate expressions from trusted configuration sources — arbitrary JavaScript can be executed here.
390
- return eval(value);
391
- }
392
- else {
393
- return value;
394
- }
395
- }
396
- /**
397
- * Cleans up every dynamically created resource: subscriptions, form control, value accessor directive and component reference.
398
- * Used both on component type change and on destroy.
399
- */
400
- cleanup() {
401
- // Disposes the resources held by the output subscriptions.
402
- this._outputsSubscriptions?.forEach((s) => s.unsubscribe());
403
- this._outputsSubscriptions = [];
404
- // Disposes the resources held by the form control subscription.
405
- this._formControlSubscription?.unsubscribe();
406
- this._formControlSubscription = undefined;
407
- // Remove the managed control from the form group.
408
- if (this._formControl && this.formGroup()) {
409
- const attributeName = this.configuration()?.attributes?.['name'];
410
- if (attributeName) {
411
- const controlName = this.evaluateExpression(attributeName, this.viewModel);
412
- // Only remove the control if it is the one this component created, so that
413
- // a pre-existing control registered under the same name is left untouched.
414
- if (typeof controlName === 'string' && this.formGroup().get(controlName) === this._formControl) {
415
- this.formGroup().removeControl(controlName);
416
- }
417
- }
418
- }
419
- this._formControl = undefined;
420
- this._managedValidatorFns = [];
421
- // A callback method that performs custom clean-up, invoked immediately before a directive, pipe, or service instance is destroyed.
422
- this._formControlDirective?.ngOnDestroy();
423
- this._formControlDirective = undefined;
424
- // Destroys the component instance and all of the data structures associated with it.
425
- this._componentRef?.destroy();
426
- this._componentRef = undefined;
427
- }
428
- /**
429
- * A callback method that performs custom clean-up, invoked immediately before a directive, pipe, or service instance is destroyed.
430
- */
431
- ngOnDestroy() {
432
- this.cleanup();
433
- }
434
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.6", ngImport: i0, type: FGDynamicComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
435
- static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.1.6", type: FGDynamicComponent, isStandalone: true, selector: "fg-dynamic", inputs: { configuration: { classPropertyName: "configuration", publicName: "configuration", isSignal: true, isRequired: true, transformFunction: null }, viewModel: { classPropertyName: "viewModel", publicName: "viewModel", isSignal: true, isRequired: false, transformFunction: null }, formGroup: { classPropertyName: "formGroup", publicName: "formGroup", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { viewModel: "viewModelChange" }, viewQueries: [{ propertyName: "_viewContainerRef", first: true, predicate: ["viewContainer"], descendants: true, read: ViewContainerRef, isSignal: true }, { propertyName: "_dynamicItems", predicate: ["dynamicItem"], descendants: true, read: ElementRef, isSignal: true }], usesOnChanges: true, ngImport: i0, template: `
64
+ function isPunctuator(token, value) {
65
+ return token.type === "punctuator" && token.value === value;
66
+ }
67
+ function isIdentifier(token, value) {
68
+ return token.type === "identifier" && token.value === value;
69
+ }
70
+ function tokenize(source) {
71
+ const tokens = [];
72
+ let index = 0;
73
+ while (index < source.length) {
74
+ const character = source[index];
75
+ if (/\s/.test(character)) {
76
+ index++;
77
+ continue;
78
+ }
79
+ if (character === "\"" || character === "'") {
80
+ const quote = character;
81
+ let value = "";
82
+ let cursor = index + 1;
83
+ let closed = false;
84
+ while (cursor < source.length) {
85
+ const current = source[cursor];
86
+ if (current === quote) {
87
+ cursor++;
88
+ closed = true;
89
+ break;
90
+ }
91
+ if (current === "\\") {
92
+ const escaped = source[cursor + 1];
93
+ if (escaped === void 0) fail("Unterminated string literal.");
94
+ switch (escaped) {
95
+ case "n":
96
+ value += "\n";
97
+ break;
98
+ case "r":
99
+ value += "\r";
100
+ break;
101
+ case "t":
102
+ value += " ";
103
+ break;
104
+ case "b":
105
+ value += "\b";
106
+ break;
107
+ case "f":
108
+ value += "\f";
109
+ break;
110
+ case "v":
111
+ value += "\v";
112
+ break;
113
+ case "0":
114
+ value += "\0";
115
+ break;
116
+ case "u": {
117
+ const hex = source.slice(cursor + 2, cursor + 6);
118
+ if (!/^[0-9a-fA-F]{4}$/.test(hex)) fail("Invalid unicode escape sequence.");
119
+ value += String.fromCharCode(parseInt(hex, 16));
120
+ cursor += 4;
121
+ break;
122
+ }
123
+ default: value += escaped;
124
+ }
125
+ cursor += 2;
126
+ continue;
127
+ }
128
+ value += current;
129
+ cursor++;
130
+ }
131
+ if (!closed) fail("Unterminated string literal.");
132
+ tokens.push({
133
+ type: "string",
134
+ value,
135
+ position: index
136
+ });
137
+ index = cursor;
138
+ continue;
139
+ }
140
+ if (/[0-9]/.test(character) || character === "." && /[0-9]/.test(source[index + 1] ?? "")) {
141
+ const match = /^(?:0[xX][0-9a-fA-F]+|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)/.exec(source.slice(index));
142
+ if (!match) fail("Invalid number literal.");
143
+ const raw = match[0];
144
+ const numeric = Number(raw);
145
+ if (!Number.isFinite(numeric)) fail("Number literal is not finite.");
146
+ tokens.push({
147
+ type: "number",
148
+ value: raw,
149
+ position: index
150
+ });
151
+ index += raw.length;
152
+ continue;
153
+ }
154
+ if (/[A-Za-z_$]/.test(character)) {
155
+ const match = /^[A-Za-z_$][A-Za-z0-9_$]*/.exec(source.slice(index));
156
+ if (!match) fail("Invalid identifier.");
157
+ tokens.push({
158
+ type: "identifier",
159
+ value: match[0],
160
+ position: index
161
+ });
162
+ index += match[0].length;
163
+ continue;
164
+ }
165
+ const punctuator = PUNCTUATORS.find((candidate) => source.startsWith(candidate, index));
166
+ if (!punctuator) fail("Unexpected character in expression.");
167
+ tokens.push({
168
+ type: "punctuator",
169
+ value: punctuator,
170
+ position: index
171
+ });
172
+ index += punctuator.length;
173
+ }
174
+ tokens.push({
175
+ type: "eof",
176
+ value: "",
177
+ position: source.length
178
+ });
179
+ if (tokens.length > MAX_TOKENS) fail("Expression is too complex.");
180
+ return tokens;
181
+ }
182
+ var ExpressionParser = class {
183
+ constructor(tokens) {
184
+ this.index = 0;
185
+ this.depth = 0;
186
+ this.tokens = tokens;
187
+ }
188
+ parse() {
189
+ const expression = this.parseExpression();
190
+ if (this.current().type !== "eof") fail("Unexpected token after expression.");
191
+ return expression;
192
+ }
193
+ current() {
194
+ return this.tokens[this.index];
195
+ }
196
+ peek(offset = 1) {
197
+ return this.tokens[this.index + offset];
198
+ }
199
+ advance() {
200
+ const token = this.tokens[this.index];
201
+ if (token.type !== "eof") this.index++;
202
+ return token;
203
+ }
204
+ matchPunctuator(value) {
205
+ if (isPunctuator(this.current(), value)) {
206
+ this.advance();
207
+ return true;
208
+ }
209
+ return false;
210
+ }
211
+ expectPunctuator(value) {
212
+ if (!this.matchPunctuator(value)) fail(`Expected "${value}".`);
213
+ }
214
+ enter() {
215
+ this.depth++;
216
+ if (this.depth > MAX_PARSE_DEPTH) fail("Expression is nested too deeply.");
217
+ }
218
+ leave() {
219
+ this.depth--;
220
+ }
221
+ parseExpression() {
222
+ this.enter();
223
+ try {
224
+ return this.parseAssignment();
225
+ } finally {
226
+ this.leave();
227
+ }
228
+ }
229
+ parseAssignment() {
230
+ if (this.isArrowStart()) return this.parseArrow();
231
+ return this.parseConditional();
232
+ }
233
+ isArrowStart() {
234
+ const token = this.current();
235
+ if (token.type === "identifier" && this.peek()?.value === "=>") return true;
236
+ if (!isPunctuator(token, "(")) return false;
237
+ let nesting = 0;
238
+ for (let cursor = this.index; cursor < this.tokens.length; cursor++) {
239
+ const candidate = this.tokens[cursor];
240
+ if (candidate.type !== "punctuator") continue;
241
+ if (candidate.value === "(") nesting++;
242
+ else if (candidate.value === ")") {
243
+ nesting--;
244
+ if (nesting === 0) return this.tokens[cursor + 1]?.value === "=>";
245
+ }
246
+ }
247
+ return false;
248
+ }
249
+ parseArrow() {
250
+ const params = [];
251
+ if (this.current().type === "identifier") params.push(this.advance().value);
252
+ else {
253
+ this.expectPunctuator("(");
254
+ if (!isPunctuator(this.current(), ")")) do {
255
+ if (isPunctuator(this.current(), ")")) break;
256
+ const parameter = this.advance();
257
+ if (parameter.type !== "identifier") fail("Arrow function parameters must be identifiers.");
258
+ if (FORBIDDEN_PROPERTIES.has(parameter.value)) fail("Forbidden arrow function parameter name.");
259
+ params.push(parameter.value);
260
+ } while (this.matchPunctuator(","));
261
+ this.expectPunctuator(")");
262
+ }
263
+ this.expectPunctuator("=>");
264
+ if (this.matchPunctuator("{")) {
265
+ while (this.matchPunctuator(";"));
266
+ if (!isIdentifier(this.current(), "return")) fail("Arrow function blocks must contain a return statement.");
267
+ this.advance();
268
+ const value = this.parseExpression();
269
+ this.matchPunctuator(";");
270
+ this.expectPunctuator("}");
271
+ return {
272
+ type: "Arrow",
273
+ params,
274
+ body: value,
275
+ block: true
276
+ };
277
+ }
278
+ return {
279
+ type: "Arrow",
280
+ params,
281
+ body: this.parseExpression(),
282
+ block: false
283
+ };
284
+ }
285
+ parseConditional() {
286
+ const test = this.parseNullish();
287
+ if (this.matchPunctuator("?")) {
288
+ const consequent = this.parseAssignment();
289
+ this.expectPunctuator(":");
290
+ return {
291
+ type: "Conditional",
292
+ test,
293
+ consequent,
294
+ alternate: this.parseAssignment()
295
+ };
296
+ }
297
+ return test;
298
+ }
299
+ parseNullish() {
300
+ let left = this.parseLogicalOr();
301
+ while (this.matchPunctuator("??")) {
302
+ const right = this.parseLogicalOr();
303
+ left = {
304
+ type: "Logical",
305
+ operator: "??",
306
+ left,
307
+ right
308
+ };
309
+ }
310
+ return left;
311
+ }
312
+ parseLogicalOr() {
313
+ let left = this.parseLogicalAnd();
314
+ while (this.matchPunctuator("||")) {
315
+ const right = this.parseLogicalAnd();
316
+ left = {
317
+ type: "Logical",
318
+ operator: "||",
319
+ left,
320
+ right
321
+ };
322
+ }
323
+ return left;
324
+ }
325
+ parseLogicalAnd() {
326
+ let left = this.parseEquality();
327
+ while (this.matchPunctuator("&&")) {
328
+ const right = this.parseEquality();
329
+ left = {
330
+ type: "Logical",
331
+ operator: "&&",
332
+ left,
333
+ right
334
+ };
335
+ }
336
+ return left;
337
+ }
338
+ parseEquality() {
339
+ let left = this.parseRelational();
340
+ while (isPunctuator(this.current(), "===") || isPunctuator(this.current(), "!==") || isPunctuator(this.current(), "==") || isPunctuator(this.current(), "!=")) {
341
+ const operator = this.advance().value;
342
+ const right = this.parseRelational();
343
+ left = {
344
+ type: "Binary",
345
+ operator,
346
+ left,
347
+ right
348
+ };
349
+ }
350
+ return left;
351
+ }
352
+ parseRelational() {
353
+ let left = this.parseAdditive();
354
+ while (isPunctuator(this.current(), "<") || isPunctuator(this.current(), ">") || isPunctuator(this.current(), "<=") || isPunctuator(this.current(), ">=")) {
355
+ const operator = this.advance().value;
356
+ const right = this.parseAdditive();
357
+ left = {
358
+ type: "Binary",
359
+ operator,
360
+ left,
361
+ right
362
+ };
363
+ }
364
+ return left;
365
+ }
366
+ parseAdditive() {
367
+ let left = this.parseMultiplicative();
368
+ while (isPunctuator(this.current(), "+") || isPunctuator(this.current(), "-")) {
369
+ const operator = this.advance().value;
370
+ const right = this.parseMultiplicative();
371
+ left = {
372
+ type: "Binary",
373
+ operator,
374
+ left,
375
+ right
376
+ };
377
+ }
378
+ return left;
379
+ }
380
+ parseMultiplicative() {
381
+ let left = this.parseExponent();
382
+ while (isPunctuator(this.current(), "*") || isPunctuator(this.current(), "/") || isPunctuator(this.current(), "%")) {
383
+ const operator = this.advance().value;
384
+ const right = this.parseExponent();
385
+ left = {
386
+ type: "Binary",
387
+ operator,
388
+ left,
389
+ right
390
+ };
391
+ }
392
+ return left;
393
+ }
394
+ parseExponent() {
395
+ const left = this.parseUnary();
396
+ if (this.matchPunctuator("**")) return {
397
+ type: "Binary",
398
+ operator: "**",
399
+ left,
400
+ right: this.parseExponent()
401
+ };
402
+ return left;
403
+ }
404
+ parseUnary() {
405
+ if (isPunctuator(this.current(), "!") || isPunctuator(this.current(), "-") || isPunctuator(this.current(), "+")) return {
406
+ type: "Unary",
407
+ operator: this.advance().value,
408
+ argument: this.parseUnary()
409
+ };
410
+ if (isIdentifier(this.current(), "typeof")) {
411
+ this.advance();
412
+ return {
413
+ type: "Unary",
414
+ operator: "typeof",
415
+ argument: this.parseUnary()
416
+ };
417
+ }
418
+ return this.parsePostfix();
419
+ }
420
+ parsePostfix() {
421
+ let node = this.parsePrimary();
422
+ for (;;) {
423
+ if (this.matchPunctuator(".")) {
424
+ const property = this.advance();
425
+ if (property.type !== "identifier") fail("Expected a property name.");
426
+ node = {
427
+ type: "Member",
428
+ object: node,
429
+ property: {
430
+ type: "Literal",
431
+ value: property.value
432
+ },
433
+ computed: false,
434
+ optional: false
435
+ };
436
+ continue;
437
+ }
438
+ if (this.matchPunctuator("?.")) {
439
+ if (this.matchPunctuator("(")) node = {
440
+ type: "Call",
441
+ callee: node,
442
+ args: this.parseArguments(),
443
+ optional: true
444
+ };
445
+ else if (this.matchPunctuator("[")) {
446
+ const property = this.parseExpression();
447
+ this.expectPunctuator("]");
448
+ node = {
449
+ type: "Member",
450
+ object: node,
451
+ property,
452
+ computed: true,
453
+ optional: true
454
+ };
455
+ } else {
456
+ const property = this.advance();
457
+ if (property.type !== "identifier") fail("Expected a property name.");
458
+ node = {
459
+ type: "Member",
460
+ object: node,
461
+ property: {
462
+ type: "Literal",
463
+ value: property.value
464
+ },
465
+ computed: false,
466
+ optional: true
467
+ };
468
+ }
469
+ continue;
470
+ }
471
+ if (this.matchPunctuator("[")) {
472
+ const property = this.parseExpression();
473
+ this.expectPunctuator("]");
474
+ node = {
475
+ type: "Member",
476
+ object: node,
477
+ property,
478
+ computed: true,
479
+ optional: false
480
+ };
481
+ continue;
482
+ }
483
+ if (this.matchPunctuator("(")) {
484
+ node = {
485
+ type: "Call",
486
+ callee: node,
487
+ args: this.parseArguments(),
488
+ optional: false
489
+ };
490
+ continue;
491
+ }
492
+ break;
493
+ }
494
+ return node;
495
+ }
496
+ parseArguments() {
497
+ const args = [];
498
+ if (!isPunctuator(this.current(), ")")) do {
499
+ if (isPunctuator(this.current(), ")")) break;
500
+ const spread = this.matchPunctuator("...");
501
+ args.push({
502
+ spread,
503
+ value: this.parseAssignment()
504
+ });
505
+ } while (this.matchPunctuator(","));
506
+ this.expectPunctuator(")");
507
+ return args;
508
+ }
509
+ parsePrimary() {
510
+ const token = this.current();
511
+ if (token.type === "number") {
512
+ this.advance();
513
+ return {
514
+ type: "Literal",
515
+ value: Number(token.value)
516
+ };
517
+ }
518
+ if (token.type === "string") {
519
+ this.advance();
520
+ return {
521
+ type: "Literal",
522
+ value: token.value
523
+ };
524
+ }
525
+ if (token.type === "identifier") {
526
+ this.advance();
527
+ switch (token.value) {
528
+ case "true": return {
529
+ type: "Literal",
530
+ value: true
531
+ };
532
+ case "false": return {
533
+ type: "Literal",
534
+ value: false
535
+ };
536
+ case "null": return {
537
+ type: "Literal",
538
+ value: null
539
+ };
540
+ case "undefined": return {
541
+ type: "Literal",
542
+ value: void 0
543
+ };
544
+ case "NaN": return {
545
+ type: "Literal",
546
+ value: NaN
547
+ };
548
+ case "Infinity": return {
549
+ type: "Literal",
550
+ value: Infinity
551
+ };
552
+ default: return {
553
+ type: "Identifier",
554
+ name: token.value
555
+ };
556
+ }
557
+ }
558
+ if (this.matchPunctuator("(")) {
559
+ const expression = this.parseExpression();
560
+ this.expectPunctuator(")");
561
+ return expression;
562
+ }
563
+ if (this.matchPunctuator("[")) return this.parseArray();
564
+ if (this.matchPunctuator("{")) return this.parseObject();
565
+ return fail("Unexpected token in expression.");
566
+ }
567
+ parseArray() {
568
+ const elements = [];
569
+ if (!isPunctuator(this.current(), "]")) do {
570
+ if (isPunctuator(this.current(), "]")) break;
571
+ const spread = this.matchPunctuator("...");
572
+ elements.push({
573
+ spread,
574
+ value: this.parseAssignment()
575
+ });
576
+ } while (this.matchPunctuator(","));
577
+ this.expectPunctuator("]");
578
+ return {
579
+ type: "Array",
580
+ elements
581
+ };
582
+ }
583
+ parseObject() {
584
+ const properties = [];
585
+ if (!isPunctuator(this.current(), "}")) do {
586
+ if (isPunctuator(this.current(), "}")) break;
587
+ if (this.matchPunctuator("...")) {
588
+ properties.push({
589
+ spread: true,
590
+ value: this.parseAssignment(),
591
+ computed: false
592
+ });
593
+ continue;
594
+ }
595
+ let key;
596
+ let computed = false;
597
+ if (this.matchPunctuator("[")) {
598
+ key = this.parseExpression();
599
+ this.expectPunctuator("]");
600
+ computed = true;
601
+ } else {
602
+ const keyToken = this.advance();
603
+ if (keyToken.type === "identifier" || keyToken.type === "string") key = {
604
+ type: "Literal",
605
+ value: keyToken.value
606
+ };
607
+ else if (keyToken.type === "number") key = {
608
+ type: "Literal",
609
+ value: String(Number(keyToken.value))
610
+ };
611
+ else return fail("Invalid object key.");
612
+ }
613
+ this.expectPunctuator(":");
614
+ const value = this.parseAssignment();
615
+ properties.push({
616
+ spread: false,
617
+ key,
618
+ value,
619
+ computed
620
+ });
621
+ } while (this.matchPunctuator(","));
622
+ this.expectPunctuator("}");
623
+ return {
624
+ type: "Object",
625
+ properties
626
+ };
627
+ }
628
+ };
629
+ function assertSafeProperty(property) {
630
+ if (FORBIDDEN_PROPERTIES.has(property)) fail("Access to a forbidden property was blocked.");
631
+ }
632
+ function defineSafeProperty(target, key, value) {
633
+ assertSafeProperty(key);
634
+ Object.defineProperty(target, key, {
635
+ value,
636
+ writable: true,
637
+ enumerable: true,
638
+ configurable: true
639
+ });
640
+ }
641
+ function readMember(target, key, optional) {
642
+ if (typeof key !== "string" && typeof key !== "number") fail("Property keys must be strings or numbers.");
643
+ const property = String(key);
644
+ assertSafeProperty(property);
645
+ if (target == null) {
646
+ if (optional) return;
647
+ fail("Cannot read properties of null or undefined.");
648
+ }
649
+ return Object(target)[property];
650
+ }
651
+ function spreadValues(value) {
652
+ if (Array.isArray(value)) return value.slice();
653
+ if (typeof value === "string") return value.split("");
654
+ return fail("Spread is only supported for arrays and strings.");
655
+ }
656
+ function isPrimitive(value) {
657
+ return value == null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint";
658
+ }
659
+ function primitiveAdd(left, right) {
660
+ if (!isPrimitive(left) || !isPrimitive(right)) fail("Arithmetic on objects is not allowed.");
661
+ return left + right;
662
+ }
663
+ function numericOperation(operator, left, right) {
664
+ if (typeof left !== "number" || typeof right !== "number") fail(`Operator "${operator}" only supports numbers.`);
665
+ switch (operator) {
666
+ case "-": return left - right;
667
+ case "*": return left * right;
668
+ case "/": return left / right;
669
+ case "%": return left % right;
670
+ case "**": return left ** right;
671
+ default: return fail(`Unsupported arithmetic operator "${operator}".`);
672
+ }
673
+ }
674
+ function looseEquals(left, right) {
675
+ if (!isPrimitive(left) || !isPrimitive(right)) fail("Loose equality is only supported for primitive values.");
676
+ return left == right;
677
+ }
678
+ function compareValues(operator, left, right) {
679
+ if (!isPrimitive(left) || !isPrimitive(right)) fail("Comparison is only supported for primitive values.");
680
+ switch (operator) {
681
+ case "<": return left < right;
682
+ case ">": return left > right;
683
+ case "<=": return left <= right;
684
+ case ">=": return left >= right;
685
+ default: return fail(`Unsupported comparison operator "${operator}".`);
686
+ }
687
+ }
688
+ function evaluateNode(node, environment, state) {
689
+ state.steps++;
690
+ state.depth++;
691
+ if (state.steps > MAX_EVALUATION_STEPS) {
692
+ state.depth--;
693
+ return fail("Expression is too complex.");
694
+ }
695
+ if (state.depth > MAX_EVALUATION_DEPTH) {
696
+ state.depth--;
697
+ return fail("Expression is nested too deeply.");
698
+ }
699
+ try {
700
+ switch (node.type) {
701
+ case "Literal": return node.value;
702
+ case "Identifier":
703
+ if (!environment.has(node.name)) return fail(`Unknown identifier "${node.name}".`);
704
+ return environment.get(node.name);
705
+ case "Member": return readMember(evaluateNode(node.object, environment, state), evaluateNode(node.property, environment, state), node.optional);
706
+ case "Call": {
707
+ let fn;
708
+ let thisArg;
709
+ if (node.callee.type === "Member") {
710
+ const object = evaluateNode(node.callee.object, environment, state);
711
+ fn = readMember(object, evaluateNode(node.callee.property, environment, state), node.callee.optional);
712
+ thisArg = object;
713
+ } else fn = evaluateNode(node.callee, environment, state);
714
+ if (fn == null && node.optional) return;
715
+ if (typeof fn !== "function") {
716
+ if (node.optional) return;
717
+ return fail("Attempted to call a non-function value.");
718
+ }
719
+ if (fn === Function || fn === eval) return fail("Calling global constructors is not allowed.");
720
+ const args = [];
721
+ for (const argument of node.args) {
722
+ const value = evaluateNode(argument.value, environment, state);
723
+ if (argument.spread) args.push(...spreadValues(value));
724
+ else args.push(value);
725
+ }
726
+ return fn.apply(thisArg, args);
727
+ }
728
+ case "Unary": {
729
+ const argument = evaluateNode(node.argument, environment, state);
730
+ switch (node.operator) {
731
+ case "!": return !argument;
732
+ case "typeof": return typeof argument;
733
+ case "-":
734
+ if (typeof argument !== "number" && typeof argument !== "bigint") return fail("Unary \"-\" only supports numbers.");
735
+ return typeof argument === "bigint" ? -argument : -argument;
736
+ case "+":
737
+ if (typeof argument !== "number") return fail("Unary \"+\" only supports numbers.");
738
+ return +argument;
739
+ default: return fail(`Unsupported unary operator "${node.operator}".`);
740
+ }
741
+ }
742
+ case "Binary": {
743
+ const left = evaluateNode(node.left, environment, state);
744
+ const right = evaluateNode(node.right, environment, state);
745
+ switch (node.operator) {
746
+ case "===": return left === right;
747
+ case "!==": return left !== right;
748
+ case "==": return looseEquals(left, right);
749
+ case "!=": return !looseEquals(left, right);
750
+ case "+": return primitiveAdd(left, right);
751
+ case "-":
752
+ case "*":
753
+ case "/":
754
+ case "%":
755
+ case "**": return numericOperation(node.operator, left, right);
756
+ case "<":
757
+ case ">":
758
+ case "<=":
759
+ case ">=": return compareValues(node.operator, left, right);
760
+ default: return fail(`Unsupported binary operator "${node.operator}".`);
761
+ }
762
+ }
763
+ case "Logical": {
764
+ const left = evaluateNode(node.left, environment, state);
765
+ switch (node.operator) {
766
+ case "&&": return left ? evaluateNode(node.right, environment, state) : left;
767
+ case "||": return left ? left : evaluateNode(node.right, environment, state);
768
+ case "??": return left == null ? evaluateNode(node.right, environment, state) : left;
769
+ default: return fail(`Unsupported logical operator "${node.operator}".`);
770
+ }
771
+ }
772
+ case "Conditional": return evaluateNode(node.test, environment, state) ? evaluateNode(node.consequent, environment, state) : evaluateNode(node.alternate, environment, state);
773
+ case "Array": {
774
+ const values = [];
775
+ for (const element of node.elements) {
776
+ const value = evaluateNode(element.value, environment, state);
777
+ if (element.spread) values.push(...spreadValues(value));
778
+ else values.push(value);
779
+ }
780
+ return values;
781
+ }
782
+ case "Object": {
783
+ const result = {};
784
+ for (const property of node.properties) {
785
+ if (property.spread) {
786
+ const source = evaluateNode(property.value, environment, state);
787
+ if (source == null || typeof source !== "object") return fail("Object spread is only supported for objects.");
788
+ for (const key of Object.keys(source)) {
789
+ const descriptor = Object.getOwnPropertyDescriptor(source, key);
790
+ if (descriptor && "value" in descriptor) defineSafeProperty(result, key, descriptor.value);
791
+ }
792
+ continue;
793
+ }
794
+ if (!property.key) return fail("Invalid object property.");
795
+ const key = property.computed ? evaluateNode(property.key, environment, state) : property.key.value;
796
+ if (typeof key !== "string" && typeof key !== "number") return fail("Object keys must be strings or numbers.");
797
+ defineSafeProperty(result, String(key), evaluateNode(property.value, environment, state));
798
+ }
799
+ return result;
800
+ }
801
+ case "Arrow": {
802
+ const params = node.params;
803
+ const body = node.body;
804
+ const closure = new Map(environment);
805
+ return function evaluateArrowFunction(...args) {
806
+ const local = new Map(closure);
807
+ params.forEach((parameter, index) => {
808
+ local.set(parameter, args[index]);
809
+ });
810
+ return evaluateNode(body, local, state);
811
+ };
812
+ }
813
+ default: return fail("Unsupported expression node.");
814
+ }
815
+ } finally {
816
+ state.depth--;
817
+ }
818
+ }
819
+ function evaluateSafeExpression(source, variables = {}) {
820
+ if (typeof source !== "string") fail("Expression must be a string.");
821
+ if (source.length === 0) fail("Expression is empty.");
822
+ if (source.length > MAX_SOURCE_LENGTH) fail("Expression is too long.");
823
+ const ast = new ExpressionParser(tokenize(source)).parse();
824
+ const environment = /* @__PURE__ */ new Map();
825
+ for (const [key, value] of Object.entries(variables)) environment.set(key, value);
826
+ return evaluateNode(ast, environment, {
827
+ steps: 0,
828
+ depth: 0
829
+ });
830
+ }
831
+ const FORBIDDEN_PATH_SEGMENTS = /* @__PURE__ */ new Set([
832
+ "__proto__",
833
+ "prototype",
834
+ "constructor"
835
+ ]);
836
+ const MAX_PATH_DEPTH = 32;
837
+ const MAX_PATH_SEGMENT_LENGTH = 128;
838
+ const MAX_CONFIGURATION_ITEMS = 1e3;
839
+ const MAX_ATTRIBUTE_NAME_LENGTH = 128;
840
+ const MAX_ATTRIBUTE_VALUE_LENGTH = 8192;
841
+ const MAX_PATTERN_LENGTH = 512;
842
+ const MAX_PATTERN_INPUT_LENGTH = 1024;
843
+ const ALLOWED_ATTRIBUTES = /* @__PURE__ */ new Set([
844
+ "class",
845
+ "id",
846
+ "name",
847
+ "role",
848
+ "title",
849
+ "tabindex",
850
+ "hidden",
851
+ "dir",
852
+ "lang",
853
+ "disabled",
854
+ "readonly",
855
+ "required",
856
+ "placeholder",
857
+ "autocomplete",
858
+ "spellcheck",
859
+ "min",
860
+ "max",
861
+ "minlength",
862
+ "maxlength",
863
+ "pattern",
864
+ "email",
865
+ "step",
866
+ "multiple",
867
+ "checked",
868
+ "selected",
869
+ "for",
870
+ "href",
871
+ "src"
872
+ ]);
873
+ const URL_ATTRIBUTES = /* @__PURE__ */ new Set(["href", "src"]);
874
+ var FGDynamicRegistry = class {
875
+ constructor() {
876
+ this._components = /* @__PURE__ */ new Map();
877
+ }
878
+ register(name, type) {
879
+ if (typeof name === "string" && name.length > 0 && type) this._components.set(name, type);
880
+ }
881
+ get(name) {
882
+ return typeof name === "string" ? this._components.get(name) : void 0;
883
+ }
884
+ has(name) {
885
+ return typeof name === "string" && this._components.has(name);
886
+ }
887
+ unregister(name) {
888
+ return this._components.delete(name);
889
+ }
890
+ clear() {
891
+ this._components.clear();
892
+ }
893
+ get names() {
894
+ return Array.from(this._components.keys());
895
+ }
896
+ };
897
+ var FGDynamicService = class FGDynamicService {
898
+ static {
899
+ this._defaultRegistry = new FGDynamicRegistry();
900
+ }
901
+ static get registry() {
902
+ return FGDynamicService._defaultRegistry;
903
+ }
904
+ static createRegistry() {
905
+ return new FGDynamicRegistry();
906
+ }
907
+ static registerComponent(name, type) {
908
+ FGDynamicService._defaultRegistry.register(name, type);
909
+ }
910
+ static getComponent(name) {
911
+ return FGDynamicService._defaultRegistry.get(name);
912
+ }
913
+ static hasComponent(name) {
914
+ return FGDynamicService._defaultRegistry.has(name);
915
+ }
916
+ static unregisterComponent(name) {
917
+ return FGDynamicService._defaultRegistry.unregister(name);
918
+ }
919
+ static clearRegistry() {
920
+ FGDynamicService._defaultRegistry.clear();
921
+ }
922
+ };
923
+ var FGDynamicComponent = class FGDynamicComponent {
924
+ constructor() {
925
+ this.configuration = input.required(...ngDevMode ? [{ debugName: "configuration" }] : /* istanbul ignore next */ []);
926
+ this.viewModel = model(...ngDevMode ? [void 0, { debugName: "viewModel" }] : /* istanbul ignore next */ []);
927
+ this.formGroup = input(...ngDevMode ? [void 0, { debugName: "formGroup" }] : /* istanbul ignore next */ []);
928
+ this.registry = input(FGDynamicService.registry, ...ngDevMode ? [{ debugName: "registry" }] : /* istanbul ignore next */ []);
929
+ this.items = computed(() => {
930
+ const configuration = this.configuration();
931
+ const items = configuration && typeof configuration === "object" && !Array.isArray(configuration) ? configuration.items : void 0;
932
+ if (!Array.isArray(items)) return [];
933
+ return items.filter((item) => item != null && typeof item === "object" && !Array.isArray(item)).slice(0, MAX_CONFIGURATION_ITEMS);
934
+ }, ...ngDevMode ? [{ debugName: "items" }] : /* istanbul ignore next */ []);
935
+ this._viewContainerRef = viewChild.required("viewContainer", {
936
+ ...ngDevMode ? { debugName: "_viewContainerRef" } : /* istanbul ignore next */ {},
937
+ read: ViewContainerRef
938
+ });
939
+ this._dynamicItems = viewChildren("dynamicItem", {
940
+ ...ngDevMode ? { debugName: "_dynamicItems" } : /* istanbul ignore next */ {},
941
+ read: ElementRef
942
+ });
943
+ this._renderer = inject(Renderer2);
944
+ this._outputsSubscriptions = [];
945
+ this._managedValidatorFns = [];
946
+ this._injector = inject(Injector);
947
+ this._ngOnChangesCounter = 0;
948
+ }
949
+ async ngOnChanges(changes) {
950
+ const counter = ++this._ngOnChangesCounter;
951
+ try {
952
+ const configuration = this.configuration();
953
+ if (configuration != null && (typeof configuration !== "object" || Array.isArray(configuration))) {
954
+ this.logError("Invalid configuration: expected an object.");
955
+ return;
956
+ }
957
+ await this.loadComponentAsync();
958
+ if (counter !== this._ngOnChangesCounter) return;
959
+ const items = this.items();
960
+ const itemsSignature = items.length > 0 ? `${items.length}:${items.map((item, index) => `${index}:${item?.type}`).join("|")}` : "";
961
+ if (this._componentRef && this._lastProjectedItemsSignature !== itemsSignature) {
962
+ this.cleanup();
963
+ this._lastProjectedItemsSignature = itemsSignature;
964
+ } else if (!this._componentRef) this._lastProjectedItemsSignature = itemsSignature;
965
+ this.createComponent();
966
+ if (counter !== this._ngOnChangesCounter) return;
967
+ this.setInputs();
968
+ this.setFormControlStatus();
969
+ this.setFormControlValidators();
970
+ this.setAttributes();
971
+ this.handleOutputsIfChanged();
972
+ if (this._componentRef?.changeDetectorRef) this._componentRef.changeDetectorRef.markForCheck();
973
+ } catch (error) {
974
+ this.logError("Error during component initialization.", error);
975
+ }
976
+ }
977
+ async loadComponentAsync() {
978
+ const configurationType = this.configuration()?.type;
979
+ if (configurationType == null) return;
980
+ let candidate;
981
+ if (typeof configurationType === "string") {
982
+ candidate = this.getRegistry().get(configurationType);
983
+ if (candidate == null) {
984
+ this.logWarning(`Component type "${configurationType}" not found in the registry.`);
985
+ return;
986
+ }
987
+ } else candidate = configurationType;
988
+ try {
989
+ const resolved = this.resolveCandidate(candidate);
990
+ const resolvedType = resolved instanceof Promise ? await resolved : resolved;
991
+ if (resolvedType && this._component !== resolvedType) this._component = resolvedType;
992
+ } catch (error) {
993
+ this.logError("Unable to resolve the dynamic component type.", error);
994
+ }
995
+ }
996
+ resolveCandidate(candidate) {
997
+ if (candidate == null) return;
998
+ if (candidate instanceof Promise) return candidate.then((resolved) => this.toComponentType(resolved));
999
+ if (typeof candidate === "function") {
1000
+ if (this.isAngularComponentType(candidate)) return candidate;
1001
+ if (candidate.length > 0) return candidate;
1002
+ const result = candidate();
1003
+ if (result instanceof Promise) return result.then((resolved) => this.toComponentType(resolved));
1004
+ return this.toComponentType(result);
1005
+ }
1006
+ this.logWarning("Invalid component type in configuration.");
1007
+ }
1008
+ toComponentType(resolved) {
1009
+ if (typeof resolved === "function") return resolved;
1010
+ this.logWarning("Component loader did not resolve to a component type.");
1011
+ }
1012
+ isAngularComponentType(candidate) {
1013
+ const metadata = candidate;
1014
+ return Boolean(metadata["ɵcmp"] || metadata["ɵdir"] || metadata["ɵpipe"] || metadata["ɵfac"] || metadata["ngComponentDef"] || metadata["ngDirectiveDef"]);
1015
+ }
1016
+ getRegistry() {
1017
+ return this.registry() ?? FGDynamicService.registry;
1018
+ }
1019
+ createComponent() {
1020
+ if (this._componentRef && this._component !== this._componentRef.componentType) this.cleanup();
1021
+ if (this._component && !this._componentRef && this._viewContainerRef()) {
1022
+ let injector = void 0;
1023
+ const attributes = this.configuration()?.attributes;
1024
+ const nameAttr = attributes && Object.hasOwn(attributes, "name") ? attributes["name"] : void 0;
1025
+ if (this.formGroup() && nameAttr != null && this.viewModel() != null) {
1026
+ const evaluatedName = this.evaluateExpression(nameAttr, this.viewModel);
1027
+ if (typeof evaluatedName === "string" && this.isSafePath(evaluatedName)) {
1028
+ this._formControlDirective = new FormControlDirective(null, null, null, null);
1029
+ injector = Injector.create({
1030
+ providers: [{
1031
+ provide: NgControl,
1032
+ useValue: this._formControlDirective
1033
+ }],
1034
+ parent: this._injector
1035
+ });
1036
+ } else if (typeof evaluatedName === "string") this.logWarning("Unsafe form control name was ignored.");
1037
+ }
1038
+ const dynamicItems = this._dynamicItems();
1039
+ this._componentRef = this._viewContainerRef().createComponent(this._component, {
1040
+ projectableNodes: dynamicItems && dynamicItems.length > 0 ? [dynamicItems.map((e) => e.nativeElement)] : void 0,
1041
+ injector
1042
+ });
1043
+ if (this._componentRef?.changeDetectorRef) this._componentRef.changeDetectorRef.markForCheck();
1044
+ this.handleOutputs();
1045
+ this.createFormControl();
1046
+ }
1047
+ }
1048
+ handleOutputs() {
1049
+ if (this._outputsSubscriptions && this._outputsSubscriptions.length > 0) {
1050
+ this._outputsSubscriptions.forEach((s) => {
1051
+ try {
1052
+ s.unsubscribe();
1053
+ } catch (e) {}
1054
+ });
1055
+ this._outputsSubscriptions = [];
1056
+ }
1057
+ const outputs = this.configuration()?.outputs;
1058
+ this._currentOutputsConfig = outputs ? { ...outputs } : void 0;
1059
+ if (outputs && typeof outputs === "object" && this._componentRef?.instance) {
1060
+ const instance = this._componentRef.instance;
1061
+ for (const outputName of Object.keys(outputs)) {
1062
+ const emitter = instance[outputName];
1063
+ if (!(emitter instanceof EventEmitter)) continue;
1064
+ this._outputsSubscriptions.push(emitter.subscribe(($event) => {
1065
+ try {
1066
+ const expr = outputs[outputName];
1067
+ const viewModelValue = this.getViewModelValue();
1068
+ const result = typeof expr === "string" ? this.evaluateExpression(expr, this.viewModel, $event) : expr;
1069
+ if (typeof result === "function") result.call(viewModelValue, $event);
1070
+ else if (typeof expr === "function") expr.call(viewModelValue, $event);
1071
+ } catch (error) {
1072
+ this.logError("Error handling output.", error);
1073
+ }
1074
+ }));
1075
+ }
1076
+ }
1077
+ }
1078
+ handleOutputsIfChanged() {
1079
+ const outputs = this.configuration()?.outputs;
1080
+ const current = this._currentOutputsConfig;
1081
+ if (!outputs && !current) return;
1082
+ if (!outputs || !current) {
1083
+ this.handleOutputs();
1084
+ return;
1085
+ }
1086
+ const currentKeys = Object.keys(current).sort();
1087
+ const newKeys = Object.keys(outputs).sort();
1088
+ if (currentKeys.length !== newKeys.length) {
1089
+ this.handleOutputs();
1090
+ return;
1091
+ }
1092
+ for (let i = 0; i < currentKeys.length; i++) if (currentKeys[i] !== newKeys[i] || current[currentKeys[i]] !== outputs[newKeys[i]]) {
1093
+ this.handleOutputs();
1094
+ return;
1095
+ }
1096
+ }
1097
+ createFormControl() {
1098
+ const attributes = this.configuration()?.attributes;
1099
+ const nameAttr = attributes && Object.hasOwn(attributes, "name") ? attributes["name"] : void 0;
1100
+ if (this.formGroup() && nameAttr != null && this.viewModel() != null) {
1101
+ const name = this.evaluateExpression(nameAttr, this.viewModel);
1102
+ if (typeof name === "string" && name.length > 0 && this.isSafePath(name)) {
1103
+ const formGroup = this.formGroup();
1104
+ const existingControl = formGroup.get(name);
1105
+ if (existingControl && existingControl !== this._formControl) {
1106
+ this.logWarning("A form control with the requested name already exists; reusing it.");
1107
+ this._formControl = existingControl;
1108
+ if (this._formControlDirective) this.attachFormControlDirective();
1109
+ return;
1110
+ }
1111
+ this._formControl = new FormControl(this.getModelPropertyValue(this.viewModel(), name, null));
1112
+ try {
1113
+ if (existingControl === this._formControl) {} else if (existingControl) formGroup.setControl(name, this._formControl);
1114
+ else formGroup.addControl(name, this._formControl);
1115
+ } catch (error) {
1116
+ this.logError("Error adding form control.", error);
1117
+ }
1118
+ if (this._formControlSubscription) this._formControlSubscription.unsubscribe();
1119
+ this._formControlSubscription = this._formControl.valueChanges.subscribe((value) => {
1120
+ let viewModel;
1121
+ try {
1122
+ viewModel = structuredClone(this.viewModel());
1123
+ } catch {
1124
+ try {
1125
+ viewModel = JSON.parse(JSON.stringify(this.viewModel()));
1126
+ } catch {
1127
+ viewModel = this.viewModel();
1128
+ }
1129
+ }
1130
+ this.setModelPropertyValue(viewModel, name, value);
1131
+ try {
1132
+ this.viewModel.set(viewModel);
1133
+ } catch (error) {
1134
+ this.logError("Error updating view model.", error);
1135
+ }
1136
+ });
1137
+ this.attachFormControlDirective();
1138
+ } else if (typeof name === "string") this.logWarning("Unsafe form control name was ignored.");
1139
+ }
1140
+ }
1141
+ setFormControlStatus() {
1142
+ if (!this._formControl) return;
1143
+ const attributes = this.configuration()?.attributes;
1144
+ if (!attributes) return;
1145
+ if (Object.hasOwn(attributes, "disabled")) {
1146
+ const disabledAttr = attributes["disabled"];
1147
+ if (disabledAttr == null || disabledAttr === false || disabledAttr === "") {
1148
+ if (this._formControl.disabled) try {
1149
+ this._formControl.enable({
1150
+ onlySelf: true,
1151
+ emitEvent: false
1152
+ });
1153
+ } catch (e) {}
1154
+ try {
1155
+ this._formControl.updateValueAndValidity({
1156
+ onlySelf: true,
1157
+ emitEvent: false
1158
+ });
1159
+ } catch (e) {}
1160
+ return;
1161
+ }
1162
+ const isDisabled = this.evaluateExpression(disabledAttr, this.viewModel);
1163
+ if (isDisabled === true || typeof isDisabled === "string" && isDisabled === "true") {
1164
+ if (this._formControl.enabled || !this._formControl.disabled) try {
1165
+ this._formControl.disable({
1166
+ onlySelf: true,
1167
+ emitEvent: false
1168
+ });
1169
+ } catch (e) {}
1170
+ } else if (isDisabled === false || isDisabled === "" || isDisabled === null || isDisabled === void 0 || typeof isDisabled === "string" && isDisabled === "false") {
1171
+ if (this._formControl.disabled) try {
1172
+ this._formControl.enable({
1173
+ onlySelf: true,
1174
+ emitEvent: false
1175
+ });
1176
+ } catch (e) {}
1177
+ } else if (typeof isDisabled === "boolean") {
1178
+ if (isDisabled && this._formControl.enabled) try {
1179
+ this._formControl.disable({
1180
+ onlySelf: true,
1181
+ emitEvent: false
1182
+ });
1183
+ } catch (e) {}
1184
+ else if (!isDisabled && this._formControl.disabled) try {
1185
+ this._formControl.enable({
1186
+ onlySelf: true,
1187
+ emitEvent: false
1188
+ });
1189
+ } catch (e) {}
1190
+ }
1191
+ }
1192
+ }
1193
+ setFormControlValidators() {
1194
+ if (!this._formControl) return;
1195
+ if (this._managedValidatorFns.length > 0) {
1196
+ try {
1197
+ this._formControl.removeValidators(this._managedValidatorFns);
1198
+ } catch (e) {}
1199
+ this._managedValidatorFns = [];
1200
+ try {
1201
+ this._formControl.updateValueAndValidity({
1202
+ onlySelf: true,
1203
+ emitEvent: false
1204
+ });
1205
+ } catch (e) {}
1206
+ }
1207
+ const attributes = this.configuration()?.attributes;
1208
+ if (attributes && Object.keys(attributes).length > 0 && this._componentRef?.location?.nativeElement) {
1209
+ const validators = [];
1210
+ if (Object.hasOwn(attributes, "min")) {
1211
+ const min = this.evaluateExpression(attributes["min"], this.viewModel);
1212
+ if (typeof min === "number" && !isNaN(min)) validators.push(Validators.min(min));
1213
+ }
1214
+ if (Object.hasOwn(attributes, "max")) {
1215
+ const max = this.evaluateExpression(attributes["max"], this.viewModel);
1216
+ if (typeof max === "number" && !isNaN(max)) validators.push(Validators.max(max));
1217
+ }
1218
+ if (Object.hasOwn(attributes, "required")) {
1219
+ if (this.evaluateExpression(attributes["required"], this.viewModel) === true) validators.push(Validators.required);
1220
+ }
1221
+ if (Object.hasOwn(attributes, "email")) {
1222
+ if (this.evaluateExpression(attributes["email"], this.viewModel) === true) validators.push(Validators.email);
1223
+ }
1224
+ if (Object.hasOwn(attributes, "maxlength")) {
1225
+ const maxLength = this.evaluateExpression(attributes["maxlength"], this.viewModel);
1226
+ if (typeof maxLength === "number" && !isNaN(maxLength) && maxLength >= 0) validators.push(Validators.maxLength(maxLength));
1227
+ }
1228
+ if (Object.hasOwn(attributes, "minlength")) {
1229
+ const minLength = this.evaluateExpression(attributes["minlength"], this.viewModel);
1230
+ if (typeof minLength === "number" && !isNaN(minLength) && minLength >= 0) validators.push(Validators.minLength(minLength));
1231
+ }
1232
+ if (Object.hasOwn(attributes, "pattern")) {
1233
+ const pattern = this.evaluateExpression(attributes["pattern"], this.viewModel);
1234
+ const patternValidator = this.createPatternValidator(pattern);
1235
+ if (patternValidator) validators.push(patternValidator);
1236
+ }
1237
+ if (validators.length > 0) {
1238
+ this._managedValidatorFns = validators;
1239
+ try {
1240
+ this._formControl.addValidators(this._managedValidatorFns);
1241
+ } catch (e) {}
1242
+ } else this._managedValidatorFns = [];
1243
+ try {
1244
+ this._formControl.updateValueAndValidity({
1245
+ onlySelf: true,
1246
+ emitEvent: false
1247
+ });
1248
+ } catch (e) {}
1249
+ } else this._managedValidatorFns = [];
1250
+ }
1251
+ createPatternValidator(pattern) {
1252
+ let regex;
1253
+ if (typeof pattern === "string") {
1254
+ if (pattern.length === 0 || pattern.length > MAX_PATTERN_LENGTH) {
1255
+ this.logWarning("Pattern validator was ignored because its source is empty or too long.");
1256
+ return null;
1257
+ }
1258
+ if (this.isUnsafeRegex(pattern)) {
1259
+ this.logWarning("Pattern validator was ignored because the expression is potentially unsafe.");
1260
+ return null;
1261
+ }
1262
+ try {
1263
+ const anchored = (pattern.startsWith("^") ? "" : "^") + pattern + (pattern.endsWith("$") ? "" : "$");
1264
+ regex = new RegExp(anchored);
1265
+ } catch (error) {
1266
+ this.logError("Pattern validator was ignored because the expression is invalid.", error);
1267
+ return null;
1268
+ }
1269
+ } else if (pattern instanceof RegExp) {
1270
+ if (pattern.source.length > MAX_PATTERN_LENGTH || this.isUnsafeRegex(pattern.source)) {
1271
+ this.logWarning("Pattern validator was ignored because the expression is potentially unsafe.");
1272
+ return null;
1273
+ }
1274
+ regex = pattern;
1275
+ } else return null;
1276
+ const baseValidator = Validators.pattern(regex);
1277
+ return (control) => {
1278
+ const value = control.value;
1279
+ if (value == null) return baseValidator(control);
1280
+ if (typeof value !== "string" && typeof value !== "number") return { pattern: { requiredPattern: regex.toString() } };
1281
+ if (typeof value === "string" && value.length > MAX_PATTERN_INPUT_LENGTH) return { pattern: { requiredPattern: regex.toString() } };
1282
+ return baseValidator(control);
1283
+ };
1284
+ }
1285
+ isUnsafeRegex(source) {
1286
+ if (source.length > MAX_PATTERN_LENGTH) return true;
1287
+ if (/\((?:[^()\\]|\\.)*[+*](?:[^()\\]|\\.)*\)(?:[+*]|\{\d)/.test(source)) return true;
1288
+ if (/\\[1-9][+*{]/.test(source)) return true;
1289
+ if (/\((?:\.\*|\.\+)[^)]*\)[+*{]/.test(source)) return true;
1290
+ return false;
1291
+ }
1292
+ attachFormControlDirective() {
1293
+ if (this._formControlDirective && this._componentRef?.injector && this._formControl) try {
1294
+ const valueAccessors = this._componentRef.injector.get(NG_VALUE_ACCESSOR, null);
1295
+ this._formControlDirective.valueAccessor = Array.isArray(valueAccessors) && valueAccessors.length > 0 ? valueAccessors[0] : null;
1296
+ this._formControlDirective.form = this._formControl;
1297
+ this._formControlDirective.ngOnChanges({ form: {
1298
+ firstChange: true,
1299
+ currentValue: this._formControl,
1300
+ previousValue: void 0,
1301
+ isFirstChange: () => true
1302
+ } });
1303
+ } catch (error) {
1304
+ this.logError("Error attaching form control directive.", error);
1305
+ }
1306
+ }
1307
+ parsePath(property) {
1308
+ if (property == null) return null;
1309
+ let pathArray = null;
1310
+ if (Array.isArray(property)) pathArray = property.filter((segment) => segment != null && segment !== "").map((segment) => String(segment));
1311
+ else if (typeof property === "string") pathArray = property.match(/([^[.\]])+/g);
1312
+ if (!pathArray || pathArray.length === 0 || pathArray.length > MAX_PATH_DEPTH) return null;
1313
+ for (const segment of pathArray) {
1314
+ if (segment.length > MAX_PATH_SEGMENT_LENGTH) return null;
1315
+ if (FORBIDDEN_PATH_SEGMENTS.has(segment.toLowerCase())) return null;
1316
+ }
1317
+ return pathArray;
1318
+ }
1319
+ isSafePath(property) {
1320
+ return this.parsePath(property) !== null;
1321
+ }
1322
+ defineOwn(target, key, value) {
1323
+ Object.defineProperty(target, key, {
1324
+ value,
1325
+ writable: true,
1326
+ enumerable: true,
1327
+ configurable: true
1328
+ });
1329
+ }
1330
+ getModelPropertyValue(model, property, defaultValue) {
1331
+ if (model == null) return defaultValue;
1332
+ const pathArray = this.parsePath(property);
1333
+ if (!pathArray) return defaultValue;
1334
+ try {
1335
+ let current = model;
1336
+ for (const key of pathArray) {
1337
+ if (current == null) return defaultValue;
1338
+ const container = Object(current);
1339
+ if (!Object.hasOwn(container, key)) return defaultValue;
1340
+ current = container[key];
1341
+ }
1342
+ return current != null ? current : defaultValue;
1343
+ } catch {
1344
+ return defaultValue;
1345
+ }
1346
+ }
1347
+ setModelPropertyValue(model, property, value) {
1348
+ if (model == null) return;
1349
+ const pathArray = this.parsePath(property);
1350
+ if (!pathArray) return;
1351
+ try {
1352
+ let current = model;
1353
+ for (let index = 0; index < pathArray.length; index++) {
1354
+ const key = pathArray[index];
1355
+ const isLast = index === pathArray.length - 1;
1356
+ if (current == null || typeof current !== "object" && typeof current !== "function") return;
1357
+ if (isLast) {
1358
+ this.defineOwn(current, key, value);
1359
+ return;
1360
+ }
1361
+ const isNumericKey = /^\d+$/.test(key);
1362
+ const existing = Object.hasOwn(current, key) ? current[key] : void 0;
1363
+ if (existing == null) {
1364
+ const next = isNumericKey ? [] : {};
1365
+ this.defineOwn(current, key, next);
1366
+ current = next;
1367
+ } else if (isNumericKey && !Array.isArray(existing)) {
1368
+ if (typeof existing !== "object") return;
1369
+ const next = [];
1370
+ this.defineOwn(current, key, next);
1371
+ current = next;
1372
+ } else if (!isNumericKey && typeof existing !== "object") {
1373
+ const next = {};
1374
+ this.defineOwn(current, key, next);
1375
+ current = next;
1376
+ } else current = existing;
1377
+ }
1378
+ } catch (error) {
1379
+ this.logError("Error setting model property value.", error);
1380
+ }
1381
+ }
1382
+ setInputs() {
1383
+ const inputs = this.configuration()?.inputs;
1384
+ if (!inputs || typeof inputs !== "object" || !this._componentRef) return;
1385
+ for (const inputName of Object.keys(inputs)) try {
1386
+ this._componentRef.setInput(inputName, this.evaluateExpression(inputs[inputName], this.viewModel));
1387
+ } catch (error) {
1388
+ this.logError(`Error setting dynamic input "${inputName}".`, error);
1389
+ }
1390
+ }
1391
+ setAttributes() {
1392
+ const attributes = this.configuration()?.attributes;
1393
+ const element = this._componentRef?.location?.nativeElement;
1394
+ if (!attributes || typeof attributes !== "object" || !element) return;
1395
+ for (const attributeName of Object.keys(attributes)) {
1396
+ if (!this.isAllowedAttribute(attributeName)) {
1397
+ this.logWarning(`Attribute "${attributeName}" is not allowed and was skipped.`);
1398
+ continue;
1399
+ }
1400
+ try {
1401
+ const value = this.evaluateExpression(attributes[attributeName], this.viewModel);
1402
+ const stringValue = this.attributeValueToString(value);
1403
+ if (stringValue === void 0) continue;
1404
+ if (stringValue === element.getAttribute(attributeName)) continue;
1405
+ if (stringValue === null) {
1406
+ this._renderer.removeAttribute(element, attributeName);
1407
+ continue;
1408
+ }
1409
+ if (URL_ATTRIBUTES.has(attributeName.toLowerCase()) && !this.isSafeUrl(stringValue)) {
1410
+ this.logWarning(`Unsafe URL for attribute "${attributeName}" was ignored.`);
1411
+ continue;
1412
+ }
1413
+ this._renderer.setAttribute(element, attributeName, stringValue);
1414
+ } catch (error) {
1415
+ this.logError(`Error setting dynamic attribute "${attributeName}".`, error);
1416
+ }
1417
+ }
1418
+ }
1419
+ isAllowedAttribute(name) {
1420
+ if (typeof name !== "string" || name.length === 0 || name.length > MAX_ATTRIBUTE_NAME_LENGTH) return false;
1421
+ const lower = name.toLowerCase();
1422
+ if (lower.startsWith("on")) return false;
1423
+ if (!/^[a-z][a-z0-9_.-]*$/i.test(name)) return false;
1424
+ if (lower.startsWith("data-") || lower.startsWith("aria-")) return true;
1425
+ return ALLOWED_ATTRIBUTES.has(lower);
1426
+ }
1427
+ attributeValueToString(value) {
1428
+ if (value == null) return null;
1429
+ const type = typeof value;
1430
+ if (type !== "string" && type !== "number" && type !== "boolean" && type !== "bigint") {
1431
+ this.logWarning("Non-primitive attribute values are ignored.");
1432
+ return;
1433
+ }
1434
+ const stringValue = String(value);
1435
+ if (stringValue.length > MAX_ATTRIBUTE_VALUE_LENGTH) {
1436
+ this.logWarning("Attribute value is too long and was ignored.");
1437
+ return;
1438
+ }
1439
+ return stringValue;
1440
+ }
1441
+ isSafeUrl(value) {
1442
+ const normalized = value.replace(/[\u0000-\u0020\u007f]/g, "").toLowerCase();
1443
+ if (normalized.length === 0) return true;
1444
+ const scheme = /^([a-z][a-z0-9+.-]*):/.exec(normalized);
1445
+ if (!scheme) return true;
1446
+ return scheme[1] === "http" || scheme[1] === "https" || scheme[1] === "mailto" || scheme[1] === "tel";
1447
+ }
1448
+ evaluateExpression(value, vmParam, eventParam) {
1449
+ if (typeof value !== "string") return value;
1450
+ const hasVm = value.includes("$vm");
1451
+ const hasEvent = value.includes("$event");
1452
+ if (!hasVm && !hasEvent) return value;
1453
+ if (hasVm && vmParam == null || hasEvent && eventParam == null) return value;
1454
+ try {
1455
+ const viewModelInput = vmParam;
1456
+ return evaluateSafeExpression(value, {
1457
+ $vm: typeof viewModelInput === "function" ? viewModelInput : () => viewModelInput,
1458
+ $event: eventParam,
1459
+ $ev: eventParam
1460
+ });
1461
+ } catch {
1462
+ this.logWarning("Expression could not be evaluated safely and was ignored.");
1463
+ return;
1464
+ }
1465
+ }
1466
+ getViewModelValue() {
1467
+ const model = this.viewModel;
1468
+ return typeof model === "function" ? model() : model;
1469
+ }
1470
+ logWarning(message) {
1471
+ if (isDevMode()) console.warn(`[fg-dynamic] ${message}`);
1472
+ }
1473
+ logError(message, error) {
1474
+ if (!isDevMode()) return;
1475
+ const detail = error instanceof Error ? ` (${error.name})` : "";
1476
+ console.error(`[fg-dynamic] ${message}${detail}`);
1477
+ }
1478
+ cleanup() {
1479
+ if (this._outputsSubscriptions) this._outputsSubscriptions.forEach((s) => {
1480
+ try {
1481
+ s.unsubscribe();
1482
+ } catch (e) {}
1483
+ });
1484
+ this._outputsSubscriptions = [];
1485
+ this._currentOutputsConfig = void 0;
1486
+ if (this._formControlSubscription) try {
1487
+ this._formControlSubscription.unsubscribe();
1488
+ } catch (e) {}
1489
+ this._formControlSubscription = void 0;
1490
+ if (this._formControl && this.formGroup()) try {
1491
+ const attributeName = (this.configuration()?.attributes)?.["name"];
1492
+ if (attributeName) {
1493
+ const controlName = this.evaluateExpression(attributeName, this.viewModel);
1494
+ if (typeof controlName === "string" && controlName.length > 0 && this.isSafePath(controlName)) {
1495
+ const formGroup = this.formGroup();
1496
+ if (formGroup.get(controlName) === this._formControl) try {
1497
+ formGroup.removeControl(controlName);
1498
+ } catch (e) {}
1499
+ }
1500
+ }
1501
+ } catch (e) {}
1502
+ this._formControl = void 0;
1503
+ this._managedValidatorFns = [];
1504
+ if (this._formControlDirective) try {
1505
+ this._formControlDirective.ngOnDestroy();
1506
+ } catch (e) {}
1507
+ this._formControlDirective = void 0;
1508
+ if (this._componentRef) try {
1509
+ this._componentRef.destroy();
1510
+ } catch (e) {}
1511
+ this._componentRef = void 0;
1512
+ }
1513
+ ngOnDestroy() {
1514
+ this.cleanup();
1515
+ }
1516
+ static {
1517
+ this.ɵfac = i0.ɵɵngDeclareFactory({
1518
+ minVersion: "12.0.0",
1519
+ version: "22.2.3",
1520
+ ngImport: i0,
1521
+ type: FGDynamicComponent,
1522
+ deps: [],
1523
+ target: i0.ɵɵFactoryTarget.Component
1524
+ });
1525
+ }
1526
+ static {
1527
+ this.ɵcmp = i0.ɵɵngDeclareComponent({
1528
+ minVersion: "17.0.0",
1529
+ version: "22.2.3",
1530
+ type: FGDynamicComponent,
1531
+ isStandalone: true,
1532
+ selector: "fg-dynamic",
1533
+ inputs: {
1534
+ configuration: {
1535
+ classPropertyName: "configuration",
1536
+ publicName: "configuration",
1537
+ isSignal: true,
1538
+ isRequired: true,
1539
+ transformFunction: null
1540
+ },
1541
+ viewModel: {
1542
+ classPropertyName: "viewModel",
1543
+ publicName: "viewModel",
1544
+ isSignal: true,
1545
+ isRequired: false,
1546
+ transformFunction: null
1547
+ },
1548
+ formGroup: {
1549
+ classPropertyName: "formGroup",
1550
+ publicName: "formGroup",
1551
+ isSignal: true,
1552
+ isRequired: false,
1553
+ transformFunction: null
1554
+ },
1555
+ registry: {
1556
+ classPropertyName: "registry",
1557
+ publicName: "registry",
1558
+ isSignal: true,
1559
+ isRequired: false,
1560
+ transformFunction: null
1561
+ }
1562
+ },
1563
+ outputs: { viewModel: "viewModelChange" },
1564
+ viewQueries: [{
1565
+ propertyName: "_viewContainerRef",
1566
+ first: true,
1567
+ predicate: ["viewContainer"],
1568
+ descendants: true,
1569
+ read: ViewContainerRef,
1570
+ isSignal: true
1571
+ }, {
1572
+ propertyName: "_dynamicItems",
1573
+ predicate: ["dynamicItem"],
1574
+ descendants: true,
1575
+ read: ElementRef,
1576
+ isSignal: true
1577
+ }],
1578
+ usesOnChanges: true,
1579
+ ngImport: i0,
1580
+ template: `
436
1581
  <ng-container #viewContainer></ng-container>
437
- @for (item of configuration()?.items; track $index) {
438
- <fg-dynamic #dynamicItem [configuration]="item" [(viewModel)]="viewModel" [formGroup]="formGroup()" />
1582
+ @for (item of items(); track $index) {
1583
+ <fg-dynamic #dynamicItem [configuration]="item" [(viewModel)]="viewModel" [formGroup]="formGroup()" [registry]="registry()" />
439
1584
  }
440
- `, isInline: true, styles: [":host{display:contents}\n"], dependencies: [{ kind: "component", type: FGDynamicComponent, selector: "fg-dynamic", inputs: ["configuration", "viewModel", "formGroup"], outputs: ["viewModelChange"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush }); }
441
- }
442
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.6", ngImport: i0, type: FGDynamicComponent, decorators: [{
443
- type: Component,
444
- args: [{ selector: 'fg-dynamic', template: `
1585
+ `,
1586
+ isInline: true,
1587
+ styles: [":host{display:contents}\n"],
1588
+ dependencies: [{
1589
+ kind: "component",
1590
+ type: FGDynamicComponent,
1591
+ selector: "fg-dynamic",
1592
+ inputs: [
1593
+ "configuration",
1594
+ "viewModel",
1595
+ "formGroup",
1596
+ "registry"
1597
+ ],
1598
+ outputs: ["viewModelChange"]
1599
+ }],
1600
+ changeDetection: i0.ChangeDetectionStrategy.OnPush
1601
+ });
1602
+ }
1603
+ };
1604
+ i0.ɵɵngDeclareClassMetadata({
1605
+ minVersion: "12.0.0",
1606
+ version: "22.2.3",
1607
+ ngImport: i0,
1608
+ type: FGDynamicComponent,
1609
+ decorators: [{
1610
+ type: Component,
1611
+ args: [{
1612
+ selector: "fg-dynamic",
1613
+ template: `
445
1614
  <ng-container #viewContainer></ng-container>
446
- @for (item of configuration()?.items; track $index) {
447
- <fg-dynamic #dynamicItem [configuration]="item" [(viewModel)]="viewModel" [formGroup]="formGroup()" />
1615
+ @for (item of items(); track $index) {
1616
+ <fg-dynamic #dynamicItem [configuration]="item" [(viewModel)]="viewModel" [formGroup]="formGroup()" [registry]="registry()" />
448
1617
  }
449
- `, changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, styles: [":host{display:contents}\n"] }]
450
- }], propDecorators: { configuration: [{ type: i0.Input, args: [{ isSignal: true, alias: "configuration", required: true }] }], viewModel: [{ type: i0.Input, args: [{ isSignal: true, alias: "viewModel", required: false }] }, { type: i0.Output, args: ["viewModelChange"] }], formGroup: [{ type: i0.Input, args: [{ isSignal: true, alias: "formGroup", required: false }] }], _viewContainerRef: [{ type: i0.ViewChild, args: ['viewContainer', { ...{
451
- read: ViewContainerRef
452
- }, isSignal: true }] }], _dynamicItems: [{ type: i0.ViewChildren, args: ['dynamicItem', { ...{
453
- read: ElementRef
454
- }, isSignal: true }] }] } });
455
-
456
- /*
457
- * Public API Surface of fg-dynamic-component
458
- */
459
-
460
- /**
461
- * Generated bundle index. Do not edit.
462
- */
1618
+ `,
1619
+ changeDetection: ChangeDetectionStrategy.OnPush,
1620
+ standalone: true,
1621
+ styles: [":host{display:contents}\n"]
1622
+ }]
1623
+ }],
1624
+ propDecorators: {
1625
+ configuration: [{
1626
+ type: i0.Input,
1627
+ args: [{
1628
+ isSignal: true,
1629
+ alias: "configuration",
1630
+ required: true
1631
+ }]
1632
+ }],
1633
+ viewModel: [{
1634
+ type: i0.Input,
1635
+ args: [{
1636
+ isSignal: true,
1637
+ alias: "viewModel",
1638
+ required: false
1639
+ }]
1640
+ }, {
1641
+ type: i0.Output,
1642
+ args: ["viewModelChange"]
1643
+ }],
1644
+ formGroup: [{
1645
+ type: i0.Input,
1646
+ args: [{
1647
+ isSignal: true,
1648
+ alias: "formGroup",
1649
+ required: false
1650
+ }]
1651
+ }],
1652
+ registry: [{
1653
+ type: i0.Input,
1654
+ args: [{
1655
+ isSignal: true,
1656
+ alias: "registry",
1657
+ required: false
1658
+ }]
1659
+ }],
1660
+ _viewContainerRef: [{
1661
+ type: i0.ViewChild,
1662
+ args: ["viewContainer", {
1663
+ read: ViewContainerRef,
1664
+ isSignal: true
1665
+ }]
1666
+ }],
1667
+ _dynamicItems: [{
1668
+ type: i0.ViewChildren,
1669
+ args: ["dynamicItem", {
1670
+ read: ElementRef,
1671
+ isSignal: true
1672
+ }]
1673
+ }]
1674
+ }
1675
+ });
1676
+ export { FGDynamicComponent, FGDynamicRegistry, FGDynamicService };
463
1677
 
464
- export { FGDynamicComponent, FGDynamicService };
465
- //# sourceMappingURL=fg-dynamic-component.mjs.map
1678
+ //# sourceMappingURL=fg-dynamic-component.mjs.map