s3db.js 7.2.0 → 7.3.1

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/dist/s3db.iife.js CHANGED
@@ -7905,583 +7905,6 @@ ${JSON.stringify(validation, null, 2)}`,
7905
7905
  }
7906
7906
  }
7907
7907
 
7908
- class BaseReplicator extends EventEmitter {
7909
- constructor(config = {}) {
7910
- super();
7911
- this.config = config;
7912
- this.name = this.constructor.name;
7913
- this.enabled = config.enabled !== false;
7914
- }
7915
- /**
7916
- * Initialize the replicator
7917
- * @param {Object} database - The s3db database instance
7918
- * @returns {Promise<void>}
7919
- */
7920
- async initialize(database) {
7921
- this.database = database;
7922
- this.emit("initialized", { replicator: this.name });
7923
- }
7924
- /**
7925
- * Replicate data to the target
7926
- * @param {string} resourceName - Name of the resource being replicated
7927
- * @param {string} operation - Operation type (insert, update, delete)
7928
- * @param {Object} data - The data to replicate
7929
- * @param {string} id - Record ID
7930
- * @returns {Promise<Object>} replicator result
7931
- */
7932
- async replicate(resourceName, operation, data, id) {
7933
- throw new Error(`replicate() method must be implemented by ${this.name}`);
7934
- }
7935
- /**
7936
- * Replicate multiple records in batch
7937
- * @param {string} resourceName - Name of the resource being replicated
7938
- * @param {Array} records - Array of records to replicate
7939
- * @returns {Promise<Object>} Batch replicator result
7940
- */
7941
- async replicateBatch(resourceName, records) {
7942
- throw new Error(`replicateBatch() method must be implemented by ${this.name}`);
7943
- }
7944
- /**
7945
- * Test the connection to the target
7946
- * @returns {Promise<boolean>} True if connection is successful
7947
- */
7948
- async testConnection() {
7949
- throw new Error(`testConnection() method must be implemented by ${this.name}`);
7950
- }
7951
- /**
7952
- * Get replicator status and statistics
7953
- * @returns {Promise<Object>} Status information
7954
- */
7955
- async getStatus() {
7956
- return {
7957
- name: this.name,
7958
- // Removed: enabled: this.enabled,
7959
- config: this.config,
7960
- connected: false
7961
- };
7962
- }
7963
- /**
7964
- * Cleanup resources
7965
- * @returns {Promise<void>}
7966
- */
7967
- async cleanup() {
7968
- this.emit("cleanup", { replicator: this.name });
7969
- }
7970
- /**
7971
- * Validate replicator configuration
7972
- * @returns {Object} Validation result
7973
- */
7974
- validateConfig() {
7975
- return { isValid: true, errors: [] };
7976
- }
7977
- }
7978
- var base_replicator_class_default = BaseReplicator;
7979
-
7980
- class BigqueryReplicator extends base_replicator_class_default {
7981
- constructor(config = {}, resources = {}) {
7982
- super(config);
7983
- this.projectId = config.projectId;
7984
- this.datasetId = config.datasetId;
7985
- this.bigqueryClient = null;
7986
- this.credentials = config.credentials;
7987
- this.location = config.location || "US";
7988
- this.logTable = config.logTable;
7989
- this.resources = this.parseResourcesConfig(resources);
7990
- }
7991
- parseResourcesConfig(resources) {
7992
- const parsed = {};
7993
- for (const [resourceName, config] of Object.entries(resources)) {
7994
- if (typeof config === "string") {
7995
- parsed[resourceName] = [{
7996
- table: config,
7997
- actions: ["insert"]
7998
- }];
7999
- } else if (Array.isArray(config)) {
8000
- parsed[resourceName] = config.map((item) => {
8001
- if (typeof item === "string") {
8002
- return { table: item, actions: ["insert"] };
8003
- }
8004
- return {
8005
- table: item.table,
8006
- actions: item.actions || ["insert"]
8007
- };
8008
- });
8009
- } else if (typeof config === "object") {
8010
- parsed[resourceName] = [{
8011
- table: config.table,
8012
- actions: config.actions || ["insert"]
8013
- }];
8014
- }
8015
- }
8016
- return parsed;
8017
- }
8018
- validateConfig() {
8019
- const errors = [];
8020
- if (!this.projectId) errors.push("projectId is required");
8021
- if (!this.datasetId) errors.push("datasetId is required");
8022
- if (Object.keys(this.resources).length === 0) errors.push("At least one resource must be configured");
8023
- for (const [resourceName, tables] of Object.entries(this.resources)) {
8024
- for (const tableConfig of tables) {
8025
- if (!tableConfig.table) {
8026
- errors.push(`Table name is required for resource '${resourceName}'`);
8027
- }
8028
- if (!Array.isArray(tableConfig.actions) || tableConfig.actions.length === 0) {
8029
- errors.push(`Actions array is required for resource '${resourceName}'`);
8030
- }
8031
- const validActions = ["insert", "update", "delete"];
8032
- const invalidActions = tableConfig.actions.filter((action) => !validActions.includes(action));
8033
- if (invalidActions.length > 0) {
8034
- errors.push(`Invalid actions for resource '${resourceName}': ${invalidActions.join(", ")}. Valid actions: ${validActions.join(", ")}`);
8035
- }
8036
- }
8037
- }
8038
- return { isValid: errors.length === 0, errors };
8039
- }
8040
- async initialize(database) {
8041
- await super.initialize(database);
8042
- const [ok, err, sdk] = await try_fn_default(() => import('@google-cloud/bigquery'));
8043
- if (!ok) {
8044
- this.emit("initialization_error", { replicator: this.name, error: err.message });
8045
- throw err;
8046
- }
8047
- const { BigQuery } = sdk;
8048
- this.bigqueryClient = new BigQuery({
8049
- projectId: this.projectId,
8050
- credentials: this.credentials,
8051
- location: this.location
8052
- });
8053
- this.emit("initialized", {
8054
- replicator: this.name,
8055
- projectId: this.projectId,
8056
- datasetId: this.datasetId,
8057
- resources: Object.keys(this.resources)
8058
- });
8059
- }
8060
- shouldReplicateResource(resourceName) {
8061
- return this.resources.hasOwnProperty(resourceName);
8062
- }
8063
- shouldReplicateAction(resourceName, operation) {
8064
- if (!this.resources[resourceName]) return false;
8065
- return this.resources[resourceName].some(
8066
- (tableConfig) => tableConfig.actions.includes(operation)
8067
- );
8068
- }
8069
- getTablesForResource(resourceName, operation) {
8070
- if (!this.resources[resourceName]) return [];
8071
- return this.resources[resourceName].filter((tableConfig) => tableConfig.actions.includes(operation)).map((tableConfig) => tableConfig.table);
8072
- }
8073
- async replicate(resourceName, operation, data, id, beforeData = null) {
8074
- if (!this.enabled || !this.shouldReplicateResource(resourceName)) {
8075
- return { skipped: true, reason: "resource_not_included" };
8076
- }
8077
- if (!this.shouldReplicateAction(resourceName, operation)) {
8078
- return { skipped: true, reason: "action_not_included" };
8079
- }
8080
- const tables = this.getTablesForResource(resourceName, operation);
8081
- if (tables.length === 0) {
8082
- return { skipped: true, reason: "no_tables_for_action" };
8083
- }
8084
- const results = [];
8085
- const errors = [];
8086
- const [ok, err, result] = await try_fn_default(async () => {
8087
- const dataset = this.bigqueryClient.dataset(this.datasetId);
8088
- for (const tableId of tables) {
8089
- const [okTable, errTable] = await try_fn_default(async () => {
8090
- const table = dataset.table(tableId);
8091
- let job;
8092
- if (operation === "insert") {
8093
- const row = { ...data };
8094
- job = await table.insert([row]);
8095
- } else if (operation === "update") {
8096
- const keys = Object.keys(data).filter((k) => k !== "id");
8097
- const setClause = keys.map((k) => `${k}=@${k}`).join(", ");
8098
- const params = { id };
8099
- keys.forEach((k) => {
8100
- params[k] = data[k];
8101
- });
8102
- const query = `UPDATE \`${this.projectId}.${this.datasetId}.${tableId}\` SET ${setClause} WHERE id=@id`;
8103
- const [updateJob] = await this.bigqueryClient.createQueryJob({
8104
- query,
8105
- params
8106
- });
8107
- await updateJob.getQueryResults();
8108
- job = [updateJob];
8109
- } else if (operation === "delete") {
8110
- const query = `DELETE FROM \`${this.projectId}.${this.datasetId}.${tableId}\` WHERE id=@id`;
8111
- const [deleteJob] = await this.bigqueryClient.createQueryJob({
8112
- query,
8113
- params: { id }
8114
- });
8115
- await deleteJob.getQueryResults();
8116
- job = [deleteJob];
8117
- } else {
8118
- throw new Error(`Unsupported operation: ${operation}`);
8119
- }
8120
- results.push({
8121
- table: tableId,
8122
- success: true,
8123
- jobId: job[0]?.id
8124
- });
8125
- });
8126
- if (!okTable) {
8127
- errors.push({
8128
- table: tableId,
8129
- error: errTable.message
8130
- });
8131
- }
8132
- }
8133
- if (this.logTable) {
8134
- const [okLog, errLog] = await try_fn_default(async () => {
8135
- const logTable = dataset.table(this.logTable);
8136
- await logTable.insert([{
8137
- resource_name: resourceName,
8138
- operation,
8139
- record_id: id,
8140
- data: JSON.stringify(data),
8141
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
8142
- source: "s3db-replicator"
8143
- }]);
8144
- });
8145
- if (!okLog) {
8146
- }
8147
- }
8148
- const success = errors.length === 0;
8149
- this.emit("replicated", {
8150
- replicator: this.name,
8151
- resourceName,
8152
- operation,
8153
- id,
8154
- tables,
8155
- results,
8156
- errors,
8157
- success
8158
- });
8159
- return {
8160
- success,
8161
- results,
8162
- errors,
8163
- tables
8164
- };
8165
- });
8166
- if (ok) return result;
8167
- this.emit("replicator_error", {
8168
- replicator: this.name,
8169
- resourceName,
8170
- operation,
8171
- id,
8172
- error: err.message
8173
- });
8174
- return { success: false, error: err.message };
8175
- }
8176
- async replicateBatch(resourceName, records) {
8177
- const results = [];
8178
- const errors = [];
8179
- for (const record of records) {
8180
- const [ok, err, res] = await try_fn_default(() => this.replicate(
8181
- resourceName,
8182
- record.operation,
8183
- record.data,
8184
- record.id,
8185
- record.beforeData
8186
- ));
8187
- if (ok) results.push(res);
8188
- else errors.push({ id: record.id, error: err.message });
8189
- }
8190
- return {
8191
- success: errors.length === 0,
8192
- results,
8193
- errors
8194
- };
8195
- }
8196
- async testConnection() {
8197
- const [ok, err] = await try_fn_default(async () => {
8198
- if (!this.bigqueryClient) await this.initialize();
8199
- const dataset = this.bigqueryClient.dataset(this.datasetId);
8200
- await dataset.getMetadata();
8201
- return true;
8202
- });
8203
- if (ok) return true;
8204
- this.emit("connection_error", { replicator: this.name, error: err.message });
8205
- return false;
8206
- }
8207
- async cleanup() {
8208
- }
8209
- getStatus() {
8210
- return {
8211
- ...super.getStatus(),
8212
- projectId: this.projectId,
8213
- datasetId: this.datasetId,
8214
- resources: this.resources,
8215
- logTable: this.logTable
8216
- };
8217
- }
8218
- }
8219
- var bigquery_replicator_class_default = BigqueryReplicator;
8220
-
8221
- class PostgresReplicator extends base_replicator_class_default {
8222
- constructor(config = {}, resources = {}) {
8223
- super(config);
8224
- this.connectionString = config.connectionString;
8225
- this.host = config.host;
8226
- this.port = config.port || 5432;
8227
- this.database = config.database;
8228
- this.user = config.user;
8229
- this.password = config.password;
8230
- this.client = null;
8231
- this.ssl = config.ssl;
8232
- this.logTable = config.logTable;
8233
- this.resources = this.parseResourcesConfig(resources);
8234
- }
8235
- parseResourcesConfig(resources) {
8236
- const parsed = {};
8237
- for (const [resourceName, config] of Object.entries(resources)) {
8238
- if (typeof config === "string") {
8239
- parsed[resourceName] = [{
8240
- table: config,
8241
- actions: ["insert"]
8242
- }];
8243
- } else if (Array.isArray(config)) {
8244
- parsed[resourceName] = config.map((item) => {
8245
- if (typeof item === "string") {
8246
- return { table: item, actions: ["insert"] };
8247
- }
8248
- return {
8249
- table: item.table,
8250
- actions: item.actions || ["insert"]
8251
- };
8252
- });
8253
- } else if (typeof config === "object") {
8254
- parsed[resourceName] = [{
8255
- table: config.table,
8256
- actions: config.actions || ["insert"]
8257
- }];
8258
- }
8259
- }
8260
- return parsed;
8261
- }
8262
- validateConfig() {
8263
- const errors = [];
8264
- if (!this.connectionString && (!this.host || !this.database)) {
8265
- errors.push("Either connectionString or host+database must be provided");
8266
- }
8267
- if (Object.keys(this.resources).length === 0) {
8268
- errors.push("At least one resource must be configured");
8269
- }
8270
- for (const [resourceName, tables] of Object.entries(this.resources)) {
8271
- for (const tableConfig of tables) {
8272
- if (!tableConfig.table) {
8273
- errors.push(`Table name is required for resource '${resourceName}'`);
8274
- }
8275
- if (!Array.isArray(tableConfig.actions) || tableConfig.actions.length === 0) {
8276
- errors.push(`Actions array is required for resource '${resourceName}'`);
8277
- }
8278
- const validActions = ["insert", "update", "delete"];
8279
- const invalidActions = tableConfig.actions.filter((action) => !validActions.includes(action));
8280
- if (invalidActions.length > 0) {
8281
- errors.push(`Invalid actions for resource '${resourceName}': ${invalidActions.join(", ")}. Valid actions: ${validActions.join(", ")}`);
8282
- }
8283
- }
8284
- }
8285
- return { isValid: errors.length === 0, errors };
8286
- }
8287
- async initialize(database) {
8288
- await super.initialize(database);
8289
- const [ok, err, sdk] = await try_fn_default(() => import('pg'));
8290
- if (!ok) {
8291
- this.emit("initialization_error", {
8292
- replicator: this.name,
8293
- error: err.message
8294
- });
8295
- throw err;
8296
- }
8297
- const { Client } = sdk;
8298
- const config = this.connectionString ? {
8299
- connectionString: this.connectionString,
8300
- ssl: this.ssl
8301
- } : {
8302
- host: this.host,
8303
- port: this.port,
8304
- database: this.database,
8305
- user: this.user,
8306
- password: this.password,
8307
- ssl: this.ssl
8308
- };
8309
- this.client = new Client(config);
8310
- await this.client.connect();
8311
- if (this.logTable) {
8312
- await this.createLogTableIfNotExists();
8313
- }
8314
- this.emit("initialized", {
8315
- replicator: this.name,
8316
- database: this.database || "postgres",
8317
- resources: Object.keys(this.resources)
8318
- });
8319
- }
8320
- async createLogTableIfNotExists() {
8321
- const createTableQuery = `
8322
- CREATE TABLE IF NOT EXISTS ${this.logTable} (
8323
- id SERIAL PRIMARY KEY,
8324
- resource_name VARCHAR(255) NOT NULL,
8325
- operation VARCHAR(50) NOT NULL,
8326
- record_id VARCHAR(255) NOT NULL,
8327
- data JSONB,
8328
- timestamp TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
8329
- source VARCHAR(100) DEFAULT 's3db-replicator',
8330
- created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
8331
- );
8332
- CREATE INDEX IF NOT EXISTS idx_${this.logTable}_resource_name ON ${this.logTable}(resource_name);
8333
- CREATE INDEX IF NOT EXISTS idx_${this.logTable}_operation ON ${this.logTable}(operation);
8334
- CREATE INDEX IF NOT EXISTS idx_${this.logTable}_record_id ON ${this.logTable}(record_id);
8335
- CREATE INDEX IF NOT EXISTS idx_${this.logTable}_timestamp ON ${this.logTable}(timestamp);
8336
- `;
8337
- await this.client.query(createTableQuery);
8338
- }
8339
- shouldReplicateResource(resourceName) {
8340
- return this.resources.hasOwnProperty(resourceName);
8341
- }
8342
- shouldReplicateAction(resourceName, operation) {
8343
- if (!this.resources[resourceName]) return false;
8344
- return this.resources[resourceName].some(
8345
- (tableConfig) => tableConfig.actions.includes(operation)
8346
- );
8347
- }
8348
- getTablesForResource(resourceName, operation) {
8349
- if (!this.resources[resourceName]) return [];
8350
- return this.resources[resourceName].filter((tableConfig) => tableConfig.actions.includes(operation)).map((tableConfig) => tableConfig.table);
8351
- }
8352
- async replicate(resourceName, operation, data, id, beforeData = null) {
8353
- if (!this.enabled || !this.shouldReplicateResource(resourceName)) {
8354
- return { skipped: true, reason: "resource_not_included" };
8355
- }
8356
- if (!this.shouldReplicateAction(resourceName, operation)) {
8357
- return { skipped: true, reason: "action_not_included" };
8358
- }
8359
- const tables = this.getTablesForResource(resourceName, operation);
8360
- if (tables.length === 0) {
8361
- return { skipped: true, reason: "no_tables_for_action" };
8362
- }
8363
- const results = [];
8364
- const errors = [];
8365
- const [ok, err, result] = await try_fn_default(async () => {
8366
- for (const table of tables) {
8367
- const [okTable, errTable] = await try_fn_default(async () => {
8368
- let result2;
8369
- if (operation === "insert") {
8370
- const keys = Object.keys(data);
8371
- const values = keys.map((k) => data[k]);
8372
- const columns = keys.map((k) => `"${k}"`).join(", ");
8373
- const params = keys.map((_, i) => `$${i + 1}`).join(", ");
8374
- const sql = `INSERT INTO ${table} (${columns}) VALUES (${params}) ON CONFLICT (id) DO NOTHING RETURNING *`;
8375
- result2 = await this.client.query(sql, values);
8376
- } else if (operation === "update") {
8377
- const keys = Object.keys(data).filter((k) => k !== "id");
8378
- const setClause = keys.map((k, i) => `"${k}"=$${i + 1}`).join(", ");
8379
- const values = keys.map((k) => data[k]);
8380
- values.push(id);
8381
- const sql = `UPDATE ${table} SET ${setClause} WHERE id=$${keys.length + 1} RETURNING *`;
8382
- result2 = await this.client.query(sql, values);
8383
- } else if (operation === "delete") {
8384
- const sql = `DELETE FROM ${table} WHERE id=$1 RETURNING *`;
8385
- result2 = await this.client.query(sql, [id]);
8386
- } else {
8387
- throw new Error(`Unsupported operation: ${operation}`);
8388
- }
8389
- results.push({
8390
- table,
8391
- success: true,
8392
- rows: result2.rows,
8393
- rowCount: result2.rowCount
8394
- });
8395
- });
8396
- if (!okTable) {
8397
- errors.push({
8398
- table,
8399
- error: errTable.message
8400
- });
8401
- }
8402
- }
8403
- if (this.logTable) {
8404
- const [okLog, errLog] = await try_fn_default(async () => {
8405
- await this.client.query(
8406
- `INSERT INTO ${this.logTable} (resource_name, operation, record_id, data, timestamp, source) VALUES ($1, $2, $3, $4, $5, $6)`,
8407
- [resourceName, operation, id, JSON.stringify(data), (/* @__PURE__ */ new Date()).toISOString(), "s3db-replicator"]
8408
- );
8409
- });
8410
- if (!okLog) {
8411
- }
8412
- }
8413
- const success = errors.length === 0;
8414
- this.emit("replicated", {
8415
- replicator: this.name,
8416
- resourceName,
8417
- operation,
8418
- id,
8419
- tables,
8420
- results,
8421
- errors,
8422
- success
8423
- });
8424
- return {
8425
- success,
8426
- results,
8427
- errors,
8428
- tables
8429
- };
8430
- });
8431
- if (ok) return result;
8432
- this.emit("replicator_error", {
8433
- replicator: this.name,
8434
- resourceName,
8435
- operation,
8436
- id,
8437
- error: err.message
8438
- });
8439
- return { success: false, error: err.message };
8440
- }
8441
- async replicateBatch(resourceName, records) {
8442
- const results = [];
8443
- const errors = [];
8444
- for (const record of records) {
8445
- const [ok, err, res] = await try_fn_default(() => this.replicate(
8446
- resourceName,
8447
- record.operation,
8448
- record.data,
8449
- record.id,
8450
- record.beforeData
8451
- ));
8452
- if (ok) results.push(res);
8453
- else errors.push({ id: record.id, error: err.message });
8454
- }
8455
- return {
8456
- success: errors.length === 0,
8457
- results,
8458
- errors
8459
- };
8460
- }
8461
- async testConnection() {
8462
- const [ok, err] = await try_fn_default(async () => {
8463
- if (!this.client) await this.initialize();
8464
- await this.client.query("SELECT 1");
8465
- return true;
8466
- });
8467
- if (ok) return true;
8468
- this.emit("connection_error", { replicator: this.name, error: err.message });
8469
- return false;
8470
- }
8471
- async cleanup() {
8472
- if (this.client) await this.client.end();
8473
- }
8474
- getStatus() {
8475
- return {
8476
- ...super.getStatus(),
8477
- database: this.database || "postgres",
8478
- resources: this.resources,
8479
- logTable: this.logTable
8480
- };
8481
- }
8482
- }
8483
- var postgres_replicator_class_default = PostgresReplicator;
8484
-
8485
7908
  const S3_DEFAULT_REGION = "us-east-1";
