@punica/form 2.0.0 → 2.1.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.
@@ -34,8 +34,8 @@ export declare class FormController<E extends object, F extends FormItem<E> = Fo
34
34
  */
35
35
  static fromEntity<E extends object, F extends FormItem<E> = FormItem<E>>(entity: E, options?: FormControllerOptions): Promise<FormController<E, F>>;
36
36
  /**
37
- * The current form. It is never changed: after a change this returns a
38
- * new object.
37
+ * The current form. A form object is never changed once it is returned:
38
+ * after `start()` and after every change this returns a new object.
39
39
  */
40
40
  getForm: () => Form<E, F>;
41
41
  /**
@@ -49,10 +49,15 @@ export declare class FormController<E extends object, F extends FormItem<E> = Fo
49
49
  */
50
50
  on<K extends keyof FormEventMap<E, F>>(event: K, handler: (payload: FormEventMap<E, F>[K]) => void): () => void;
51
51
  /**
52
- * The service of a class listed in `@Services`.
53
- * @throws When the form has no service of the class
52
+ * The service of a class listed in `@Services`, or of a subclass of it.
53
+ * @throws When the form is not started yet or has no service of the class
54
54
  */
55
55
  getService<S extends IService>(service: ServiceClass<S>): BoundService<S, E, F>;
56
+ /**
57
+ * Runs changes as one: subscribers and UPDATE_FORM listeners are notified
58
+ * once, after the function returned or the promise it returned settled.
59
+ */
60
+ batch: <T>(change: () => T) => T;
56
61
  /**
57
62
  * Starts the form: runs its readers and starters and initializes its
58
63
  * services.
@@ -6,4 +6,4 @@ export declare const DECORATOR_READERS = "form-readers";
6
6
  /**
7
7
  * Decorator for adding readers to a form class.
8
8
  */
9
- export declare const Readers: <E, F extends FormItem<E>>(data: IReader<E, F>[]) => FormClassDecorator;
9
+ export declare const Readers: <E, F extends FormItem<E>>(data: Array<IReader<E, F>>) => FormClassDecorator;
@@ -6,4 +6,4 @@ export declare const DECORATOR_SERVICES = "form-services";
6
6
  /**
7
7
  * Decorator for adding services to a form class.
8
8
  */
9
- export declare const Services: (data: Array<IService>) => FormClassDecorator;
9
+ export declare const Services: (data: Array<IService | (new () => IService)>) => FormClassDecorator;
@@ -6,4 +6,4 @@ export declare const DECORATOR_STARTERS = "form-starters";
6
6
  /**
7
7
  * Decorator for adding starters to a form class.
8
8
  */
9
- export declare const Starters: <E, F extends FormItem<E>>(data: IStarter<E, F>[]) => FormClassDecorator;
9
+ export declare const Starters: <E, F extends FormItem<E>>(data: Array<IStarter<E, F>>) => FormClassDecorator;
@@ -11,5 +11,5 @@ export declare const FORM_ITEMS = "form-items";
11
11
  */
12
12
  declare const defineFormItem: <T extends object>(type: string, renderer: Renderer, options?: {
13
13
  register?: FormItemRegister;
14
- }) => (data: T) => FormPropertyDecorator;
14
+ }) => ((data: T) => FormPropertyDecorator);
15
15
  export default defineFormItem;
@@ -4,5 +4,5 @@ import { FormPropertyDecorator } from './decorator';
4
4
  * class. Read it back in a reader with `getFormItemProperties(entity, key)`.
5
5
  * @param key - Identifies the data
6
6
  */
7
- declare const defineFormItemProperty: <T>(key: string) => (data: T) => FormPropertyDecorator;
7
+ declare const defineFormItemProperty: <T>(key: string) => ((data: T) => FormPropertyDecorator);
8
8
  export default defineFormItemProperty;
@@ -4,5 +4,5 @@ import { FormClassDecorator } from './decorator';
4
4
  * in a reader with `getFormProperty(entity, key)`.
5
5
  * @param key - Identifies the data
6
6
  */
7
- declare const defineFormProperty: <T>(key: string) => (data: T) => FormClassDecorator;
7
+ declare const defineFormProperty: <T>(key: string) => ((data: T) => FormClassDecorator);
8
8
  export default defineFormProperty;
@@ -3,7 +3,7 @@
3
3
  * the legacy one (`experimentalDecorators`) and the standard one.
4
4
  */
5
5
  /** A class decorator. Both implementations pass the class first. */
6
- export type FormClassDecorator = (target: Function, context?: ClassDecoratorContext) => void;
6
+ export type FormClassDecorator = (target: object, context?: ClassDecoratorContext) => void;
7
7
  /**
8
8
  * A property decorator: `(prototype, propertyKey)` for the legacy
9
9
  * implementation, `(undefined, context)` for the standard one.
package/dist/index.js CHANGED
@@ -24,6 +24,14 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
24
24
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
25
25
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
26
26
  var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
27
+ var __privateWrapper = (obj, member, setter, getter) => ({
28
+ set _(value) {
29
+ __privateSet(obj, member, value, setter);
30
+ },
31
+ get _() {
32
+ return __privateGet(obj, member, getter);
33
+ }
34
+ });
27
35
 
28
36
  // lib/index.ts
29
37
  var index_exports = {};
@@ -49,13 +57,24 @@ __export(index_exports, {
49
57
  enableDevTools: () => enableDevTools,
50
58
  getFormItemProperties: () => getFormItemProperties,
51
59
  getFormProperty: () => getFormProperty,
52
- isDevToolsEnabled: () => isDevToolsEnabled
60
+ isDevToolsEnabled: () => isDevToolsEnabled,
61
+ readPropertyPath: () => readPropertyPath,
62
+ writeToPropertyPath: () => writeToPropertyPath
53
63
  });
54
64
  module.exports = __toCommonJS(index_exports);
55
65
 
66
+ // lib/shared.ts
67
+ var KEY = /* @__PURE__ */ Symbol.for("@punica/form");
68
+ var scope = globalThis;
69
+ var shared = scope[KEY] ?? (scope[KEY] = {
70
+ formProperties: /* @__PURE__ */ new WeakMap(),
71
+ formItemProperties: /* @__PURE__ */ new WeakMap(),
72
+ devTools: false,
73
+ usedServices: /* @__PURE__ */ new WeakSet()
74
+ });
75
+
56
76
  // lib/metadata/index.ts
