@alwatr/nitrobase-user-management 7.5.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.
package/README.md ADDED
@@ -0,0 +1,101 @@
1
+ # Nitrobase User Management
2
+
3
+ User management module for Nitrobase, providing user creation, authentication, and data management capabilities.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @alwatr/nitrobase
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```typescript
14
+ import {AlwatrNitrobase, NitrobaseUserManagement, type NewUser} from '@alwatr/nitrobase';
15
+
16
+ // Define your user data structure
17
+ interface MyUserData {
18
+ name: string;
19
+ email: string;
20
+ // ... other properties
21
+ }
22
+
23
+ // Initialize Nitrobase
24
+ const nitrobase = new AlwatrNitrobase({
25
+ // ... your nitrobase configuration
26
+ });
27
+
28
+ // Initialize User Management
29
+ await NitrobaseUserManagement.initialize(nitrobase);
30
+
31
+ const userManagement = new NitrobaseUserManagement<MyUserData>(nitrobase);
32
+
33
+ // Create a new user
34
+ const newUser: NewUser<MyUserData> = {
35
+ userId: 'user123',
36
+ userToken: 'some_secure_token',
37
+ data: {
38
+ name: 'John Doe',
39
+ email: 'john.doe@example.com',
40
+ },
41
+ };
42
+
43
+ await userManagement.newUser(newUser);
44
+
45
+ // Check if a user exists
46
+ const userExists = await userManagement.hasUser('user123');
47
+ console.log('User exists:', userExists); // Output: User exists: true
48
+
49
+ // Get user data
50
+ const userData = await userManagement.getUserData('user123');
51
+ console.log('User data:', userData); // Output: User data: { name: 'John Doe', email: 'john.doe@example.com' }
52
+
53
+ // Verify user token
54
+ const isValidToken = await userManagement.verifyUserToken('user123', 'some_secure_token');
55
+ console.log('Is valid token:', isValidToken); // Output: Is valid token: true
56
+
57
+ // Save user data (after modifications)
58
+ userData.email = 'john.updated@example.com'
59
+ userManagement.save('user123') // Background save
60
+ userManagement.saveImmediate('user123') // Immediate save (blocking)
61
+
62
+
63
+ // Get all user IDs
64
+ const userIds = await userManagement.userIds();
65
+ for await (const userId of userIds) {
66
+ console.log('User ID:', userId);
67
+ }
68
+
69
+ // Get user directory
70
+ const userDir = await userManagement.getUserDirectory('user123');
71
+ console.log('User directory:', userDir);
72
+ ```
73
+
74
+ ## API
75
+
76
+ ### `NitrobaseUserManagement`
77
+
78
+ - **`static initialize(nitrobase: AlwatrNitrobase): Promise<void>`:** Initializes the user management module. Must be called before creating a `NitrobaseUserManagement` instance.
79
+ - **`newUser(user: NewUser<TUser>): Promise<void>`:** Creates a new user with the provided data and token. Sets up necessary storage and metadata.
80
+ - **`hasUser(userId: string): Promise<boolean>`:** Checks if a user with the given ID exists.
81
+ - **`getUserData(userId: string): Promise<TUser>`:** Retrieves the data associated with the given user ID.
82
+ - **`getUserMeta(userId: string): Promise<Readonly<StoreFileMeta>>`:** Retrieves metadata about the user's stored information.
83
+ - **`verifyUserToken(userId: string, token: string): Promise<boolean>`:** Verifies the provided token against the stored token for the user.
84
+ - **`save(userId: string): void`:** Saves any changes to the user's data. This operation is non-blocking.
85
+ - **`saveImmediate(userId: string): void`:** Immediately saves changes to the user's data. This operation is blocking.
86
+ - **`userIds(): Promise<Generator<string, void, void>>`:** Returns an asynchronous generator that yields all user IDs.
87
+ - **`getUserDirectory(userId: string): Promise<string>`:** Retrieves the file system directory associated with the user.
88
+
89
+ ## Types
90
+
91
+ - **`NewUser<TUser extends JsonObject>`:** Represents the data required to create a new user. Includes user ID, token, and user-specific data.
92
+
93
+ ## Contributing
94
+
95
+ Contributions are welcome! Please read our [contribution guidelines](https://github.com/Alwatr/.github/blob/next/CONTRIBUTING.md) before submitting a pull request.
96
+
97
+ ## License
98
+
99
+ This project is licensed under the [AGPL-3.0 License](LICENSE).
100
+
101
+ ```
@@ -0,0 +1,2 @@
1
+ export declare const logger: import("@alwatr/logger").AlwatrLogger;
2
+ //# sourceMappingURL=logger.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,MAAM,uCAAiD,CAAC"}
package/dist/main.cjs ADDED
@@ -0,0 +1,182 @@
1
+ /* @alwatr/nitrobase-user-management v7.5.0 */
2
+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/main.ts
22
+ var main_exports = {};
23
+ __export(main_exports, {
24
+ NitrobaseUserManagement: () => NitrobaseUserManagement
25
+ });
26
+ module.exports = __toCommonJS(main_exports);
27
+
28
+ // src/user-management.ts
29
+ var import_node_path = require("node:path");
30
+ var import_nanolib2 = require("@alwatr/nanolib");
31
+ var import_node_fs = require("@alwatr/nanolib/node-fs");
32
+ var import_nitrobase_types = require("@alwatr/nitrobase-types");
33
+
34
+ // src/logger.ts
35
+ var import_nanolib = require("@alwatr/nanolib");
36
+ __dev_mode__: import_nanolib.packageTracer.add("@alwatr/nitrobase-user-management", "7.5.0");
37
+ var logger = /* @__PURE__ */ (0, import_nanolib.createLogger)("@alwatr/nitrobase-user-management");
38
+
39
+ // src/user-management.ts
40
+ var _NitrobaseUserManagement = class _NitrobaseUserManagement {
41
+ /**
42
+ * Create a new instance of NitrobaseUserManagement.
43
+ * @param nitrobase_ The Nitrobase instance.
44
+ */
45
+ constructor(nitrobase_) {
46
+ this.nitrobase_ = nitrobase_;
47
+ this.logger_ = (0, import_nanolib2.createLogger)("user-management");
48
+ this.logger_.logMethod?.("constructor");
49
+ this.userListCollection_ = this.nitrobase_.openCollection(_NitrobaseUserManagement.nitrobaseIds.userList);
50
+ }
51
+ /**
52
+ * Initialize the user management module.
53
+ * @param nitrobase The Nitrobase instance.
54
+ */
55
+ static async initialize(nitrobase) {
56
+ logger.logMethod?.("NitrobaseUserManagement.initialize");
57
+ nitrobase.newCollection(this.nitrobaseIds.userList);
58
+ }
59
+ // Implementation of NitrobaseUserManagementInterface methods with JSDoc comments
60
+ async newUser(user) {
61
+ this.logger_.logMethodArgs?.("newUser", user);
62
+ (await this.userListCollection_).addItem(user.userId, {});
63
+ this.newUserInfoDocument_(user.userId, user.data);
64
+ await this.makeTokenFile_(user.userId, user.userToken, user.isManager);
65
+ }
66
+ async hasUser(userId) {
67
+ const userExists = (await this.userListCollection_).hasItem(userId);
68
+ this.logger_.logMethodFull?.("hasUser", { userId }, userExists);
69
+ return userExists;
70
+ }
71
+ async getUserData(userId) {
72
+ this.logger_.logMethodArgs?.("getUserData", userId);
73
+ const userInfoDocument = await this.openUserInfoDocument_(userId);
74
+ return userInfoDocument.getData();
75
+ }
76
+ async getUserMeta(userId) {
77
+ this.logger_.logMethodArgs?.("getUserMeta", userId);
78
+ const document = await this.openUserInfoDocument_(userId);
79
+ return document.getStoreMeta();
80
+ }
81
+ save(userId) {
82
+ this.logger_.logMethodArgs?.("save", userId);
83
+ this.openUserInfoDocument_(userId).then((document) => {
84
+ document.save();
85
+ });
86
+ }
87
+ saveImmediate(userId) {
88
+ this.logger_.logMethodArgs?.("saveImmediate", userId);
89
+ this.openUserInfoDocument_(userId).then((document) => {
90
+ document.saveImmediate();
91
+ });
92
+ }
93
+ async userIds() {
94
+ return (await this.userListCollection_).ids();
95
+ }
96
+ async verifyUserToken(userId, token) {
97
+ const tokenFileExist = (0, import_node_fs.existsSync)(await this.getUserTokenFilePath_(userId, token));
98
+ this.logger_.logMethodFull?.("verifyUserToken", { userId, token: token.slice(0, 12) + "..." }, tokenFileExist);
99
+ return tokenFileExist;
100
+ }
101
+ async getUserDirectory(userId) {
102
+ const userInfoDocument = await this.openUserInfoDocument_(userId);
103
+ const userDirectoryPath = (0, import_node_path.dirname)((0, import_node_path.resolve)(this.nitrobase_.config.rootPath, userInfoDocument.path));
104
+ this.logger_.logMethodFull?.("getUserDirectory", { userId }, userDirectoryPath);
105
+ return userDirectoryPath;
106
+ }
107
+ /**
108
+ * Create a new user info document.
109
+ * @param userId The user ID.
110
+ * @param userInfo The user info data.
111
+ */
112
+ newUserInfoDocument_(userId, userInfo) {
113
+ this.logger_.logMethodArgs?.("newUserInfoDocument", { userId, userInfo });
114
+ const storeId = {
115
+ ..._NitrobaseUserManagement.nitrobaseIds.userInfo,
116
+ ownerId: userId
117
+ };
118
+ if (this.nitrobase_.hasStore(storeId)) {
119
+ this.logger_.accident?.("newUserInfoDocument_", "store_already_exists", storeId);
120
+ return;
121
+ }
122
+ this.nitrobase_.newDocument(storeId, userInfo);
123
+ }
124
+ /**
125
+ * Open the user info document.
126
+ * @param userId The user ID.
127
+ * @returns A promise resolving to the user info document.
128
+ */
129
+ openUserInfoDocument_(userId) {
130
+ this.logger_.logMethodArgs?.("openUserInfoDocument_", userId);
131
+ return this.nitrobase_.openDocument({
132
+ ..._NitrobaseUserManagement.nitrobaseIds.userInfo,
133
+ ownerId: userId
134
+ });
135
+ }
136
+ /**
137
+ * Create a token file for the user.
138
+ * @param userId The user ID.
139
+ * @param token The user token.
140
+ * @param isManager Whether the user is a manager.
141
+ */
142
+ async makeTokenFile_(userId, token, isManager) {
143
+ this.logger_.logMethodArgs?.("makeTokenFile", { userId, token: token.slice(0, 12) + "...", isManager });
144
+ const userDirectory = await this.getUserDirectory(userId);
145
+ await (0, import_node_fs.makeEmptyFile)((0, import_node_path.resolve)(userDirectory, `.token/${token}.asn`));
146
+ if (isManager === true) {
147
+ await (0, import_node_fs.makeEmptyFile)((0, import_node_path.resolve)(userDirectory, ".auth/manager.asn"));
148
+ }
149
+ }
150
+ /**
151
+ * Get the path to the user token file.
152
+ * @param userId The user ID.
153
+ * @param token The user token.
154
+ * @returns The path to the user token file.
155
+ */
156
+ async getUserTokenFilePath_(userId, token) {
157
+ const userTokenFilePath = (0, import_node_path.resolve)(await this.getUserDirectory(userId), `.token/${token}.asn`);
158
+ this.logger_.logMethodFull?.("getTokenFilePath", { userId, token: token.slice(0, 12) + "..." }, userTokenFilePath);
159
+ return userTokenFilePath;
160
+ }
161
+ };
162
+ /**
163
+ * Default Nitrobase store IDs used by this class.
164
+ */
165
+ _NitrobaseUserManagement.nitrobaseIds = {
166
+ userList: {
167
+ name: "user-list",
168
+ region: import_nitrobase_types.Region.Managers,
169
+ schemaVer: 1
170
+ },
171
+ userInfo: {
172
+ name: "user-info",
173
+ region: import_nitrobase_types.Region.PerUser
174
+ }
175
+ };
176
+ var NitrobaseUserManagement = _NitrobaseUserManagement;
177
+ // Annotate the CommonJS export names for ESM import in node:
178
+ 0 && (module.exports = {
179
+ NitrobaseUserManagement
180
+ });
181
+ /*! For license information please see main.cjs.LEGAL.txt */
182
+ //# sourceMappingURL=main.cjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/main.ts", "../src/user-management.ts", "../src/logger.ts"],
4
+ "sourcesContent": ["export * from './user-management.js';\n", "import {dirname, resolve} from 'node:path';\n\nimport {createLogger} from '@alwatr/nanolib';\nimport {existsSync, makeEmptyFile} from '@alwatr/nanolib/node-fs';\nimport {Region, type AlwatrAuth, type StoreFileId, type StoreFileMeta} from '@alwatr/nitrobase-types';\n\nimport {logger} from './logger.js';\n\nimport type {AlwatrNitrobase} from '@alwatr/nitrobase-engine';\nimport type {DocumentReference} from '@alwatr/nitrobase-reference';\n\n/**\n * New user data type.\n */\nexport type NewUser<TUser extends JsonObject> = AlwatrAuth & {\n data: TUser;\n isManager?: true;\n};\n\n/**\n * Nitrobase User Management Interface.\n */\ninterface NitrobaseUserManagementInterface<TUser extends JsonObject> {\n\n /**\n * Create a new user.\n * @param user The new user data.\n */\n newUser(user: NewUser<TUser>): Promise<void>;\n\n /**\n * Check if a user exists.\n * @param userId The user ID.\n * @returns True if the user exists, false otherwise.\n */\n hasUser(userId: string): Promise<boolean>;\n\n /**\n * Get user data.\n * @param userId The user ID.\n * @returns The user data.\n */\n getUserData(userId: string): Promise<TUser>;\n\n /**\n * Get user meta data.\n * @param userId The user ID.\n * @returns The user meta data.\n */\n getUserMeta(userId: string): Promise<Readonly<StoreFileMeta>>;\n\n /**\n * Verify user token.\n * @param userId The user ID.\n * @param token The user token.\n * @returns True if the token is valid, false otherwise.\n */\n verifyUserToken(userId: string, token: string): Promise<boolean>;\n\n\n /**\n * Save user data to storage.\n * @param userId The user ID.\n */\n save(userId: string): void;\n\n /**\n * Immediately save user data to storage.\n * @param userId The user ID.\n */\n saveImmediate(userId: string): void;\n\n /**\n * Get all user IDs.\n * @returns An async generator of user IDs.\n */\n userIds(): Promise<Generator<string, void, void>>;\n\n /**\n * Get the user directory path.\n * @param userId The user ID.\n * @returns The user directory path.\n */\n getUserDirectory(userId: string): Promise<string>;\n}\n\n/**\n * Nitrobase User Management Class.\n * Manages user data and authentication.\n */\nexport class NitrobaseUserManagement<TUser extends JsonObject> implements NitrobaseUserManagementInterface<TUser> {\n\n /**\n * Default Nitrobase store IDs used by this class.\n */\n static readonly nitrobaseIds = {\n userList: {\n name: 'user-list',\n region: Region.Managers,\n schemaVer: 1,\n } as Readonly<StoreFileId>,\n\n userInfo: {\n name: 'user-info',\n region: Region.PerUser,\n } as Readonly<StoreFileId>,\n } as const;\n\n /**\n * Initialize the user management module.\n * @param nitrobase The Nitrobase instance.\n */\n static async initialize(nitrobase: AlwatrNitrobase): Promise<void> {\n logger.logMethod?.('NitrobaseUserManagement.initialize');\n nitrobase.newCollection(this.nitrobaseIds.userList);\n }\n\n protected logger_ = createLogger('user-management');\n\n protected userListCollection_;\n\n /**\n * Create a new instance of NitrobaseUserManagement.\n * @param nitrobase_ The Nitrobase instance.\n */\n constructor(\n protected readonly nitrobase_: AlwatrNitrobase,\n ) {\n this.logger_.logMethod?.('constructor');\n this.userListCollection_ = this.nitrobase_.openCollection(NitrobaseUserManagement.nitrobaseIds.userList);\n }\n\n\n\n // Implementation of NitrobaseUserManagementInterface methods with JSDoc comments\n\n async newUser(user: NewUser<TUser>): Promise<void> {\n this.logger_.logMethodArgs?.('newUser', user);\n\n (await this.userListCollection_).addItem(user.userId, {});\n\n this.newUserInfoDocument_(user.userId, user.data);\n\n await this.makeTokenFile_(user.userId, user.userToken, user.isManager);\n }\n\n async hasUser(userId: string): Promise<boolean> {\n const userExists = (await this.userListCollection_).hasItem(userId);\n this.logger_.logMethodFull?.('hasUser', {userId}, userExists);\n return userExists;\n }\n\n async getUserData(userId: string): Promise<TUser> {\n this.logger_.logMethodArgs?.('getUserData', userId);\n const userInfoDocument = await this.openUserInfoDocument_(userId);\n return userInfoDocument.getData();\n }\n\n async getUserMeta(userId: string): Promise<Readonly<StoreFileMeta>> {\n this.logger_.logMethodArgs?.('getUserMeta', userId);\n const document = await this.openUserInfoDocument_(userId);\n return document.getStoreMeta();\n }\n\n save(userId: string): void {\n this.logger_.logMethodArgs?.('save', userId);\n this.openUserInfoDocument_(userId).then((document) => {\n document.save();\n });\n }\n\n saveImmediate(userId: string): void {\n this.logger_.logMethodArgs?.('saveImmediate', userId);\n this.openUserInfoDocument_(userId).then((document) => {\n document.saveImmediate();\n });\n }\n\n async userIds(): Promise<Generator<string, void, void>> {\n return (await this.userListCollection_).ids();\n }\n\n async verifyUserToken(userId: string, token: string): Promise<boolean> {\n const tokenFileExist = existsSync(await this.getUserTokenFilePath_(userId, token));\n this.logger_.logMethodFull?.('verifyUserToken', {userId, token: token.slice(0, 12) + '...'}, tokenFileExist);\n return tokenFileExist;\n }\n\n async getUserDirectory(userId: string): Promise<string> {\n const userInfoDocument = await this.openUserInfoDocument_(userId);\n const userDirectoryPath = dirname(resolve(this.nitrobase_.config.rootPath, userInfoDocument.path));\n this.logger_.logMethodFull?.('getUserDirectory', {userId}, userDirectoryPath);\n return userDirectoryPath;\n }\n\n /**\n * Create a new user info document.\n * @param userId The user ID.\n * @param userInfo The user info data.\n */\n protected newUserInfoDocument_(userId: string, userInfo: TUser): void {\n this.logger_.logMethodArgs?.('newUserInfoDocument', {userId, userInfo});\n const storeId: StoreFileId = {\n ...NitrobaseUserManagement.nitrobaseIds.userInfo,\n ownerId: userId,\n };\n if (this.nitrobase_.hasStore(storeId)) {\n this.logger_.accident?.('newUserInfoDocument_', 'store_already_exists', storeId);\n return;\n }\n this.nitrobase_.newDocument<TUser>(storeId, userInfo);\n }\n\n /**\n * Open the user info document.\n * @param userId The user ID.\n * @returns A promise resolving to the user info document.\n */\n protected openUserInfoDocument_(userId: string): Promise<DocumentReference<TUser>> {\n this.logger_.logMethodArgs?.('openUserInfoDocument_', userId);\n return this.nitrobase_.openDocument<TUser>({\n ...NitrobaseUserManagement.nitrobaseIds.userInfo,\n ownerId: userId,\n });\n }\n\n /**\n * Create a token file for the user.\n * @param userId The user ID.\n * @param token The user token.\n * @param isManager Whether the user is a manager.\n */\n protected async makeTokenFile_(userId: string, token: string, isManager?: true): Promise<void> {\n this.logger_.logMethodArgs?.('makeTokenFile', {userId, token: token.slice(0, 12) + '...', isManager});\n const userDirectory = await this.getUserDirectory(userId);\n\n await makeEmptyFile(resolve(userDirectory, `.token/${token}.asn`));\n\n if (isManager === true) {\n await makeEmptyFile(resolve(userDirectory, '.auth/manager.asn'));\n }\n }\n\n /**\n * Get the path to the user token file.\n * @param userId The user ID.\n * @param token The user token.\n * @returns The path to the user token file.\n */\n protected async getUserTokenFilePath_(userId: string, token: string): Promise<string> {\n const userTokenFilePath = resolve(await this.getUserDirectory(userId), `.token/${token}.asn`);\n this.logger_.logMethodFull?.('getTokenFilePath', {userId, token: token.slice(0, 12) + '...'}, userTokenFilePath);\n return userTokenFilePath;\n }\n}\n", "import {createLogger, packageTracer} from '@alwatr/nanolib';\n\n__dev_mode__: packageTracer.add(__package_name__, __package_version__);\n\nexport const logger = /* #__PURE__ */ createLogger(__package_name__);\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,uBAA+B;AAE/B,IAAAA,kBAA2B;AAC3B,qBAAwC;AACxC,6BAA4E;;;ACJ5E,qBAA0C;AAE1C,aAAc,8BAAc,IAAI,qCAAkB,OAAmB;AAE9D,IAAM,SAAyB,iDAAa,mCAAgB;;;ADsF5D,IAAM,2BAAN,MAAM,yBAAqG;AAAA;AAAA;AAAA;AAAA;AAAA,EAmChH,YACqB,YACnB;AADmB;AATrB,SAAU,cAAU,8BAAa,iBAAiB;AAWhD,SAAK,QAAQ,YAAY,aAAa;AACtC,SAAK,sBAAsB,KAAK,WAAW,eAAe,yBAAwB,aAAa,QAAQ;AAAA,EACzG;AAAA;AAAA;AAAA;AAAA;AAAA,EAlBA,aAAa,WAAW,WAA2C;AACjE,WAAO,YAAY,oCAAoC;AACvD,cAAU,cAAc,KAAK,aAAa,QAAQ;AAAA,EACpD;AAAA;AAAA,EAqBA,MAAM,QAAQ,MAAqC;AACjD,SAAK,QAAQ,gBAAgB,WAAW,IAAI;AAE5C,KAAC,MAAM,KAAK,qBAAqB,QAAQ,KAAK,QAAQ,CAAC,CAAC;AAExD,SAAK,qBAAqB,KAAK,QAAQ,KAAK,IAAI;AAEhD,UAAM,KAAK,eAAe,KAAK,QAAQ,KAAK,WAAW,KAAK,SAAS;AAAA,EACvE;AAAA,EAEA,MAAM,QAAQ,QAAkC;AAC9C,UAAM,cAAc,MAAM,KAAK,qBAAqB,QAAQ,MAAM;AAClE,SAAK,QAAQ,gBAAgB,WAAW,EAAC,OAAM,GAAG,UAAU;AAC5D,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,YAAY,QAAgC;AAChD,SAAK,QAAQ,gBAAgB,eAAe,MAAM;AAClD,UAAM,mBA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,8BAAO;AAAA,IACf,WAAW;AAAA,EACb;AAAA,EAEA,UAAU;AAAA,IACR,MAAM;AAAA,IACN,QAAQ,8BAAO;AAAA,EACjB;AACF;AAhBK,IAAM,0BAAN;",
6
+ "names": ["import_nanolib"]
7
+ }
package/dist/main.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './user-management.js';
2
+ //# sourceMappingURL=main.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA,cAAc,sBAAsB,CAAC"}
package/dist/main.mjs ADDED
@@ -0,0 +1,156 @@
1
+ /* @alwatr/nitrobase-user-management v7.5.0 */
2
+
3
+ // src/user-management.ts
4
+ import { dirname, resolve } from "node:path";
5
+ import { createLogger as createLogger2 } from "@alwatr/nanolib";
6
+ import { existsSync, makeEmptyFile } from "@alwatr/nanolib/node-fs";
7
+ import { Region } from "@alwatr/nitrobase-types";
8
+
9
+ // src/logger.ts
10
+ import { createLogger, packageTracer } from "@alwatr/nanolib";
11
+ __dev_mode__: packageTracer.add("@alwatr/nitrobase-user-management", "7.5.0");
12
+ var logger = /* @__PURE__ */ createLogger("@alwatr/nitrobase-user-management");
13
+
14
+ // src/user-management.ts
15
+ var _NitrobaseUserManagement = class _NitrobaseUserManagement {
16
+ /**
17
+ * Create a new instance of NitrobaseUserManagement.
18
+ * @param nitrobase_ The Nitrobase instance.
19
+ */
20
+ constructor(nitrobase_) {
21
+ this.nitrobase_ = nitrobase_;
22
+ this.logger_ = createLogger2("user-management");
23
+ this.logger_.logMethod?.("constructor");
24
+ this.userListCollection_ = this.nitrobase_.openCollection(_NitrobaseUserManagement.nitrobaseIds.userList);
25
+ }
26
+ /**
27
+ * Initialize the user management module.
28
+ * @param nitrobase The Nitrobase instance.
29
+ */
30
+ static async initialize(nitrobase) {
31
+ logger.logMethod?.("NitrobaseUserManagement.initialize");
32
+ nitrobase.newCollection(this.nitrobaseIds.userList);
33
+ }
34
+ // Implementation of NitrobaseUserManagementInterface methods with JSDoc comments
35
+ async newUser(user) {
36
+ this.logger_.logMethodArgs?.("newUser", user);
37
+ (await this.userListCollection_).addItem(user.userId, {});
38
+ this.newUserInfoDocument_(user.userId, user.data);
39
+ await this.makeTokenFile_(user.userId, user.userToken, user.isManager);
40
+ }
41
+ async hasUser(userId) {
42
+ const userExists = (await this.userListCollection_).hasItem(userId);
43
+ this.logger_.logMethodFull?.("hasUser", { userId }, userExists);
44
+ return userExists;
45
+ }
46
+ async getUserData(userId) {
47
+ this.logger_.logMethodArgs?.("getUserData", userId);
48
+ const userInfoDocument = await this.openUserInfoDocument_(userId);
49
+ return userInfoDocument.getData();
50
+ }
51
+ async getUserMeta(userId) {
52
+ this.logger_.logMethodArgs?.("getUserMeta", userId);
53
+ const document = await this.openUserInfoDocument_(userId);
54
+ return document.getStoreMeta();
55
+ }
56
+ save(userId) {
57
+ this.logger_.logMethodArgs?.("save", userId);
58
+ this.openUserInfoDocument_(userId).then((document) => {
59
+ document.save();
60
+ });
61
+ }
62
+ saveImmediate(userId) {
63
+ this.logger_.logMethodArgs?.("saveImmediate", userId);
64
+ this.openUserInfoDocument_(userId).then((document) => {
65
+ document.saveImmediate();
66
+ });
67
+ }
68
+ async userIds() {
69
+ return (await this.userListCollection_).ids();
70
+ }
71
+ async verifyUserToken(userId, token) {
72
+ const tokenFileExist = existsSync(await this.getUserTokenFilePath_(userId, token));
73
+ this.logger_.logMethodFull?.("verifyUserToken", { userId, token: token.slice(0, 12) + "..." }, tokenFileExist);
74
+ return tokenFileExist;
75
+ }
76
+ async getUserDirectory(userId) {
77
+ const userInfoDocument = await this.openUserInfoDocument_(userId);
78
+ const userDirectoryPath = dirname(resolve(this.nitrobase_.config.rootPath, userInfoDocument.path));
79
+ this.logger_.logMethodFull?.("getUserDirectory", { userId }, userDirectoryPath);
80
+ return userDirectoryPath;
81
+ }
82
+ /**
83
+ * Create a new user info document.
84
+ * @param userId The user ID.
85
+ * @param userInfo The user info data.
86
+ */
87
+ newUserInfoDocument_(userId, userInfo) {
88
+ this.logger_.logMethodArgs?.("newUserInfoDocument", { userId, userInfo });
89
+ const storeId = {
90
+ ..._NitrobaseUserManagement.nitrobaseIds.userInfo,
91
+ ownerId: userId
92
+ };
93
+ if (this.nitrobase_.hasStore(storeId)) {
94
+ this.logger_.accident?.("newUserInfoDocument_", "store_already_exists", storeId);
95
+ return;
96
+ }
97
+ this.nitrobase_.newDocument(storeId, userInfo);
98
+ }
99
+ /**
100
+ * Open the user info document.
101
+ * @param userId The user ID.
102
+ * @returns A promise resolving to the user info document.
103
+ */
104
+ openUserInfoDocument_(userId) {
105
+ this.logger_.logMethodArgs?.("openUserInfoDocument_", userId);
106
+ return this.nitrobase_.openDocument({
107
+ ..._NitrobaseUserManagement.nitrobaseIds.userInfo,
108
+ ownerId: userId
109
+ });
110
+ }
111
+ /**
112
+ * Create a token file for the user.
113
+ * @param userId The user ID.
114
+ * @param token The user token.
115
+ * @param isManager Whether the user is a manager.
116
+ */
117
+ async makeTokenFile_(userId, token, isManager) {
118
+ this.logger_.logMethodArgs?.("makeTokenFile", { userId, token: token.slice(0, 12) + "...", isManager });
119
+ const userDirectory = await this.getUserDirectory(userId);
120
+ await makeEmptyFile(resolve(userDirectory, `.token/${token}.asn`));
121
+ if (isManager === true) {
122
+ await makeEmptyFile(resolve(userDirectory, ".auth/manager.asn"));
123
+ }
124
+ }
125
+ /**
126
+ * Get the path to the user token file.
127
+ * @param userId The user ID.
128
+ * @param token The user token.
129
+ * @returns The path to the user token file.
130
+ */
131
+ async getUserTokenFilePath_(userId, token) {
132
+ const userTokenFilePath = resolve(await this.getUserDirectory(userId), `.token/${token}.asn`);
133
+ this.logger_.logMethodFull?.("getTokenFilePath", { userId, token: token.slice(0, 12) + "..." }, userTokenFilePath);
134
+ return userTokenFilePath;
135
+ }
136
+ };
137
+ /**
138
+ * Default Nitrobase store IDs used by this class.
139
+ */
140
+ _NitrobaseUserManagement.nitrobaseIds = {
141
+ userList: {
142
+ name: "user-list",
143
+ region: Region.Managers,
144
+ schemaVer: 1
145
+ },
146
+ userInfo: {
147
+ name: "user-info",
148
+ region: Region.PerUser
149
+ }
150
+ };
151
+ var NitrobaseUserManagement = _NitrobaseUserManagement;
152
+ export {
153
+ NitrobaseUserManagement
154
+ };
155
+ /*! For license information please see main.mjs.LEGAL.txt */
156
+ //# sourceMappingURL=main.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/user-management.ts", "../src/logger.ts"],
4
+ "sourcesContent": ["import {dirname, resolve} from 'node:path';\n\nimport {createLogger} from '@alwatr/nanolib';\nimport {existsSync, makeEmptyFile} from '@alwatr/nanolib/node-fs';\nimport {Region, type AlwatrAuth, type StoreFileId, type StoreFileMeta} from '@alwatr/nitrobase-types';\n\nimport {logger} from './logger.js';\n\nimport type {AlwatrNitrobase} from '@alwatr/nitrobase-engine';\nimport type {DocumentReference} from '@alwatr/nitrobase-reference';\n\n/**\n * New user data type.\n */\nexport type NewUser<TUser extends JsonObject> = AlwatrAuth & {\n data: TUser;\n isManager?: true;\n};\n\n/**\n * Nitrobase User Management Interface.\n */\ninterface NitrobaseUserManagementInterface<TUser extends JsonObject> {\n\n /**\n * Create a new user.\n * @param user The new user data.\n */\n newUser(user: NewUser<TUser>): Promise<void>;\n\n /**\n * Check if a user exists.\n * @param userId The user ID.\n * @returns True if the user exists, false otherwise.\n */\n hasUser(userId: string): Promise<boolean>;\n\n /**\n * Get user data.\n * @param userId The user ID.\n * @returns The user data.\n */\n getUserData(userId: string): Promise<TUser>;\n\n /**\n * Get user meta data.\n * @param userId The user ID.\n * @returns The user meta data.\n */\n getUserMeta(userId: string): Promise<Readonly<StoreFileMeta>>;\n\n /**\n * Verify user token.\n * @param userId The user ID.\n * @param token The user token.\n * @returns True if the token is valid, false otherwise.\n */\n verifyUserToken(userId: string, token: string): Promise<boolean>;\n\n\n /**\n * Save user data to storage.\n * @param userId The user ID.\n */\n save(userId: string): void;\n\n /**\n * Immediately save user data to storage.\n * @param userId The user ID.\n */\n saveImmediate(userId: string): void;\n\n /**\n * Get all user IDs.\n * @returns An async generator of user IDs.\n */\n userIds(): Promise<Generator<string, void, void>>;\n\n /**\n * Get the user directory path.\n * @param userId The user ID.\n * @returns The user directory path.\n */\n getUserDirectory(userId: string): Promise<string>;\n}\n\n/**\n * Nitrobase User Management Class.\n * Manages user data and authentication.\n */\nexport class NitrobaseUserManagement<TUser extends JsonObject> implements NitrobaseUserManagementInterface<TUser> {\n\n /**\n * Default Nitrobase store IDs used by this class.\n */\n static readonly nitrobaseIds = {\n userList: {\n name: 'user-list',\n region: Region.Managers,\n schemaVer: 1,\n } as Readonly<StoreFileId>,\n\n userInfo: {\n name: 'user-info',\n region: Region.PerUser,\n } as Readonly<StoreFileId>,\n } as const;\n\n /**\n * Initialize the user management module.\n * @param nitrobase The Nitrobase instance.\n */\n static async initialize(nitrobase: AlwatrNitrobase): Promise<void> {\n logger.logMethod?.('NitrobaseUserManagement.initialize');\n nitrobase.newCollection(this.nitrobaseIds.userList);\n }\n\n protected logger_ = createLogger('user-management');\n\n protected userListCollection_;\n\n /**\n * Create a new instance of NitrobaseUserManagement.\n * @param nitrobase_ The Nitrobase instance.\n */\n constructor(\n protected readonly nitrobase_: AlwatrNitrobase,\n ) {\n this.logger_.logMethod?.('constructor');\n this.userListCollection_ = this.nitrobase_.openCollection(NitrobaseUserManagement.nitrobaseIds.userList);\n }\n\n\n\n // Implementation of NitrobaseUserManagementInterface methods with JSDoc comments\n\n async newUser(user: NewUser<TUser>): Promise<void> {\n this.logger_.logMethodArgs?.('newUser', user);\n\n (await this.userListCollection_).addItem(user.userId, {});\n\n this.newUserInfoDocument_(user.userId, user.data);\n\n await this.makeTokenFile_(user.userId, user.userToken, user.isManager);\n }\n\n async hasUser(userId: string): Promise<boolean> {\n const userExists = (await this.userListCollection_).hasItem(userId);\n this.logger_.logMethodFull?.('hasUser', {userId}, userExists);\n return userExists;\n }\n\n async getUserData(userId: string): Promise<TUser> {\n this.logger_.logMethodArgs?.('getUserData', userId);\n const userInfoDocument = await this.openUserInfoDocument_(userId);\n return userInfoDocument.getData();\n }\n\n async getUserMeta(userId: string): Promise<Readonly<StoreFileMeta>> {\n this.logger_.logMethodArgs?.('getUserMeta', userId);\n const document = await this.openUserInfoDocument_(userId);\n return document.getStoreMeta();\n }\n\n save(userId: string): void {\n this.logger_.logMethodArgs?.('save', userId);\n this.openUserInfoDocument_(userId).then((document) => {\n document.save();\n });\n }\n\n saveImmediate(userId: string): void {\n this.logger_.logMethodArgs?.('saveImmediate', userId);\n this.openUserInfoDocument_(userId).then((document) => {\n document.saveImmediate();\n });\n }\n\n async userIds(): Promise<Generator<string, void, void>> {\n return (await this.userListCollection_).ids();\n }\n\n async verifyUserToken(userId: string, token: string): Promise<boolean> {\n const tokenFileExist = existsSync(await this.getUserTokenFilePath_(userId, token));\n this.logger_.logMethodFull?.('verifyUserToken', {userId, token: token.slice(0, 12) + '...'}, tokenFileExist);\n return tokenFileExist;\n }\n\n async getUserDirectory(userId: string): Promise<string> {\n const userInfoDocument = await this.openUserInfoDocument_(userId);\n const userDirectoryPath = dirname(resolve(this.nitrobase_.config.rootPath, userInfoDocument.path));\n this.logger_.logMethodFull?.('getUserDirectory', {userId}, userDirectoryPath);\n return userDirectoryPath;\n }\n\n /**\n * Create a new user info document.\n * @param userId The user ID.\n * @param userInfo The user info data.\n */\n protected newUserInfoDocument_(userId: string, userInfo: TUser): void {\n this.logger_.logMethodArgs?.('newUserInfoDocument', {userId, userInfo});\n const storeId: StoreFileId = {\n ...NitrobaseUserManagement.nitrobaseIds.userInfo,\n ownerId: userId,\n };\n if (this.nitrobase_.hasStore(storeId)) {\n this.logger_.accident?.('newUserInfoDocument_', 'store_already_exists', storeId);\n return;\n }\n this.nitrobase_.newDocument<TUser>(storeId, userInfo);\n }\n\n /**\n * Open the user info document.\n * @param userId The user ID.\n * @returns A promise resolving to the user info document.\n */\n protected openUserInfoDocument_(userId: string): Promise<DocumentReference<TUser>> {\n this.logger_.logMethodArgs?.('openUserInfoDocument_', userId);\n return this.nitrobase_.openDocument<TUser>({\n ...NitrobaseUserManagement.nitrobaseIds.userInfo,\n ownerId: userId,\n });\n }\n\n /**\n * Create a token file for the user.\n * @param userId The user ID.\n * @param token The user token.\n * @param isManager Whether the user is a manager.\n */\n protected async makeTokenFile_(userId: string, token: string, isManager?: true): Promise<void> {\n this.logger_.logMethodArgs?.('makeTokenFile', {userId, token: token.slice(0, 12) + '...', isManager});\n const userDirectory = await this.getUserDirectory(userId);\n\n await makeEmptyFile(resolve(userDirectory, `.token/${token}.asn`));\n\n if (isManager === true) {\n await makeEmptyFile(resolve(userDirectory, '.auth/manager.asn'));\n }\n }\n\n /**\n * Get the path to the user token file.\n * @param userId The user ID.\n * @param token The user token.\n * @returns The path to the user token file.\n */\n protected async getUserTokenFilePath_(userId: string, token: string): Promise<string> {\n const userTokenFilePath = resolve(await this.getUserDirectory(userId), `.token/${token}.asn`);\n this.logger_.logMethodFull?.('getTokenFilePath', {userId, token: token.slice(0, 12) + '...'}, userTokenFilePath);\n return userTokenFilePath;\n }\n}\n", "import {createLogger, packageTracer} from '@alwatr/nanolib';\n\n__dev_mode__: packageTracer.add(__package_name__, __package_version__);\n\nexport const logger = /* #__PURE__ */ createLogger(__package_name__);\n"],
5
+ "mappings": ";;;AAAA,SAAQ,SAAS,eAAc;AAE/B,SAAQ,gBAAAA,qBAAmB;AAC3B,SAAQ,YAAY,qBAAoB;AACxC,SAAQ,cAAoE;;;ACJ5E,SAAQ,cAAc,qBAAoB;AAE1C,aAAc,eAAc,IAAI,qCAAkB,OAAmB;AAE9D,IAAM,SAAyB,6BAAa,mCAAgB;;;ADsF5D,IAAM,2BAAN,MAAM,yBAAqG;AAAA;AAAA;AAAA;AAAA;AAAA,EAmChH,YACqB,YACnB;AADmB;AATrB,SAAU,UAAUC,cAAa,iBAAiB;AAWhD,SAAK,QAAQ,YAAY,aAAa;AACtC,SAAK,s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AgB,OAAe,WAAiC;AAC7F,SAAK,QAAQ,gBAAgB,iBAAiB,EAAC,QAAQ,OAAO,MAAM,MAAM,GAAG,EAAE,IAAI,OAAO,UAAS,CAAC;AACpG,UAAM,gBAAgB,MAAM,KAAK,iBAAiB,MAAM;AAExD,UAAM,cAAc,QAAQ,eAAe,UAAU,KAAK,MAAM,CAAC;AAEjE,QAAI,cAAc,MAAM;AACtB,YAAM,cAAc,QAAQ,eAAe,mBAAmB,CAAC;AAAA,IACjE;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAgB,sBAAsB,QAAgB,OAAgC;AACpF,UAAM,oBAAoB,QAAQ,MAAM,KAAK,iBAAiB,MAAM,GAAG,UAAU,KAAK,MAAM;AAC5F,SAAK,QAAQ,gBAAgB,oBAAoB,EAAC,QAAQ,OAAO,MAAM,MAAM,GAAG,EAAE,IAAI,MAAK,GAAG,iBAAiB;AAC/G,WAAO;AAAA,EACT;AACF;AAAA;AAAA;AAAA;AApKa,yBAKK,eAAe;AAAA,EAC7B,UAAU;AAAA,IACR,MAAM;AAAA,IACN,QAAQ,OAAO;AAAA,IACf,WAAW;AAAA,EACb;AAAA,EAEA,UAAU;AAAA,IACR,MAAM;AAAA,IACN,QAAQ,OAAO;AAAA,EACjB;AACF;AAhBK,IAAM,0BAAN;",
6
+ "names": ["createLogger", "createLogger"]
7
+ }
@@ -0,0 +1,129 @@
1
+ import { type AlwatrAuth, type StoreFileId, type StoreFileMeta } from '@alwatr/nitrobase-types';
2
+ import type { AlwatrNitrobase } from '@alwatr/nitrobase-engine';
3
+ import type { DocumentReference } from '@alwatr/nitrobase-reference';
4
+ /**
5
+ * New user data type.
6
+ */
7
+ export type NewUser<TUser extends JsonObject> = AlwatrAuth & {
8
+ data: TUser;
9
+ isManager?: true;
10
+ };
11
+ /**
12
+ * Nitrobase User Management Interface.
13
+ */
14
+ interface NitrobaseUserManagementInterface<TUser extends JsonObject> {
15
+ /**
16
+ * Create a new user.
17
+ * @param user The new user data.
18
+ */
19
+ newUser(user: NewUser<TUser>): Promise<void>;
20
+ /**
21
+ * Check if a user exists.
22
+ * @param userId The user ID.
23
+ * @returns True if the user exists, false otherwise.
24
+ */
25
+ hasUser(userId: string): Promise<boolean>;
26
+ /**
27
+ * Get user data.
28
+ * @param userId The user ID.
29
+ * @returns The user data.
30
+ */
31
+ getUserData(userId: string): Promise<TUser>;
32
+ /**
33
+ * Get user meta data.
34
+ * @param userId The user ID.
35
+ * @returns The user meta data.
36
+ */
37
+ getUserMeta(userId: string): Promise<Readonly<StoreFileMeta>>;
38
+ /**
39
+ * Verify user token.
40
+ * @param userId The user ID.
41
+ * @param token The user token.
42
+ * @returns True if the token is valid, false otherwise.
43
+ */
44
+ verifyUserToken(userId: string, token: string): Promise<boolean>;
45
+ /**
46
+ * Save user data to storage.
47
+ * @param userId The user ID.
48
+ */
49
+ save(userId: string): void;
50
+ /**
51
+ * Immediately save user data to storage.
52
+ * @param userId The user ID.
53
+ */
54
+ saveImmediate(userId: string): void;
55
+ /**
56
+ * Get all user IDs.
57
+ * @returns An async generator of user IDs.
58
+ */
59
+ userIds(): Promise<Generator<string, void, void>>;
60
+ /**
61
+ * Get the user directory path.
62
+ * @param userId The user ID.
63
+ * @returns The user directory path.
64
+ */
65
+ getUserDirectory(userId: string): Promise<string>;
66
+ }
67
+ /**
68
+ * Nitrobase User Management Class.
69
+ * Manages user data and authentication.
70
+ */
71
+ export declare class NitrobaseUserManagement<TUser extends JsonObject> implements NitrobaseUserManagementInterface<TUser> {
72
+ protected readonly nitrobase_: AlwatrNitrobase;
73
+ /**
74
+ * Default Nitrobase store IDs used by this class.
75
+ */
76
+ static readonly nitrobaseIds: {
77
+ readonly userList: Readonly<StoreFileId>;
78
+ readonly userInfo: Readonly<StoreFileId>;
79
+ };
80
+ /**
81
+ * Initialize the user management module.
82
+ * @param nitrobase The Nitrobase instance.
83
+ */
84
+ static initialize(nitrobase: AlwatrNitrobase): Promise<void>;
85
+ protected logger_: import("@alwatr/logger").AlwatrLogger;
86
+ protected userListCollection_: Promise<import("@alwatr/nitrobase-reference").CollectionReference<import("@alwatr/type-helper").JsonObject>>;
87
+ /**
88
+ * Create a new instance of NitrobaseUserManagement.
89
+ * @param nitrobase_ The Nitrobase instance.
90
+ */
91
+ constructor(nitrobase_: AlwatrNitrobase);
92
+ newUser(user: NewUser<TUser>): Promise<void>;
93
+ hasUser(userId: string): Promise<boolean>;
94
+ getUserData(userId: string): Promise<TUser>;
95
+ getUserMeta(userId: string): Promise<Readonly<StoreFileMeta>>;
96
+ save(userId: string): void;
97
+ saveImmediate(userId: string): void;
98
+ userIds(): Promise<Generator<string, void, void>>;
99
+ verifyUserToken(userId: string, token: string): Promise<boolean>;
100
+ getUserDirectory(userId: string): Promise<string>;
101
+ /**
102
+ * Create a new user info document.
103
+ * @param userId The user ID.
104
+ * @param userInfo The user info data.
105
+ */
106
+ protected newUserInfoDocument_(userId: string, userInfo: TUser): void;
107
+ /**
108
+ * Open the user info document.
109
+ * @param userId The user ID.
110
+ * @returns A promise resolving to the user info document.
111
+ */
112
+ protected openUserInfoDocument_(userId: string): Promise<DocumentReference<TUser>>;
113
+ /**
114
+ * Create a token file for the user.
115
+ * @param userId The user ID.
116
+ * @param token The user token.
117
+ * @param isManager Whether the user is a manager.
118
+ */
119
+ protected makeTokenFile_(userId: string, token: string, isManager?: true): Promise<void>;
120
+ /**
121
+ * Get the path to the user token file.
122
+ * @param userId The user ID.
123
+ * @param token The user token.
124
+ * @returns The path to the user token file.
125
+ */
126
+ protected getUserTokenFilePath_(userId: string, token: string): Promise<string>;
127
+ }
128
+ export {};
129
+ //# sourceMappingURL=user-management.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"user-management.d.ts","sourceRoot":"","sources":["../src/user-management.ts"],"names":[],"mappings":"AAIA,OAAO,EAAS,KAAK,UAAU,EAAE,KAAK,WAAW,EAAE,KAAK,aAAa,EAAC,MAAM,yBAAyB,CAAC;AAItG,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