@aventoapp/framework 0.2.1 → 0.2.3

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 CHANGED
@@ -8,12 +8,22 @@ npm i @aventoapp/framework
8
8
 
9
9
  | Subpath | What it holds |
10
10
  |---|---|
11
- | `@aventoapp/framework/server` | Express middleware, database clients, workflow engine, services, and the server half of the offline kit (`applyFieldLWW`) |
12
- | `@aventoapp/framework/web` | React web modules |
11
+ | `@aventoapp/framework/server` | Express middleware, the Postgres client, workflow engine, services, and the server half of the offline kit (`applyFieldLWW`) |
12
+ | `@aventoapp/framework/server/mongo` | The MongoDB client (`MongoConnection`, `getMongoConnection`, `createMongoConnection`, `mongoose`). Install `mongoose` beside the framework to use it |
13
+ | `@aventoapp/framework/web` | React web modules. Install `@mui/material`, `@mui/icons-material`, `@emotion/react` and `@emotion/styled` beside the framework to use it |
13
14
  | `@aventoapp/framework/shared` | Code shared by server and web |
14
15
  | `@aventoapp/framework/offline` | The offline sync kit: read cache, write outbox, sync engine. No React, no DOM required |
15
16
  | `@aventoapp/framework/native` | React Native modules |
16
17
 
