@aventoapp/framework 0.2.2 → 0.2.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.
@@ -0,0 +1,109 @@
1
+ // src/server/db/mongo.js
2
+ import mongoose from "mongoose";
3
+ var MongoConnection = class {
4
+ constructor(config = {}) {
5
+ this.config = {
6
+ host: config.host || process.env.MONGO_HOST || "localhost",
7
+ port: config.port || process.env.MONGO_PORT || 27017,
8
+ database: config.database || process.env.MONGO_DB || "avento",
9
+ user: config.user || process.env.MONGO_USER || "",
10
+ password: config.password || process.env.MONGO_PASSWORD || "",
11
+ options: config.options || {}
12
+ };
13
+ this.connection = null;
14
+ }
15
+ /**
16
+ * Build MongoDB connection URI
17
+ */
18
+ _buildUri() {
19
+ const { host, port, database, user, password } = this.config;
20
+ if (user && password) {
21
+ return `mongodb://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${host}:${port}/${database}`;
22
+ }
23
+ return `mongodb://${host}:${port}/${database}`;
24
+ }
25
+ /**
26
+ * Connect to MongoDB
27
+ */
28
+ async connect() {
29
+ if (this.connection && this.connection.readyState === 1) {
30
+ return this.connection;
31
+ }
32
+ const uri = this.config.uri || this._buildUri();
33
+ const options = {
34
+ maxPoolSize: 10,
35
+ serverSelectionTimeoutMS: 5e3,
36
+ socketTimeoutMS: 45e3,
37
+ ...this.config.options
38
+ };
39
+ try {
40
+ this.connection = await mongoose.connect(uri, options);
41
+ console.log(`[MongoDB] Connected to ${this.config.host}:${this.config.port}/${this.config.database}`);
42
+ mongoose.connection.on("error", (err) => {
43
+ console.error("[MongoDB] Connection error:", err);
44
+ });
45
+ mongoose.connection.on("disconnected", () => {
46
+ console.log("[MongoDB] Disconnected");
47
+ });
48
+ return this.connection;
49
+ } catch (err) {
50
+ console.error("[MongoDB] Connection failed:", err.message);
51
+ throw err;
52
+ }
53
+ }
54
+ /**
55
+ * Get the Mongoose connection
56
+ */
57
+ getConnection() {
58
+ return mongoose.connection;
59
+ }
60
+ /**
61
+ * Get or create a model (with tenant scoping support)
62
+ * @param {string} name - Model name
63
+ * @param {Object} schema - Mongoose schema definition
64
+ * @param {Object} options - Schema options
65
+ */
66
+ createModel(name, schemaDefinition, options = {}) {
67
+ const tenantedSchema = {
68
+ tenant_id: {
69
+ type: mongoose.Schema.Types.ObjectId,
70
+ required: true,
71
+ index: true
72
+ },
73
+ ...schemaDefinition
74
+ };
75
+ const schema = new mongoose.Schema(tenantedSchema, {
76
+ timestamps: { createdAt: "created_at", updatedAt: "updated_at" },
77
+ ...options
78
+ });
79
+ schema.index({ tenant_id: 1, created_at: -1 });
80
+ return mongoose.model(name, schema);
81
+ }
82
+ /**
83
+ * Disconnect from MongoDB
84
+ */
85
+ async disconnect() {
86
+ if (mongoose.connection.readyState !== 0) {
87
+ await mongoose.disconnect();
88
+ this.connection = null;
89
+ console.log("[MongoDB] Disconnected");
90
+ }
91
+ }
92
+ };
93
+ var defaultConnection = null;
94
+ function getMongoConnection(config) {
95
+ if (!defaultConnection) {
96
+ defaultConnection = new MongoConnection(config);
97
+ }
98
+ return defaultConnection;
99
+ }
100
+ function createMongoConnection(config) {
101
+ return new MongoConnection(config);
102
+ }
103
+ export {
104
+ MongoConnection,
105
+ createMongoConnection,
106
+ getMongoConnection,
107
+ mongoose
108
+ };
109
+ //# sourceMappingURL=mongo.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/server/db/mongo.js"],
4
+ "sourcesContent": ["import mongoose from 'mongoose';\n\n/**\n * MongoDB connection manager using Mongoose\n */\nexport class MongoConnection {\n constructor(config = {}) {\n this.config = {\n host: config.host || process.env.MONGO_HOST || 'localhost',\n port: config.port || process.env.MONGO_PORT || 27017,\n database: config.database || process.env.MONGO_DB || 'avento',\n user: config.user || process.env.MONGO_USER || '',\n password: config.password || process.env.MONGO_PASSWORD || '',\n options: config.options || {}\n };\n\n this.connection = null;\n }\n\n /**\n * Build MongoDB connection URI\n */\n _buildUri() {\n const { host, port, database, user, password } = this.config;\n\n if (user && password) {\n return `mongodb://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${host}:${port}/${database}`;\n }\n\n return `mongodb://${host}:${port}/${database}`;\n }\n\n /**\n * Connect to MongoDB\n */\n async connect() {\n if (this.connection && this.connection.readyState === 1) {\n return this.connection;\n }\n\n const uri = this.config.uri || this._buildUri();\n\n const options = {\n maxPoolSize: 10,\n serverSelectionTimeoutMS: 5000,\n socketTimeoutMS: 45000,\n ...this.config.options\n };\n\n try {\n this.connection = await mongoose.connect(uri, options);\n console.log(`[MongoDB] Connected to ${this.config.host}:${this.config.port}/${this.config.database}`);\n\n // Handle connection events\n mongoose.connection.on('error', (err) => {\n console.error('[MongoDB] Connection error:', err);\n });\n\n mongoose.connection.on('disconnected', () => {\n console.log('[MongoDB] Disconnected');\n });\n\n return this.connection;\n } catch (err) {\n console.error('[MongoDB] Connection failed:', err.message);\n throw err;\n }\n }\n\n /**\n * Get the Mongoose connection\n */\n getConnection() {\n return mongoose.connection;\n }\n\n /**\n * Get or create a model (with tenant scoping support)\n * @param {string} name - Model name\n * @param {Object} schema - Mongoose schema definition\n * @param {Object} options - Schema options\n */\n createModel(name, schemaDefinition, options = {}) {\n // Add tenant_id to all schemas by default\n const tenantedSchema = {\n tenant_id: {\n type: mongoose.Schema.Types.ObjectId,\n required: true,\n index: true\n },\n ...schemaDefinition\n };\n\n const schema = new mongoose.Schema(tenantedSchema, {\n timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' },\n ...options\n });\n\n // Add compound index for tenant + common queries\n schema.index({ tenant_id: 1, created_at: -1 });\n\n return mongoose.model(name, schema);\n }\n\n /**\n * Disconnect from MongoDB\n */\n async disconnect() {\n if (mongoose.connection.readyState !== 0) {\n await mongoose.disconnect();\n this.connection = null;\n console.log('[MongoDB] Disconnected');\n }\n }\n}\n\n// Singleton instance\nlet defaultConnection = null;\n\n/**\n * Get or create the default MongoDB connection\n */\nexport function getMongoConnection(config) {\n if (!defaultConnection) {\n defaultConnection = new MongoConnection(config);\n }\n return defaultConnection;\n}\n\n/**\n * Create a new MongoDB connection\n */\nexport function createMongoConnection(config) {\n return new MongoConnection(config);\n}\n\nexport { mongoose };\n"],
5
+ "mappings": ";AAAA,OAAO,cAAc;AAKd,IAAM,kBAAN,MAAsB;AAAA,EAC3B,YAAY,SAAS,CAAC,GAAG;AACvB,SAAK,SAAS;AAAA,MACZ,MAAM,OAAO,QAAQ,QAAQ,IAAI,cAAc;AAAA,MAC/C,MAAM,OAAO,QAAQ,QAAQ,IAAI,cAAc;AAAA,MAC/C,UAAU,OAAO,YAAY,QAAQ,IAAI,YAAY;AAAA,MACrD,MAAM,OAAO,QAAQ,QAAQ,IAAI,cAAc;AAAA,MAC/C,UAAU,OAAO,YAAY,QAAQ,IAAI,kBAAkB;AAAA,MAC3D,SAAS,OAAO,WAAW,CAAC;AAAA,IAC9B;AAEA,SAAK,aAAa;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA,EAKA,YAAY;AACV,UAAM,EAAE,MAAM,MAAM,UAAU,MAAM,SAAS,IAAI,KAAK;AAEtD,QAAI,QAAQ,UAAU;AACpB,aAAO,aAAa,mBAAmB,IAAI,CAAC,IAAI,mBAAmB,QAAQ,CAAC,IAAI,IAAI,IAAI,IAAI,IAAI,QAAQ;AAAA,IAC1G;AAEA,WAAO,aAAa,IAAI,IAAI,IAAI,IAAI,QAAQ;AAAA,EAC9C;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,UAAU;AACd,QAAI,KAAK,cAAc,KAAK,WAAW,eAAe,GAAG;AACvD,aAAO,KAAK;AAAA,IACd;AAEA,UAAM,MAAM,KAAK,OAAO,OAAO,KAAK,UAAU;AAE9C,UAAM,UAAU;AAAA,MACd,aAAa;AAAA,MACb,0BAA0B;AAAA,MAC1B,iBAAiB;AAAA,MACjB,GAAG,KAAK,OAAO;AAAA,IACjB;AAEA,QAAI;AACF,WAAK,aAAa,MAAM,SAAS,QAAQ,KAAK,OAAO;AACrD,cAAQ,IAAI,0BAA0B,KAAK,OAAO,IAAI,IAAI,KAAK,OAAO,IAAI,IAAI,KAAK,OAAO,QAAQ,EAAE;AAGpG,eAAS,WAAW,GAAG,SAAS,CAAC,QAAQ;AACvC,gBAAQ,MAAM,+BAA+B,GAAG;AAAA,MAClD,CAAC;AAED,eAAS,WAAW,GAAG,gBAAgB,MAAM;AAC3C,gBAAQ,IAAI,wBAAwB;AAAA,MACtC,CAAC;AAED,aAAO,KAAK;AAAA,IACd,SAAS,KAAK;AACZ,cAAQ,MAAM,gCAAgC,IAAI,OAAO;AACzD,YAAM;AAAA,IACR;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,gBAAgB;AACd,WAAO,SAAS;AAAA,EAClB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,YAAY,MAAM,kBAAkB,UAAU,CAAC,GAAG;AAEhD,UAAM,iBAAiB;AAAA,MACrB,WAAW;AAAA,QACT,MAAM,SAAS,OAAO,MAAM;AAAA,QAC5B,UAAU;AAAA,QACV,OAAO;AAAA,MACT;AAAA,MACA,GAAG;AAAA,IACL;AAEA,UAAM,SAAS,IAAI,SAAS,OAAO,gBAAgB;AAAA,MACjD,YAAY,EAAE,WAAW,cAAc,WAAW,aAAa;AAAA,MAC/D,GAAG;AAAA,IACL,CAAC;AAGD,WAAO,MAAM,EAAE,WAAW,GAAG,YAAY,GAAG,CAAC;AAE7C,WAAO,SAAS,MAAM,MAAM,MAAM;AAAA,EACpC;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,aAAa;AACjB,QAAI,SAAS,WAAW,eAAe,GAAG;AACxC,YAAM,SAAS,WAAW;AAC1B,WAAK,aAAa;AAClB,cAAQ,IAAI,wBAAwB;AAAA,IACtC;AAAA,EACF;AACF;AAGA,IAAI,oBAAoB;AAKjB,SAAS,mBAAmB,QAAQ;AACzC,MAAI,CAAC,mBAAmB;AACtB,wBAAoB,IAAI,gBAAgB,MAAM;AAAA,EAChD;AACA,SAAO;AACT;AAKO,SAAS,sBAAsB,QAAQ;AAC5C,SAAO,IAAI,gBAAgB,MAAM;AACnC;",
6
+ "names": []
7
+ }
@@ -0,0 +1,471 @@
1
+ // No local copy of a module that moved into @aventoapp/framework (vector#6359).
2
+ //
3
+ // Why: the shell's ports drifted from Vector's because a module that should
4
+ // have been shared was copied instead, and a fix to one copy never reached the
5
+ // other. Once a module moves into the framework, moved.json (beside this
6
+ // package's package.json) lists it, and this guard, shipped in the package so
7
+ // Vector and avento-apps run the very same code, fails the app's gate when:
8
+ //
9
+ // 1. a listed OLD PATH comes back holding code of its own, or
10
+ // 2. a file anywhere else in the app holds the framework export's body,
11
+ // compared with comments and whitespace ignored (strings are kept).
12
+ //
13
+ // The one exception is the move recipe's sweep period: the old path may hold
14
+ // a single line, `export { name } from '<entry.package>';`, plus a comment that
15
+ // names the sweep idea which will rewrite its importers and delete the file
16
+ // (entry.sweep when the entry names one). Nothing else may share that file.
17
+ //
18
+ // It never passes silently: a missing or malformed moved.json, a listed export
19
+ // the framework does not declare and export, or a scan that finds no app files
20
+ // is a failure with its own message. An empty list is valid and passes.
21
+ //
22
+ // The fix for a failure is always the same: fix the module in the framework,
23
+ // publish, and bump the app (avento scripts/bump-consumers.mjs). A fix that only
24
+ // one app needs is still made in the framework.
25
+ //
26
+ // Plain Node, no dependencies: this file is published as-is (package.json
27
+ // `files`), not bundled, and is imported as `@aventoapp/framework/guard`.
28
+
29
+ import fs from 'node:fs';
30
+ import path from 'node:path';
31
+ import { fileURLToPath } from 'node:url';
32
+
33
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
34
+ export const FRAMEWORK_DIR = path.resolve(HERE, '..');
35
+
36
+ export const APPS = ['vector', 'avento-apps'];
37
+ // JSX is not read: the lexer knows JavaScript, not markup, and what moves into
38
+ // the framework is server and shared code.
39
+ const CODE_EXT = new Set(['.js', '.mjs', '.cjs', '.ts']);
40
+ const SKIP_DIRS = new Set(['node_modules', 'dist', 'build', 'coverage', 'test-results']);
41
+ const IDENT = /^[A-Za-z_$][\w$]*$/;
42
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
43
+ const PACKAGE = /^@aventoapp\/framework(\/[\w./-]+)?$/;
44
+
45
+ // ── Lexing: just enough JavaScript to tell code from strings and comments ──
46
+
47
+ const REGEX_AFTER_CHAR = new Set([...'(,=:[!&|?{};+-*%<>~^']);
48
+ const REGEX_AFTER_WORD = new Set(['return', 'typeof', 'case', 'in', 'of', 'delete', 'void', 'throw', 'new', 'else', 'do', 'yield', 'await', 'instanceof']);
49
+
50
+ /**
51
+ * Split source into segments: `code`, `str` (string, template or regex
52
+ * literal, kept verbatim) and `comment`. Each has its [start, end) offsets.
53
+ */
54
+ export function lexSource(src) {
55
+ const out = [];
56
+ let i = 0;
57
+ let codeStart = 0;
58
+ const n = src.length;
59
+ const flushCode = (end) => {
60
+ if (end > codeStart) out.push({ type: 'code', start: codeStart, end, text: src.slice(codeStart, end) });
61
+ };
62
+ const push = (type, start, end) => {
63
+ flushCode(start);
64
+ out.push({ type, start, end, text: src.slice(start, end) });
65
+ codeStart = end;
66
+ };
67
+ const prevSignificant = () => {
68
+ // The last non-space character of code since the previous non-code
69
+ // segment or, failing that, the end of the last segment pushed.
70
+ let j = i - 1;
71
+ while (j >= codeStart && /\s/.test(src[j])) j--;
72
+ if (j >= codeStart) {
73
+ if (/[\w$]/.test(src[j])) {
74
+ let k = j;
75
+ while (k > codeStart && /[\w$]/.test(src[k - 1])) k--;
76
+ return { word: src.slice(k, j + 1) };
77
+ }
78
+ return { char: src[j] };
79
+ }
80
+ const last = out[out.length - 1];
81
+ if (!last) return { start: true };
82
+ if (last.type === 'comment') {
83
+ // Look through comments to the code before them.
84
+ for (let s = out.length - 1; s >= 0; s--) {
85
+ if (out[s].type === 'comment') continue;
86
+ if (out[s].type === 'str') return { char: 'x' };
87
+ const t = out[s].text.replace(/\s+$/, '');
88
+ if (!t) continue;
89
+ const m = /[\w$]+$/.exec(t);
90
+ return m ? { word: m[0] } : { char: t[t.length - 1] };
91
+ }
92
+ return { start: true };
93
+ }
94
+ return { char: 'x' }; // after a string: division
95
+ };
96
+ const skipQuoted = (q, j) => {
97
+ j++;
98
+ while (j < n && src[j] !== q) {
99
+ if (src[j] === '\\') j++;
100
+ else if (src[j] === '\n') return j;
101
+ j++;
102
+ }
103
+ return Math.min(j + 1, n);
104
+ };
105
+ const skipTemplate = (j) => {
106
+ j++;
107
+ while (j < n && src[j] !== '`') {
108
+ if (src[j] === '\\') { j += 2; continue; }
109
+ if (src[j] === '$' && src[j + 1] === '{') {
110
+ j += 2;
111
+ let depth = 1;
112
+ while (j < n && depth > 0) {
113
+ const c = src[j];
114
+ if (c === "'" || c === '"') { j = skipQuoted(c, j); continue; }
115
+ if (c === '`') { j = skipTemplate(j); continue; }
116
+ if (c === '{') depth++;
117
+ else if (c === '}') depth--;
118
+ j++;
119
+ }
120
+ continue;
121
+ }
122
+ j++;
123
+ }
124
+ return Math.min(j + 1, n);
125
+ };
126
+ while (i < n) {
127
+ const c = src[i];
128
+ const d = src[i + 1];
129
+ if (c === '/' && d === '/') {
130
+ let j = src.indexOf('\n', i);
131
+ if (j === -1) j = n;
132
+ push('comment', i, j);
133
+ i = j;
134
+ } else if (c === '/' && d === '*') {
135
+ let j = src.indexOf('*/', i + 2);
136
+ j = j === -1 ? n : j + 2;
137
+ push('comment', i, j);
138
+ i = j;
139
+ } else if (c === "'" || c === '"') {
140
+ const j = skipQuoted(c, i);
141
+ push('str', i, j);
142
+ i = j;
143
+ } else if (c === '`') {
144
+ const j = skipTemplate(i);
145
+ push('str', i, j);
146
+ i = j;
147
+ } else if (c === '/') {
148
+ const p = prevSignificant();
149
+ const isRegex = p.start || (p.char && REGEX_AFTER_CHAR.has(p.char)) || (p.word && REGEX_AFTER_WORD.has(p.word));
150
+ if (!isRegex) { i++; continue; }
151
+ let j = i + 1;
152
+ let inClass = false;
153
+ while (j < n && src[j] !== '\n') {
154
+ if (src[j] === '\\') { j += 2; continue; }
155
+ if (src[j] === '[') inClass = true;
156
+ else if (src[j] === ']') inClass = false;
157
+ else if (src[j] === '/' && !inClass) break;
158
+ j++;
159
+ }
160
+ j++;
161
+ while (j < n && /[a-z]/i.test(src[j])) j++;
162
+ push('str', i, Math.min(j, n));
163
+ i = Math.min(j, n);
164
+ } else {
165
+ i++;
166
+ }
167
+ }
168
+ flushCode(n);
169
+ return out;
170
+ }
171
+
172
+ /** Comments dropped, whitespace outside strings dropped, strings kept. */
173
+ export function normalizeSource(src) {
174
+ return lexSource(src)
175
+ .filter((s) => s.type !== 'comment')
176
+ .map((s) => (s.type === 'code' ? s.text.replace(/\s+/g, '') : s.text))
177
+ .join('');
178
+ }
179
+
180
+ /** The source with strings and comments blanked (same length), for structure. */
181
+ function maskSource(src) {
182
+ const chars = src.split('');
183
+ for (const s of lexSource(src)) {
184
+ if (s.type === 'code') continue;
185
+ for (let k = s.start; k < s.end; k++) {
186
+ if (chars[k] === '\n') continue;
187
+ chars[k] = s.type === 'str' && (k === s.start || k === s.end - 1) ? '"' : ' ';
188
+ }
189
+ }
190
+ return chars.join('');
191
+ }
192
+
193
+ function matchBracket(masked, open) {
194
+ const pairs = { '(': ')', '[': ']', '{': '}' };
195
+ const stack = [];
196
+ for (let k = open; k < masked.length; k++) {
197
+ const c = masked[k];
198
+ if (pairs[c]) stack.push(pairs[c]);
199
+ else if (c === ')' || c === ']' || c === '}') {
200
+ if (stack.pop() !== c) return -1;
201
+ if (stack.length === 0) return k;
202
+ }
203
+ }
204
+ return -1;
205
+ }
206
+
207
+ const escapeRe = (s) => s.replace(/[$]/g, '\\$');
208
+
209
+ /**
210
+ * Find `name`'s declaration in one source file. Returns null, or
211
+ * { kind, exported, key } where key is the normalized text after the name:
212
+ * `(params){body}` for a function, `extends X{...}` for a class, `=expr` for
213
+ * a const. That is what a copy, even a renamed one, still contains.
214
+ */
215
+ export function findDeclaration(src, name) {
216
+ const masked = maskSource(src);
217
+ const N = escapeRe(name);
218
+ const forms = [
219
+ { kind: 'function', re: new RegExp(`(^|[\\s;{}])(export\\s+(?:default\\s+)?)?(?:async\\s+)?function\\s*\\*?\\s*(${N})\\s*\\(`, 'd') },
220
+ { kind: 'class', re: new RegExp(`(^|[\\s;{}])(export\\s+(?:default\\s+)?)?class\\s+(${N})(?![\\w$])`, 'd') },
221
+ { kind: 'const', re: new RegExp(`(^|[\\s;{}])(export\\s+)?(?:const|let|var)\\s+(${N})\\s*=`, 'd') },
222
+ ];
223
+ for (const { kind, re } of forms) {
224
+ const m = re.exec(masked);
225
+ if (!m) continue;
226
+ const afterName = m.indices[3][1];
227
+ let end = -1;
228
+ if (kind === 'function') {
229
+ const open = masked.indexOf('(', afterName);
230
+ const close = matchBracket(masked, open);
231
+ const body = close === -1 ? -1 : masked.indexOf('{', close);
232
+ end = body === -1 ? -1 : matchBracket(masked, body);
233
+ } else if (kind === 'class') {
234
+ const body = masked.indexOf('{', afterName);
235
+ end = body === -1 ? -1 : matchBracket(masked, body);
236
+ } else {
237
+ end = constEnd(masked, afterName);
238
+ }
239
+ if (end === -1) continue;
240
+ const listed = new RegExp(`export\\s*\\{[^}]*(?<![\\w$])${N}(?![\\w$])[^}]*\\}(?!\\s*from)`).test(masked);
241
+ const keyEnd = kind === 'const' ? end : end + 1;
242
+ return { kind, exported: Boolean(m[2]) || listed, key: normalizeSource(src.slice(afterName, keyEnd)) };
243
+ }
244
+ return null;
245
+ }
246
+
247
+ function constEnd(masked, from) {
248
+ const pairs = { '(': ')', '[': ']', '{': '}' };
249
+ const stack = [];
250
+ for (let k = from; k < masked.length; k++) {
251
+ const c = masked[k];
252
+ if (pairs[c]) stack.push(pairs[c]);
253
+ else if (c === ')' || c === ']' || c === '}') stack.pop();
254
+ else if (stack.length === 0 && c === ';') return k;
255
+ else if (stack.length === 0 && c === '\n') {
256
+ const before = masked.slice(from, k).replace(/\s+$/, '');
257
+ const after = masked.slice(k).replace(/^\s+/, '');
258
+ if (!/[=+\-*/%&|^<>?:,(]$/.test(before) && !/^[.?:+\-*/%&|^=<>,([]/.test(after)) return k;
259
+ }
260
+ }
261
+ return masked.length;
262
+ }
263
+
264
+ const PREFIX = {
265
+ function: /function\*?[\w$]*$/,
266
+ class: /class[\w$]*$/,
267
+ const: /(?:const|let|var)[\w$]+$/,
268
+ };
269
+
270
+ // ── moved.json ──
271
+
272
+ function loadMoved(movedPath) {
273
+ const shown = path.basename(movedPath);
274
+ if (!fs.existsSync(movedPath)) {
275
+ return { errors: [`${shown} not found at ${movedPath}: the framework's moved-module list is missing, so nothing can be checked. Restore it (an empty list is { "moved": [] }).`] };
276
+ }
277
+ let data;
278
+ try {
279
+ data = JSON.parse(fs.readFileSync(movedPath, 'utf8'));
280
+ } catch (err) {
281
+ return { errors: [`${shown} is not valid JSON (${movedPath}): ${err.message}`] };
282
+ }
283
+ if (!data || typeof data !== 'object' || Array.isArray(data) || !Array.isArray(data.moved)) {
284
+ return { errors: [`${shown} must be an object with a "moved" array (${movedPath}); an empty list is { "moved": [] }.`] };
285
+ }
286
+ const errors = [];
287
+ data.moved.forEach((e, idx) => {
288
+ const at = `${shown} moved[${idx}]${e && typeof e.name === 'string' ? ` (${e.name})` : ''}`;
289
+ if (!e || typeof e !== 'object' || Array.isArray(e)) { errors.push(`${at}: an entry must be an object`); return; }
290
+ if (typeof e.name !== 'string' || !e.name) errors.push(`${at}: "name" (the module's name) is required`);
291
+ if (typeof e.export !== 'string' || !IDENT.test(e.export)) errors.push(`${at}: "export" must be the framework export's identifier`);
292
+ if (typeof e.package !== 'string' || !PACKAGE.test(e.package)) errors.push(`${at}: "package" must be @aventoapp/framework or one of its subpaths, e.g. @aventoapp/framework/server`);
293
+ if (typeof e.date !== 'string' || !DATE.test(e.date)) errors.push(`${at}: "date" must be the move's date, YYYY-MM-DD`);
294
+ if (e.sweep !== undefined && (typeof e.sweep !== 'string' || !e.sweep)) errors.push(`${at}: "sweep", when given, names the sweep idea, e.g. "I-6801"`);
295
+ if (e.source !== undefined && (typeof e.source !== 'string' || !e.source)) errors.push(`${at}: "source", when given, is the framework file that declares the export, e.g. src/server/x.js`);
296
+ if (!e.oldPaths || typeof e.oldPaths !== 'object' || Array.isArray(e.oldPaths)) {
297
+ errors.push(`${at}: "oldPaths" must be an object keyed by app (${APPS.join(', ')}) listing each app's old paths`);
298
+ } else {
299
+ for (const [app, list] of Object.entries(e.oldPaths)) {
300
+ if (!APPS.includes(app)) errors.push(`${at}: oldPaths has an unknown app "${app}" (known: ${APPS.join(', ')})`);
301
+ else if (!Array.isArray(list) || list.some((p) => typeof p !== 'string' || !p || path.isAbsolute(p) || p.split(/[\\/]/).includes('..'))) {
302
+ errors.push(`${at}: oldPaths.${app} must be a list of repo-relative paths`);
303
+ }
304
+ }
305
+ }
306
+ });
307
+ return { errors, entries: errors.length ? [] : data.moved };
308
+ }
309
+
310
+ // ── File walking ──
311
+
312
+ function walk(root, rel, out) {
313
+ let dirents;
314
+ try {
315
+ dirents = fs.readdirSync(path.join(root, rel), { withFileTypes: true });
316
+ } catch {
317
+ return;
318
+ }
319
+ for (const d of dirents) {
320
+ const child = rel ? `${rel}/${d.name}` : d.name;
321
+ if (d.isDirectory()) {
322
+ if (d.name.startsWith('.') || SKIP_DIRS.has(d.name)) continue;
323
+ walk(root, child, out);
324
+ } else if (d.isFile() && CODE_EXT.has(path.extname(d.name))) {
325
+ out.push(child);
326
+ }
327
+ }
328
+ }
329
+
330
+ function listFiles(root, roots) {
331
+ const out = [];
332
+ for (const r of roots) {
333
+ const rel = r.replace(/\\/g, '/').replace(/\/+$/, '');
334
+ const abs = path.join(root, rel);
335
+ if (!fs.existsSync(abs)) continue;
336
+ if (fs.statSync(abs).isFile()) out.push(rel);
337
+ else walk(root, rel, out);
338
+ }
339
+ return [...new Set(out)].sort();
340
+ }
341
+
342
+ // ── The re-export the move recipe allows during its sweep ──
343
+
344
+ function checkOldPath(rel, src, entry) {
345
+ const segs = lexSource(src);
346
+ const code = segs.filter((s) => s.type !== 'comment').map((s) => s.text).join('').trim();
347
+ const comments = segs.filter((s) => s.type === 'comment').map((s) => s.text).join('\n');
348
+ const norm = normalizeSource(code);
349
+ const m = /^export\{([\w$,]+)\}from(['"])([^'"]+)\2;?$/.exec(norm);
350
+ const names = m ? m[1].split(',').filter(Boolean) : [];
351
+ const moved = `${entry.export} moved to ${entry.package} on ${entry.date} (${entry.name})`;
352
+ if (!m || code.includes('\n') || m[3] !== entry.package || !names.includes(entry.export)) {
353
+ return `${rel}: ${moved}, and this old path is back with code of its own. Import ${entry.export} from ${entry.package} and delete this file; during the sweep it may hold only \`export { ${entry.export} } from '${entry.package}';\` and a comment naming the sweep idea. Fix the module in the framework, not here.`;
354
+ }
355
+ if (entry.sweep ? !comments.includes(entry.sweep) : !/\bI-\d+\b|#\d+\b/.test(comments)) {
356
+ return `${rel}: ${moved}. The re-export here needs a comment naming the sweep idea that deletes it${entry.sweep ? ` (${entry.sweep})` : ', e.g. "// I-6801 rewrites the imports and deletes this file"'}.`;
357
+ }
358
+ return null;
359
+ }
360
+
361
+ // ── The check ──
362
+
363
+ function collectFrameworkFiles(frameworkDir) {
364
+ const out = [];
365
+ walk(frameworkDir, 'src', out);
366
+ return out;
367
+ }
368
+
369
+ /**
370
+ * Check an app against the framework's moved-module list.
371
+ *
372
+ * @param {object} o
373
+ * @param {string} o.appRoot the app repo's root
374
+ * @param {string} o.app 'vector' or 'avento-apps' (selects oldPaths)
375
+ * @param {string[]} o.roots repo-relative directories to scan
376
+ * @param {string} [o.frameworkDir] defaults to this installed package
377
+ * @param {string} [o.movedPath] defaults to <frameworkDir>/moved.json
378
+ * @returns {{ ok: boolean, errors: string[], entries: number, scanned: number }}
379
+ */
380
+ export function checkNoFrameworkCopy({ appRoot, app, roots, frameworkDir = FRAMEWORK_DIR, movedPath }) {
381
+ if (!APPS.includes(app)) throw new Error(`check-no-framework-copy: unknown app "${app}" (known: ${APPS.join(', ')})`);
382
+ if (!Array.isArray(roots) || roots.length === 0) throw new Error('check-no-framework-copy: roots must list the directories to scan');
383
+ const errors = [];
384
+ const loaded = loadMoved(movedPath || path.join(frameworkDir, 'moved.json'));
385
+ errors.push(...loaded.errors);
386
+ const files = listFiles(appRoot, roots);
387
+ if (files.length === 0) {
388
+ errors.push(`found no app files to scan under ${roots.join(', ')} in ${appRoot}: the guard would pass without looking. Check the runner's roots.`);
389
+ }
390
+ const entries = loaded.entries || [];
391
+ if (errors.length || entries.length === 0) {
392
+ return { ok: errors.length === 0, errors, entries: entries.length, scanned: files.length };
393
+ }
394
+
395
+ // Each entry's declaration in the framework.
396
+ const frameworkFiles = collectFrameworkFiles(frameworkDir);
397
+ const sources = new Map();
398
+ const readFw = (rel) => {
399
+ if (!sources.has(rel)) sources.set(rel, fs.readFileSync(path.join(frameworkDir, rel), 'utf8'));
400
+ return sources.get(rel);
401
+ };
402
+ const decls = [];
403
+ for (const entry of entries) {
404
+ const candidates = entry.source ? [entry.source] : frameworkFiles;
405
+ let found = null;
406
+ for (const rel of candidates) {
407
+ if (!fs.existsSync(path.join(frameworkDir, rel))) continue;
408
+ const d = findDeclaration(readFw(rel), entry.export);
409
+ if (d && d.exported) { found = { ...d, file: rel }; break; }
410
+ }
411
+ if (!found) {
412
+ errors.push(`moved.json ${entry.name}: export ${entry.export} was not found declared and exported in the framework (${entry.source || 'src/**'}). Fix the entry, or the framework is missing the module it says moved.`);
413
+ } else {
414
+ decls.push({ entry, ...found });
415
+ }
416
+ }
417
+
418
+ // Old paths that came back.
419
+ const oldPathOf = new Map();
420
+ for (const entry of entries) {
421
+ for (const p of entry.oldPaths[app] || []) {
422
+ const rel = p.replace(/\\/g, '/');
423
+ oldPathOf.set(rel, [...(oldPathOf.get(rel) || []), entry]);
424
+ const abs = path.join(appRoot, rel);
425
+ if (!fs.existsSync(abs)) continue;
426
+ const problem = checkOldPath(rel, fs.readFileSync(abs, 'utf8'), entry);
427
+ if (problem) errors.push(problem);
428
+ }
429
+ }
430
+
431
+ // A body matching the framework export anywhere else.
432
+ for (const rel of files) {
433
+ const norm = normalizeSource(fs.readFileSync(path.join(appRoot, rel), 'utf8'));
434
+ for (const d of decls) {
435
+ if (!d.key) continue;
436
+ let at = norm.indexOf(d.key);
437
+ while (at !== -1) {
438
+ if (PREFIX[d.kind].test(norm.slice(Math.max(0, at - 200), at))) {
439
+ errors.push(`${rel}: holds a copy of ${d.entry.export}, which moved to ${d.entry.package} on ${d.entry.date} (${d.entry.name}; framework ${d.file}). Import it from ${d.entry.package} and delete the copy; fix the module in the framework.`);
440
+ break;
441
+ }
442
+ at = norm.indexOf(d.key, at + 1);
443
+ }
444
+ }
445
+ }
446
+ return { ok: errors.length === 0, errors, entries: entries.length, scanned: files.length };
447
+ }
448
+
449
+ /** Run the check, print its result, and return the exit code. */
450
+ export function runNoFrameworkCopy(opts) {
451
+ let r;
452
+ try {
453
+ r = checkNoFrameworkCopy(opts);
454
+ } catch (err) {
455
+ console.error(`check-no-framework-copy: ${err.message}`);
456
+ return 1;
457
+ }
458
+ let version = '';
459
+ try {
460
+ version = JSON.parse(fs.readFileSync(path.join(opts.frameworkDir || FRAMEWORK_DIR, 'package.json'), 'utf8')).version;
461
+ } catch { /* a fixture framework has no package.json */ }
462
+ const from = version ? `@aventoapp/framework ${version}` : 'the framework';
463
+ if (r.ok) {
464
+ console.log(`check-no-framework-copy: OK, ${r.entries} moved module${r.entries === 1 ? '' : 's'} (${from}), ${r.scanned} files scanned, no local copy.`);
465
+ return 0;
466
+ }
467
+ console.error(`check-no-framework-copy: FAILED (${from}, ${r.scanned} files scanned)`);
468
+ for (const e of r.errors) console.error(` - ${e}`);
469
+ console.error('A module listed in moved.json lives in @aventoapp/framework: fix it there, publish, and bump the app (avento scripts/bump-consumers.mjs).');
470
+ return 1;
471
+ }
package/moved.json ADDED
@@ -0,0 +1,4 @@
1
+ {
2
+ "//": "Modules moved into @aventoapp/framework (vector#6359). guard/no-framework-copy.js, which Vector and avento-apps both run, fails when an old path comes back with code of its own or a body matching the export appears anywhere else in the app. An entry: { name, export, package (the subpath that exports it), date (YYYY-MM-DD), oldPaths: { vector: [...], avento-apps: [...] }, sweep? (the idea that deletes a one-line re-export left at an old path), source? (the framework file declaring it, when the name is ambiguous) }. The move recipe: vector docs/audits/2026-11-29-vector-avento-dedupe-inventory.md, 'How each move is done'.",
3
+ "moved": []
4
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aventoapp/framework",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "type": "module",
5
5
  "description": "Avento framework - server and web modules for multi-tenant SaaS apps",
6
6
  "repository": {
@@ -12,16 +12,19 @@
12
12
  "exports": {
13
13
  ".": "./dist/index.js",
14
14
  "./server": "./dist/server/index.js",
15
+ "./server/mongo": "./dist/server/mongo.js",
15
16
  "./server/workflow": "./dist/server/workflow/index.js",
16
17
  "./web": "./dist/web/index.js",
17
18
  "./shared": "./dist/shared/index.js",
18
19
  "./offline": "./dist/offline/index.js",
20
+ "./guard": "./guard/no-framework-copy.js",
21
+ "./moved.json": "./moved.json",
19
22
  "./native": {
20
23
  "react-native": "./src/native/index.js",
21
24
  "default": "./dist/native/index.js"
22
25
  }
23
26
  },
24
- "files": ["dist", "src", "schemas"],
27
+ "files": ["dist", "src", "schemas", "guard", "moved.json"],
25
28
  "publishConfig": {
26
29
  "access": "public"
27
30
  },
@@ -34,14 +37,9 @@
34
37
  "clean": "rm -rf dist"
35
38
  },
36
39
  "dependencies": {
37
- "@emotion/react": "^11.11.0",
38
- "@emotion/styled": "^11.11.0",
39
- "@mui/icons-material": "^5.15.0",
40
- "@mui/material": "^5.15.0",
41
40
  "bcrypt": "^5.1.1",
42
41
  "express": "^4.18.2",
43
42
  "jsonwebtoken": "^9.0.2",
44
- "mongoose": "^8.0.0",
45
43
  "nodemailer": "^6.9.0",
46
44
  "passport": "^0.7.0",
47
45
  "passport-jwt": "^4.0.1",
@@ -53,7 +51,8 @@
53
51
  },
54
52
  "devDependencies": {
55
53
  "esbuild": "^0.19.0",
56
- "fake-indexeddb": "^6.0.0"
54
+ "fake-indexeddb": "^6.0.0",
55
+ "mongoose": "^8.0.0"
57
56
  },
58
57
  "peerDependencies": {
59
58
  "react": "^18.0.0",
@@ -5,10 +5,10 @@ export {
5
5
  createPostgresConnection
6
6
  } from './postgres.js';
7
7
 
8
- // Re-export all from mongo
9
- export {
10
- MongoConnection,
11
- getMongoConnection,
12
- createMongoConnection,
13
- mongoose
14
- } from './mongo.js';
8
+ // The Mongo helpers (MongoConnection, getMongoConnection,
9
+ // createMongoConnection, mongoose) are NOT re-exported here: db/mongo.js
10
+ // imports mongoose at its top, and this barrel is part of
11
+ // @aventoapp/framework/server, so every importer paid ~300 ms and ~15 MB at
12
+ // boot for it, Mongo user or not (vector#6334). Import them from
13
+ // '@aventoapp/framework/server/mongo', with mongoose installed beside it
14
+ // (the framework does not install it).