@prestizni-software/client-dem 0.1.26

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.
@@ -0,0 +1,77 @@
1
+ import { Socket } from "socket.io-client";
2
+ import { AutoUpdateManager } from "./AutoUpdateManagerClass.js";
3
+ import { createAutoUpdatedClass } from "./AutoUpdatedClientObjectClass.js";
4
+ import { Constructor, IsData, LoggersType } from "./CommonTypes.js";
5
+ export type WrappedInstances<T extends Record<string, Constructor<any>>> = {
6
+ [K in keyof T]: AutoUpdateClientManager<T[K]>;
7
+ };
8
+
9
+ // ---------------------- Factory ----------------------
10
+ export async function AUCManagerFactory<
11
+ T extends Record<string, Constructor<any>>
12
+ >(defs: T, loggers: LoggersType, socket: Socket): Promise<WrappedInstances<T>> {
13
+ const classers = {} as WrappedInstances<T>;
14
+
15
+ for (const key in defs) {
16
+ const Model = defs[key];
17
+ const c = new AutoUpdateClientManager(
18
+ Model,
19
+ loggers,
20
+ socket,
21
+ classers as any
22
+ );
23
+ classers[key] = c;
24
+ }
25
+
26
+ return classers;
27
+ }
28
+
29
+ export class AutoUpdateClientManager<
30
+ T extends Constructor<any>
31
+ > extends AutoUpdateManager<T> {
32
+ constructor(
33
+ classParam: T,
34
+ loggers: LoggersType,
35
+ socket: Socket,
36
+ classers: Record<string, AutoUpdateManager<any>>
37
+ ) {
38
+ super(classParam, socket, loggers, classers);
39
+ socket.emit("startup" + classParam.name, async (data: string[]) => {
40
+ for (const id of data) {
41
+ this.classes[id] = await this.handleGetMissingObject(id);
42
+ this.classesAsArray.push(this.classes[id]);
43
+ }
44
+ });
45
+ socket.on("new" + classParam.name, async (id: string) => {
46
+ this.classes[id] = await this.handleGetMissingObject(id);
47
+ this.classesAsArray.push(this.classes[id]);
48
+ });
49
+ socket.on("delete" + classParam.name, (id: string) => {
50
+ this.deleteObject(id);
51
+ });
52
+ }
53
+
54
+ protected async handleGetMissingObject(_id: string) {
55
+ if (!this.classers) throw new Error(`No classers.`);
56
+ return await createAutoUpdatedClass(
57
+ this.classParam,
58
+ this.socket,
59
+ _id,
60
+ this.loggers,
61
+ this.classers
62
+ );
63
+ }
64
+
65
+ public async createObject(data: IsData<InstanceType<T>>) {
66
+ if (!this.classers) throw new Error(`No classers.`);
67
+ const object = await createAutoUpdatedClass(
68
+ this.classParam,
69
+ this.socket,
70
+ data,
71
+ this.loggers,
72
+ this.classers
73
+ );
74
+ this.classes[object._id as any] = object;
75
+ return object;
76
+ }
77
+ }
@@ -0,0 +1,71 @@
1
+ import { AutoUpdated } from "./AutoUpdatedClientObjectClass.js";
2
+ import { Constructor, IsData, LoggersType, SocketType } from "./CommonTypes.js";
3
+
4
+ export abstract class AutoUpdateManager<T extends Constructor<any>> {
5
+ protected classes: { [_id: string]: AutoUpdated<T> } = {};
6
+ public socket: SocketType;
7
+ protected classParam: T;
8
+ protected properties: (keyof T)[];
9
+ protected classers: Record<string, AutoUpdateManager<any>>;
10
+ protected loggers: LoggersType = {
11
+ info: () => {},
12
+ debug: () => {},
13
+ error: () => {},
14
+ warn: () => {},
15
+ };
16
+ protected classesAsArray: AutoUpdated<T>[] = [];
17
+ constructor(
18
+ classParam: T,
19
+ socket: SocketType,
20
+ loggers: LoggersType,
21
+ classers: Record<string, AutoUpdateManager<any>>
22
+ ) {
23
+ this.classers = classers;
24
+ this.socket = socket;
25
+ this.classParam = classParam;
26
+ this.properties = Reflect.getMetadata(
27
+ "props",
28
+ Object.getPrototypeOf(classParam)
29
+ );
30
+ loggers.warn = loggers.warn ?? loggers.info;
31
+ this.loggers = loggers;
32
+ }
33
+
34
+
35
+ public getObject(
36
+ _id: string
37
+ ): AutoUpdated<T> | null {
38
+ return this.classes[_id];
39
+ }
40
+
41
+ public async deleteObject(_id: string): Promise<void> {
42
+ if (typeof this.classes[_id] === "string")
43
+ this.classes[_id] = await this.handleGetMissingObject(this.classes[_id]);
44
+ (this.classes[_id]).destroy();
45
+ this.classesAsArray.splice(this.classesAsArray.indexOf(this.classes[_id]), 1);
46
+ delete this.classes[_id];
47
+ }
48
+
49
+ public get objectIDs(): string[] {
50
+ return Object.keys(this.classes);
51
+ }
52
+
53
+ public get objects(): { [_id: string]: AutoUpdated<T> | string } {
54
+ return this.classes;
55
+ }
56
+
57
+ public get objectsAsArray(): AutoUpdated<T>[] {
58
+ return this.classesAsArray;
59
+ }
60
+
61
+ public get className(): string {
62
+ return this.classParam.name;
63
+ }
64
+
65
+ protected abstract handleGetMissingObject(
66
+ _id: string
67
+ ): Promise<AutoUpdated<T>>;
68
+ public abstract createObject(
69
+ data: IsData<InstanceType<T>>
70
+ ): Promise<AutoUpdated<T>>;
71
+ }
@@ -0,0 +1,434 @@
1
+ import EventEmitter from "node:events";
2
+ import "reflect-metadata";
3
+ import {
4
+ Constructor,
5
+ DeRef,
6
+ InstanceOf,
7
+ IsData,
8
+ LoggersType,
9
+ LoggersTypeInternal,
10
+ Paths,
11
+ PathValueOf,
12
+ ServerResponse,
13
+ ServerUpdateRequest,
14
+ SocketType,
15
+ } from "./CommonTypes.js";
16
+ import { AutoUpdateManager } from "./AutoUpdateManagerClass.js";
17
+ import { ObjectId } from "bson";
18
+
19
+ export type AutoUpdated<T extends Constructor<any>> =
20
+ AutoUpdatedClientObject<T> & DeRef<InstanceOf<T>>;
21
+ export async function createAutoUpdatedClass<C extends Constructor<any>>(
22
+ classParam: C,
23
+ socket: SocketType,
24
+ data: IsData<InstanceType<C>> | string,
25
+ loggers: LoggersType,
26
+ autoClassers: { [key: string]: AutoUpdateManager<any> }
27
+ ): Promise<AutoUpdated<C>> {
28
+ if (typeof data !== "string")
29
+ processIsRefProperties(data, classParam.prototype, undefined, [], loggers);
30
+
31
+ const instance = new (class extends AutoUpdatedClientObject<C> {})(
32
+ socket,
33
+ data,
34
+ loggers,
35
+ Reflect.getMetadata("props", classParam.prototype),
36
+ classParam.name,
37
+ classParam,
38
+ autoClassers
39
+ );
40
+
41
+ await instance.isLoadedAsync();
42
+
43
+ return instance as any;
44
+ }
45
+
46
+ export abstract class AutoUpdatedClientObject<T extends Constructor<any>> {
47
+ protected readonly socket: SocketType;
48
+ //protected updates: string[] = [];
49
+ protected data: IsData<T>;
50
+ protected readonly isServer: boolean = false;
51
+ protected readonly loggers: LoggersTypeInternal = {
52
+ info: () => {},
53
+ debug: () => {},
54
+ error: () => {},
55
+ warn: () => {},
56
+ };
57
+ protected isLoading = false;
58
+ protected readonly emitter = new EventEmitter();
59
+ protected readonly properties: (keyof T)[];
60
+ protected readonly className: string;
61
+ protected autoClassers: Record<string, AutoUpdateManager<any>>;
62
+ protected isLoadingReferences = false;
63
+ public readonly classProp: Constructor<T>;
64
+
65
+ private readonly loadShit = async () => {
66
+ if (this.isLoaded()) {
67
+ try {
68
+ await this.loadForceReferences();
69
+ } catch (error) {
70
+ this.loggers.error(error);
71
+ }
72
+ this.isLoadingReferences = false;
73
+
74
+ return;
75
+ }
76
+ this.emitter.once("loaded", async () => {
77
+ try {
78
+ await this.loadForceReferences();
79
+ } catch (error) {
80
+ this.loggers.error(error);
81
+ }
82
+ this.isLoadingReferences = false;
83
+ });
84
+ };
85
+ constructor(
86
+ socket: SocketType,
87
+ data: string | IsData<T>,
88
+ loggers: LoggersType,
89
+ properties: (keyof T)[],
90
+ className: string,
91
+ classProperty: Constructor<T>,
92
+ autoClassers: Record<string, AutoUpdateManager<any>>
93
+ ) {
94
+ this.classProp = classProperty;
95
+ this.isLoadingReferences = true;
96
+ this.isLoading = true;
97
+ this.autoClassers = autoClassers;
98
+ this.className = className;
99
+ this.properties = properties;
100
+ this.loggers.debug = loggers.debug;
101
+ this.loggers.info = loggers.info;
102
+ this.loggers.error = loggers.error;
103
+ this.loggers.warn = loggers.warn ?? loggers.info;
104
+ this.socket = socket;
105
+ if (typeof data === "string") {
106
+ if (data === "")
107
+ throw new Error(
108
+ "Cannot create a new AutoUpdatedClientClass with an empty string for ID."
109
+ );
110
+ this.socket.emit(
111
+ "get" + this.className + data,
112
+ null,
113
+ (res: ServerResponse<T>) => {
114
+ if (!res.success) {
115
+ this.isLoading = false;
116
+ this.loggers.error("Could not load data from server:", res.message);
117
+ this.emitter.emit("loaded");
118
+ return;
119
+ }
120
+ this.data = res.data as IsData<T>;
121
+ this.isLoading = false;
122
+ this.emitter.emit("loaded");
123
+ }
124
+ );
125
+ this.data = { _id: data } as IsData<T>;
126
+ } else {
127
+ this.isLoading = true;
128
+ this.data = data;
129
+ if (this.data._id === "") this.handleNewObject(data);
130
+ else this.isLoading = false;
131
+ }
132
+ if (!this.isServer) this.openSockets();
133
+ this.generateSettersAndGetters();
134
+ }
135
+
136
+ protected handleNewObject(data: IsData<T>) {
137
+ this.isLoading = true;
138
+ if (!this.className)
139
+ throw new Error(
140
+ "Cannot create a new AutoUpdatedClientClass without a class name."
141
+ );
142
+ this.socket.emit("new" + this.className, data, (res: ServerResponse<T>) => {
143
+ if (!res.success) {
144
+ this.isLoading = false;
145
+ this.loggers.error("Could not create data on server:", res.message);
146
+ this.emitter.emit("loaded");
147
+ return;
148
+ }
149
+ this.data = res.data as IsData<T>;
150
+ this.isLoading = false;
151
+ this.emitter.emit("loaded");
152
+ });
153
+ }
154
+
155
+ public get extractedData(): {
156
+ [K in keyof InstanceType<T>]: InstanceOf<InstanceType<T>>[K];
157
+ } {
158
+ return structuredClone(this.data) as any as {
159
+ [K in keyof InstanceType<T>]: InstanceOf<InstanceType<T>>[K];
160
+ };
161
+ }
162
+
163
+ public isLoaded(): boolean {
164
+ return !this.isLoading;
165
+ }
166
+
167
+ public async isLoadedAsync(): Promise<boolean> {
168
+ await this.loadShit();
169
+ return this.isLoading
170
+ ? new Promise((resolve) => {
171
+ this.emitter.once("loaded", () => {
172
+ resolve(this.isLoading === false);
173
+ });
174
+ })
175
+ : true;
176
+ }
177
+
178
+ private openSockets() {
179
+ this.loggers.debug(`[${this.data._id}] Opening socket listeners`);
180
+
181
+ this.socket.on(
182
+ "update" + this.className + this.data._id,
183
+ async (update: ServerUpdateRequest<T>) => {
184
+ await this.handleUpdateRequest(update);
185
+ }
186
+ );
187
+ }
188
+ // Example server-side handler
189
+ private async handleUpdateRequest(
190
+ update: ServerUpdateRequest<T>
191
+ ): Promise<ServerResponse<undefined>> {
192
+ try {
193
+ const path = update.key.split(".");
194
+ let dataRef: any = this.data;
195
+ for (let i = 0; i < path.length - 1; i++) {
196
+ if (!dataRef[path[i]]) dataRef[path[i]] = {};
197
+ dataRef = dataRef[path[i]];
198
+ }
199
+ dataRef[path.at(-1)!] = update.value;
200
+
201
+ this.loggers.debug(
202
+ `[${this.data._id}] Applied patch ${update.key} set to ${update.value}`
203
+ );
204
+
205
+ // Return success with the applied patch
206
+ return { success: true, data: undefined, message: "" };
207
+ } catch (error) {
208
+ this.loggers.error(`[${this.data._id}] Error applying patch:`, error);
209
+ return {
210
+ success: false,
211
+ message: "Error applying update: " + (error as Error).message,
212
+ };
213
+ }
214
+ }
215
+
216
+ private generateSettersAndGetters() {
217
+ this.properties.forEach((key) => {
218
+ if (typeof key !== "string") return;
219
+
220
+ const k = key as keyof IsData<T>;
221
+ const isRef = this.getMetadataRecursive(
222
+ "isRef",
223
+ this.classProp.prototype,
224
+ key
225
+ );
226
+
227
+ Object.defineProperty(this, key, {
228
+ get: () =>
229
+ isRef ? this.findReference(this.data[k] as string) : this.data[k],
230
+ set: () => {
231
+ throw new Error(
232
+ `Cannot set ${key} this way, use "setValue" function.`
233
+ );
234
+ },
235
+ enumerable: true,
236
+ configurable: true,
237
+ });
238
+ });
239
+ }
240
+
241
+ protected findReference(id: string): AutoUpdated<any> | undefined {
242
+ for (const classer of Object.values(this.autoClassers)) {
243
+ const result = classer.getObject(id);
244
+ if (result) return result;
245
+ }
246
+ }
247
+
248
+ public async setValue<K extends Paths<InstanceOf<T>>>(
249
+ key: K,
250
+ val: PathValueOf<T, K>
251
+ ): Promise<boolean> {
252
+ let value = val as any;
253
+ this.loggers.debug(
254
+ `[${(this.data as any)._id}] Setting ${key} to ${value}`
255
+ );
256
+ try {
257
+ if (value instanceof AutoUpdatedClientObject)
258
+ value = (value as any).extractedData._id;
259
+ const path = key.split(".");
260
+ let obj = this.data as any;
261
+ let lastClass = this as any;
262
+ let lastPath = key as string;
263
+ for (let i = 0; i < path.length - 1; i++) {
264
+ if (
265
+ typeof obj[path[i]] !== "object" ||
266
+ obj[path[i]] instanceof ObjectId
267
+ ) {
268
+ let temp = this.resolveReference(
269
+ obj[path[i]].toString()
270
+ ) as AutoUpdated<any>;
271
+ if (!temp) {
272
+ return false;
273
+ }
274
+ lastClass = temp;
275
+ lastPath = path.slice(i + 1).join(".");
276
+ return await lastClass.setValue(lastPath, value);
277
+ } else obj = obj[path[i]];
278
+ }
279
+
280
+ if (lastClass !== this || lastPath !== (key as any))
281
+ throw new Error("???");
282
+
283
+ const success = await this.setValueInternal(lastPath, value);
284
+
285
+ if (!success) {
286
+ return false;
287
+ }
288
+ const pathArr = lastPath.split(".");
289
+ if (pathArr.length === 1) {
290
+ (this.data as any)[key as any] = value;
291
+ return true;
292
+ }
293
+ const pathMinusLast = pathArr.splice(0, 1);
294
+ let ref = this as any;
295
+ for (const p of pathMinusLast) {
296
+ ref = ref[p];
297
+ }
298
+ ref[pathArr.at(-1)!] = value;
299
+ return true;
300
+ } catch (error) {
301
+ this.loggers.error(error);
302
+ return false;
303
+ }
304
+ }
305
+
306
+ protected async setValueInternal(key: string, value: any): Promise<boolean> {
307
+ const update: ServerUpdateRequest<T> = this.makeUpdate(key, value);
308
+ const promise = new Promise<boolean>((resolve) => {
309
+ try {
310
+ this.socket.emit(
311
+ "update" + this.className + this.data._id,
312
+ update,
313
+ (res: ServerResponse<T>) => {
314
+ resolve(res.success);
315
+ }
316
+ );
317
+ } catch (error) {
318
+ this.loggers.error("Error sending update:", error);
319
+ resolve(false);
320
+ }
321
+ });
322
+ return promise;
323
+ }
324
+
325
+ protected makeUpdate(key: string, value: any): any {
326
+ const id = this.data._id.toString();
327
+ return { _id: id, key, value } as any;
328
+ }
329
+
330
+ private getMetadataRecursive(metaKey: string, proto: any, prop: string) {
331
+ while (proto) {
332
+ const meta = Reflect.getMetadata(metaKey, proto, prop);
333
+ if (meta !== undefined) return meta;
334
+ proto = Object.getPrototypeOf(proto);
335
+ }
336
+ return undefined;
337
+ }
338
+
339
+ // return a properly typed AutoUpdatedClientClass (or null)
340
+ // inside AutoUpdatedClientClass
341
+ protected resolveReference(id: string): AutoUpdatedClientObject<any> | null {
342
+ if (!this.autoClassers) throw new Error("No autoClassers");
343
+ for (const autoClasser of Object.values(this.autoClassers)) {
344
+ const data = autoClasser.getObject(id);
345
+ if (data) return data;
346
+ }
347
+ return null;
348
+ }
349
+
350
+ private async loadForceReferences(
351
+ obj: any = this.data,
352
+ proto: any = Object.getPrototypeOf(this)
353
+ ) {
354
+ const props: string[] = Reflect.getMetadata("props", proto) || [];
355
+
356
+ for (const key of props) {
357
+ const isRef = Reflect.getMetadata("isRef", proto, key);
358
+
359
+ if (isRef) {
360
+ await this.handleLoadOnForced(obj, key);
361
+ }
362
+
363
+ // If the property itself is a nested object, check deeper
364
+ if (obj[key] && typeof obj[key] === "object") {
365
+ const nestedProto = Object.getPrototypeOf(obj[key]);
366
+ if (nestedProto) {
367
+ await this.loadForceReferences(obj[key], nestedProto);
368
+ }
369
+ }
370
+ }
371
+ }
372
+
373
+ private async handleLoadOnForced(obj: any, key: string) {
374
+ if (!this.autoClassers) throw new Error("No autoClassers");
375
+ const refId = obj[key];
376
+ if (refId) {
377
+ for (const classer of Object.values(this.autoClassers)) {
378
+ const result = classer.getObject(refId);
379
+ if (result) {
380
+ obj[key] = result;
381
+
382
+ // Recursively load refs inside the resolved object
383
+ if (typeof result.loadForceReferences === "function") {
384
+ await result.loadForceReferences();
385
+ }
386
+ break;
387
+ }
388
+ }
389
+ }
390
+ }
391
+ public async destroy(): Promise<void> {
392
+ this.socket.emit("delete" + this.className, this.data._id);
393
+ this.wipeSelf();
394
+ }
395
+
396
+ protected wipeSelf() {
397
+ for (const key of Object.keys(this.data)) {
398
+ delete (this.data as any)[key];
399
+ }
400
+ this.loggers.info(`[${this.data._id}] ${this.className} object wiped`);
401
+ }
402
+ }
403
+
404
+ export function processIsRefProperties(
405
+ instance: any,
406
+ target: any,
407
+ prefix = "",
408
+ allProps: string[] = [],
409
+ loggers?: LoggersType
410
+ ) {
411
+ const props: string[] = Reflect.getMetadata("props", target) || [];
412
+
413
+ for (const prop of props) {
414
+ const path = prefix ? `${prefix}.${prop}` : prop;
415
+ allProps.push(path);
416
+ if (Reflect.getMetadata("isRef", target, prop)) {
417
+ // 👇 here’s where you mutate
418
+ (loggers ?? console).debug("Changing isRef:", path);
419
+
420
+ // Example: replace with a proxy or a marker object
421
+ instance[prop] = instance[prop]._id;
422
+ }
423
+
424
+ // recurse into nested objects
425
+ const type = Reflect.getMetadata("design:type", target, prop);
426
+ if (type?.prototype) {
427
+ const nestedProps = Reflect.getMetadata("props", type.prototype);
428
+ if (nestedProps && instance[prop]) {
429
+ processIsRefProperties(instance[prop], type.prototype, path, allProps);
430
+ }
431
+ }
432
+ }
433
+ return allProps;
434
+ }
package/CHANGELOG.md ADDED
@@ -0,0 +1,9 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
+
5
+ ### 0.1.26 (2025-11-04)
6
+
7
+ # Changelog
8
+
9
+ All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
package/CommonTypes.ts ADDED
@@ -0,0 +1,159 @@
1
+ import { DefaultEventsMap, Server } from "socket.io";
2
+ import { Socket as SocketClient } from "socket.io-client";
3
+ import { ObjectId } from "bson";
4
+ import { Test } from "./server.js";
5
+
6
+ export type Ref<T> = T & { _id: string };
7
+ export type LoggersTypeInternal = LoggersType & {
8
+ warn: (...args: any[]) => void;
9
+ };
10
+
11
+ export type LoggersType = {
12
+ info: (...args: any[]) => void;
13
+ debug: (...args: any[]) => void;
14
+ error: (...args: any[]) => void;
15
+ warn?: (...args: any[]) => void;
16
+ };
17
+ export type SocketType =
18
+ | SocketClient<DefaultEventsMap, DefaultEventsMap>
19
+ | Server<DefaultEventsMap, DefaultEventsMap, DefaultEventsMap, any>;
20
+ export type IsData<T> = T extends { _id: string | ObjectId } ? T : never;
21
+ export type ServerResponse<T> =
22
+ | {
23
+ data: T; // in this case, the applied patch
24
+ message: string;
25
+ success: true;
26
+ }
27
+ | {
28
+ data?: null;
29
+ message: string;
30
+ success: false;
31
+ };
32
+
33
+ export type ServerUpdateResponse<T> = {
34
+ data: Partial<IsData<T>>;
35
+ message: string;
36
+ success: true;
37
+ updateId: string;
38
+ };
39
+
40
+ export type ServerUpdateRequest<T> = {
41
+ _id: string;
42
+ key: string;
43
+ value: any;
44
+ };
45
+ export function classProp(target: any, propertyKey: string) {
46
+ const props = Reflect.getMetadata("props", target) || [];
47
+ props.push(propertyKey);
48
+ Reflect.defineMetadata("props", props, target);
49
+ }
50
+
51
+ export function classRef(target: any, propertyKey: string) {
52
+ Reflect.defineMetadata("isRef", true, target, propertyKey);
53
+ }
54
+
55
+ // ---------------------- Core ----------------------
56
+ export type AutoProps<T> = {
57
+ readonly [K in keyof T]: T[K];
58
+ };
59
+
60
+ export type Constructor<T> = new (...args: any[]) => T;
61
+ export type UnboxConstructor<T> = T extends new (...args: any[]) => infer I
62
+ ? I
63
+ : T;
64
+
65
+ // ---------------------- DeRef ----------------------
66
+ export type NonOptional<T> = Exclude<T, null | undefined>;
67
+
68
+ export type DeRef<T> = {
69
+ [K in keyof T]: T[K] extends Ref<infer U>
70
+ ? NonOptional<U>
71
+ : T[K] extends Ref<infer U> | null | undefined
72
+ ? NonOptional<U>
73
+ : NonOptional<T[K]>;
74
+ };
75
+
76
+ // ---------------------- Instance helper ----------------------
77
+ export type InstanceOf<T> = T extends Constructor<infer I> ? I : T;
78
+
79
+ // Generic filter for any desired type
80
+ export type NeededTypeAtPath<C extends Constructor<any>, T> = {
81
+ [P in Paths<C>]: PathValueOf<C, P> extends T ? P : never;
82
+ }[Paths<C>];
83
+
84
+ // ---------------------- Paths ----------------------
85
+
86
+ type Prev = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
87
+ type StripPrototypePrefix<P extends string> = P extends "prototype"
88
+ ? never
89
+ : P extends `prototype.${infer Rest}`
90
+ ? Rest
91
+ : P;
92
+
93
+ type ResolveRef<T> = T extends Ref<infer U> ? U : T;
94
+ type Recurseable<T> = T extends object
95
+ ? T extends Array<any> | Function
96
+ ? never
97
+ : T
98
+ : never;
99
+ type Join<K extends string, P extends string> = `${K}.${P}`;
100
+ type OnlyClassKeys<T> = {
101
+ [K in keyof T]: K;
102
+ }[keyof T] &
103
+ string;
104
+ // ---------------------- Paths ----------------------
105
+ export type Paths<
106
+ T,
107
+ Depth extends number = 5,
108
+ OriginalDepth extends number = Depth
109
+ > = Depth extends never
110
+ ? never
111
+ : {
112
+ [K in OnlyClassKeys<DeRef<NonOptional<T>>>]: K extends "_id"
113
+ ? StripPrototypePrefix<`${K}`>
114
+ : StripPrototypePrefix<
115
+ PathsHelper<K, DeRef<NonOptional<T>>[K], Depth, OriginalDepth>
116
+ >;
117
+ }[OnlyClassKeys<DeRef<NonOptional<T>>>];
118
+
119
+ type PathsHelper<
120
+ K extends string,
121
+ V,
122
+ Depth extends number,
123
+ OriginalDepth extends number
124
+ > = Recurseable<V> extends never
125
+ ? `${K}`
126
+ : `${K}` | Join<K, Paths<DeRef<NonOptional<V>>, Prev[Depth], OriginalDepth>>;
127
+
128
+ // ---------------------- PathValueOf ----------------------
129
+ type Split<S extends string> = S extends `${infer L}.${infer R}`
130
+ ? [L, ...Split<R>]
131
+ : [S];
132
+
133
+ type PathValue<
134
+ T,
135
+ Parts extends readonly string[],
136
+ Depth extends number = 5
137
+ > = Depth extends 0
138
+ ? any
139
+ : Parts extends [infer K, ...infer Rest]
140
+ ? K extends keyof T
141
+ ? Rest extends readonly string[]
142
+ ? Rest["length"] extends 0
143
+ ? ResolveRef<T[K]>
144
+ : PathValue<ResolveRef<T[K]>, Rest, Prev[Depth]>
145
+ : never
146
+ : never
147
+ : T;
148
+
149
+ export type PathValueOf<
150
+ T,
151
+ P extends string,
152
+ Depth extends number = 5
153
+ > = PathValue<DeRef<InstanceOf<T>>, Split<P>, Depth>;
154
+
155
+ // ---------------------- Pretty ----------------------
156
+ export type Pretty<T> = { [K in keyof T]: T[K] };
157
+
158
+ let test1: Paths<Test> = "test2";
159
+ let test2: PathValueOf<Test, "test2.loggers2">;
package/README.md ADDED
Binary file
package/client.ts ADDED
@@ -0,0 +1,120 @@
1
+ import { io } from "socket.io-client";
2
+ import readline from "readline";
3
+ import { classProp, classRef, LoggersType } from "./CommonTypes.js";
4
+ import { AUCManagerFactory } from "./AutoUpdateClientManagerClass.js";
5
+
6
+ class Test2 {
7
+ @classProp public _id!: string;
8
+ @classProp public login!: string;
9
+ @classProp public loggers!: LoggersType;
10
+ public func = () => {
11
+ console.log("func");
12
+ };
13
+ }
14
+
15
+ class Test {
16
+ @classProp public _id!: string;
17
+ @classProp public login!: string[];
18
+ @classProp public loggers!: LoggersType;
19
+
20
+ // mark as compile-time Ref<Test2> (runtime is still string id)
21
+ @classProp @classRef public test2!: Test2;
22
+
23
+ // force-loaded ref
24
+ @classProp @classRef public test3!: Test2;
25
+ }
26
+ const loggers: LoggersType = {
27
+ info: console.log,
28
+ debug: console.debug,
29
+ error: console.error,
30
+ warn: console.warn,
31
+ };
32
+
33
+ const socket = io("http://localhost:3000", {
34
+ extraHeaders: {
35
+ //HEADRY
36
+ Authorization: "Bearer " + "token",
37
+ },
38
+ });
39
+ socket.on("connect", async () => {
40
+
41
+ const classers = await AUCManagerFactory({ Test, Test2 }, loggers, socket);
42
+
43
+ // ---------------------- Setup CLI ----------------------
44
+ const rl = readline.createInterface({
45
+ input: process.stdin,
46
+ output: process.stdout,
47
+ });
48
+
49
+ setTimeout(async () => {
50
+ const ass = ((classers).Test.getObject("68c9f23872cff1778cb1abe2"));
51
+ ass?.test2.loggers.info("test");
52
+ ass?.test2.func();
53
+ }, 100);
54
+
55
+ // ---------------------- Interactive CLI ----------------------
56
+ function prompt() {
57
+ rl.question(
58
+ "\nCommands:\n[list] List all collections\n[show <collection> <id> <field?>] Show object\n[set <collection> <id> <field> <value>] Update field\n[new <collection>] Request new object\n[exit] Exit\n> ",
59
+ async (input) => {
60
+ const args = input.trim().split(" ");
61
+ const cmd = args[0];
62
+
63
+ switch (cmd) {
64
+ case "list":
65
+ console.log("Collections:");
66
+ for (const classer of Object.values(classers)) {
67
+ console.log(`- ${classer.className}`);
68
+ for (const id of classer.objectIDs) {
69
+ console.log(` • ${id}`);
70
+ }
71
+ }
72
+ break;
73
+
74
+ case "show":
75
+ if (args.length < 3)
76
+ return console.log("❌ Usage: show <collection> <id> <field?>");
77
+
78
+ const objShow = await (classers as any)[args[1]]?.getClass(args[2]);
79
+ if (!objShow) return console.log("❌ Collection not found");
80
+
81
+ if (args[3]) {
82
+ const val = objShow.getValue(args[3]);
83
+ console.log(val !== undefined ? val : "❌ Field not found");
84
+ } else {
85
+ console.log(objShow.extractData);
86
+ }
87
+ break;
88
+
89
+ case "set":
90
+ if (args.length < 5)
91
+ return console.log(
92
+ "❌ Usage: set <collection> <id> <field> <value>"
93
+ );
94
+
95
+ const objSet = await (classers as any)[args[1]]?.getClass(args[2]);
96
+ if (!objSet) return console.log("❌ Object not found");
97
+
98
+ const fieldPath = args[3];
99
+ const value = args.slice(4).join(" "); // allow spaces in value
100
+
101
+ if (fieldPath === "_id") return console.log("❌ Cannot change _id");
102
+
103
+ objSet.setValue(fieldPath, value);
104
+ console.log(`✅ Updated ${fieldPath} = ${value}`);
105
+ break;
106
+
107
+ case "exit":
108
+ console.log("👋 Exiting...");
109
+ process.exit(0);
110
+
111
+ default:
112
+ console.log("❌ Unknown command");
113
+ }
114
+
115
+ prompt();
116
+ }
117
+ );
118
+ }
119
+ prompt();
120
+ });
package/package.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "@prestizni-software/client-dem",
3
+ "version": "0.1.26",
4
+ "description": "An solution for when making http requests is not a good solution",
5
+ "keywords": [
6
+ "websockets"
7
+ ],
8
+ "license": "ISC",
9
+ "author": "xx0055",
10
+ "type": "module",
11
+ "main": "none",
12
+ "publishConfig": {
13
+ "access": "public",
14
+ "registry": "https://registry.npmjs.org/"
15
+ },
16
+ "scripts": {
17
+ "release": "standard-version && git push --follow-tags && npm publish --access public"
18
+ },
19
+ "dependencies": {
20
+ "socket.io": "^4.8.1",
21
+ "socket.io-client": "^4.8.1"
22
+ }
23
+ }