8486
7909
  const S3_DEFAULT_ENDPOINT = "https://s3.us-east-1.amazonaws.com";
8487
7910
  class ConnectionString {
@@ -12199,7 +11622,7 @@ ${JSON.stringify(validation, null, 2)}`,
12199
11622
  super();
12200
11623
  this.version = "1";
12201
11624
  this.s3dbVersion = (() => {
12202
- const [ok, err, version] = try_fn_default(() => true ? "7.2.0" : "latest");
11625
+ const [ok, err, version] = try_fn_default(() => true ? "7.2.1" : "latest");
12203
11626
  return ok ? version : "latest";
12204
11627
  })();
12205
11628
  this.resources = {};
@@ -12674,580 +12097,34 @@ ${JSON.stringify(validation, null, 2)}`,
12674
12097
  class S3db extends Database {
12675
12098
  }
12676
12099
 
12677
- function normalizeResourceName$1(name) {
12678
- return typeof name === "string" ? name.trim().toLowerCase() : name;
12679
- }
12680
- class S3dbReplicator extends base_replicator_class_default {
12681
- constructor(config = {}, resources = [], client = null) {
12682
- super(config);
12683
- this.instanceId = Math.random().toString(36).slice(2, 10);
12684
- this.client = client;
12685
- this.connectionString = config.connectionString;
12686
- let normalizedResources = resources;
12687
- if (!resources) normalizedResources = {};
12688
- else if (Array.isArray(resources)) {
12689
- normalizedResources = {};
12690
- for (const res of resources) {
12691
- if (typeof res === "string") normalizedResources[normalizeResourceName$1(res)] = res;
12692
- }
12693
- } else if (typeof resources === "string") {
12694
- normalizedResources[normalizeResourceName$1(resources)] = resources;
12695
- }
12696
- this.resourcesMap = this._normalizeResources(normalizedResources);
12697
- }
12698
- _normalizeResources(resources) {
12699
- if (!resources) return {};
12700
- if (Array.isArray(resources)) {
12701
- const map = {};
12702
- for (const res of resources) {
12703
- if (typeof res === "string") map[normalizeResourceName$1(res)] = res;
12704
- else if (Array.isArray(res) && typeof res[0] === "string") map[normalizeResourceName$1(res[0])] = res;
12705
- else if (typeof res === "object" && res.resource) {
12706
- map[normalizeResourceName$1(res.resource)] = { ...res };
12707
- }
12708
- }
12709
- return map;
12710
- }
12711
- if (typeof resources === "object") {
12712
- const map = {};
12713
- for (const [src, dest] of Object.entries(resources)) {
12714
- const normSrc = normalizeResourceName$1(src);
12715
- if (typeof dest === "string") map[normSrc] = dest;
12716
- else if (Array.isArray(dest)) {
12717
- map[normSrc] = dest.map((item) => {
12718
- if (typeof item === "string") return item;
12719
- if (typeof item === "function") return item;
12720
- if (typeof item === "object" && item.resource) {
12721
- return { ...item };
12722
- }
12723
- return item;
12724
- });
12725
- } else if (typeof dest === "function") map[normSrc] = dest;
12726
- else if (typeof dest === "object" && dest.resource) {
12727
- map[normSrc] = { ...dest };
12728
- }
12729
- }
12730
- return map;
12731
- }
12732
- if (typeof resources === "function") {
12733
- return resources;
12734
- }
12735
- if (typeof resources === "string") {
12736
- const map = { [normalizeResourceName$1(resources)]: resources };
12737
- return map;
12738
- }
12739
- return {};
12740
- }
12741
- validateConfig() {
12742
- const errors = [];
12743
- if (!this.client && !this.connectionString) {
12744
- errors.push("You must provide a client or a connectionString");
12745
- }
12746
- if (!this.resourcesMap || typeof this.resourcesMap === "object" && Object.keys(this.resourcesMap).length === 0) {
12747
- errors.push("You must provide a resources map or array");
12748
- }
12749
- return { isValid: errors.length === 0, errors };
12750
- }
12751
- async initialize(database) {
12752
- try {
12753
- await super.initialize(database);
12754
- if (this.client) {
12755
- this.targetDatabase = this.client;
12756
- } else if (this.connectionString) {
12757
- const targetConfig = {
12758
- connectionString: this.connectionString,
12759
- region: this.region,
12760
- keyPrefix: this.keyPrefix,
12761
- verbose: this.config.verbose || false
12762
- };
12763
- this.targetDatabase = new S3db(targetConfig);
12764
- await this.targetDatabase.connect();
12765
- } else {
12766
- throw new Error("S3dbReplicator: No client or connectionString provided");
12767
- }
12768
- this.emit("connected", {
12769
- replicator: this.name,
12770
- target: this.connectionString || "client-provided"
12771
- });
12772
- } catch (err) {
12773
- throw err;
12774
- }
12775
- }
12776
- // Change signature to accept id
12777
- async replicate({ resource, operation, data, id: explicitId }) {
12778
- const normResource = normalizeResourceName$1(resource);
12779
- const destResource = this._resolveDestResource(normResource, data);
12780
- const destResourceObj = this._getDestResourceObj(destResource);
12781
- const transformedData = this._applyTransformer(normResource, data);
12782
- let result;
12783
- if (operation === "insert") {
12784
- result = await destResourceObj.insert(transformedData);
12785
- } else if (operation === "update") {
12786
- result = await destResourceObj.update(explicitId, transformedData);
12787
- } else if (operation === "delete") {
12788
- result = await destResourceObj.delete(explicitId);
12789
- } else {
12790
- throw new Error(`Invalid operation: ${operation}. Supported operations are: insert, update, delete`);
12791
- }
12792
- return result;
12793
- }
12794
- _applyTransformer(resource, data) {
12795
- const normResource = normalizeResourceName$1(resource);
12796
- const entry = this.resourcesMap[normResource];
12797
- let result;
12798
- if (!entry) return data;
12799
- if (Array.isArray(entry) && typeof entry[1] === "function") {
12800
- result = entry[1](data);
12801
- } else if (typeof entry === "function") {
12802
- result = entry(data);
12803
- } else if (typeof entry === "object") {
12804
- if (typeof entry.transform === "function") result = entry.transform(data);
12805
- else if (typeof entry.transformer === "function") result = entry.transformer(data);
12806
- } else {
12807
- result = data;
12808
- }
12809
- if (result && data && data.id && !result.id) result.id = data.id;
12810
- if (!result && data) result = data;
12811
- return result;
12812
- }
12813
- _resolveDestResource(resource, data) {
12814
- const normResource = normalizeResourceName$1(resource);
12815
- const entry = this.resourcesMap[normResource];
12816
- if (!entry) return resource;
12817
- if (Array.isArray(entry)) {
12818
- if (typeof entry[0] === "string") return entry[0];
12819
- if (typeof entry[0] === "object" && entry[0].resource) return entry[0].resource;
12820
- if (typeof entry[0] === "function") return resource;
12821
- }
12822
- if (typeof entry === "string") return entry;
12823
- if (typeof entry === "function") return resource;
12824
- if (typeof entry === "object" && entry.resource) return entry.resource;
12825
- return resource;
12826
- }
12827
- _getDestResourceObj(resource) {
12828
- if (!this.client || !this.client.resources) return null;
12829
- const available = Object.keys(this.client.resources);
12830
- const norm = normalizeResourceName$1(resource);
12831
- const found = available.find((r) => normalizeResourceName$1(r) === norm);
12832
- if (!found) {
12833
- throw new Error(`[S3dbReplicator] Destination resource not found: ${resource}. Available: ${available.join(", ")}`);
12834
- }
12835
- return this.client.resources[found];
12836
- }
12837
- async replicateBatch(resourceName, records) {
12838
- if (!this.enabled || !this.shouldReplicateResource(resourceName)) {
12839
- return { skipped: true, reason: "resource_not_included" };
12840
- }
12841
- const results = [];
12842
- const errors = [];
12843
- for (const record of records) {
12844
- const [ok, err, result] = await try_fn_default(() => this.replicate({
12845
- resource: resourceName,
12846
- operation: record.operation,
12847
- id: record.id,
12848
- data: record.data,
12849
- beforeData: record.beforeData
12850
- }));
12851
- if (ok) results.push(result);
12852
- else errors.push({ id: record.id, error: err.message });
12853
- }
12854
- this.emit("batch_replicated", {
12855
- replicator: this.name,
12856
- resourceName,
12857
- total: records.length,
12858
- successful: results.length,
12859
- errors: errors.length
12860
- });
12861
- return {
12862
- success: errors.length === 0,
12863
- results,
12864
- errors,
12865
- total: records.length
12866
- };
12867
- }
12868
- async testConnection() {
12869
- const [ok, err] = await try_fn_default(async () => {
12870
- if (!this.targetDatabase) {
12871
- await this.initialize(this.database);
12872
- }
12873
- await this.targetDatabase.listResources();
12874
- return true;
12875
- });
12876
- if (ok) return true;
12877
- this.emit("connection_error", {
12878
- replicator: this.name,
12879
- error: err.message
12880
- });
12881
- return false;
12882
- }
12883
- async getStatus() {
12884
- const baseStatus = await super.getStatus();
12885
- return {
12886
- ...baseStatus,
12887
- connected: !!this.targetDatabase,
12888
- targetDatabase: this.connectionString || "client-provided",
12889
- resources: Object.keys(this.resourcesMap || {}),
12890
- totalreplicators: this.listenerCount("replicated"),
12891
- totalErrors: this.listenerCount("replicator_error")
12892
- };
12893
- }
12894
- async cleanup() {
12895
- if (this.targetDatabase) {
12896
- this.targetDatabase.removeAllListeners();
12897
- }
12898
- await super.cleanup();
12899
- }
12900
- shouldReplicateResource(resource, action) {
12901
- const normResource = normalizeResourceName$1(resource);
12902
- const entry = this.resourcesMap[normResource];
12903
- if (!entry) return false;
12904
- if (!action) return true;
12905
- if (Array.isArray(entry)) {
12906
- for (const item of entry) {
12907
- if (typeof item === "object" && item.resource) {
12908
- if (item.actions && Array.isArray(item.actions)) {
12909
- if (item.actions.includes(action)) return true;
12910
- } else {
12911
- return true;
12912
- }
12913
- } else if (typeof item === "string" || typeof item === "function") {
12914
- return true;
12915
- }
12916
- }
12917
- return false;
12918
- }
12919
- if (typeof entry === "object" && entry.resource) {
12920
- if (entry.actions && Array.isArray(entry.actions)) {
12921
- return entry.actions.includes(action);
12922
- }
12923
- return true;
12924
- }
12925
- if (typeof entry === "string" || typeof entry === "function") {
12926
- return true;
12927
- }
12928
- return false;
12929
- }
12930
- }
12931
- var s3db_replicator_class_default = S3dbReplicator;
12932
-
12933
- class SqsReplicator extends base_replicator_class_default {
12934
- constructor(config = {}, resources = [], client = null) {
12935
- super(config);
12936
- this.resources = resources;
12937
- this.client = client;
12938
- this.queueUrl = config.queueUrl;
12939
- this.queues = config.queues || {};
12940
- this.defaultQueue = config.defaultQueue || config.defaultQueueUrl || config.queueUrlDefault;
12941
- this.region = config.region || "us-east-1";
12942
- this.sqsClient = client || null;
12943
- this.messageGroupId = config.messageGroupId;
12944
- this.deduplicationId = config.deduplicationId;
12945
- if (resources && typeof resources === "object") {
12946
- for (const [resourceName, resourceConfig] of Object.entries(resources)) {
12947
- if (resourceConfig.queueUrl) {
12948
- this.queues[resourceName] = resourceConfig.queueUrl;
12949
- }
12950
- }
12951
- }
12952
- }
12953
- validateConfig() {
12954
- const errors = [];
12955
- if (!this.queueUrl && Object.keys(this.queues).length === 0 && !this.defaultQueue && !this.resourceQueueMap) {
12956
- errors.push("Either queueUrl, queues object, defaultQueue, or resourceQueueMap must be provided");
12957
- }
12958
- return {
12959
- isValid: errors.length === 0,
12960
- errors
12961
- };
12962
- }
12963
- getQueueUrlsForResource(resource) {
12964
- if (this.resourceQueueMap && this.resourceQueueMap[resource]) {
12965
- return this.resourceQueueMap[resource];
12966
- }
12967
- if (this.queues[resource]) {
12968
- return [this.queues[resource]];
12969
- }
12970
- if (this.queueUrl) {
12971
- return [this.queueUrl];
12972
- }
12973
- if (this.defaultQueue) {
12974
- return [this.defaultQueue];
12975
- }
12976
- throw new Error(`No queue URL found for resource '${resource}'`);
12977
- }
12978
- _applyTransformer(resource, data) {
12979
- const entry = this.resources[resource];
12980
- let result = data;
12981
- if (!entry) return data;
12982
- if (typeof entry.transform === "function") {
12983
- result = entry.transform(data);
12984
- } else if (typeof entry.transformer === "function") {
12985
- result = entry.transformer(data);
12986
- }
12987
- return result || data;
12988
- }
12989
- /**
12990
- * Create standardized message structure
12991
- */
12992
- createMessage(resource, operation, data, id, beforeData = null) {
12993
- const baseMessage = {
12994
- resource,
12995
- // padronizado para 'resource'
12996
- action: operation,
12997
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
12998
- source: "s3db-replicator"
12999
- };
13000
- switch (operation) {
13001
- case "insert":
13002
- return {
13003
- ...baseMessage,
13004
- data
13005
- };
13006
- case "update":
13007
- return {
13008
- ...baseMessage,
13009
- before: beforeData,
13010
- data
13011
- };
13012
- case "delete":
13013
- return {
13014
- ...baseMessage,
13015
- data
13016
- };
13017
- default:
13018
- return {
13019
- ...baseMessage,
13020
- data
13021
- };
13022
- }
13023
- }
13024
- async initialize(database, client) {
13025
- await super.initialize(database);
13026
- if (!this.sqsClient) {
13027
- const [ok, err, sdk] = await try_fn_default(() => import('@aws-sdk/client-sqs'));
13028
- if (!ok) {
13029
- this.emit("initialization_error", {
13030
- replicator: this.name,
13031
- error: err.message
13032
- });
13033
- throw err;
13034
- }
13035
- const { SQSClient } = sdk;
13036
- this.sqsClient = client || new SQSClient({
13037
- region: this.region,
13038
- credentials: this.config.credentials
13039
- });
13040
- this.emit("initialized", {
13041
- replicator: this.name,
13042
- queueUrl: this.queueUrl,
13043
- queues: this.queues,
13044
- defaultQueue: this.defaultQueue
13045
- });
13046
- }
13047
- }
13048
- async replicate(resource, operation, data, id, beforeData = null) {
13049
- if (!this.enabled || !this.shouldReplicateResource(resource)) {
13050
- return { skipped: true, reason: "resource_not_included" };
13051
- }
13052
- const [ok, err, result] = await try_fn_default(async () => {
13053
- const { SendMessageCommand } = await import('@aws-sdk/client-sqs');
13054
- const queueUrls = this.getQueueUrlsForResource(resource);
13055
- const transformedData = this._applyTransformer(resource, data);
13056
- const message = this.createMessage(resource, operation, transformedData, id, beforeData);
13057
- const results = [];
13058
- for (const queueUrl of queueUrls) {
13059
- const command = new SendMessageCommand({
13060
- QueueUrl: queueUrl,
13061
- MessageBody: JSON.stringify(message),
13062
- MessageGroupId: this.messageGroupId,
13063
- MessageDeduplicationId: this.deduplicationId ? `${resource}:${operation}:${id}` : void 0
13064
- });
13065
- const result2 = await this.sqsClient.send(command);
13066
- results.push({ queueUrl, messageId: result2.MessageId });
13067
- this.emit("replicated", {
13068
- replicator: this.name,
13069
- resource,
13070
- operation,
13071
- id,
13072
- queueUrl,
13073
- messageId: result2.MessageId,
13074
- success: true
13075
- });
13076
- }
13077
- return { success: true, results };
13078
- });
13079
- if (ok) return result;
13080
- this.emit("replicator_error", {
13081
- replicator: this.name,
13082
- resource,
13083
- operation,
13084
- id,
13085
- error: err.message
13086
- });
13087
- return { success: false, error: err.message };
13088
- }
13089
- async replicateBatch(resource, records) {
13090
- if (!this.enabled || !this.shouldReplicateResource(resource)) {
13091
- return { skipped: true, reason: "resource_not_included" };
13092
- }
13093
- const [ok, err, result] = await try_fn_default(async () => {
13094
- const { SendMessageBatchCommand } = await import('@aws-sdk/client-sqs');
13095
- const queueUrls = this.getQueueUrlsForResource(resource);
13096
- const batchSize = 10;
13097
- const batches = [];
13098
- for (let i = 0; i < records.length; i += batchSize) {
13099
- batches.push(records.slice(i, i + batchSize));
13100
- }
13101
- const results = [];
13102
- const errors = [];
13103
- for (const batch of batches) {
13104
- const [okBatch, errBatch] = await try_fn_default(async () => {
13105
- const entries = batch.map((record, index) => ({
13106
- Id: `${record.id}-${index}`,
13107
- MessageBody: JSON.stringify(this.createMessage(
13108
- resource,
13109
- record.operation,
13110
- record.data,
13111
- record.id,
13112
- record.beforeData
13113
- )),
13114
- MessageGroupId: this.messageGroupId,
13115
- MessageDeduplicationId: this.deduplicationId ? `${resource}:${record.operation}:${record.id}` : void 0
13116
- }));
13117
- const command = new SendMessageBatchCommand({
13118
- QueueUrl: queueUrls[0],
13119
- // Assuming all queueUrls in a batch are the same for batching
13120
- Entries: entries
13121
- });
13122
- const result2 = await this.sqsClient.send(command);
13123
- results.push(result2);
13124
- });
13125
- if (!okBatch) {
13126
- errors.push({ batch: batch.length, error: errBatch.message });
13127
- if (errBatch.message && (errBatch.message.includes("Batch error") || errBatch.message.includes("Connection") || errBatch.message.includes("Network"))) {
13128
- throw errBatch;
13129
- }
13130
- }
13131
- }
13132
- this.emit("batch_replicated", {
13133
- replicator: this.name,
13134
- resource,
13135
- queueUrl: queueUrls[0],
13136
- // Assuming all queueUrls in a batch are the same for batching
13137
- total: records.length,
13138
- successful: results.length,
13139
- errors: errors.length
13140
- });
13141
- return {
13142
- success: errors.length === 0,
13143
- results,
13144
- errors,
13145
- total: records.length,
13146
- queueUrl: queueUrls[0]
13147
- // Assuming all queueUrls in a batch are the same for batching
13148
- };
13149
- });
13150
- if (ok) return result;
13151
- const errorMessage = err?.message || err || "Unknown error";
13152
- this.emit("batch_replicator_error", {
13153
- replicator: this.name,
13154
- resource,
13155
- error: errorMessage
13156
- });
13157
- return { success: false, error: errorMessage };
13158
- }
13159
- async testConnection() {
13160
- const [ok, err] = await try_fn_default(async () => {
13161
- if (!this.sqsClient) {
13162
- await this.initialize(this.database);
13163
- }
13164
- const { GetQueueAttributesCommand } = await import('@aws-sdk/client-sqs');
13165
- const command = new GetQueueAttributesCommand({
13166
- QueueUrl: this.queueUrl,
13167
- AttributeNames: ["QueueArn"]
13168
- });
13169
- await this.sqsClient.send(command);
13170
- return true;
13171
- });
13172
- if (ok) return true;
13173
- this.emit("connection_error", {
13174
- replicator: this.name,
13175
- error: err.message
13176
- });
13177
- return false;
13178
- }
13179
- async getStatus() {
13180
- const baseStatus = await super.getStatus();
13181
- return {
13182
- ...baseStatus,
13183
- connected: !!this.sqsClient,
13184
- queueUrl: this.queueUrl,
13185
- region: this.region,
13186
- resources: this.resources,
13187
- totalreplicators: this.listenerCount("replicated"),
13188
- totalErrors: this.listenerCount("replicator_error")
13189
- };
13190
- }
13191
- async cleanup() {
13192
- if (this.sqsClient) {
13193
- this.sqsClient.destroy();
13194
- }
13195
- await super.cleanup();
13196
- }
13197
- shouldReplicateResource(resource) {
13198
- const result = this.resourceQueueMap && Object.keys(this.resourceQueueMap).includes(resource) || this.queues && Object.keys(this.queues).includes(resource) || !!(this.defaultQueue || this.queueUrl) || this.resources && Object.keys(this.resources).includes(resource) || false;
13199
- return result;
13200
- }
13201
- }
13202
- var sqs_replicator_class_default = SqsReplicator;
13203
-
13204
- const REPLICATOR_DRIVERS = {
13205
- s3db: s3db_replicator_class_default,
13206
- sqs: sqs_replicator_class_default,
13207
- bigquery: bigquery_replicator_class_default,
13208
- postgres: postgres_replicator_class_default
13209
- };
13210
- function createReplicator(driver, config = {}, resources = [], client = null) {
13211
- const ReplicatorClass = REPLICATOR_DRIVERS[driver];
13212
- if (!ReplicatorClass) {
13213
- throw new Error(`Unknown replicator driver: ${driver}. Available drivers: ${Object.keys(REPLICATOR_DRIVERS).join(", ")}`);
13214
- }
13215
- return new ReplicatorClass(config, resources, client);
13216
- }
13217
-
13218
12100
  function normalizeResourceName(name) {
13219
12101
  return typeof name === "string" ? name.trim().toLowerCase() : name;
13220
12102
  }
13221
12103
  class ReplicatorPlugin extends plugin_class_default {
13222
12104
  constructor(options = {}) {
13223
12105
  super();
13224
- if (options.verbose) {
13225
- console.log("[PLUGIN][CONSTRUCTOR] ReplicatorPlugin constructor called");
13226
- }
13227
- if (options.verbose) {
13228
- console.log("[PLUGIN][constructor] New ReplicatorPlugin instance created with config:", options);
13229
- }
13230
12106
  if (!options.replicators || !Array.isArray(options.replicators)) {
13231
12107
  throw new Error("ReplicatorPlugin: replicators array is required");
13232
12108
  }
13233
12109
  for (const rep of options.replicators) {
13234
12110
  if (!rep.driver) throw new Error("ReplicatorPlugin: each replicator must have a driver");
12111
+ if (!rep.resources || typeof rep.resources !== "object") throw new Error("ReplicatorPlugin: each replicator must have resources config");
12112
+ if (Object.keys(rep.resources).length === 0) throw new Error("ReplicatorPlugin: each replicator must have at least one resource configured");
13235
12113
  }
13236
12114
  this.config = {
13237
- verbose: options.verbose ?? false,
13238
- persistReplicatorLog: options.persistReplicatorLog ?? false,
13239
- replicatorLogResource: options.replicatorLogResource ?? "replicator_logs",
13240
- replicators: options.replicators || []
12115
+ replicators: options.replicators || [],
12116
+ logErrors: options.logErrors !== false,
12117
+ replicatorLogResource: options.replicatorLogResource || "replicator_log",
12118
+ enabled: options.enabled !== false,
12119
+ batchSize: options.batchSize || 100,
12120
+ maxRetries: options.maxRetries || 3,
12121
+ timeout: options.timeout || 3e4,
12122
+ verbose: options.verbose || false,
12123
+ ...options
13241
12124
  };
13242
12125
  this.replicators = [];
13243
- this.queue = [];
13244
- this.isProcessing = false;
13245
- this.stats = {
13246
- totalOperations: 0,
13247
- totalErrors: 0,
13248
- lastError: null
13249
- };
13250
- this._installedListeners = [];
12126
+ this.database = null;
12127
+ this.eventListenersInstalled = /* @__PURE__ */ new Set();
13251
12128
  }
13252
12129
  /**
13253
12130
  * Decompress data if it was compressed
@@ -13266,79 +12143,34 @@ ${JSON.stringify(validation, null, 2)}`,
13266
12143
  }
13267
12144
  return filtered;
13268
12145
  }
13269
- installEventListeners(resource) {
13270
- const plugin = this;
13271
- if (plugin.config.verbose) {
13272
- console.log("[PLUGIN] installEventListeners called for:", resource && resource.name, {
13273
- hasDatabase: !!resource.database,
13274
- sameDatabase: resource.database === plugin.database,
13275
- alreadyInstalled: resource._replicatorListenersInstalled,
13276
- resourceObj: resource,
13277
- resourceObjId: resource && resource.id,
13278
- resourceObjType: typeof resource,
13279
- resourceObjIs: resource && Object.is(resource, plugin.database.resources && plugin.database.resources[resource.name]),
13280
- resourceObjEq: resource === (plugin.database.resources && plugin.database.resources[resource.name])
13281
- });
13282
- }
13283
- if (!resource || resource.name === plugin.config.replicatorLogResource || !resource.database || resource.database !== plugin.database) return;
13284
- if (resource._replicatorListenersInstalled) return;
13285
- resource._replicatorListenersInstalled = true;
13286
- this._installedListeners.push(resource);
13287
- if (plugin.config.verbose) {
13288
- console.log(`[PLUGIN] installEventListeners INSTALLED for resource: ${resource && resource.name}`);
12146
+ installEventListeners(resource, database, plugin) {
12147
+ if (!resource || this.eventListenersInstalled.has(resource.name)) {
12148
+ return;
13289
12149
  }
13290
12150
  resource.on("insert", async (data) => {
13291
- if (plugin.config.verbose) {
13292
- console.log("[PLUGIN] Listener INSERT on", resource.name, "plugin.replicators.length:", plugin.replicators.length, plugin.replicators.map((r) => ({ id: r.id, driver: r.driver })));
13293
- }
13294
12151
  try {
13295
- const completeData = await plugin.getCompleteData(resource, data);
13296
- if (plugin.config.verbose) {
13297
- console.log(`[PLUGIN] Listener INSERT completeData for ${resource.name} id=${data && data.id}:`, completeData);
13298
- }
13299
- await plugin.processReplicatorEvent(resource.name, "insert", data.id, completeData, null);
13300
- } catch (err) {
13301
- if (plugin.config.verbose) {
13302
- console.error(`[PLUGIN] Listener INSERT error on ${resource.name} id=${data && data.id}:`, err);
13303
- }
12152
+ const completeData = { ...data, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
12153
+ await plugin.processReplicatorEvent("insert", resource.name, completeData.id, completeData);
12154
+ } catch (error) {
12155
+ this.emit("error", { operation: "insert", error: error.message, resource: resource.name });
13304
12156
  }
13305
12157
  });
13306
- resource.on("update", async (data) => {
13307
- console.log("[PLUGIN][Listener][UPDATE][START] triggered for resource:", resource.name, "data:", data);
13308
- const beforeData = data && data.$before;
13309
- if (plugin.config.verbose) {
13310
- console.log("[PLUGIN] Listener UPDATE on", resource.name, "plugin.replicators.length:", plugin.replicators.length, plugin.replicators.map((r) => ({ id: r.id, driver: r.driver })), "data:", data, "beforeData:", beforeData);
13311
- }
12158
+ resource.on("update", async (data, beforeData) => {
13312
12159
  try {
13313
- let completeData;
13314
- const [ok, err, record] = await try_fn_default(() => resource.get(data.id));
13315
- if (ok && record) {
13316
- completeData = record;
13317
- } else {
13318
- completeData = data;
13319
- }
13320
- await plugin.processReplicatorEvent(resource.name, "update", data.id, completeData, beforeData);
13321
- } catch (err) {
13322
- if (plugin.config.verbose) {
13323
- console.error(`[PLUGIN] Listener UPDATE erro em ${resource.name} id=${data && data.id}:`, err);
13324
- }
12160
+ const completeData = { ...data, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
12161
+ await plugin.processReplicatorEvent("update", resource.name, completeData.id, completeData, beforeData);
12162
+ } catch (error) {
12163
+ this.emit("error", { operation: "update", error: error.message, resource: resource.name });
13325
12164
  }
13326
12165
  });
13327
- resource.on("delete", async (data, beforeData) => {
13328
- if (plugin.config.verbose) {
13329
- console.log("[PLUGIN] Listener DELETE on", resource.name, "plugin.replicators.length:", plugin.replicators.length, plugin.replicators.map((r) => ({ id: r.id, driver: r.driver })));
13330
- }
12166
+ resource.on("delete", async (data) => {
13331
12167
  try {
13332
- await plugin.processReplicatorEvent(resource.name, "delete", data.id, null, beforeData);
13333
- } catch (err) {
13334
- if (plugin.config.verbose) {
13335
- console.error(`[PLUGIN] Listener DELETE erro em ${resource.name} id=${data && data.id}:`, err);
13336
- }
12168
+ await plugin.processReplicatorEvent("delete", resource.name, data.id, data);
12169
+ } catch (error) {
12170
+ this.emit("error", { operation: "delete", error: error.message, resource: resource.name });
13337
12171
  }
13338
12172
  });
13339
- if (plugin.config.verbose) {
13340
- console.log(`[PLUGIN] Listeners instalados para resource: ${resource && resource.name} (insert: ${resource.listenerCount("insert")}, update: ${resource.listenerCount("update")}, delete: ${resource.listenerCount("delete")})`);
13341
- }
12173
+ this.eventListenersInstalled.add(resource.name);
13342
12174
  }
13343
12175
  /**
13344
12176
  * Get complete data by always fetching the full record from the resource
@@ -13349,112 +12181,53 @@ ${JSON.stringify(validation, null, 2)}`,
13349
12181
  return ok ? completeRecord : data;
13350
12182
  }
13351
12183
  async setup(database) {
13352
- console.log("[PLUGIN][SETUP] setup called");
13353
- if (this.config.verbose) {
13354
- console.log("[PLUGIN][setup] called with database:", database && database.name);
13355
- }
13356
12184
  this.database = database;
13357
- if (this.config.persistReplicatorLog) {
13358
- let logRes = database.resources[normalizeResourceName(this.config.replicatorLogResource)];
13359
- if (!logRes) {
13360
- logRes = await database.createResource({
12185
+ try {
12186
+ await this.initializeReplicators(database);
12187
+ } catch (error) {
12188
+ this.emit("error", { operation: "setup", error: error.message });
12189
+ throw error;
12190
+ }
12191
+ try {
12192
+ if (this.config.replicatorLogResource) {
12193
+ const logRes = await database.createResource({
13361
12194
  name: this.config.replicatorLogResource,
13362
- behavior: "truncate-data",
12195
+ behavior: "body-overflow",
13363
12196
  attributes: {
13364
- id: "string|required",
13365
- resource: "string|required",
13366
- action: "string|required",
13367
- data: "object",
13368
- timestamp: "number|required",
13369
- createdAt: "string|required"
13370
- },
13371
- partitions: {
13372
- byDate: { fields: { "createdAt": "string|maxlength:10" } }
12197
+ operation: "string",
12198
+ resourceName: "string",
12199
+ recordId: "string",
12200
+ data: "string",
12201
+ error: "string|optional",
12202
+ replicator: "string",
12203
+ timestamp: "string",
12204
+ status: "string"
13373
12205
  }
13374
12206
  });
13375
- if (this.config.verbose) {
13376
- console.log("[PLUGIN] Log resource created:", this.config.replicatorLogResource, !!logRes);
13377
- }
13378
- }
13379
- database.resources[normalizeResourceName(this.config.replicatorLogResource)] = logRes;
13380
- this.replicatorLog = logRes;
13381
- if (this.config.verbose) {
13382
- console.log("[PLUGIN] Log resource created and registered:", this.config.replicatorLogResource, !!database.resources[normalizeResourceName(this.config.replicatorLogResource)]);
13383
- }
13384
- if (typeof database.uploadMetadataFile === "function") {
13385
- await database.uploadMetadataFile();
13386
- if (this.config.verbose) {
13387
- console.log("[PLUGIN] uploadMetadataFile called. database.resources keys:", Object.keys(database.resources));
13388
- }
13389
- }
13390
- }
13391
- if (this.config.replicators && this.config.replicators.length > 0 && this.replicators.length === 0) {
13392
- await this.initializeReplicators();
13393
- console.log("[PLUGIN][SETUP] after initializeReplicators, replicators.length:", this.replicators.length);
13394
- if (this.config.verbose) {
13395
- console.log("[PLUGIN][setup] After initializeReplicators, replicators.length:", this.replicators.length, this.replicators.map((r) => ({ id: r.id, driver: r.driver })));
13396
- }
13397
- }
13398
- for (const resourceName in database.resources) {
13399
- if (normalizeResourceName(resourceName) !== normalizeResourceName(this.config.replicatorLogResource)) {
13400
- this.installEventListeners(database.resources[resourceName]);
13401
12207
  }
12208
+ } catch (error) {
13402
12209
  }
13403
- database.on("connected", () => {
13404
- for (const resourceName in database.resources) {
13405
- if (normalizeResourceName(resourceName) !== normalizeResourceName(this.config.replicatorLogResource)) {
13406
- this.installEventListeners(database.resources[resourceName]);
13407
- }
13408
- }
13409
- });
12210
+ await this.uploadMetadataFile(database);
13410
12211
  const originalCreateResource = database.createResource.bind(database);
13411
12212
  database.createResource = async (config) => {
13412
- if (this.config.verbose) {
13413
- console.log("[PLUGIN] createResource proxy called for:", config && config.name);
13414
- }
13415
12213
  const resource = await originalCreateResource(config);
13416
- if (resource && resource.name !== this.config.replicatorLogResource) {
13417
- this.installEventListeners(resource);
12214
+ if (resource) {
12215
+ this.installEventListeners(resource, database, this);
13418
12216
  }
13419
12217
  return resource;
13420
12218
  };
13421
- database.on("s3db.resourceCreated", (resourceName) => {
13422
- const resource = database.resources[resourceName];
13423
- if (resource && resource.name !== this.config.replicatorLogResource) {
13424
- this.installEventListeners(resource);
13425
- }
13426
- });
13427
- database.on("s3db.resourceUpdated", (resourceName) => {
12219
+ for (const resourceName in database.resources) {
13428
12220
  const resource = database.resources[resourceName];
13429
- if (resource && resource.name !== this.config.replicatorLogResource) {
13430
- this.installEventListeners(resource);
13431
- }
13432
- });
12221
+ this.installEventListeners(resource, database, this);
12222
+ }
13433
12223
  }
13434
- async initializeReplicators() {
13435
- console.log("[PLUGIN][INIT] initializeReplicators called");
12224
+ async initializeReplicators(database) {
13436
12225
  for (const replicatorConfig of this.config.replicators) {
13437
- try {
13438
- console.log("[PLUGIN][INIT] processing replicatorConfig:", replicatorConfig);
13439
- const driver = replicatorConfig.driver;
13440
- const resources = replicatorConfig.resources;
13441
- const client = replicatorConfig.client;
13442
- const replicator = createReplicator(driver, replicatorConfig, resources, client);
13443
- if (replicator) {
13444
- await replicator.initialize(this.database);
13445
- this.replicators.push({
13446
- id: Math.random().toString(36).slice(2),
13447
- driver,
13448
- config: replicatorConfig,
13449
- resources,
13450
- instance: replicator
13451
- });
13452
- console.log("[PLUGIN][INIT] pushed replicator:", driver, resources);
13453
- } else {
13454
- console.log("[PLUGIN][INIT] createReplicator returned null/undefined for driver:", driver);
13455
- }
13456
- } catch (err) {
13457
- console.error("[PLUGIN][INIT] Error creating replicator:", err);
12226
+ const { driver, config, resources } = replicatorConfig;
12227
+ const replicator = this.createReplicator(driver, config, resources);
12228
+ if (replicator) {
12229
+ await replicator.initialize(database);
12230
+ this.replicators.push(replicator);
13458
12231
  }
13459
12232
  }
13460
12233
  }
@@ -13462,160 +12235,102 @@ ${JSON.stringify(validation, null, 2)}`,
13462
12235
  }
13463
12236
  async stop() {
13464
12237
  }
13465
- async processReplicatorEvent(resourceName, operation, recordId, data, beforeData = null) {
13466
- if (this.config.verbose) {
13467
- console.log("[PLUGIN][processReplicatorEvent] replicators.length:", this.replicators.length, this.replicators.map((r) => ({ id: r.id, driver: r.driver })));
13468
- console.log(`[PLUGIN][processReplicatorEvent] operation: ${operation}, resource: ${resourceName}, recordId: ${recordId}, data:`, data, "beforeData:", beforeData);
13469
- }
13470
- if (this.config.verbose) {
13471
- console.log(`[PLUGIN] processReplicatorEvent: resource=${resourceName} op=${operation} id=${recordId} data=`, data);
13472
- }
13473
- if (this.config.verbose) {
13474
- console.log(`[PLUGIN] processReplicatorEvent: resource=${resourceName} op=${operation} replicators=${this.replicators.length}`);
13475
- }
13476
- if (this.replicators.length === 0) {
13477
- if (this.config.verbose) {
13478
- console.log("[PLUGIN] No replicators registered");
13479
- }
13480
- return;
13481
- }
12238
+ async processReplicatorEvent(operation, resourceName, recordId, data, beforeData = null) {
12239
+ if (!this.config.enabled) return;
13482
12240
  const applicableReplicators = this.replicators.filter((replicator) => {
13483
- const should = replicator.instance.shouldReplicateResource(resourceName, operation);
13484
- if (this.config.verbose) {
13485
- console.log(`[PLUGIN] Replicator ${replicator.driver} shouldReplicateResource(${resourceName}, ${operation}):`, should);
13486
- }
12241
+ const should = replicator.shouldReplicateResource && replicator.shouldReplicateResource(resourceName, operation);
13487
12242
  return should;
13488
12243
  });
13489
- if (this.config.verbose) {
13490
- console.log(`[PLUGIN] processReplicatorEvent: applicableReplicators for resource=${resourceName}:`, applicableReplicators.map((r) => r.driver));
13491
- }
13492
12244
  if (applicableReplicators.length === 0) {
13493
- if (this.config.verbose) {
13494
- console.log("[PLUGIN] No applicable replicators for resource", resourceName);
13495
- }
13496
12245
  return;
13497
12246
  }
13498
- const filteredData = this.filterInternalFields(lodashEs.isPlainObject(data) ? data : { raw: data });
13499
- const filteredBeforeData = beforeData ? this.filterInternalFields(lodashEs.isPlainObject(beforeData) ? beforeData : { raw: beforeData }) : null;
13500
- const item = {
13501
- id: `repl-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
13502
- resourceName,
13503
- operation,
13504
- recordId,
13505
- data: filteredData,
13506
- beforeData: filteredBeforeData,
13507
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
13508
- attempts: 0
13509
- };
13510
- const logId = await this.logreplicator(item);
13511
- const [ok, err, result] = await try_fn_default(async () => this.processreplicatorItem(item));
13512
- if (ok) {
13513
- if (logId) {
13514
- await this.updatereplicatorLog(logId, {
13515
- status: result.success ? "success" : "failed",
13516
- attempts: 1,
13517
- error: result.success ? "" : JSON.stringify(result.results)
12247
+ const promises = applicableReplicators.map(async (replicator) => {
12248
+ try {
12249
+ const result = await this.retryWithBackoff(
12250
+ () => replicator.replicate(resourceName, operation, data, recordId, beforeData),
12251
+ this.config.maxRetries
12252
+ );
12253
+ this.emit("replicated", {
12254
+ replicator: replicator.name || replicator.id,
12255
+ resourceName,
12256
+ operation,
12257
+ recordId,
12258
+ result,
12259
+ success: true
13518
12260
  });
13519
- }
13520
- this.stats.totalOperations++;
13521
- if (result.success) {
13522
- this.stats.successfulOperations++;
13523
- } else {
13524
- this.stats.failedOperations++;
13525
- }
13526
- } else {
13527
- if (logId) {
13528
- await this.updatereplicatorLog(logId, {
13529
- status: "failed",
13530
- attempts: 1,
13531
- error: err.message
12261
+ return result;
12262
+ } catch (error) {
12263
+ this.emit("replicator_error", {
12264
+ replicator: replicator.name || replicator.id,
12265
+ resourceName,
12266
+ operation,
12267
+ recordId,
12268
+ error: error.message
13532
12269
  });
12270
+ if (this.config.logErrors && this.database) {
12271
+ await this.logError(replicator, resourceName, operation, recordId, data, error);
12272
+ }
12273
+ throw error;
13533
12274
  }
13534
- this.stats.failedOperations++;
13535
- }
12275
+ });
12276
+ return Promise.allSettled(promises);
13536
12277
  }
13537
12278
  async processreplicatorItem(item) {
13538
- if (this.config.verbose) {
13539
- console.log("[PLUGIN][processreplicatorItem] called with item:", item);
13540
- }
13541
12279
  const applicableReplicators = this.replicators.filter((replicator) => {
13542
- const should = replicator.instance.shouldReplicateResource(item.resourceName, item.operation);
13543
- if (this.config.verbose) {
13544
- console.log(`[PLUGIN] processreplicatorItem: Replicator ${replicator.driver} shouldReplicateResource(${item.resourceName}, ${item.operation}):`, should);
13545
- }
12280
+ const should = replicator.shouldReplicateResource && replicator.shouldReplicateResource(item.resourceName, item.operation);
13546
12281
  return should;
13547
12282
  });
13548
- if (this.config.verbose) {
13549
- console.log(`[PLUGIN] processreplicatorItem: applicableReplicators for resource=${item.resourceName}:`, applicableReplicators.map((r) => r.driver));
13550
- }
13551
12283
  if (applicableReplicators.length === 0) {
13552
- if (this.config.verbose) {
13553
- console.log("[PLUGIN] processreplicatorItem: No applicable replicators for resource", item.resourceName);
13554
- }
13555
- return { success: true, skipped: true, reason: "no_applicable_replicators" };
12284
+ return;
13556
12285
  }
13557
- const results = [];
13558
- for (const replicator of applicableReplicators) {
13559
- let result;
13560
- let ok, err;
13561
- if (this.config.verbose) {
13562
- console.log("[PLUGIN] processReplicatorItem", {
13563
- resource: item.resourceName,
12286
+ const promises = applicableReplicators.map(async (replicator) => {
12287
+ try {
12288
+ const [ok, err, result] = await try_fn_default(
12289
+ () => replicator.replicate(item.resourceName, item.operation, item.data, item.recordId, item.beforeData)
12290
+ );
12291
+ if (!ok) {
12292
+ this.emit("replicator_error", {
12293
+ replicator: replicator.name || replicator.id,
12294
+ resourceName: item.resourceName,
12295
+ operation: item.operation,
12296
+ recordId: item.recordId,
12297
+ error: err.message
12298
+ });
12299
+ if (this.config.logErrors && this.database) {
12300
+ await this.logError(replicator, item.resourceName, item.operation, item.recordId, item.data, err);
12301
+ }
12302
+ return { success: false, error: err.message };
12303
+ }
12304
+ this.emit("replicated", {
12305
+ replicator: replicator.name || replicator.id,
12306
+ resourceName: item.resourceName,
13564
12307
  operation: item.operation,
13565
- data: item.data,
13566
- beforeData: item.beforeData,
13567
- replicator: replicator.instance?.constructor?.name
12308
+ recordId: item.recordId,
12309
+ result,
12310
+ success: true
13568
12311
  });
12312
+ return { success: true, result };
12313
+ } catch (error) {
12314
+ this.emit("replicator_error", {
12315
+ replicator: replicator.name || replicator.id,
12316
+ resourceName: item.resourceName,
12317
+ operation: item.operation,
12318
+ recordId: item.recordId,
12319
+ error: error.message
12320
+ });
12321
+ if (this.config.logErrors && this.database) {
12322
+ await this.logError(replicator, item.resourceName, item.operation, item.recordId, item.data, error);
12323
+ }
12324
+ return { success: false, error: error.message };
13569
12325
  }
13570
- if (replicator.instance && replicator.instance.constructor && replicator.instance.constructor.name === "S3dbReplicator") {
13571
- [ok, err, result] = await try_fn_default(
13572
- () => replicator.instance.replicate({
13573
- resource: item.resourceName,
13574
- operation: item.operation,
13575
- data: item.data,
13576
- id: item.recordId,
13577
- beforeData: item.beforeData
13578
- })
13579
- );
13580
- } else {
13581
- [ok, err, result] = await try_fn_default(
13582
- () => replicator.instance.replicate(
13583
- item.resourceName,
13584
- item.operation,
13585
- item.data,
13586
- item.recordId,
13587
- item.beforeData
13588
- )
13589
- );
13590
- }
13591
- results.push({
13592
- replicatorId: replicator.id,
13593
- driver: replicator.driver,
13594
- success: result && result.success,
13595
- error: result && result.error,
13596
- skipped: result && result.skipped
13597
- });
13598
- }
13599
- return {
13600
- success: results.every((r) => r.success || r.skipped),
13601
- results
13602
- };
12326
+ });
12327
+ return Promise.allSettled(promises);
13603
12328
  }
13604
12329
  async logreplicator(item) {
13605
12330
  const logRes = this.replicatorLog || this.database.resources[normalizeResourceName(this.config.replicatorLogResource)];
13606
12331
  if (!logRes) {
13607
- if (this.config.verbose) {
13608
- console.error("[PLUGIN] replicator log resource not found!");
13609
- }
13610
12332
  if (this.database) {
13611
- if (this.config.verbose) {
13612
- console.warn("[PLUGIN] database.resources keys:", Object.keys(this.database.resources));
13613
- }
13614
- if (this.database.options && this.database.options.connectionString) {
13615
- if (this.config.verbose) {
13616
- console.warn("[PLUGIN] database connectionString:", this.database.options.connectionString);
13617
- }
13618
- }
12333
+ if (this.database.options && this.database.options.connectionString) ;
13619
12334
  }
13620
12335
  this.emit("replicator.log.failed", { error: "replicator log resource not found", item });
13621
12336
  return;
@@ -13631,9 +12346,6 @@ ${JSON.stringify(validation, null, 2)}`,
13631
12346
  try {
13632
12347
  await logRes.insert(logItem);
13633
12348
  } catch (err) {
13634
- if (this.config.verbose) {
13635
- console.error("[PLUGIN] Error writing to replicator log:", err);
13636
- }
13637
12349
  this.emit("replicator.log.failed", { error: err, item });
13638
12350
  }
13639
12351
  }
@@ -13715,10 +12427,6 @@ ${JSON.stringify(validation, null, 2)}`,
13715
12427
  });
13716
12428
  if (ok) {
13717
12429
  retried++;
13718
- } else {
13719
- if (this.config.verbose) {
13720
- console.error("Failed to retry replicator:", err);
13721
- }
13722
12430
  }
13723
12431
  }
13724
12432
  return { retried };
@@ -13743,40 +12451,23 @@ ${JSON.stringify(validation, null, 2)}`,
13743
12451
  this.emit("replicator.sync.completed", { replicatorId, stats: this.stats });
13744
12452
  }
13745
12453
  async cleanup() {
13746
- if (this.config.verbose) {
13747
- console.log("[PLUGIN][CLEANUP] Cleaning up ReplicatorPlugin");
13748
- }
13749
- if (this._installedListeners && Array.isArray(this._installedListeners)) {
13750
- for (const resource of this._installedListeners) {
13751
- if (resource && typeof resource.removeAllListeners === "function") {
13752
- resource.removeAllListeners("insert");
13753
- resource.removeAllListeners("update");
13754
- resource.removeAllListeners("delete");
13755
- }
13756
- resource._replicatorListenersInstalled = false;
13757
- }
13758
- this._installedListeners = [];
13759
- }
13760
- if (this.database && typeof this.database.removeAllListeners === "function") {
13761
- this.database.removeAllListeners();
13762
- }
13763
- if (this.replicators && Array.isArray(this.replicators)) {
13764
- for (const rep of this.replicators) {
13765
- if (rep.instance && typeof rep.instance.cleanup === "function") {
13766
- await rep.instance.cleanup();
13767
- }
12454
+ try {
12455
+ if (this.replicators && this.replicators.length > 0) {
12456
+ const cleanupPromises = this.replicators.map(async (replicator) => {
12457
+ try {
12458
+ if (replicator && typeof replicator.cleanup === "function") {
12459
+ await replicator.cleanup();
12460
+ }
12461
+ } catch (error) {
12462
+ }
12463
+ });
12464
+ await Promise.allSettled(cleanupPromises);
13768
12465
  }
13769
12466
  this.replicators = [];
13770
- }
13771
- this.queue = [];
13772
- this.isProcessing = false;
13773
- this.stats = {
13774
- totalOperations: 0,
13775
- totalErrors: 0,
13776
- lastError: null
13777
- };
13778
- if (this.config.verbose) {
13779
- console.log("[PLUGIN][CLEANUP] ReplicatorPlugin cleanup complete");
12467
+ this.database = null;
12468
+ this.eventListenersInstalled.clear();
12469
+ this.removeAllListeners();
12470
+ } catch (error) {
13780
12471
  }
13781
12472
  }
13782
12473
  }