@nano-app/frontend 0.3.5 → 0.4.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.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +187 -0
  3. package/build/core/const.d.ts +4 -0
  4. package/build/core/const.js +9 -0
  5. package/build/core/loader/FileLoader.js +38 -0
  6. package/build/core/loader/FileReader.js +30 -0
  7. package/build/core/loader/Validator.js +70 -0
  8. package/build/core/types/objects.d.ts +4 -0
  9. package/build/core/utils/Formatter.js +14 -0
  10. package/build/creators/createController.d.ts +6 -0
  11. package/build/creators/createController.js +21 -0
  12. package/build/creators/createStores.js +15 -0
  13. package/build/index.d.ts +4 -0
  14. package/build/index.js +3 -0
  15. package/build/next.d.ts +8 -0
  16. package/build/next.js +21 -0
  17. package/build/proxy.d.ts +5 -0
  18. package/build/proxy.js +25 -0
  19. package/build/react/NanoAppProvider.d.ts +7 -0
  20. package/build/react/NanoAppProvider.js +25 -0
  21. package/build/stores/ApiStore.js +76 -0
  22. package/build/stores/Store.d.ts +15 -0
  23. package/build/stores/Store.js +33 -0
  24. package/build/types/component.d.ts +19 -0
  25. package/build/types/store.d.ts +9 -0
  26. package/package.json +53 -32
  27. package/bin/generate-stores.mjs +0 -128
  28. package/dist/auto-register.mjs +0 -327
  29. package/dist/index.d.ts +0 -10
  30. package/dist/index.js +0 -34
  31. package/dist/store/ApiStore.d.ts +0 -13
  32. package/dist/store/ApiStore.js +0 -51
  33. package/dist/store/AppStore.d.ts +0 -25
  34. package/dist/store/AppStore.js +0 -59
  35. package/dist/store/RenderManager.d.ts +0 -47
  36. package/dist/store/RenderManager.js +0 -78
  37. package/dist/store/StoreManager.d.ts +0 -15
  38. package/dist/store/StoreManager.js +0 -30
  39. package/dist/ui/Controller.d.ts +0 -20
  40. package/dist/ui/Controller.js +0 -49
  41. package/dist/ui/createComponent.d.ts +0 -17
  42. package/dist/ui/createComponent.js +0 -32
  43. package/dist/utils/QueryBuilder.d.ts +0 -19
  44. package/dist/utils/QueryBuilder.js +0 -31
  45. package/dist/utils/Toast.d.ts +0 -12
  46. package/dist/utils/Toast.js +0 -28
  47. package/dist/utils/TokenHelper.d.ts +0 -5
  48. package/dist/utils/TokenHelper.js +0 -17