18
+ Since 0.2.3 the framework does not install Mongoose, MUI or Emotion, and
19
+ `/server` does not load Mongoose: an app that never touches MongoDB or the
20
+ React web modules paid ~15 MB of heap and ~300 ms at boot, and 100+ MB of
21
+ packages, for them (bwoody77/vector#6334). They are not peer dependencies
22
+ either, optional or not: npm 11 still resolves an optional peer, so MUI's
23
+ Emotion would drag in React and break an install whose React does not match
24
+ this package's own `react` peer. An app that uses `/web` or `/server/mongo`
25
+ lists them in its own `package.json`.
26
+
17
27
  ## Offline sync kit
18
28
 
19
29
  The kit lets a web or mobile client keep working with no signal. Reads come
@@ -179,7 +189,7 @@ router.patch('/api/trips/:id', async (req, res) => {
179
189
  const fields = Object.fromEntries(Object.entries(body).filter(([k]) => EDITABLE.includes(k)));
180
190
 
181
191
  if (_fieldTimes && typeof _fieldTimes === 'object') {
182
- const result = await applyFieldLWW(client, {
192
+ const result = await applyFieldLWW(req.db, {
183
193
  table: 'trips',
184
194
  id: req.params.id,
185
195
  tenantId: req.tenant.id,
@@ -200,11 +210,18 @@ tenantCol = 'tenant_id', fieldTsCol = 'field_ts' })` reads the row's
200
210
  `field_ts`, writes each field whose incoming timestamp is greater than or equal
201
211
  to the stored one, stores the new timestamps, and sets `updated_at = now()`.
202
212
  A field with no timestamp counts as `0`, so it loses to any timestamped write
203
- and wins only where nothing was ever stamped. `db` is anything with
204
- `query(sql, params)`: pass the client of the transaction you are in, so the
205
- read and the write see the same row. It resolves to
206
- `{ applied, skipped }`, or `{ applied: [], skipped, notFound: true }` when no
207
- row matches the id and tenant.
213
+ and wins only where nothing was ever stamped.
214
+
215
+ It reads `field_ts` with `SELECT ... FOR UPDATE` and holds that row lock
216
+ through the write, so two replays of one record racing each other keep both
217
+ stamps. `db` is a pg client, a `pg.Pool`, or the framework connection:
218
+ inside a transaction you opened, it locks and writes there and leaves the
219
+ commit to you (the lock lasts until you commit); on a client with no
220
+ transaction it opens and commits one; on a pool it checks out a client, runs
221
+ its own transaction and releases it. You do not wrap it in a lock of your own.
222
+ A handle with only `query()` is refused, since its statements could run on
223
+ different connections. It resolves to `{ applied, skipped }`, or
224
+ `{ applied: [], skipped, notFound: true }` when no row matches the id and tenant.
208
225
 
209
226
  `buildFieldLWWUpdate({ fields, fieldTimes, storedFieldTs })` is the same
210
227
  decision with no database, for tests or for a store that is not Postgres.
@@ -249,12 +266,26 @@ Kit methods: `defineSyncedResource(def)`, `readSynced(name, id)`,
249
266
  Releases publish from GitHub Actions with npm Trusted Publishing
250
267
  (`.github/workflows/publish-framework.yml`), so no token and no 2FA prompt.
251
268
  Bump `version` in `package.json` (and the `packages/framework` entry in the
252
- root `package-lock.json`), commit, then push a tag matching the version:
269
+ root `package-lock.json`), commit and push `master`, then tag that commit
270
+ and push the tag ON ITS OWN:
253
271
 
254
272
  ```bash
255
- git tag framework-v0.2.1
256
- git push origin master framework-v0.2.1
273
+ git push origin master
274
+ git tag framework-v0.2.2
275
+ git push origin framework-v0.2.2
257
276
  ```
258
277
 
278
+ Two pushes, not one. 0.2.1's tag rode in the same push as the commit that
279
+ first added the workflow file (`git push origin master framework-v0.2.1`),
280
+ and GitHub registered the workflow from that push without starting a run for
281
+ the tag. A tag pushed by itself, after its commit is already on GitHub, is a
282
+ plain `push` event that `framework-v*.*.*` matches.
283
+
259
284
  The workflow checks that the tag matches the version, runs the offline kit's
260
285
  tests, and runs `npm publish`, whose `prepublishOnly` builds `dist/` first.
286
+
287
+ If a tag push still starts no run, start it by hand on the tag:
288
+ `gh workflow run publish-framework.yml --repo bwoody77/avento --ref framework-v0.2.2`.
289
+ A publish that fails with `OIDC token exchange error - package not found`
290
+ means the Trusted Publisher on npmjs.com does not match: user `bwoody77`,
291
+ repository `avento`, workflow `publish-framework.yml`, environment blank.
@@ -1126,13 +1126,9 @@ function requireEntityRoleOr(entityType, getEntityId, ...globalRoles) {
1126
1126
  // src/server/db/index.js
1127
1127
  var db_exports = {};
1128
1128
  __export(db_exports, {
1129
- MongoConnection: () => MongoConnection,
1130
1129
  PostgresConnection: () => PostgresConnection,
1131
- createMongoConnection: () => createMongoConnection,
1132
1130
  createPostgresConnection: () => createPostgresConnection,
1133
- getMongoConnection: () => getMongoConnection,
1134
- getPostgresConnection: () => getPostgresConnection,
1135
- mongoose: () => mongoose
1131
+ getPostgresConnection: () => getPostgresConnection
1136
1132
  });
1137
1133
 
1138
1134
  // src/server/db/postgres.js
@@ -1248,109 +1244,6 @@ function createPostgresConnection(config) {
1248
1244
  return new PostgresConnection(config);
1249
1245
  }
1250
1246
 
1251
- // src/server/db/mongo.js
1252
- import mongoose from "mongoose";
1253
- var MongoConnection = class {
1254
- constructor(config = {}) {
1255
- this.config = {
1256
- host: config.host || process.env.MONGO_HOST || "localhost",
1257
- port: config.port || process.env.MONGO_PORT || 27017,
1258
- database: config.database || process.env.MONGO_DB || "avento",
1259
- user: config.user || process.env.MONGO_USER || "",
1260
- password: config.password || process.env.MONGO_PASSWORD || "",
1261
- options: config.options || {}
1262
- };
1263
- this.connection = null;
1264
- }
1265
- /**
1266
- * Build MongoDB connection URI
1267
- */
1268
- _buildUri() {
1269
- const { host, port, database, user, password } = this.config;
1270
- if (user && password) {
1271
- return `mongodb://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${host}:${port}/${database}`;
1272
- }
1273
- return `mongodb://${host}:${port}/${database}`;
1274
- }
1275
- /**
1276
- * Connect to MongoDB
1277
- */
1278
- async connect() {
1279
- if (this.connection && this.connection.readyState === 1) {
1280
- return this.connection;
1281
- }
1282
- const uri = this.config.uri || this._buildUri();
1283
- const options = {
1284
- maxPoolSize: 10,
1285
- serverSelectionTimeoutMS: 5e3,
1286
- socketTimeoutMS: 45e3,
1287
- ...this.config.options
1288
- };
1289
- try {
1290
- this.connection = await mongoose.connect(uri, options);
1291
- console.log(`[MongoDB] Connected to ${this.config.host}:${this.config.port}/${this.config.database}`);
1292
- mongoose.connection.on("error", (err) => {
1293
- console.error("[MongoDB] Connection error:", err);
1294
- });
1295
- mongoose.connection.on("disconnected", () => {
1296
- console.log("[MongoDB] Disconnected");
1297
- });
1298
- return this.connection;
1299
- } catch (err) {
1300
- console.error("[MongoDB] Connection failed:", err.message);
1301
- throw err;
1302
- }
1303
- }
1304
- /**
1305
- * Get the Mongoose connection
1306
- */
1307
- getConnection() {
1308
- return mongoose.connection;
1309
- }
1310
- /**
1311
- * Get or create a model (with tenant scoping support)
1312
- * @param {string} name - Model name
1313
- * @param {Object} schema - Mongoose schema definition
1314
- * @param {Object} options - Schema options
1315
- */
1316
- createModel(name, schemaDefinition, options = {}) {
1317
- const tenantedSchema = {
1318
- tenant_id: {
1319
- type: mongoose.Schema.Types.ObjectId,
1320
- required: true,
1321
- index: true
1322
- },
1323
- ...schemaDefinition
1324
- };
1325
- const schema = new mongoose.Schema(tenantedSchema, {
1326
- timestamps: { createdAt: "created_at", updatedAt: "updated_at" },
1327
- ...options
1328
- });
1329
- schema.index({ tenant_id: 1, created_at: -1 });
1330
- return mongoose.model(name, schema);
1331
- }
1332
- /**
1333
- * Disconnect from MongoDB
1334
- */
1335
- async disconnect() {
1336
- if (mongoose.connection.readyState !== 0) {
1337
- await mongoose.disconnect();
1338
- this.connection = null;
1339
- console.log("[MongoDB] Disconnected");
1340
- }
1341
- }
1342
- };
1343
- var defaultConnection2 = null;
1344
- function getMongoConnection(config) {
1345
- if (!defaultConnection2) {
1346
- defaultConnection2 = new MongoConnection(config);
1347
- }
1348
- return defaultConnection2;
1349
- }
1350
- function createMongoConnection(config) {
1351
- return new MongoConnection(config);
1352
- }
1353
-
1354
1247
  // src/server/utils/index.js
1355
1248
  var utils_exports = {};
1356
1249
  __export(utils_exports, {
@@ -2712,7 +2605,37 @@ function buildFieldLWWUpdate({ fields, fieldTimes = {}, storedFieldTs = {} }) {
2712
2605
  }
2713
2606
  return { winners, nextFieldTs };
2714
2607
  }
2715
- async function applyFieldLWW(db, {
2608
+ async function applyFieldLWW(db, opts) {
2609
+ const { table, idCol = "id", tenantCol = "tenant_id", fieldTsCol = "field_ts" } = opts;
2610
+ assertSafeIdent(table);
2611
+ assertSafeIdent(idCol);
2612
+ assertSafeIdent(tenantCol);
2613
+ assertSafeIdent(fieldTsCol);
2614
+ if (isClient(db)) {
2615
+ if (await inTransaction(db))
2616
+ return lockedApply(db, opts);
2617
+ return inOwnTransaction(db, opts);
2618
+ }
2619
+ const client = await checkOut(db);
2620
+ try {
2621
+ return await inOwnTransaction(client, opts);
2622
+ } finally {
2623
+ client.release();
2624
+ }
2625
+ }
2626
+ async function inOwnTransaction(client, opts) {
2627
+ await client.query("BEGIN");
2628
+ try {
2629
+ const result = await lockedApply(client, opts);
2630
+ await client.query("COMMIT");
2631
+ return result;
2632
+ } catch (err) {
2633
+ await client.query("ROLLBACK").catch(() => {
2634
+ });
2635
+ throw err;
2636
+ }
2637
+ }
2638
+ async function lockedApply(db, {
2716
2639
  table,
2717
2640
  id,
2718
2641
  tenantId,
@@ -2722,11 +2645,7 @@ async function applyFieldLWW(db, {
2722
2645
  tenantCol = "tenant_id",
2723
2646
  fieldTsCol = "field_ts"
2724
2647
  }) {
2725
- assertSafeIdent(table);
2726
- assertSafeIdent(idCol);
2727
- assertSafeIdent(tenantCol);
2728
- assertSafeIdent(fieldTsCol);
2729
- const readSql = `SELECT ${fieldTsCol} AS field_ts FROM ${table} WHERE ${idCol} = $1 AND ${tenantCol} = $2`;
2648
+ const readSql = `SELECT ${fieldTsCol} AS field_ts FROM ${table} WHERE ${idCol} = $1 AND ${tenantCol} = $2 FOR UPDATE`;
2730
2649
  const read = await db.query(readSql, [id, tenantId]);
2731
2650
  if (read.rows.length === 0) {
2732
2651
  return { applied: [], skipped: Object.keys(fields), notFound: true };
@@ -2757,6 +2676,43 @@ async function applyFieldLWW(db, {
2757
2676
  const skipped = Object.keys(fields).filter((c) => !winnerCols.includes(c));
2758
2677
  return { applied: winnerCols, skipped };
2759
2678
  }
2679
+ function isClient(db) {
2680
+ return !!db && typeof db.query === "function" && (typeof db.release === "function" || typeof db.getTransactionStatus === "function" || "processID" in db);
2681
+ }
2682
+ async function checkOut(db) {
2683
+ let client;
2684
+ if (db && typeof db.getClient === "function")
2685
+ client = await db.getClient();
2686
+ else if (db && typeof db.connect === "function")
2687
+ client = await db.connect();
2688
+ else {
2689
+ throw new TypeError(
2690
+ "applyFieldLWW: pass a client, a pg.Pool or the framework connection. A handle with only query() cannot hold the row lock across the read and the write."
2691
+ );
2692
+ }
2693
+ if (!client || typeof client.query !== "function" || typeof client.release !== "function") {
2694
+ throw new TypeError("applyFieldLWW: the handle checked out something with no release(), so not a client.");
2695
+ }
2696
+ return client;
2697
+ }
2698
+ async function inTransaction(client) {
2699
+ if (typeof client.getTransactionStatus === "function") {
2700
+ const status = client.getTransactionStatus();
2701
+ if (status === "T" || status === "E")
2702
+ return true;
2703
+ if (status === "I")
2704
+ return false;
2705
+ }
2706
+ try {
2707
+ await client.query("SAVEPOINT avento_field_lww_probe");
2708
+ } catch (err) {
2709
+ if (err && err.code === "25P01")
2710
+ return false;
2711
+ throw err;
2712
+ }
2713
+ await client.query("RELEASE SAVEPOINT avento_field_lww_probe");
2714
+ return true;
2715
+ }
2760
2716
  function assertSafeIdent(name) {
2761
2717
  if (!/^[a-z_][a-z0-9_]*$/i.test(name)) {
2762
2718
  throw new Error(`Unsafe SQL identifier: ${name}`);
@@ -2767,7 +2723,6 @@ export {
2767
2723
  EmailService,
2768
2724
  EventBus,
2769
2725
  MemoryCache,
2770
- MongoConnection,
2771
2726
  PostgresConnection,
2772
2727
  QueryBuilder,
2773
2728
  SmtpEmailService,
@@ -2788,7 +2743,6 @@ export {
2788
2743
  createEmailService,
2789
2744
  createForgotPasswordHandler,
2790
2745
  createLoginHandler,
2791
- createMongoConnection,
2792
2746
  createPermissionChecker,
2793
2747
  createPostgresConnection,
2794
2748
  createQueryBuilder,
@@ -2811,7 +2765,6 @@ export {
2811
2765
  generateToken,
2812
2766
  generateTokenExpiry,
2813
2767
  getCache,
2814
- getMongoConnection,
2815
2768
  getPostgresConnection,
2816
2769
  getSqlPagination,
2817
2770
  getTenantId,
@@ -2824,7 +2777,6 @@ export {
2824
2777
  initAuth,
2825
2778
  isValidUUID,
2826
2779
  middleware_exports as middleware,
2827
- mongoose,
2828
2780
  mountGeneratedRoutes,
2829
2781
  offline_exports as offline,
2830
2782
  optionalAuth,