@nuxodin/item 0.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +176 -0
  3. package/item.d.ts +116 -0
  4. package/item.js +361 -0
  5. package/package.json +24 -0
  6. package/src/AsyncDataPoint.d.ts +52 -0
  7. package/src/AsyncDataPoint.js +280 -0
  8. package/src/Collection.experiment.js +63 -0
  9. package/src/Emitter.js +103 -0
  10. package/src/proxy.js +77 -0
  11. package/src/signal.js +95 -0
  12. package/tools/AsyncChild.js +44 -0
  13. package/tools/access.js +36 -0
  14. package/tools/beta/collectChanges.js +88 -0
  15. package/tools/beta/syncWith.js +22 -0
  16. package/tools/condition.js +65 -0
  17. package/tools/csvDataItem.js +139 -0
  18. package/tools/db/connect.js +27 -0
  19. package/tools/db/dialect/mysql.js +12 -0
  20. package/tools/db/dialect/pg.js +15 -0
  21. package/tools/db/dialect/sqlite.js +12 -0
  22. package/tools/db/shared.js +7 -0
  23. package/tools/db/sql.d.ts +24 -0
  24. package/tools/db/sql.js +83 -0
  25. package/tools/httpRouter.js +66 -0
  26. package/tools/jsonDataItem.js +29 -0
  27. package/tools/schema/build/input.js +120 -0
  28. package/tools/schema/db/indexeddb/from-db.js +29 -0
  29. package/tools/schema/db/indexeddb/to-db.js +115 -0
  30. package/tools/schema/db/mysql/from-db.js +16 -0
  31. package/tools/schema/db/mysql/from-field.js +101 -0
  32. package/tools/schema/db/mysql/to-db.js +275 -0
  33. package/tools/schema/db/mysql/to-field.js +60 -0
  34. package/tools/schema/db/pg/from-db.js +48 -0
  35. package/tools/schema/db/pg/from-field.js +71 -0
  36. package/tools/schema/db/pg/to-db.js +223 -0
  37. package/tools/schema/db/pg/to-field.js +52 -0
  38. package/tools/schema/db/shared/from-db.js +29 -0
  39. package/tools/schema/db/shared/sql.js +26 -0
  40. package/tools/schema/db/sqlite/from-db.js +39 -0
  41. package/tools/schema/db/sqlite/from-field.js +49 -0
  42. package/tools/schema/db/sqlite/to-db.js +127 -0
  43. package/tools/schema/db/sqlite/to-field.js +34 -0
  44. package/tools/schema/diff.js +90 -0
  45. package/tools/schema/dom/toInput.js +6 -0
  46. package/tools/schema/render/dom.js +26 -0
  47. package/tools/schema/render/html.js +40 -0
  48. package/tools/schema/utils.js +131 -0
  49. package/tools/schema/validator.js +92 -0
  50. package/tools/view/dom.js +96 -0
  51. package/tools/view/uhtml.js +40 -0
  52. package/tools/wsDenoRouter.js +108 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Tobias Buschor
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,176 @@
1
+ # item.js
2
+
3
+ **A primitive abstraction layer for reactive data structures**
4
+
5
+ ## The Problem
6
+
7
+ Every data source has its own API: Files use `fs.readFile()`, localStorage uses
8
+ `getItem()`, databases use SQL queries, MQTT uses pub/sub. This means:
9
+
10
+ - 🔄 Different APIs for every backend
11
+ - 🎯 No unified reactivity
12
+ - 🔗 Hard to switch or combine data sources
13
+ - 🧩 Complex integration code
14
+
15
+ ## The Solution
16
+
17
+ `item.js` provides **one uniform API** for all structured data sources.
18
+
19
+ ```js
20
+ // Same API, different backends:
21
+ fileSystem.item("project").item("readme.md").value = "### Hello World";
22
+ dbItem.item("users").item("123").item("name").value = "Alice";
23
+ mqttItem.item("sensors").item("temp").value = 23.5;
24
+ localStorage.item("theme").value = "dark";
25
+ ```
26
+
27
+ ## Installation
28
+
29
+ ```js
30
+ import { item } from "https://cdn.jsdelivr.net/gh/nuxodin/item.js@main/item.js"
31
+ ```
32
+
33
+ ## Wrapped value
34
+
35
+ ```js
36
+ const a = item(1);
37
+ a.value === 1; // true
38
+
39
+ // using object
40
+ const a = item({ b: 1 });
41
+ a.isObject // true
42
+ a.value; // {b: 1}
43
+ const b = a.item("b"); // property 'b' is also an "Item"
44
+ b.parent === a;
45
+ b.key === "b";
46
+ b.path; // ['b'];
47
+ a.sub(["a", "b", "c"]); // equals b.item('a').item('b').item('c');
48
+ a.item("c").item("d"); // Automatic property creation (Autovivification)
49
+ ```
50
+
51
+ ## Effect
52
+
53
+ ```js
54
+ // effect
55
+ effect(() => {
56
+ console.log(a.item("b").value);
57
+ console.log(b.item("c").value);
58
+ });
59
+ a.item("b").value = 2;
60
+ b.item("c").value = 3;
61
+ // triggers effect batched after a microtask
62
+ ```
63
+
64
+ ## Events
65
+
66
+ ```js
67
+ a.addEventListener("change", (event) => {
68
+ console.log(event.oldValue, event.value);
69
+ });
70
+ a.value = 3; // triggers 'change' event
71
+
72
+ // bubbling (changeIn)
73
+ a.addEventListener("changeIn", ({ target, oldValue, value }) => {
74
+ target === a.item("b"); // true
75
+ console.log(target, oldValue, value);
76
+ });
77
+ a.item("b").value = 2; // triggers 'changeIn' event on 'a' (bubbles up)
78
+
79
+ // object-related:
80
+ a.addEventListener("changeIn", event => {
81
+ if (event.add) {
82
+ console.log(event.target, "added property", event.add); // child-item
83
+ }
84
+ if (event.remove) {
85
+ console.log(event.target, "removed property", event.remove);
86
+ }
87
+ });
88
+ ```
89
+
90
+ ## Proxy
91
+
92
+ ```js
93
+ const p = item({ a: 1 }).proxy;
94
+ p.a === 1; // equals `i.item('a').value === 1`
95
+ p.a = 2;
96
+ ```
97
+
98
+ ## Extend from Item
99
+
100
+ ```js
101
+ import { Item } from "../item.js";
102
+
103
+ class UpperCaseItem extends Item {
104
+ $get() { // overwrite getter
105
+ const value = super.$get();
106
+ return typeof value === "string" ? value.toUpperCase() : value;
107
+ }
108
+ }
109
+
110
+ // Usage:
111
+ const a = new UpperCaseItem();
112
+ a.value = { a: "Hello", b: "World" };
113
+ console.log(a.value); // {a: 'HELLO', b: 'WORLD'}
114
+ ```
115
+
116
+ ## Async: the tree is the cache
117
+
118
+ > **The item tree is the cache. `io` is only transport.**
119
+
120
+ *Which slice?* (depth, subtree, query) is answered by the tree — *running? done? failed?* by
121
+ `io`. Keep those apart and the async side stays simple. See [doc/async.md](./doc/async.md).
122
+
123
+ ## See how easy it is to use "item.js" with different drivers
124
+
125
+ ```js
126
+ // indexeddb
127
+ import {IDB} from "../drivers/indexedDb.js";
128
+ const db = IDB().item('db');
129
+ db.open(2, { upgrade(db, oldVersion, newVersion, transaction) { ... } });
130
+
131
+ db.item('store').item('1').item('name').value = 'demo';
132
+
133
+ // MySQL
134
+ import {Mysql} from "../drivers/sql/Mysql.js";
135
+ const db = new Mysql({host: 'localhost'}).item('db');
136
+ await db.connect();
137
+
138
+ db.item('table').item('1').item('name').value = 'demo';
139
+
140
+ // MQTT
141
+ import {createMqtt} from "../adapter/deno/mqtt.js";
142
+ const root = await createMqtt({url: 'mqtt://mqtt.org:1883'});
143
+
144
+ root.item('house1').item('counters').item('electricity').value = 876;
145
+
146
+ // localStorage
147
+ import {local} from "../drivers/localStorage.js";
148
+
149
+ local.item('someItem').value = 'Hello World';
150
+
151
+ // cookies
152
+ import {cookies} from "../drivers/cookies.js";
153
+ const root = cookies();
154
+
155
+ root.item('myCookie').value = 'Hello World';
156
+ ```
157
+
158
+ Even easier with proxies:
159
+
160
+ ```js
161
+ const db = dbItem.proxy;
162
+
163
+ db.myTable[1] = { name: "demo", age: 42 };
164
+
165
+ // and react to changes
166
+ effect(() => {
167
+ input.value = mqtt.house1.counters.electricity;
168
+ });
169
+ ```
170
+
171
+ ## About
172
+
173
+ - MIT License, Copyright (c) 2022 <u1> (like all repositories in this
174
+ organization) <br>
175
+ - Suggestions, ideas, finding bugs and making pull requests make us very happy.
176
+ ♥
package/item.d.ts ADDED
@@ -0,0 +1,116 @@
1
+ import { Emitter } from "./src/Emitter.js";
2
+ import type { AsyncDataPoint } from "./src/AsyncDataPoint.js";
3
+
4
+ export const $item: unique symbol;
5
+
6
+ export class Item<TRoot extends Item<any> = Item<any>> extends Emitter {
7
+ constructor(parent?: Item, key?: string);
8
+
9
+ readonly key: string | null;
10
+ readonly parent: TRoot | null;
11
+ readonly filled: boolean;
12
+ readonly isObject: boolean | null;
13
+ value: any;
14
+
15
+ // Async Status & IO
16
+ readonly io: AsyncDataPoint;
17
+ readonly pending: boolean;
18
+ readonly error: Error | undefined;
19
+ /** Nearest self-or-ancestor with a reader/writer — the item that talks to the source for this one. */
20
+ readonly ioOwner: Item | null;
21
+ /** Did the region's full value ever arrive from its source? Resolves via ioOwner; expires with io ttl. */
22
+ readonly loaded: boolean;
23
+ promise: Promise<any>;
24
+
25
+ // Hooks (Callbacks)
26
+ reader?: (query?: any, options?: any) => Promise<any>;
27
+ writer?: (value: any, options?: any) => Promise<any>;
28
+ /** Declares: my reader delivers the whole region. Enables partial writes (child set/patch) once loaded. */
29
+ readsFull?: boolean;
30
+ adder?: (value: any) => Promise<{key: string}>;
31
+ remover?: (options?: any) => Promise<any>;
32
+
33
+ // Core Methods
34
+ get(options?: { depth?: number }): any;
35
+ set(value: any, options?: { patch?: boolean, local?: boolean, depth?: number }): Promise<any> | undefined;
36
+ patch(value: any): Promise<any> | undefined;
37
+ clear(): void;
38
+
39
+ // Traversal & Structure
40
+ item(key: any): TRoot;
41
+ sub(...keys: (string | string[])[]): Item;
42
+ add(value: any): Promise<Item>;
43
+ generateKey(): string;
44
+ remove(options?: { local?: boolean }): Promise<void>;
45
+ has(...keys: (string | string[])[]): Item | undefined;
46
+
47
+ readonly keys: string[] | readonly never[];
48
+ readonly path: string[] | readonly never[];
49
+ readonly root: TRoot;
50
+ items(): Item[];
51
+
52
+ // Data Sync
53
+ read(query?: object): Promise<any>;
54
+
55
+ // JSON Schema
56
+ setSchema(schema: object): void;
57
+ readonly schema: Record<string, any> | null;
58
+
59
+ // Misc
60
+ readonly proxy: ItemProxy;
61
+ toJSON(): any;
62
+ toString(): string;
63
+ [Symbol.toPrimitive](hint: "string" | "number" | "default"): any;
64
+
65
+ // Iterators
66
+ [Symbol.iterator](): Iterator<Item>;
67
+ [Symbol.asyncIterator](): AsyncIterator<Item>;
68
+
69
+ // Static & Customization
70
+ ChildClass: typeof Item | false | undefined;
71
+ static ChildClass: typeof Item | false | undefined;
72
+ static isPrimitive(value: unknown): boolean;
73
+ static equals(a: unknown, b: unknown): boolean;
74
+ }
75
+
76
+ /*
77
+ export type ItemValue = unknown;
78
+
79
+ export type ItemProxy = ItemProxyMethods & {
80
+ [key: string]: ItemProxy;
81
+ };
82
+
83
+ export interface ItemProxyMethods {
84
+ readonly [$item]: Item;
85
+ (): ItemValue;
86
+ (value: ItemValue): Promise<any> | undefined;
87
+ then<TResult1 = ItemValue, TResult2 = never>(
88
+ onfulfilled?: ((value: ItemValue) => TResult1 | PromiseLike<TResult1>) | null,
89
+ onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null,
90
+ ): PromiseLike<TResult1 | TResult2>;
91
+ [Symbol.iterator](): Iterator<ItemProxy>;
92
+ }
93
+ */
94
+
95
+ export type ItemValue = unknown;
96
+
97
+ export type ItemProxy<T = ItemValue, TRaw extends Item = Item> = ItemProxyMethods<T, TRaw> & ItemProxyChildren;
98
+
99
+ export interface ItemProxyChildren { [key: string]: ItemProxy<unknown, Item>; }
100
+
101
+ export interface ItemProxyMethods<T = ItemValue,TRaw extends Item = Item> {
102
+ readonly [$item]: TRaw;
103
+ <TValue = T>(): TValue;
104
+ (value: unknown): Promise<any> | undefined;
105
+ then<TResult1 = T, TResult2 = never>(
106
+ onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,
107
+ onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null,
108
+ ): PromiseLike<TResult1 | TResult2>;
109
+ [Symbol.iterator](): Iterator<ItemProxy>;
110
+ [Symbol.asyncIterator](): AsyncIterator<Item>;
111
+ }
112
+ /* */
113
+
114
+ export function item(...args: any[]): Item;
115
+
116
+ export function dispatch(item: Item, eventName: string, options: object): { defaultPrevented: boolean };
package/item.js ADDED
@@ -0,0 +1,361 @@
1
+ // @ts-self-types="./item.d.ts"
2
+ import { toProxy, $item } from "./src/proxy.js";
3
+ import { asyncIteratorFromEventTarget, Emitter, ItemEvent, } from "./src/Emitter.js";
4
+ import { AsyncDataPoint } from "./src/AsyncDataPoint.js";
5
+ import { effect, track, notify } from "./src/signal.js";
6
+ export { effect, $item };
7
+
8
+ const EMPTY_ARRAY = Object.freeze([]);
9
+
10
+ export class Item extends Emitter {
11
+
12
+ #value;
13
+ #parent = null;
14
+ #key = null;
15
+ #path;
16
+ #root;
17
+ #isObject = null; // null:not filled, true:object, false:primitive value
18
+ #isSetting = false;
19
+ #isGetting = false;
20
+
21
+ constructor(parent, key) {
22
+ super();
23
+ this.#parent = parent ?? null;
24
+ this.#key = key ?? null;
25
+ }
26
+
27
+ get key() { return this.#key; }
28
+ get parent() { return this.#parent; }
29
+ get filled() { return this.#isObject !== null; }
30
+ get isObject() { return this.#isObject; }
31
+ set value(value) { this.set(value); }
32
+ get value() { return this.get(); }
33
+
34
+ get(options) {
35
+ const value = this.$get(options);
36
+ if (options?.silent) return value;
37
+ if (this.#isGetting) throw new Error("[item.js] circular get");
38
+ this.#isGetting = true;
39
+ try {
40
+ const event = dispatch(this, 'get', { value, options });
41
+ track(this);
42
+ return event.defaultPrevented ? undefined : event.value;
43
+ } finally {
44
+ this.#isGetting = false;
45
+ }
46
+ }
47
+
48
+ $get(options) {
49
+ if (!this.#isObject) return this.#value;
50
+ const depth = options?.depth ?? Infinity;
51
+ const value = this.#value;
52
+ const result = Object.create(null);
53
+ for (const key in value) {
54
+ result[key] = depth > 1 ? value[key].get({ ...options, depth: depth - 1 }) : null;
55
+ }
56
+ return result;
57
+ }
58
+
59
+ peek() { return this.get({ silent: true }); }
60
+
61
+ /** Returns a promise while an io-write is running, else undefined (no writer, local, unchanged
62
+ * or prevented). Await it to know *when* the write landed — not *what* it resolves to. */
63
+ set(value, options) {
64
+ if (this.#isSetting) throw new Error("[item.js] circular set");
65
+ this.#isSetting = true;
66
+ try {
67
+ const event = dispatch(this, "set", {oldValue: this.#value, value, options});
68
+ let ioPromise = undefined;
69
+ if (!event.defaultPrevented) {
70
+ value = event.value;
71
+
72
+ const owner = options?.local ? null : this.ioOwner;
73
+
74
+ // `set` on the owner itself is a deliberate full replace — everything else is partial
75
+ if (owner !== this || options?.patch) this.#assertRegionLicence(owner);
76
+
77
+ this.$set(value, { ...options, local: options?.local || !!owner?.writer }); // children "local only" — the owner writes them
78
+
79
+ if (owner?.writer) ioPromise = owner.io.set(owner.peek());
80
+
81
+ }
82
+ return ioPromise;
83
+ } finally {
84
+ this.#isSetting = false;
85
+ }
86
+ }
87
+
88
+ patch(value) { return this.set(value, { patch: true }); }
89
+
90
+ $set(value, options) {
91
+ const oldValue = this.#value;
92
+
93
+ if (this.constructor.isPrimitive(value)) {
94
+ const equal = this.#isObject === false && this.constructor.equals(oldValue, value);
95
+ if (!equal) {
96
+ if (this.#isObject) this.#clearChildren();
97
+ this.#value = value;
98
+ this.#isObject = false;
99
+ dispatch(this, "change", { oldValue, value, options });
100
+ }
101
+ } else {
102
+ this.#ensureObject();
103
+ const entries = Object.entries(value);
104
+ const depth = options?.depth ?? Infinity;
105
+ for (const [key, val] of entries) {
106
+ const item = this.item(key);
107
+ if (depth > 1) item.set(val, { ...options, depth: depth - 1 });
108
+ }
109
+ if (!options?.patch) {
110
+ for (const key in this.#value) {
111
+ (key in value) || this.#value[key].remove(options);
112
+ }
113
+ }
114
+ }
115
+ }
116
+
117
+ clear() {
118
+ if (this.#isObject) this.#clearChildren();
119
+ this.#io?.dispose();
120
+ this.removeAllListeners();
121
+ this.#value = undefined;
122
+ this.#isObject = this.#io = this.#path = this.#root = null;
123
+ }
124
+
125
+ /* object related */
126
+
127
+ #clearChildren() {
128
+ for (const child of Object.values(this.#value)) child.clear();
129
+ }
130
+
131
+ #ensureObject() {
132
+ if (!this.#isObject) {
133
+ //dispatch(this, "change", { oldValue:this.#value, value:null }); // null ok?
134
+ this.#value = Object.create(null);
135
+ this.#isObject = true;
136
+ }
137
+ }
138
+
139
+ item(key) {
140
+ key = String(key);
141
+ this.#ensureObject();
142
+ if (!(key in this.#value)) {
143
+ if (this.ChildClass === false) throw new Error(`[item.js] ${this.constructor.name} has no children`);
144
+ const Klass = this.ChildClass ?? this.constructor;
145
+ const item = new Klass(this, key);
146
+ this.#value[key] = item;
147
+ dispatch(this, "change", { add: item });
148
+ }
149
+ return this.#value[key];
150
+ }
151
+
152
+ async add(value) {
153
+ const key = this.adder ? (await this.adder(value)).key : this.generateKey();
154
+ if (key == null) throw new Error("[item.js] a key must be generated");
155
+ if (this.has(key)) throw new Error(`[item.js] key "${key}" already exists`)
156
+ const item = this.item(key);
157
+ item.set(value, { local: true });
158
+ return item;
159
+ }
160
+
161
+ generateKey() { return crypto.randomUUID() } // items with no ".adder()"
162
+
163
+ async remove(options) {
164
+ if (!this.#parent) throw new Error("[item.js] cannot remove root item");
165
+ // no own remover → the removal is a partial write of the surrounding region
166
+ const owner = options?.local || this.remover ? null : this.#parent.ioOwner;
167
+ this.#assertRegionLicence(owner);
168
+ delete this.#parent.#value[this.#key];
169
+ dispatch(this.#parent, "change", { remove: this, options });
170
+ if (this.remover && !options?.local) await this.remover();
171
+ else if (owner?.writer) await owner.io.set(owner.peek());
172
+ this.clear();
173
+ }
174
+
175
+ sub(...keys) {
176
+ let current = this;
177
+ for (const key of keys.flat()) current = current.item(key);
178
+ return current;
179
+ }
180
+
181
+ #has(key) {
182
+ track(this);
183
+ return this.#isObject && key in this.#value ? this.item(key) : undefined;
184
+ }
185
+
186
+ has(...keys) {
187
+ let current = this;
188
+ for (const key of keys.flat()) if (!(current = current.#has(key))) return;
189
+ return current;
190
+ }
191
+
192
+ get keys() {
193
+ track(this);
194
+ return this.#isObject ? Object.keys(this.#value ?? {}) : EMPTY_ARRAY;
195
+ }
196
+
197
+ get path() { return this.#path ??= this.#parent == null ? EMPTY_ARRAY : [...this.#parent.path, this.#key]; }
198
+
199
+ get root() { return this.#root ??= this.#parent?.root ?? this; }
200
+
201
+ *[Symbol.iterator]() {
202
+ for (const key of this.keys) yield this.#value[key];
203
+ }
204
+
205
+ items() {
206
+ track(this);
207
+ if (this.#isObject !== true) return EMPTY_ARRAY;
208
+ return Object.values(this.#value);
209
+ }
210
+
211
+ /* Async */
212
+
213
+ #io = null;
214
+
215
+ get io() {
216
+ if (!this.#io) {
217
+ this.#io = new AsyncDataPoint({
218
+ get: async (signal) => {
219
+ const data = await this.reader(null, {signal});
220
+ // declared full but delivered shallow → reject, so the region stays unloaded
221
+ if (this.readsFull && data?.value !== undefined && ![true, Infinity].includes(data.depth)) throw new Error(`[item.js] "${this.path.join('.')}" declares readsFull but its reader delivered depth ${data.depth}`);
222
+ return data;
223
+ },
224
+ set: (v, signal) => this.writer(v, {signal}),
225
+ });
226
+ if (this.#parent?.#io) this.#io.options = this.#parent.#io.options;
227
+ this.#io.onchange = ({value, error}) => {
228
+ if (error) return dispatch(this, "change", { error });
229
+ this.#onReceiveData(value);
230
+ }
231
+ this.#io.onpending = () => dispatch(this, "change", { pending: true });
232
+ }
233
+ return this.#io;
234
+ }
235
+
236
+ /** Item talking to the source for this one — itself, else the nearest ancestor with a hook. */
237
+ get ioOwner() {
238
+ if (this.reader || this.writer) return this;
239
+ return this.#parent?.ioOwner ?? null;
240
+ }
241
+
242
+ /** A partial write sends the owner's WHOLE region — only sound if that region is complete. */
243
+ #assertRegionLicence(owner) {
244
+ if (!owner?.writer || !owner.reader) return; // writer-only: the tree is the only truth
245
+ const why = !owner.readsFull ? 'does not declare readsFull' : !owner.loaded ? 'is not loaded, await read() first' : null;
246
+ if (why) throw new Error(`[item.js] cannot partially write "${this.path.join('.')}" — its io owner ${why}`);
247
+ }
248
+
249
+ async read(query) {
250
+ if (!query) return (this.reader || this.#io?.isPending) ? await this.io.get() : false;
251
+ // a query is a slice: bypasses io (io is always the whole value), patches, never marks loaded
252
+ if (!this.reader) throw new Error('[item.js] read(query) requires a reader');
253
+ const data = await this.reader(query);
254
+ this.#onReceiveData(data, { patch: true });
255
+ return data;
256
+ }
257
+ #onReceiveData(data, opts) {
258
+ // if (query?.depth && query.depth !== data.depth) console.log("reader depth mismatch", query.depth, data.depth);
259
+ if (data === undefined) return;
260
+ if (data?.depth !== undefined && data?.value !== undefined) {
261
+ const depth = data.depth === true ? Infinity : data.depth;
262
+ this.set(data.value, { local: true, depth, ...opts });
263
+ } else {
264
+ // A readsFull owner promises its reader delivers the whole region — merge deep.
265
+ this.set(data, { local: true, depth: this.readsFull ? Infinity : 1, ...opts });
266
+ }
267
+ }
268
+ async *[Symbol.asyncIterator]() {
269
+ for (const item of Object.values(this.#value ?? {})) {
270
+ if (!this.isObject) return; // no longer an object (or cleared)
271
+ yield item;
272
+ }
273
+ if (!this.isObject) return; // no longer an object (or cleared)
274
+ const abortCtrl = new AbortController();
275
+ const iterator = asyncIteratorFromEventTarget(this, "change", { signal: abortCtrl.signal });
276
+ this.read().then(() => abortCtrl.abort());
277
+ for await (const { add } of iterator) {
278
+ if (add) {
279
+ if (!this.isObject) return; // no longer an object (or cleared)
280
+ yield add;
281
+ }
282
+ }
283
+ }
284
+
285
+ set promise(promise) { this.io.setFromPromise(promise); }
286
+ get pending() { track(this); return this.#io?.isPending ?? false; }
287
+ get error() { track(this); return this.#io?.lastError ?? undefined; }
288
+ /** Did the region value ever arrive? An io statement, unlike `filled` (local tree, set by navigation). */
289
+ get loaded() { track(this); const o = this.ioOwner; return (o === this ? this.#io?.isLoaded : o?.loaded) ?? false; }
290
+
291
+ /* JSON Schema */
292
+
293
+ #schema = null;
294
+
295
+ setSchema(schema) {
296
+ for (let p = this.#parent; p; p = p.#parent) {
297
+ if (p.#schema) throw new Error(`[item.js] ancestor "${p.path.join('.')}" already has a schema`);
298
+ }
299
+ this.#schema = schema;
300
+ }
301
+
302
+ get schema() {
303
+ if (this.#schema != null) return this.#schema;
304
+ const p = this.#parent?.schema;
305
+ if (!p) return null;
306
+ const k = this.#key;
307
+ return (
308
+ p.properties?.[k] ??
309
+ Object.entries(p.patternProperties ?? {}).find(([pat]) => new RegExp(pat).test(k))?.[1] ??
310
+ (/^\d+$/.test(k) ? p.items : undefined) ??
311
+ p.additionalProperties ??
312
+ null
313
+ );
314
+ }
315
+
316
+ set schema(v) { throw new Error('[item.js] use setSchema() to assign a schema'); }
317
+
318
+ /* misc */
319
+
320
+ get proxy() { return toProxy(this); }
321
+
322
+ toJSON() { return this.get(); }
323
+ toString() {
324
+ if (this.#isObject) { track(this); return this.#key ?? ""; }
325
+ return String(this.get() ?? "");
326
+ }
327
+ valueOf() { return this[Symbol.toPrimitive](); }
328
+ [Symbol.toPrimitive](hint) {
329
+ if (hint === "string") return this.toString();
330
+ const value = this.#isObject ? this.#key : this.get();
331
+ return hint === "number" ? Number(value) : value;
332
+ }
333
+
334
+ ChildClass = this.constructor.ChildClass;
335
+
336
+ /* static members */
337
+
338
+ static isPrimitive(value) {
339
+ const t = typeof value;
340
+ return t !== 'object' && t !== 'function' || value === null;
341
+ }
342
+
343
+ static equals(a, b) { return Object.is(a, b); }
344
+
345
+ static ChildClass;
346
+ }
347
+
348
+ export function item(...args) {
349
+ const v = new Item();
350
+ if (args.length > 0) v.set(args[0]);
351
+ return v;
352
+ }
353
+
354
+ export function dispatch(item, eventName, options) {
355
+ const event = new ItemEvent(eventName, options);
356
+ item.dispatchEvent(event);
357
+ if (eventName === 'change') notify(item);
358
+ event.type = eventName+'In'; // reuse event object
359
+ for (let i = item; i; i = i.parent) i.dispatchEvent(event);
360
+ return event;
361
+ }
package/package.json ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "@nuxodin/item",
3
+ "version": "0.6.4",
4
+ "description": "Reactive state library",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Tobias Buschor",
8
+ "types": "./item.d.ts",
9
+ "exports": {
10
+ ".": "./item.js",
11
+ "./*": "./*"
12
+ },
13
+ "files": [
14
+ "item.js",
15
+ "item.d.ts",
16
+ "src",
17
+ "tools",
18
+ "!**/tests"
19
+ ],
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "https://github.com/nuxodin/item.js"
23
+ }
24
+ }