@@ -1,51 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ApiStore = void 0;
4
- const AppStore_1 = require("./AppStore");
5
- const QueryBuilder_1 = require("../utils/QueryBuilder");
6
- const TokenHelper_1 = require("../utils/TokenHelper");
7
- const Toast_1 = require("../utils/Toast");
8
- class ApiStore extends AppStore_1.AppStore {
9
- baseUrl;
10
- busyCount = 0;
11
- constructor(initialData = {}, storeName = "", baseUrl = "/api") {
12
- super({}, storeName);
13
- this.baseUrl = baseUrl;
14
- }
15
- create = (entity, body) => this.request("POST", entity, body);
16
- read = async (query, params = {}) => {
17
- const path = query.split("?")[0];
18
- const response = await this.request("GET", QueryBuilder_1.QueryBuilder.build(query, params));
19
- this.set(`${path}`, response.result);
20
- return response;
21
- };
22
- update = (entity, body) => this.request("PUT", entity, body);
23
- delete = (entity, id) => this.request("DELETE", entity, id);
24
- async request(method, path, body) {
25
- let oResponse = { result: null, success: false, message: "", warning: false };
26
- this.busyCount++;
27
- this.set("/busy", true);
28
- try {
29
- oResponse = await fetch(`${this.baseUrl}${path}`, {
30
- method,
31
- headers: {
32
- "Content-Type": "application/json",
33
- Authorization: `Bearer ${TokenHelper_1.TokenHelper.get()}`,
34
- },
35
- body: body ? JSON.stringify(body) : undefined,
36
- })
37
- .then((res) => res.json())
38
- .then((res) => Toast_1.Toast.apiResponse(res));
39
- }
40
- catch (error) {
41
- console.error(error);
42
- }
43
- finally {
44
- this.busyCount--;
45
- if (this.busyCount < 1)
46
- this.set("/busy", false);
47
- }
48
- return oResponse;
49
- }
50
- }
51
- exports.ApiStore = ApiStore;
@@ -1,25 +0,0 @@
1
- export type StoreData = Record<string, any>;
2
- export declare class AppStore {
3
- protected name: string;
4
- private state;
5
- constructor(initialData?: StoreData, name?: string);
6
- /**
7
- * Gestiona el estado de la store
8
- * @param path - El path del estado
9
- * @param value - El valor a asignar
10
- * @returns El valor del estado
11
- */
12
- private manageState;
13
- /**
14
- * Obtiene el valor del estado
15
- * @param path - El path del estado
16
- * @returns El valor del estado
17
- */
18
- get(path: string): any;
19
- /**
20
- * Asigna un valor al estado
21
- * @param path - El path del estado
22
- * @param value - El valor a asignar
23
- */
24
- set(path: string, value: any): void;
25
- }
@@ -1,59 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.AppStore = void 0;
7
- const RenderManager_1 = __importDefault(require("./RenderManager"));
8
- class AppStore {
9
- name;
10
- state;
11
- constructor(initialData = {}, name = "app") {
12
- this.name = name;
13
- this.state = initialData;
14
- }
15
- /**
16
- * Gestiona el estado de la store
17
- * @param path - El path del estado
18
- * @param value - El valor a asignar
19
- * @returns El valor del estado
20
- */
21
- manageState(path, value) {
22
- // Divide el path en segmentos y obtiene el ultimo segmento
23
- const segments = path.split("/").filter(Boolean);
24
- if (segments.length === 0)
25
- return this.state;
26
- const last = segments.pop();
27
- // Recorre los segmentos y crea el objeto si no existe
28
- let current = this.state;
29
- for (const seg of segments) {
30
- if (current[seg] == null)
31
- current[seg] = {};
32
- current = current[seg];
33
- }
34
- // Si se proporciona un valor, lo asigna al ultimo segmento
35
- if (arguments.length >= 2) {
36
- current[last] = value;
37
- }
38
- // Retorna el valor del ultimo segmento
39
- return current[last];
40
- }
41
- /**
42
- * Obtiene el valor del estado
43
- * @param path - El path del estado
44
- * @returns El valor del estado
45
- */
46
- get(path) {
47
- return this.manageState(path);
48
- }
49
- /**
50
- * Asigna un valor al estado
51
- * @param path - El path del estado
52
- * @param value - El valor a asignar
53
- */
54
- set(path, value) {
55
- this.manageState(path, value);
56
- RenderManager_1.default.refresh(path, this.name);
57
- }
58
- }
59
- exports.AppStore = AppStore;
@@ -1,47 +0,0 @@
1
- type ComponentId = symbol;
2
- /**
3
- {
4
- store1: {
5
- path1: {
6
- component1: true,
7
- component2: true,
8
- },
9
- path2: {
10
- component1: true,
11
- },
12
- path3: {
13
- component1: true,
14
- },
15
- }
16
- }
17
- */
18
- export declare class RenderManager {
19
- private dependenciesMap;
20
- private hooksMap;
21
- /**
22
- * Registra un hook de re-render para un componente
23
- * @param componentId - El id del componente
24
- * @param hook - El hook de re-render
25
- */
26
- register(componentId: ComponentId, hook: () => void): void;
27
- /**
28
- * Agrega una dependencia de path a un componente
29
- * @param componentId - El id del componente
30
- * @param path - El path del estado
31
- * @param storeName - El nombre del store
32
- */
33
- dependsOn(componentId: ComponentId, path: string, storeName: string): void;
34
- /**
35
- * Actualiza los componentes que dependen de este path
36
- * @param path - El path del estado
37
- * @param storeName - El nombre del store
38
- */
39
- refresh(path: string, storeName: string): void;
40
- /**
41
- * Elimina un componente del manager
42
- * @param componentId - El id del componente
43
- */
44
- unregister(componentId: ComponentId): void;
45
- }
46
- declare const _default: RenderManager;
47
- export default _default;
@@ -1,78 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RenderManager = void 0;
4
- /**
5
- {
6
- store1: {
7
- path1: {
8
- component1: true,
9
- component2: true,
10
- },
11
- path2: {
12
- component1: true,
13
- },
14
- path3: {
15
- component1: true,
16
- },
17
- }
18
- }
19
- */
20
- class RenderManager {
21
- dependenciesMap = new Map();
22
- hooksMap = new Map();
23
- /**
24
- * Registra un hook de re-render para un componente
25
- * @param componentId - El id del componente
26
- * @param hook - El hook de re-render
27
- */
28
- register(componentId, hook) {
29
- this.hooksMap.set(componentId, hook);
30
- }
31
- /**
32
- * Agrega una dependencia de path a un componente
33
- * @param componentId - El id del componente
34
- * @param path - El path del estado
35
- * @param storeName - El nombre del store
36
- */
37
- dependsOn(componentId, path, storeName) {
38
- // Si no existe el store, crea un nuevo mapa
39
- if (!this.dependenciesMap.has(storeName)) {
40
- this.dependenciesMap.set(storeName, new Map());
41
- }
42
- // Si no existe el path, crea un nuevo conjunto
43
- if (!this.dependenciesMap.get(storeName)?.has(path)) {
44
- this.dependenciesMap.get(storeName)?.set(path, new Set());
45
- }
46
- // Agrega el componente al conjunto de dependencias
47
- this.dependenciesMap.get(storeName)?.get(path)?.add(componentId);
48
- }
49
- /**
50
- * Actualiza los componentes que dependen de este path
51
- * @param path - El path del estado
52
- * @param storeName - El nombre del store
53
- */
54
- refresh(path, storeName) {
55
- // Obtiene los componentes que dependen de este path
56
- const components = this.dependenciesMap.get(storeName)?.get(path);
57
- // Si hay componentes que dependen de este path, actualiza cada uno
58
- if (components) {
59
- components.forEach((componentId) => {
60
- this.hooksMap.get(componentId)?.();
61
- });
62
- }
63
- }
64
- /**
65
- * Elimina un componente del manager
66
- * @param componentId - El id del componente
67
- */
68
- unregister(componentId) {
69
- this.hooksMap.delete(componentId);
70
- this.dependenciesMap.forEach((store) => {
71
- store.forEach((path) => {
72
- path.delete(componentId);
73
- });
74
- });
75
- }
76
- }
77
- exports.RenderManager = RenderManager;
78
- exports.default = new RenderManager();
@@ -1,15 +0,0 @@
1
- import { ApiStore } from "./ApiStore";
2
- import { AppStore } from "./AppStore";
3
- type StoreEntry = {
4
- name: string;
5
- type: "app" | "api";
6
- path?: string;
7
- data?: Record<string, unknown>;
8
- };
9
- export declare class StoreManager {
10
- private stores;
11
- init(entries: StoreEntry[]): void;
12
- getStore(name: string): AppStore | ApiStore;
13
- }
14
- declare const _default: StoreManager;
15
- export default _default;
@@ -1,30 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.StoreManager = void 0;
4
- const ApiStore_1 = require("./ApiStore");
5
- const AppStore_1 = require("./AppStore");
6
- class StoreManager {
7
- stores = new Map();
8
- init(entries) {
9
- if (entries.length === 0) {
10
- this.stores.set("app", new AppStore_1.AppStore({}));
11
- return;
12
- }
13
- entries.forEach(entry => {
14
- if (entry.type === "api") {
15
- this.stores.set(entry.name, new ApiStore_1.ApiStore(entry.data ?? {}, entry.name, entry.path ?? "/api"));
16
- }
17
- else {
18
- this.stores.set(entry.name, new AppStore_1.AppStore(entry.data ?? {}, entry.name));
19
- }
20
- });
21
- }
22
- getStore(name) {
23
- const store = this.stores.get(name);
24
- if (!store)
25
- throw new Error(`Store "${name}" no encontrado.`);
26
- return store;
27
- }
28
- }
29
- exports.StoreManager = StoreManager;
30
- exports.default = new StoreManager();
@@ -1,20 +0,0 @@
1
- import { ApiResponse } from "@nano-app/backend";
2
- import { ReactNode } from "react";
3
- export type ReactParams = Record<string, any> & {
4
- children?: ReactNode;
5
- hook?: () => void;
6
- };
7
- export declare abstract class Controller {
8
- private componentId;
9
- constructor(hook: () => void, params: any);
10
- get<T = any>(path: string, name?: string): T;
11
- read<T = any>(path: string, params?: {}, name?: string): Promise<ApiResponse<T>>;
12
- set(path: string, value: any, name?: string): void;
13
- create<T = any>(path: string, body: any, name?: string): Promise<ApiResponse<T>>;
14
- update<T = any>(path: string, body: any, name?: string): Promise<ApiResponse<T>>;
15
- delete<T = any>(path: string, id: any, name?: string): Promise<ApiResponse<T>>;
16
- destroy(): void;
17
- onInit(params?: any): void;
18
- onRender(params?: any): void;
19
- useHooks(): void;
20
- }
@@ -1,49 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.Controller = void 0;
7
- const StoreManager_1 = __importDefault(require("../store/StoreManager"));
8
- const RenderManager_1 = __importDefault(require("../store/RenderManager"));
9
- class Controller {
10
- componentId;
11
- constructor(hook, params) {
12
- // Registra el componente para reactividad
13
- this.componentId = Symbol();
14
- RenderManager_1.default.register(this.componentId, hook);
15
- // Inicializa el controller
16
- this.onInit(params);
17
- }
18
- get(path, name = 'app') {
19
- // Registra el path como dependencia
20
- RenderManager_1.default.dependsOn(this.componentId, path, name);
21
- // Retorna el valor del store
22
- return StoreManager_1.default.getStore(name)?.get(path);
23
- }
24
- read(path, params = {}, name = 'api') {
25
- // Registra el path como dependencia
26
- RenderManager_1.default.dependsOn(this.componentId, path, name);
27
- // Retorna el valor de la api
28
- return StoreManager_1.default.getStore(name)?.read(path, params);
29
- }
30
- set(path, value, name = 'app') {
31
- StoreManager_1.default.getStore(name)?.set(path, value);
32
- }
33
- create(path, body, name = 'api') {
34
- return StoreManager_1.default.getStore(name)?.create(path, body);
35
- }
36
- update(path, body, name = 'api') {
37
- return StoreManager_1.default.getStore(name)?.update(path, body);
38
- }
39
- delete(path, id, name = 'api') {
40
- return StoreManager_1.default.getStore(name)?.delete(path, id);
41
- }
42
- destroy() {
43
- RenderManager_1.default.unregister(this.componentId);
44
- }
45
- onInit(params) { }
46
- onRender(params) { }
47
- useHooks() { }
48
- }
49
- exports.Controller = Controller;
@@ -1,17 +0,0 @@
1
- import { ReactNode } from "react";
2
- import { Controller } from "./Controller";
3
- export type ViewParams = any & {
4
- children?: ReactNode;
5
- };
6
- export type View<C> = (controller: C, params: ViewParams) => ReactNode;
7
- export type CreateComponentProps<C> = {
8
- controller?: new (hook: () => void, params: any) => C;
9
- view?: View<C>;
10
- };
11
- /**
12
- * Crea un componente reactivo que se actualiza automáticamente cuando los datos de los stores cambian.
13
- * @param ControllerClass - Clase del controller
14
- * @param view - Función que renderiza el componente
15
- * @returns - Función que retorna el componente reactivo
16
- */
17
- export declare function createComponent<C extends Controller = Controller>({ controller, view }: CreateComponentProps<C>): (params: ViewParams) => ReactNode;
@@ -1,32 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createComponent = createComponent;
4
- const react_1 = require("react");
5
- const Controller_1 = require("./Controller");
6
- class BaseController extends Controller_1.Controller {
7
- }
8
- const BaseView = (_, { children }) => children;
9
- /**
10
- * Crea un componente reactivo que se actualiza automáticamente cuando los datos de los stores cambian.
11
- * @param ControllerClass - Clase del controller
12
- * @param view - Función que renderiza el componente
13
- * @returns - Función que retorna el componente reactivo
14
- */
15
- function createComponent({ controller, view }) {
16
- return function (params) {
17
- // Hook para re-renderizar el componente
18
- const [, setTick] = (0, react_1.useState)(0);
19
- // Instancia el controller
20
- const controllerRef = (0, react_1.useRef)();
21
- if (!controllerRef.current) {
22
- controllerRef.current = new (controller || BaseController)(() => setTick((t) => t + 1), params);
23
- }
24
- // Ejecuta el método onRender del controller
25
- controllerRef.current.onRender(params);
26
- // Ejecuta las hooks del usuario
27
- controllerRef.current.useHooks();
28
- // Cleanup del componente
29
- (0, react_1.useEffect)(() => () => controllerRef.current?.destroy(), []);
30
- return view ? view(controllerRef.current, params) : BaseView(controllerRef.current, params);
31
- };
32
- }
@@ -1,19 +0,0 @@
1
- type Filter = {
2
- op: string;
3
- value: any;
4
- };
5
- export type Filters = {
6
- and?: boolean;
7
- filters?: Record<string, Filter>;
8
- };
9
- export type QueryParams = {
10
- skip?: number;
11
- top?: number;
12
- filters?: Filters;
13
- expand?: string;
14
- orderby?: string;
15
- };
16
- export declare class QueryBuilder {
17
- static build(path: string, params?: QueryParams): string;
18
- }
19
- export {};
@@ -1,31 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.QueryBuilder = void 0;
4
- function buildFilters(filters) {
5
- if (!filters)
6
- return "";
7
- return Object.entries(filters.filters ?? {})
8
- .map(([key, { op, value }]) => `${key} ${op} ${value}`)
9
- .join(filters.and ? " and " : " or ");
10
- }
11
- class QueryBuilder {
12
- static build(path, params = {}) {
13
- const { skip, filters, expand, orderby, top, ...extraParams } = params;
14
- const queryParams = [
15
- ...Object.entries(extraParams).map(([key, value]) => `${key}=${value}`)
16
- ];
17
- const filtersQuery = buildFilters(filters);
18
- if (filtersQuery)
19
- queryParams.push(`filter=${filtersQuery}`);
20
- if (expand)
21
- queryParams.push(`expand=${expand}`);
22
- if (orderby)
23
- queryParams.push(`orderby=${orderby}`);
24
- if (top != null)
25
- queryParams.push(`top=${top}`);
26
- if (skip != null)
27
- queryParams.push(`skip=${skip}`);
28
- return queryParams.length ? `${path}?${queryParams.join("&")}` : path;
29
- }
30
- }
31
- exports.QueryBuilder = QueryBuilder;
@@ -1,12 +0,0 @@
1
- import type { ApiResponse } from "@nano-app/backend";
2
- /**
3
- * Toast: implementación por defecto no-op.
4
- * La app puede reasignar los métodos (ej. Toast.error = (m) => addToast(...))
5
- * para mostrar notificaciones con su UI.
6
- */
7
- export declare class Toast {
8
- static error(_message: string): void;
9
- static success(_message: string): void;
10
- static warning(_message: string): void;
11
- static apiResponse<T>(response: ApiResponse<T>): ApiResponse<T>;
12
- }
@@ -1,28 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Toast = void 0;
4
- /**
5
- * Toast: implementación por defecto no-op.
6
- * La app puede reasignar los métodos (ej. Toast.error = (m) => addToast(...))
7
- * para mostrar notificaciones con su UI.
8
- */
9
- class Toast {
10
- static error(_message) { }
11
- static success(_message) { }
12
- static warning(_message) { }
13
- static apiResponse(response) {
14
- if (response.message) {
15
- if (response.warning) {
16
- Toast.warning(response.message);
17
- }
18
- else if (response.success) {
19
- Toast.success(response.message);
20
- }
21
- else {
22
- Toast.error(response.message);
23
- }
24
- }
25
- return response;
26
- }
27
- }
28
- exports.Toast = Toast;
@@ -1,5 +0,0 @@
1
- export declare class TokenHelper {
2
- private static TOKEN_KEY;
3
- static set(token: string): void;
4
- static get(): string;
5
- }
@@ -1,17 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TokenHelper = void 0;
4
- class TokenHelper {
5
- static TOKEN_KEY = "app_token";
6
- static set(token) {
7
- if (typeof localStorage !== "undefined") {
8
- localStorage.setItem(this.TOKEN_KEY, token);
9
- }
10
- }
11
- static get() {
12
- if (typeof localStorage === "undefined")
13
- return "";
14
- return localStorage.getItem(this.TOKEN_KEY) ?? "";
15
- }
16
- }
17
- exports.TokenHelper = TokenHelper;