57
- var formProperties = /* @__PURE__ */ new WeakMap();
58
- var formItemProperties = /* @__PURE__ */ new WeakMap();
77
+ var { formProperties, formItemProperties } = shared;
59
78
  var classesOf = (entity) => {
60
79
  const classes = [];
61
80
  let current = Object.getPrototypeOf(entity);
@@ -123,7 +142,8 @@ _items = new WeakMap();
123
142
  var createFormItemRegister = () => {
124
143
  return new FormItemRegister();
125
144
  };
126
- var defaultFormItemRegister = createFormItemRegister();
145
+ var _a;
146
+ var defaultFormItemRegister = (_a = shared).register ?? (_a.register = createFormItemRegister());
127
147
 
128
148
  // lib/define/decorator.ts
129
149
  var propertyDecorator = (register) => {
@@ -181,18 +201,21 @@ var Services = (data) => {
181
201
  };
182
202
 
183
203
  // lib/reader/index.ts
184
- var import_util = require("@punica/util");
185
204
  var createInitialReader = () => ({
186
205
  async read(entity, form) {
187
206
  form.services = getFormProperty(entity, DECORATOR_SERVICES);
188
207
  form.readers = getFormProperty(entity, DECORATOR_READERS);
189
208
  form.starters = getFormProperty(entity, DECORATOR_STARTERS);
190
209
  const definitions = getFormItemProperties(entity, FORM_ITEMS);
191
- form.items = Object.keys(entity).filter((property) => definitions[property]).map((property) => {
210
+ const properties = /* @__PURE__ */ new Set([
211
+ ...Object.keys(entity).filter((property) => definitions[property]),
212
+ ...Object.keys(definitions)
213
+ ]);
214
+ form.items = [...properties].map((property) => {
192
215
  const item = { ...definitions[property], property };
193
216
  return {
194
217
  ...item,
195
- value: item.path ? (0, import_util.readPropertyPath)(entity, item.path) : entity[property]
218
+ value: item.path ? readPropertyPath(entity, item.path) : entity[property]
196
219
  };
197
220
  });
198
221
  const getItem = (property) => {
@@ -216,15 +239,14 @@ var createInitialReader = () => ({
216
239
  // lib/utils/devtools.ts
217
240
  var DEVTOOLS_MESSAGE_SOURCE = "punica-form-devtools";
218
241
  var DEVTOOLS_PROTOCOL_VERSION = 2;
219
- var enabled = false;
220
242
  var enableDevTools = () => {
221
- enabled = true;
243
+ shared.devTools = true;
222
244
  };
223
245
  var disableDevTools = () => {
224
- enabled = false;
246
+ shared.devTools = false;
225
247
  };
226
248
  var isDevToolsEnabled = () => {
227
- return enabled && typeof window !== "undefined";
249
+ return shared.devTools && typeof window !== "undefined";
228
250
  };
229
251
  var sendToDevTools = (formId, type, data, formItemKey) => {
230
252
  if (!isDevToolsEnabled()) {
@@ -248,23 +270,28 @@ var sendToDevTools = (formId, type, data, formItemKey) => {
248
270
 
249
271
  // lib/controller/index.ts
250
272
  var formCount = 0;
251
- var _form, _initialItems, _itemsMap, _services, _subscribers, _listeners, _initialEntity, _register, _name, _FormController_instances, mapItems_fn, _getItem, _setItems, _emit, _createCommandItem, _createCommandService, sendEntityToDevTools_fn;
273
+ var _form, _initialItems, _itemsMap, _services, _started, _batching, _dirty, _epoch, _writes, _subscribers, _listeners, _initialEntity, _register, _name, _FormController_instances, mapItems_fn, _getItem, _setItems, notify_fn, _supersede, _emit, _createCommandItem, _createCommandService, sendEntityToDevTools_fn;
252
274
  var _FormController = class _FormController {
253
275
  constructor(form, entity, options) {
254
276
  __privateAdd(this, _FormController_instances);
255
277
  __privateAdd(this, _form);
256
278
  __privateAdd(this, _initialItems, []);
257
279
  __privateAdd(this, _itemsMap, /* @__PURE__ */ new Map());
258
- // eslint-disable-next-line @typescript-eslint/ban-types
280
+ /** The services of the form, by their class. */
259
281
  __privateAdd(this, _services, /* @__PURE__ */ new Map());
282
+ __privateAdd(this, _started, false);
283
+ __privateAdd(this, _batching, 0);
284
+ __privateAdd(this, _dirty, false);
285
+ __privateAdd(this, _epoch, 0);
286
+ __privateAdd(this, _writes, /* @__PURE__ */ new Map());
260
287
  __privateAdd(this, _subscribers, /* @__PURE__ */ new Set());
261
288
  __privateAdd(this, _listeners, /* @__PURE__ */ new Map());
262
289
  __privateAdd(this, _initialEntity);
263
290
  __privateAdd(this, _register);
264
291
  __privateAdd(this, _name);
265
292
  /**
266
- * The current form. It is never changed: after a change this returns a
267
- * new object.
293
+ * The current form. A form object is never changed once it is returned:
294
+ * after `start()` and after every change this returns a new object.
268
295
  */
269
296
  this.getForm = () => {
270
297
  return __privateGet(this, _form);
@@ -277,6 +304,30 @@ var _FormController = class _FormController {
277
304
  __privateGet(this, _subscribers).add(listener);
278
305
  return () => __privateGet(this, _subscribers).delete(listener);
279
306
  };
307
+ /**
308
+ * Runs changes as one: subscribers and UPDATE_FORM listeners are notified
309
+ * once, after the function returned or the promise it returned settled.
310
+ */
311
+ this.batch = (change) => {
312
+ const done = () => {
313
+ if (--__privateWrapper(this, _batching)._ === 0 && __privateGet(this, _dirty)) {
314
+ __privateSet(this, _dirty, false);
315
+ __privateMethod(this, _FormController_instances, notify_fn).call(this);
316
+ }
317
+ };
318
+ __privateWrapper(this, _batching)._++;
319
+ try {
320
+ const result = change();
321
+ if (result instanceof Promise) {
322
+ return result.finally(done);
323
+ }
324
+ done();
325
+ return result;
326
+ } catch (error) {
327
+ done();
328
+ throw error;
329
+ }
330
+ };
280
331
  __privateAdd(this, _getItem, (property) => {
281
332
  const index = __privateGet(this, _itemsMap).get(property);
282
333
  return index === void 0 ? void 0 : __privateGet(this, _form).items[index];
@@ -296,9 +347,21 @@ var _FormController = class _FormController {
296
347
  return;
297
348
  }
298
349
  __privateSet(this, _form, { ...__privateGet(this, _form), items: next });
299
- __privateGet(this, _subscribers).forEach((listener) => listener());
300
- __privateGet(this, _emit).call(this, "UPDATE_FORM", __privateGet(this, _form));
301
- __privateMethod(this, _FormController_instances, sendEntityToDevTools_fn).call(this);
350
+ if (__privateGet(this, _batching)) {
351
+ __privateSet(this, _dirty, true);
352
+ } else {
353
+ __privateMethod(this, _FormController_instances, notify_fn).call(this);
354
+ }
355
+ });
356
+ __privateAdd(this, _supersede, (property) => {
357
+ if (property === void 0) {
358
+ __privateWrapper(this, _epoch)._++;
359
+ } else {
360
+ __privateGet(this, _writes).set(property, (__privateGet(this, _writes).get(property) ?? 0) + 1);
361
+ }
362
+ const epoch = __privateGet(this, _epoch);
363
+ const write = property === void 0 ? 0 : __privateGet(this, _writes).get(property);
364
+ return () => epoch === __privateGet(this, _epoch) && (property === void 0 || write === __privateGet(this, _writes).get(property));
302
365
  });
303
366
  __privateAdd(this, _emit, (event, payload) => {
304
367
  __privateGet(this, _listeners).get(event)?.forEach((handler) => handler(payload));
@@ -311,7 +374,7 @@ var _FormController = class _FormController {
311
374
  }
312
375
  });
313
376
  __privateAdd(this, _createCommandItem, (item) => {
314
- const features = (__privateGet(this, _form).services ?? []).reduce(
377
+ const features = [...__privateGet(this, _services).values()].reduce(
315
378
  (all, service) => ({
316
379
  ...all,
317
380
  ...service.addCustomFeaturesForCommandItem?.()
@@ -334,6 +397,7 @@ var _FormController = class _FormController {
334
397
  getInitialItems: () => __privateGet(this, _initialItems),
335
398
  getItem: __privateGet(this, _getItem),
336
399
  setItems: __privateGet(this, _setItems),
400
+ supersede: __privateGet(this, _supersede),
337
401
  emit: __privateGet(this, _emit),
338
402
  createCommandItem: __privateGet(this, _createCommandItem)
339
403
  }));
@@ -369,11 +433,16 @@ var _FormController = class _FormController {
369
433
  return () => handlers.delete(handler);
370
434
  }
371
435
  /**
372
- * The service of a class listed in `@Services`.
373
- * @throws When the form has no service of the class
436
+ * The service of a class listed in `@Services`, or of a subclass of it.
437
+ * @throws When the form is not started yet or has no service of the class
374
438
  */
375
439
  getService(service) {
376
- const instance = __privateGet(this, _services).get(service);
440
+ if (!__privateGet(this, _started)) {
441
+ throw new Error(
442
+ `Services are available after start(): ${service.name} was read too early.`
443
+ );
444
+ }
445
+ const instance = __privateGet(this, _services).get(service) ?? [...__privateGet(this, _services).values()].find((other) => other instanceof service);
377
446
  if (!instance) {
378
447
  throw new Error(
379
448
  `Service not found: ${service.name}. Add it to @Services.`
@@ -388,23 +457,35 @@ var _FormController = class _FormController {
388
457
  */
389
458
  async start() {
390
459
  __privateGet(this, _emit).call(this, "REGISTER_ITEMS", __privateGet(this, _register).getItemKeys());
391
- for (const reader of __privateGet(this, _form).readers ?? []) {
392
- await reader.read(__privateGet(this, _initialEntity), __privateGet(this, _form));
460
+ let form = { ...__privateGet(this, _form), items: [...__privateGet(this, _form).items] };
461
+ for (const reader of form.readers ?? []) {
462
+ await reader.read(__privateGet(this, _initialEntity), form);
393
463
  }
394
- for (const starter of __privateGet(this, _form).starters ?? []) {
395
- __privateSet(this, _form, await starter.run(__privateGet(this, _form), __privateGet(this, _initialEntity)));
464
+ for (const starter of form.starters ?? []) {
465
+ form = await starter.run(form, __privateGet(this, _initialEntity));
396
466
  }
467
+ __privateSet(this, _form, form);
397
468
  __privateMethod(this, _FormController_instances, mapItems_fn).call(this);
398
469
  const command = __privateGet(this, _createCommandService).call(this);
399
- for (const service of __privateGet(this, _form).services ?? []) {
470
+ for (const entry of form.services ?? []) {
471
+ const service = typeof entry === "function" ? new entry() : entry;
472
+ if (typeof entry !== "function") {
473
+ if (shared.usedServices.has(service)) {
474
+ console.warn(
475
+ `[punica-form] The same ${service.constructor.name} instance is used by more than one form. Pass the class to @Services instead.`
476
+ );
477
+ }
478
+ shared.usedServices.add(service);
479
+ }
400
480
  __privateGet(this, _services).set(service.constructor, service);
401
481
  await service.initialize?.(
402
482
  command
403
483
  );
404
484
  }
405
485
  __privateSet(this, _initialItems, deepCopy(__privateGet(this, _form).items));
486
+ __privateSet(this, _started, true);
406
487
  sendToDevTools(__privateGet(this, _name), "@@INIT", __privateGet(this, _form));
407
- __privateMethod(this, _FormController_instances, sendEntityToDevTools_fn).call(this);
488
+ __privateMethod(this, _FormController_instances, notify_fn).call(this);
408
489
  return __privateGet(this, _form);
409
490
  }
410
491
  };
@@ -412,6 +493,11 @@ _form = new WeakMap();
412
493
  _initialItems = new WeakMap();
413
494
  _itemsMap = new WeakMap();
414
495
  _services = new WeakMap();
496
+ _started = new WeakMap();
497
+ _batching = new WeakMap();
498
+ _dirty = new WeakMap();
499
+ _epoch = new WeakMap();
500
+ _writes = new WeakMap();
415
501
  _subscribers = new WeakMap();
416
502
  _listeners = new WeakMap();
417
503
  _initialEntity = new WeakMap();
@@ -425,11 +511,21 @@ mapItems_fn = function() {
425
511
  };
426
512
  _getItem = new WeakMap();
427
513
  _setItems = new WeakMap();
514
+ /** Tells everyone who follows the form that it changed. */
515
+ notify_fn = function() {
516
+ __privateGet(this, _subscribers).forEach((listener) => listener());
517
+ __privateGet(this, _emit).call(this, "UPDATE_FORM", __privateGet(this, _form));
518
+ __privateMethod(this, _FormController_instances, sendEntityToDevTools_fn).call(this);
519
+ };
520
+ _supersede = new WeakMap();
428
521
  _emit = new WeakMap();
429
522
  _createCommandItem = new WeakMap();
430
523
  _createCommandService = new WeakMap();
431
524
  /** Developer tools show the entity as the `getValues` service returns it. */
432
525
  sendEntityToDevTools_fn = function() {
526
+ if (!isDevToolsEnabled()) {
527
+ return;
528
+ }
433
529
  const getValues = [...__privateGet(this, _services).values()].find(
434
530
  (service) => service.name === "getValues"
435
531
  );
@@ -470,6 +566,32 @@ var deepCopy = (value, seen = /* @__PURE__ */ new WeakMap()) => {
470
566
  }
471
567
  return copy;
472
568
  };
569
+
570
+ // lib/utils/path.ts
571
+ var keysOf = (path) => path.split("/").filter(Boolean);
572
+ var isIndex = (key) => /^\d+$/.test(key);
573
+ var readPropertyPath = (entity, path) => {
574
+ let value = entity;
575
+ for (const key of keysOf(path)) {
576
+ if (!value || typeof value !== "object" || !(key in value)) {
577
+ return void 0;
578
+ }
579
+ value = value[key];
580
+ }
581
+ return value;
582
+ };
583
+ var writeToPropertyPath = (entity, path, value) => {
584
+ const keys = keysOf(path);
585
+ let current = entity;
586
+ keys.forEach((key, index) => {
587
+ if (index === keys.length - 1) {
588
+ current[key] = value;
589
+ } else {
590
+ current[key] ?? (current[key] = isIndex(keys[index + 1]) ? [] : {});
591
+ current = current[key];
592
+ }
593
+ });
594
+ };
473
595
  // Annotate the CommonJS export names for ESM import in node:
474
596
  0 && (module.exports = {
475
597
  DECORATOR_READERS,
@@ -493,5 +615,7 @@ var deepCopy = (value, seen = /* @__PURE__ */ new WeakMap()) => {
493
615
  enableDevTools,
494
616
  getFormItemProperties,
495
617
  getFormProperty,
496
- isDevToolsEnabled
618
+ isDevToolsEnabled,
619
+ readPropertyPath,
620
+ writeToPropertyPath
497
621
  });
package/dist/index.mjs CHANGED
@@ -6,10 +6,27 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
6
6
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
7
7
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
8
8
  var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
9
+ var __privateWrapper = (obj, member, setter, getter) => ({
10
+ set _(value) {
11
+ __privateSet(obj, member, value, setter);
12
+ },
13
+ get _() {
14
+ return __privateGet(obj, member, getter);
15
+ }
16
+ });
17
+
18
+ // lib/shared.ts
19
+ var KEY = /* @__PURE__ */ Symbol.for("@punica/form");
20
+ var scope = globalThis;
21
+ var shared = scope[KEY] ?? (scope[KEY] = {
22
+ formProperties: /* @__PURE__ */ new WeakMap(),
23
+ formItemProperties: /* @__PURE__ */ new WeakMap(),
24
+ devTools: false,
25
+ usedServices: /* @__PURE__ */ new WeakSet()
26
+ });
9
27
 
10
28
  // lib/metadata/index.ts
11
- var formProperties = /* @__PURE__ */ new WeakMap();
12
- var formItemProperties = /* @__PURE__ */ new WeakMap();
29
+ var { formProperties, formItemProperties } = shared;
13
30
  var classesOf = (entity) => {
14
31
  const classes = [];
15
32
  let current = Object.getPrototypeOf(entity);
@@ -77,7 +94,8 @@ _items = new WeakMap();
77
94
  var createFormItemRegister = () => {
78
95
  return new FormItemRegister();
79
96
  };
80
- var defaultFormItemRegister = createFormItemRegister();
97
+ var _a;
98
+ var defaultFormItemRegister = (_a = shared).register ?? (_a.register = createFormItemRegister());
81
99
 
82
100
  // lib/define/decorator.ts
83
101
  var propertyDecorator = (register) => {
@@ -135,14 +153,17 @@ var Services = (data) => {
135
153
  };
136
154
 
137
155
  // lib/reader/index.ts
138
- import { readPropertyPath } from "@punica/util";
139
156
  var createInitialReader = () => ({
140
157
  async read(entity, form) {
141
158
  form.services = getFormProperty(entity, DECORATOR_SERVICES);
142
159
  form.readers = getFormProperty(entity, DECORATOR_READERS);
143
160
  form.starters = getFormProperty(entity, DECORATOR_STARTERS);
144
161
  const definitions = getFormItemProperties(entity, FORM_ITEMS);
145
- form.items = Object.keys(entity).filter((property) => definitions[property]).map((property) => {
162
+ const properties = /* @__PURE__ */ new Set([
163
+ ...Object.keys(entity).filter((property) => definitions[property]),
164
+ ...Object.keys(definitions)
165
+ ]);
166
+ form.items = [...properties].map((property) => {
146
167
  const item = { ...definitions[property], property };
147
168
  return {
148
169
  ...item,
@@ -170,15 +191,14 @@ var createInitialReader = () => ({
170
191
  // lib/utils/devtools.ts
171
192
  var DEVTOOLS_MESSAGE_SOURCE = "punica-form-devtools";
172
193
  var DEVTOOLS_PROTOCOL_VERSION = 2;
173
- var enabled = false;
174
194
  var enableDevTools = () => {
175
- enabled = true;
195
+ shared.devTools = true;
176
196
  };
177
197
  var disableDevTools = () => {
178
- enabled = false;
198
+ shared.devTools = false;
179
199
  };
180
200
  var isDevToolsEnabled = () => {
181
- return enabled && typeof window !== "undefined";
201
+ return shared.devTools && typeof window !== "undefined";
182
202
  };
183
203
  var sendToDevTools = (formId, type, data, formItemKey) => {
184
204
  if (!isDevToolsEnabled()) {
@@ -202,23 +222,28 @@ var sendToDevTools = (formId, type, data, formItemKey) => {
202
222
 
203
223
  // lib/controller/index.ts
204
224
  var formCount = 0;
205
- var _form, _initialItems, _itemsMap, _services, _subscribers, _listeners, _initialEntity, _register, _name, _FormController_instances, mapItems_fn, _getItem, _setItems, _emit, _createCommandItem, _createCommandService, sendEntityToDevTools_fn;
225
+ var _form, _initialItems, _itemsMap, _services, _started, _batching, _dirty, _epoch, _writes, _subscribers, _listeners, _initialEntity, _register, _name, _FormController_instances, mapItems_fn, _getItem, _setItems, notify_fn, _supersede, _emit, _createCommandItem, _createCommandService, sendEntityToDevTools_fn;
206
226
  var _FormController = class _FormController {
207
227
  constructor(form, entity, options) {
208
228
  __privateAdd(this, _FormController_instances);
209
229
  __privateAdd(this, _form);
210
230
  __privateAdd(this, _initialItems, []);
211
231
  __privateAdd(this, _itemsMap, /* @__PURE__ */ new Map());
212
- // eslint-disable-next-line @typescript-eslint/ban-types
232
+ /** The services of the form, by their class. */
213
233
  __privateAdd(this, _services, /* @__PURE__ */ new Map());
234
+ __privateAdd(this, _started, false);
235
+ __privateAdd(this, _batching, 0);
236
+ __privateAdd(this, _dirty, false);
237
+ __privateAdd(this, _epoch, 0);
238
+ __privateAdd(this, _writes, /* @__PURE__ */ new Map());
214
239
  __privateAdd(this, _subscribers, /* @__PURE__ */ new Set());
215
240
  __privateAdd(this, _listeners, /* @__PURE__ */ new Map());
216
241
  __privateAdd(this, _initialEntity);
217
242
  __privateAdd(this, _register);
218
243
  __privateAdd(this, _name);
219
244
  /**
220
- * The current form. It is never changed: after a change this returns a
221
- * new object.
245
+ * The current form. A form object is never changed once it is returned:
246
+ * after `start()` and after every change this returns a new object.
222
247
  */
223
248
  this.getForm = () => {
224
249
  return __privateGet(this, _form);
@@ -231,6 +256,30 @@ var _FormController = class _FormController {
231
256
  __privateGet(this, _subscribers).add(listener);
232
257
  return () => __privateGet(this, _subscribers).delete(listener);
233
258
  };
259
+ /**
260
+ * Runs changes as one: subscribers and UPDATE_FORM listeners are notified
261
+ * once, after the function returned or the promise it returned settled.
262
+ */
263
+ this.batch = (change) => {
264
+ const done = () => {
265
+ if (--__privateWrapper(this, _batching)._ === 0 && __privateGet(this, _dirty)) {
266
+ __privateSet(this, _dirty, false);
267
+ __privateMethod(this, _FormController_instances, notify_fn).call(this);
268
+ }
269
+ };
270
+ __privateWrapper(this, _batching)._++;
271
+ try {
272
+ const result = change();
273
+ if (result instanceof Promise) {
274
+ return result.finally(done);
275
+ }
276
+ done();
277
+ return result;
278
+ } catch (error) {
279
+ done();
280
+ throw error;
281
+ }
282
+ };
234
283
  __privateAdd(this, _getItem, (property) => {
235
284
  const index = __privateGet(this, _itemsMap).get(property);
236
285
  return index === void 0 ? void 0 : __privateGet(this, _form).items[index];
@@ -250,9 +299,21 @@ var _FormController = class _FormController {
250
299
  return;
251
300
  }
252
301
  __privateSet(this, _form, { ...__privateGet(this, _form), items: next });
253
- __privateGet(this, _subscribers).forEach((listener) => listener());
254
- __privateGet(this, _emit).call(this, "UPDATE_FORM", __privateGet(this, _form));
255
- __privateMethod(this, _FormController_instances, sendEntityToDevTools_fn).call(this);
302
+ if (__privateGet(this, _batching)) {
303
+ __privateSet(this, _dirty, true);
304
+ } else {
305
+ __privateMethod(this, _FormController_instances, notify_fn).call(this);
306
+ }
307
+ });
308
+ __privateAdd(this, _supersede, (property) => {
309
+ if (property === void 0) {
310
+ __privateWrapper(this, _epoch)._++;
311
+ } else {
312
+ __privateGet(this, _writes).set(property, (__privateGet(this, _writes).get(property) ?? 0) + 1);
313
+ }
314
+ const epoch = __privateGet(this, _epoch);
315
+ const write = property === void 0 ? 0 : __privateGet(this, _writes).get(property);
316
+ return () => epoch === __privateGet(this, _epoch) && (property === void 0 || write === __privateGet(this, _writes).get(property));
256
317
  });
257
318
  __privateAdd(this, _emit, (event, payload) => {
258
319
  __privateGet(this, _listeners).get(event)?.forEach((handler) => handler(payload));
@@ -265,7 +326,7 @@ var _FormController = class _FormController {
265
326
  }
266
327
  });
267
328
  __privateAdd(this, _createCommandItem, (item) => {
268
- const features = (__privateGet(this, _form).services ?? []).reduce(
329
+ const features = [...__privateGet(this, _services).values()].reduce(
269
330
  (all, service) => ({
270
331
  ...all,
271
332
  ...service.addCustomFeaturesForCommandItem?.()
@@ -288,6 +349,7 @@ var _FormController = class _FormController {
288
349
  getInitialItems: () => __privateGet(this, _initialItems),
289
350
  getItem: __privateGet(this, _getItem),
290
351
  setItems: __privateGet(this, _setItems),
352
+ supersede: __privateGet(this, _supersede),
291
353
  emit: __privateGet(this, _emit),
292
354
  createCommandItem: __privateGet(this, _createCommandItem)
293
355
  }));
@@ -323,11 +385,16 @@ var _FormController = class _FormController {
323
385
  return () => handlers.delete(handler);
324
386
  }
325
387
  /**
326
- * The service of a class listed in `@Services`.
327
- * @throws When the form has no service of the class
388
+ * The service of a class listed in `@Services`, or of a subclass of it.
389
+ * @throws When the form is not started yet or has no service of the class
328
390
  */
329
391
  getService(service) {
330
- const instance = __privateGet(this, _services).get(service);
392
+ if (!__privateGet(this, _started)) {
393
+ throw new Error(
394
+ `Services are available after start(): ${service.name} was read too early.`
395
+ );
396
+ }
397
+ const instance = __privateGet(this, _services).get(service) ?? [...__privateGet(this, _services).values()].find((other) => other instanceof service);
331
398
  if (!instance) {
332
399
  throw new Error(
333
400
  `Service not found: ${service.name}. Add it to @Services.`
@@ -342,23 +409,35 @@ var _FormController = class _FormController {
342
409
  */
343
410
  async start() {
344
411
  __privateGet(this, _emit).call(this, "REGISTER_ITEMS", __privateGet(this, _register).getItemKeys());
345
- for (const reader of __privateGet(this, _form).readers ?? []) {
346
- await reader.read(__privateGet(this, _initialEntity), __privateGet(this, _form));
412
+ let form = { ...__privateGet(this, _form), items: [...__privateGet(this, _form).items] };
413
+ for (const reader of form.readers ?? []) {
414
+ await reader.read(__privateGet(this, _initialEntity), form);
347
415
  }
348
- for (const starter of __privateGet(this, _form).starters ?? []) {
349
- __privateSet(this, _form, await starter.run(__privateGet(this, _form), __privateGet(this, _initialEntity)));
416
+ for (const starter of form.starters ?? []) {
417
+ form = await starter.run(form, __privateGet(this, _initialEntity));
350
418
  }
419
+ __privateSet(this, _form, form);
351
420
  __privateMethod(this, _FormController_instances, mapItems_fn).call(this);
352
421
  const command = __privateGet(this, _createCommandService).call(this);
353
- for (const service of __privateGet(this, _form).services ?? []) {
422
+ for (const entry of form.services ?? []) {
423
+ const service = typeof entry === "function" ? new entry() : entry;
424
+ if (typeof entry !== "function") {
425
+ if (shared.usedServices.has(service)) {
426
+ console.warn(
427
+ `[punica-form] The same ${service.constructor.name} instance is used by more than one form. Pass the class to @Services instead.`
428
+ );
429
+ }
430
+ shared.usedServices.add(service);
431
+ }
354
432
  __privateGet(this, _services).set(service.constructor, service);
355
433
  await service.initialize?.(
356
434
  command
357
435
  );
358
436
  }
359
437
  __privateSet(this, _initialItems, deepCopy(__privateGet(this, _form).items));
438
+ __privateSet(this, _started, true);
360
439
  sendToDevTools(__privateGet(this, _name), "@@INIT", __privateGet(this, _form));
361
- __privateMethod(this, _FormController_instances, sendEntityToDevTools_fn).call(this);
440
+ __privateMethod(this, _FormController_instances, notify_fn).call(this);
362
441
  return __privateGet(this, _form);
363
442
  }
364
443
  };
@@ -366,6 +445,11 @@ _form = new WeakMap();
366
445
  _initialItems = new WeakMap();
367
446
  _itemsMap = new WeakMap();
368
447
  _services = new WeakMap();
448
+ _started = new WeakMap();
449
+ _batching = new WeakMap();
450
+ _dirty = new WeakMap();
451
+ _epoch = new WeakMap();
452
+ _writes = new WeakMap();
369
453
  _subscribers = new WeakMap();
370
454
  _listeners = new WeakMap();
371
455
  _initialEntity = new WeakMap();
@@ -379,11 +463,21 @@ mapItems_fn = function() {
379
463
  };
380
464
  _getItem = new WeakMap();
381
465
  _setItems = new WeakMap();
466
+ /** Tells everyone who follows the form that it changed. */
467
+ notify_fn = function() {
468
+ __privateGet(this, _subscribers).forEach((listener) => listener());
469
+ __privateGet(this, _emit).call(this, "UPDATE_FORM", __privateGet(this, _form));
470
+ __privateMethod(this, _FormController_instances, sendEntityToDevTools_fn).call(this);
471
+ };
472
+ _supersede = new WeakMap();
382
473
  _emit = new WeakMap();
383
474
  _createCommandItem = new WeakMap();
384
475
  _createCommandService = new WeakMap();
385
476
  /** Developer tools show the entity as the `getValues` service returns it. */
386
477
  sendEntityToDevTools_fn = function() {
478
+ if (!isDevToolsEnabled()) {
479
+ return;
480
+ }
387
481
  const getValues = [...__privateGet(this, _services).values()].find(
388
482
  (service) => service.name === "getValues"
389
483
  );
@@ -424,6 +518,32 @@ var deepCopy = (value, seen = /* @__PURE__ */ new WeakMap()) => {
424
518
  }
425
519
  return copy;
426
520
  };
521
+
522
+ // lib/utils/path.ts
523
+ var keysOf = (path) => path.split("/").filter(Boolean);
524
+ var isIndex = (key) => /^\d+$/.test(key);
525
+ var readPropertyPath = (entity, path) => {
526
+ let value = entity;
527
+ for (const key of keysOf(path)) {
528
+ if (!value || typeof value !== "object" || !(key in value)) {
529
+ return void 0;
530
+ }
531
+ value = value[key];
532
+ }
533
+ return value;
534
+ };
535
+ var writeToPropertyPath = (entity, path, value) => {
536
+ const keys = keysOf(path);
537
+ let current = entity;
538
+ keys.forEach((key, index) => {
539
+ if (index === keys.length - 1) {
540
+ current[key] = value;
541
+ } else {
542
+ current[key] ?? (current[key] = isIndex(keys[index + 1]) ? [] : {});
543
+ current = current[key];
544
+ }
545
+ });
546
+ };
427
547
  export {
428
548
  DECORATOR_READERS,
429
549
  DECORATOR_SERVICES,
@@ -446,5 +566,7 @@ export {
446
566
  enableDevTools,
447
567
  getFormItemProperties,
448
568
  getFormProperty,
449
- isDevToolsEnabled
569
+ isDevToolsEnabled,
570
+ readPropertyPath,
571
+ writeToPropertyPath
450
572
  };
@@ -1,7 +1,3 @@
1
- /**
2
- * The metadata decorators attach to form classes. It is kept per class, so
3
- * no reflection polyfill is needed.
4
- */
5
1
  export declare const setFormProperty: (target: object, key: string, data: unknown) => void;
6
2
  export declare const setFormItemProperty: (target: object, key: string, property: string, data: unknown) => void;
7
3
  /**
@@ -17,6 +17,12 @@ export type CommandService<E, F extends FormItem<E>> = {
17
17
  * reference and UPDATE_FORM is fired. Unknown properties are ignored.
18
18
  */
19
19
  setItems: (items: Array<FormItem<E>>) => void;
20
+ /**
21
+ * Marks the pending asynchronous writes of a property, or of the whole
22
+ * form when no property is given, as superseded by a newer one.
23
+ * @returns A function that tells whether this write is still the newest
24
+ */
25
+ supersede: (property?: keyof E) => () => boolean;
20
26
  /** Fires an event of the controller. */
21
27
  emit: <K extends keyof FormEventMap<E, F>>(event: K, payload: FormEventMap<E, F>[K]) => void;
22
28
  /** Creates what the functions of a form item receive. */
@@ -5,7 +5,8 @@ import { FormItem, IReader, IService, IStarter } from '../..';
5
5
  */
6
6
  export type Form<E, F extends FormItem<E> = FormItem<E>> = {
7
7
  items: F[];
8
- services?: IService[];
8
+ /** Service classes (one instance per form) or instances. */
9
+ services?: Array<IService | (new () => IService)>;
9
10
  readers?: Array<IReader<E, F>>;
10
11
  starters?: Array<IStarter<E, F>>;
11
12
  [key: string]: unknown;
@@ -25,12 +25,26 @@ export type FormItem<E> = {
25
25
  /** The messages of the last failed validation. */
26
26
  errorMessages?: string[];
27
27
  /** Runs once while the form is created; the returned items are written to the form. */
28
- initialize?: (command: CommandItem<E, FormItem<E>>) => Promise<Array<FormItem<E>>>;
28
+ initialize?(command: CommandItem<E, FormItem<E>>): Promise<Array<FormItem<E>>>;
29
29
  /** Runs after the value of the item was set; the returned items are written to the form. */
30
- control?: (command: CommandItem<E, FormItem<E>>) => Promise<Array<FormItem<E>>>;
30
+ control?(command: CommandItem<E, FormItem<E>>): Promise<Array<FormItem<E>>>;
31
31
  /** Validates the item. */
32
- validation?: (command: CommandItem<E, FormItem<E>>) => Promise<ErrorDetail>;
32
+ validation?(command: CommandItem<E, FormItem<E>>): Promise<ErrorDetail>;
33
33
  };
34
+ /**
35
+ * A form item whose `value` has the type of its property. Use it as the item
36
+ * type of a form to get checked values after narrowing by `property`:
37
+ *
38
+ * const controller = await FormController.fromEntity<User, TypedFormItem<User>>(user);
39
+ * const item = controller.getForm().items[0];
40
+ * if (item.property === 'age') item.value; // number | undefined
41
+ */
42
+ export type TypedFormItem<E, F extends FormItem<E> = FormItem<E>> = {
43
+ [K in keyof E]: Omit<F, 'property' | 'value'> & {
44
+ property: K;
45
+ value?: E[K];
46
+ };
47
+ }[keyof E];
34
48
  /**
35
49
  * The result of a validation.
36
50
  */
@@ -3,8 +3,9 @@ import { FormItem, IReader } from '..';
3
3
  * Creates the reader that turns an entity into a form:
4
4
  *
5
5
  * 1. the services, readers and starters of the class decorators
6
- * 2. one item for every decorated property the entity holds, in the order
7
- * of the properties
6
+ * 2. one item for every decorated property, in the order of the properties
7
+ * of the entity; decorated properties the entity does not hold (declared
8
+ * without a value) follow
8
9
  * 3. the values of the entity
9
10
  * 4. the `initialize` function of every item that has one
10
11
  */
@@ -0,0 +1,20 @@
1
+ import type { FormItemRegister } from './register';
2
+ /**
3
+ * The state every copy of this package shares. A project can load the ESM
4
+ * and the CommonJS build side by side (an app and its test runner, for
5
+ * example); decorators applied through one copy must be visible to the other.
6
+ */
7
+ type Shared = {
8
+ /** Class → key → data of the class decorators. */
9
+ formProperties: WeakMap<object, Map<string, unknown>>;
10
+ /** Class → key → property → data of the property decorators. */
11
+ formItemProperties: WeakMap<object, Map<string, Record<string, unknown>>>;
12
+ /** The default form item register, created on first use. */
13
+ register?: FormItemRegister;
14
+ /** Whether forms report to the DevTools extension. */
15
+ devTools: boolean;
16
+ /** Service instances that were given to a controller. */
17
+ usedServices: WeakSet<object>;
18
+ };
19
+ export declare const shared: Shared;
20
+ export {};
@@ -1,2 +1,3 @@
1
1
  export { DEVTOOLS_MESSAGE_SOURCE, DEVTOOLS_PROTOCOL_VERSION, disableDevTools, enableDevTools, isDevToolsEnabled } from './devtools';
2
2
  export * from './deepCopy';
3
+ export * from './path';
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Reads the value at a path inside an object.
3
+ * @returns The value, or `undefined` when the path does not exist
4
+ */
5
+ export declare const readPropertyPath: (entity: unknown, path: string) => unknown;
6
+ /**
7
+ * Writes a value at a path inside an object, creating the objects and
8
+ * arrays on the way that do not exist yet.
9
+ */
10
+ export declare const writeToPropertyPath: (entity: object, path: string, value: unknown) => void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@punica/form",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "Headless, framework-agnostic form engine",
5
5
  "author": {
6
6
  "name": "Uryan Sezgin TEKE",
@@ -28,7 +28,8 @@
28
28
  },
29
29
  "sideEffects": false,
30
30
  "publishConfig": {
31
- "access": "public"
31
+ "access": "public",
32
+ "provenance": true
32
33
  },
33
34
  "repository": {
34
35
  "url": "git+https://github.com/punicalab/punica-form.git"
@@ -36,9 +37,6 @@
36
37
  "files": [
37
38
  "dist"
38
39
  ],
39
- "dependencies": {
40
- "@punica/util": "^1.0.2"
41
- },
42
40
  "scripts": {
43
41
  "build": "tsup lib/index.ts --format esm,cjs --target es2020 --clean && tsc -p tsconfig.build.json --emitDeclarationOnly",
44
42
  "clean": "rimraf dist",