sonamu 0.2.47 → 0.2.48

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.
@@ -4796,6 +4796,7 @@ var SonamuClass = class {
4796
4796
  this._dbConfig = null;
4797
4797
  this._syncer = null;
4798
4798
  this._config = null;
4799
+ this._secrets = null;
4799
4800
  }
4800
4801
  set apiRootPath(apiRootPath) {
4801
4802
  this._apiRootPath = apiRootPath;
@@ -4836,6 +4837,12 @@ var SonamuClass = class {
4836
4837
  }
4837
4838
  return this._config;
4838
4839
  }
4840
+ set secrets(secrets) {
4841
+ this._secrets = secrets;
4842
+ }
4843
+ get secrets() {
4844
+ return this._secrets;
4845
+ }
4839
4846
  async init(doSilent = false, enableSync = true, apiRootPath) {
4840
4847
  if (this.isInitialized) {
4841
4848
  return;
@@ -4843,12 +4850,18 @@ var SonamuClass = class {
4843
4850
  !doSilent && console.time(_chalk2.default.cyan("Sonamu.init"));
4844
4851
  this.apiRootPath = await _asyncNullishCoalesce(apiRootPath, async () => ( await findApiRootPath()));
4845
4852
  const configPath = _path2.default.join(this.apiRootPath, "sonamu.config.json");
4853
+ const secretsPath = _path2.default.join(this.apiRootPath, "sonamu.secrets.json");
4846
4854
  if (_fsextra2.default.existsSync(configPath) === false) {
4847
4855
  throw new Error(`Cannot find sonamu.config.json in ${configPath}`);
4848
4856
  }
4849
4857
  this.config = JSON.parse(
4850
4858
  _fsextra2.default.readFileSync(configPath).toString()
4851
4859
  );
4860
+ if (_fsextra2.default.existsSync(secretsPath)) {
4861
+ this.secrets = JSON.parse(
4862
+ _fsextra2.default.readFileSync(secretsPath).toString()
4863
+ );
4864
+ }
4852
4865
  this.dbConfig = await DB.readKnexfile();
4853
4866
  !doSilent && console.log(_chalk2.default.green("DB Config Loaded!"));
4854
4867
  attachOnDuplicateUpdate();
@@ -7177,10 +7190,13 @@ ${onlyTs.map((f) => f.name).join("\n")}`
7177
7190
 
7178
7191
 
7179
7192
 
7193
+
7194
+ var _fs = require('fs');
7180
7195
  var FixtureManagerClass = class {
7181
7196
  constructor() {
7182
7197
  this._tdb = null;
7183
7198
  this._fdb = null;
7199
+ this.dependencyGraph = /* @__PURE__ */ new Map();
7184
7200
  }
7185
7201
  set tdb(tdb) {
7186
7202
  this._tdb = tdb;
@@ -7357,6 +7373,305 @@ var FixtureManagerClass = class {
7357
7373
  }
7358
7374
  await BaseModel.destroy();
7359
7375
  }
7376
+ async getFixtures(sourceDBName, targetDBName, searchOptions) {
7377
+ const sourceDB = _knex2.default.call(void 0, Sonamu.dbConfig[sourceDBName]);
7378
+ const targetDB = _knex2.default.call(void 0, Sonamu.dbConfig[targetDBName]);
7379
+ const { entityId, field, value, searchType } = searchOptions;
7380
+ const entity = EntityManager.get(entityId);
7381
+ const column = _optionalChain([entity, 'access', _89 => _89.props, 'access', _90 => _90.find, 'call', _91 => _91((prop) => prop.name === field), 'optionalAccess', _92 => _92.type]) === "relation" ? `${field}_id` : field;
7382
+ let query = sourceDB(entity.table);
7383
+ if (searchType === "equals") {
7384
+ query = query.where(column, value);
7385
+ } else if (searchType === "like") {
7386
+ query = query.where(column, "like", `%${value}%`);
7387
+ }
7388
+ const rows = await query;
7389
+ if (rows.length === 0) {
7390
+ throw new Error("No records found");
7391
+ }
7392
+ const visitedEntities = /* @__PURE__ */ new Set();
7393
+ const records = [];
7394
+ for (const row of rows) {
7395
+ const initialRecordsLength = records.length;
7396
+ await this.createFixtureRecord(entity, row, visitedEntities, records);
7397
+ const currentFixtureRecord = records.find(
7398
+ (r) => r.fixtureId === `${entityId}#${row.id}`
7399
+ );
7400
+ if (currentFixtureRecord) {
7401
+ currentFixtureRecord.fetchedRecords = records.filter((r) => r.fixtureId !== currentFixtureRecord.fixtureId).slice(initialRecordsLength).map((r) => r.fixtureId);
7402
+ }
7403
+ }
7404
+ for await (const record of records) {
7405
+ const entity2 = EntityManager.get(record.entityId);
7406
+ const rows2 = [];
7407
+ const row = await targetDB(entity2.table).where("id", record.id).first();
7408
+ if (row) {
7409
+ await this.createFixtureRecord(
7410
+ entity2,
7411
+ row,
7412
+ /* @__PURE__ */ new Set(),
7413
+ rows2,
7414
+ true,
7415
+ targetDB
7416
+ );
7417
+ record.target = rows2[0];
7418
+ }
7419
+ }
7420
+ return records;
7421
+ }
7422
+ async createFixtureRecord(entity, row, visitedEntities, records, singleRecord = false, _db) {
7423
+ const fixtureId = `${entity.id}#${row.id}`;
7424
+ if (visitedEntities.has(fixtureId)) {
7425
+ return;
7426
+ }
7427
+ visitedEntities.add(fixtureId);
7428
+ const record = {
7429
+ fixtureId,
7430
+ entityId: entity.id,
7431
+ id: row.id,
7432
+ columns: {},
7433
+ fetchedRecords: [],
7434
+ belongsRecords: []
7435
+ };
7436
+ for (const prop of entity.props) {
7437
+ if (isVirtualProp(prop)) {
7438
+ continue;
7439
+ }
7440
+ record.columns[prop.name] = {
7441
+ prop,
7442
+ value: row[prop.name]
7443
+ };
7444
+ const db = _nullishCoalesce(_db, () => ( BaseModel.getDB("w")));
7445
+ if (isManyToManyRelationProp(prop)) {
7446
+ const relatedEntity = EntityManager.get(prop.with);
7447
+ const throughTable = prop.joinTable;
7448
+ const fromColumn = `${_inflection2.default.singularize(entity.table)}_id`;
7449
+ const toColumn = `${_inflection2.default.singularize(relatedEntity.table)}_id`;
7450
+ const relatedIds = await db(throughTable).where(fromColumn, row.id).pluck(toColumn);
7451
+ record.columns[prop.name].value = relatedIds;
7452
+ } else if (isHasManyRelationProp(prop)) {
7453
+ const relatedEntity = EntityManager.get(prop.with);
7454
+ const relatedIds = await db(relatedEntity.table).where(prop.joinColumn, row.id).pluck("id");
7455
+ record.columns[prop.name].value = relatedIds;
7456
+ } else if (isOneToOneRelationProp(prop) && !prop.hasJoinColumn) {
7457
+ const relatedEntity = EntityManager.get(prop.with);
7458
+ const relatedProp = relatedEntity.props.find(
7459
+ (p) => p.type === "relation" && p.with === entity.id
7460
+ );
7461
+ if (relatedProp) {
7462
+ const relatedRow = await db(relatedEntity.table).where("id", row.id).first();
7463
+ record.columns[prop.name].value = _optionalChain([relatedRow, 'optionalAccess', _93 => _93.id]);
7464
+ }
7465
+ } else if (isRelationProp(prop)) {
7466
+ const relatedId = row[`${prop.name}_id`];
7467
+ record.columns[prop.name].value = relatedId;
7468
+ if (relatedId) {
7469
+ record.belongsRecords.push(`${prop.with}#${relatedId}`);
7470
+ }
7471
+ if (!singleRecord && relatedId) {
7472
+ const relatedEntity = EntityManager.get(prop.with);
7473
+ const relatedRow = await db(relatedEntity.table).where("id", relatedId).first();
7474
+ if (relatedRow) {
7475
+ await this.createFixtureRecord(
7476
+ relatedEntity,
7477
+ relatedRow,
7478
+ visitedEntities,
7479
+ records,
7480
+ singleRecord,
7481
+ _db
7482
+ );
7483
+ }
7484
+ }
7485
+ }
7486
+ }
7487
+ records.push(record);
7488
+ }
7489
+ async insertFixtures(dbName, fixtures) {
7490
+ this.buildDependencyGraph(fixtures);
7491
+ const insertionOrder = this.getInsertionOrder();
7492
+ const db = _knex2.default.call(void 0, Sonamu.dbConfig[dbName]);
7493
+ await db.transaction(async (trx) => {
7494
+ await trx.raw(`SET FOREIGN_KEY_CHECKS = 0`);
7495
+ for (const fixtureId of insertionOrder) {
7496
+ const fixture = fixtures.find((f) => f.fixtureId === fixtureId);
7497
+ await this.insertFixture(trx, fixture);
7498
+ }
7499
+ for (const fixtureId of insertionOrder) {
7500
+ const fixture = fixtures.find((f) => f.fixtureId === fixtureId);
7501
+ await this.handleManyToManyRelations(trx, fixture, fixtures);
7502
+ }
7503
+ await trx.raw(`SET FOREIGN_KEY_CHECKS = 1`);
7504
+ });
7505
+ const records = [];
7506
+ for await (const r of fixtures) {
7507
+ const entity = EntityManager.get(r.entityId);
7508
+ const record = await db(entity.table).where("id", r.id).first();
7509
+ records.push({
7510
+ entityId: r.entityId,
7511
+ data: record
7512
+ });
7513
+ }
7514
+ return records;
7515
+ }
7516
+ getInsertionOrder() {
7517
+ const visited = /* @__PURE__ */ new Set();
7518
+ const order = [];
7519
+ const tempVisited = /* @__PURE__ */ new Set();
7520
+ const visit = (fixtureId) => {
7521
+ if (visited.has(fixtureId)) return;
7522
+ if (tempVisited.has(fixtureId)) {
7523
+ console.warn(`Circular dependency detected involving: ${fixtureId}`);
7524
+ return;
7525
+ }
7526
+ tempVisited.add(fixtureId);
7527
+ const node = this.dependencyGraph.get(fixtureId);
7528
+ const entity = EntityManager.get(node.entityId);
7529
+ for (const depId of node.dependencies) {
7530
+ const depNode = this.dependencyGraph.get(depId);
7531
+ const relationProp = entity.props.find(
7532
+ (prop) => isRelationProp(prop) && (isBelongsToOneRelationProp(prop) || isOneToOneRelationProp(prop) && prop.hasJoinColumn) && prop.with === depNode.entityId
7533
+ );
7534
+ if (relationProp && !relationProp.nullable) {
7535
+ visit(depId);
7536
+ }
7537
+ }
7538
+ tempVisited.delete(fixtureId);
7539
+ visited.add(fixtureId);
7540
+ order.push(fixtureId);
7541
+ };
7542
+ for (const fixtureId of this.dependencyGraph.keys()) {
7543
+ visit(fixtureId);
7544
+ }
7545
+ for (const fixtureId of this.dependencyGraph.keys()) {
7546
+ if (!visited.has(fixtureId)) {
7547
+ order.push(fixtureId);
7548
+ }
7549
+ }
7550
+ return order;
7551
+ }
7552
+ prepareInsertData(fixture) {
7553
+ const insertData = {};
7554
+ for (const [propName, column] of Object.entries(fixture.columns)) {
7555
+ if (isVirtualProp(column.prop)) {
7556
+ continue;
7557
+ }
7558
+ const prop = column.prop;
7559
+ if (!isRelationProp(prop)) {
7560
+ if (prop.type === "json") {
7561
+ insertData[propName] = JSON.stringify(column.value);
7562
+ } else {
7563
+ insertData[propName] = column.value;
7564
+ }
7565
+ } else if (isBelongsToOneRelationProp(prop) || isOneToOneRelationProp(prop) && prop.hasJoinColumn) {
7566
+ insertData[`${propName}_id`] = column.value;
7567
+ }
7568
+ }
7569
+ return insertData;
7570
+ }
7571
+ buildDependencyGraph(fixtures) {
7572
+ this.dependencyGraph.clear();
7573
+ for (const fixture of fixtures) {
7574
+ this.dependencyGraph.set(fixture.fixtureId, {
7575
+ fixtureId: fixture.fixtureId,
7576
+ entityId: fixture.entityId,
7577
+ dependencies: /* @__PURE__ */ new Set()
7578
+ });
7579
+ }
7580
+ for (const fixture of fixtures) {
7581
+ const node = this.dependencyGraph.get(fixture.fixtureId);
7582
+ for (const [, column] of Object.entries(fixture.columns)) {
7583
+ const prop = column.prop;
7584
+ if (isRelationProp(prop)) {
7585
+ if (isBelongsToOneRelationProp(prop) || isOneToOneRelationProp(prop) && prop.hasJoinColumn) {
7586
+ const relatedFixtureId = `${prop.with}#${column.value}`;
7587
+ if (this.dependencyGraph.has(relatedFixtureId)) {
7588
+ node.dependencies.add(relatedFixtureId);
7589
+ }
7590
+ } else if (isManyToManyRelationProp(prop)) {
7591
+ const relatedIds = column.value;
7592
+ for (const relatedId of relatedIds) {
7593
+ const relatedFixtureId = `${prop.with}#${relatedId}`;
7594
+ if (this.dependencyGraph.has(relatedFixtureId)) {
7595
+ node.dependencies.add(relatedFixtureId);
7596
+ this.dependencyGraph.get(relatedFixtureId).dependencies.add(fixture.fixtureId);
7597
+ }
7598
+ }
7599
+ }
7600
+ }
7601
+ }
7602
+ }
7603
+ }
7604
+ async insertFixture(db, fixture) {
7605
+ const insertData = this.prepareInsertData(fixture);
7606
+ const entity = EntityManager.get(fixture.entityId);
7607
+ try {
7608
+ const found = await db(entity.table).where("id", fixture.id).first();
7609
+ if (found && !fixture.override) {
7610
+ return {
7611
+ entityId: fixture.entityId,
7612
+ id: found.id
7613
+ };
7614
+ }
7615
+ const q = db.insert(insertData).into(entity.table);
7616
+ await q.onDuplicateUpdate.apply(q, Object.keys(insertData));
7617
+ return {
7618
+ entityId: fixture.entityId,
7619
+ id: fixture.id
7620
+ };
7621
+ } catch (err) {
7622
+ console.log(err);
7623
+ throw err;
7624
+ }
7625
+ }
7626
+ async handleManyToManyRelations(db, fixture, fixtures) {
7627
+ for (const [, column] of Object.entries(fixture.columns)) {
7628
+ const prop = column.prop;
7629
+ if (isManyToManyRelationProp(prop)) {
7630
+ const joinTable = prop.joinTable;
7631
+ const relatedIds = column.value;
7632
+ for (const relatedId of relatedIds) {
7633
+ if (!fixtures.find((f) => f.fixtureId === `${prop.with}#${relatedId}`)) {
7634
+ continue;
7635
+ }
7636
+ const entity = EntityManager.get(fixture.entityId);
7637
+ const relatedEntity = EntityManager.get(prop.with);
7638
+ if (!entity || !relatedEntity) {
7639
+ throw new Error(
7640
+ `Entity not found: ${fixture.entityId}, ${prop.with}`
7641
+ );
7642
+ }
7643
+ const [found] = await db(joinTable).where({
7644
+ [`${_inflection2.default.singularize(entity.table)}_id`]: fixture.id,
7645
+ [`${_inflection2.default.singularize(relatedEntity.table)}_id`]: relatedId
7646
+ }).limit(1);
7647
+ if (found) {
7648
+ continue;
7649
+ }
7650
+ const newIds = await db(joinTable).insert({
7651
+ [`${_inflection2.default.singularize(entity.table)}_id`]: fixture.id,
7652
+ [`${_inflection2.default.singularize(relatedEntity.table)}_id`]: relatedId
7653
+ });
7654
+ console.log(
7655
+ _chalk2.default.green(
7656
+ `Inserted into ${joinTable}: ${entity.table}(${fixture.id}) - ${relatedEntity.table}(${relatedId}) ID: ${newIds}`
7657
+ )
7658
+ );
7659
+ }
7660
+ }
7661
+ }
7662
+ }
7663
+ async addFixtureLoader(code) {
7664
+ const path8 = Sonamu.apiRootPath + "/src/testing/fixture.ts";
7665
+ let content = _fs.readFileSync.call(void 0, path8).toString();
7666
+ const fixtureLoaderStart = content.indexOf("const fixtureLoader = {");
7667
+ const fixtureLoaderEnd = content.indexOf("};", fixtureLoaderStart);
7668
+ if (fixtureLoaderStart !== -1 && fixtureLoaderEnd !== -1) {
7669
+ const newContent = content.slice(0, fixtureLoaderEnd) + " " + code + "\n" + content.slice(fixtureLoaderEnd);
7670
+ _fs.writeFileSync.call(void 0, path8, newContent);
7671
+ } else {
7672
+ throw new Error("Failed to find fixtureLoader in fixture.ts");
7673
+ }
7674
+ }
7360
7675
  };
7361
7676
  var FixtureManager = new FixtureManagerClass();
7362
7677
 
@@ -7443,4 +7758,4 @@ var FixtureManager = new FixtureManagerClass();
7443
7758
 
7444
7759
 
7445
7760
  exports.SQLDateTimeString = SQLDateTimeString; exports.zArrayable = zArrayable; exports.isIntegerProp = isIntegerProp; exports.isBigIntegerProp = isBigIntegerProp; exports.isTextProp = isTextProp; exports.isStringProp = isStringProp; exports.isEnumProp = isEnumProp; exports.isFloatProp = isFloatProp; exports.isDoubleProp = isDoubleProp; exports.isDecimalProp = isDecimalProp; exports.isBooleanProp = isBooleanProp; exports.isDateProp = isDateProp; exports.isDateTimeProp = isDateTimeProp; exports.isTimeProp = isTimeProp; exports.isTimestampProp = isTimestampProp; exports.isJsonProp = isJsonProp; exports.isUuidProp = isUuidProp; exports.isVirtualProp = isVirtualProp; exports.isRelationProp = isRelationProp; exports.isOneToOneRelationProp = isOneToOneRelationProp; exports.isBelongsToOneRelationProp = isBelongsToOneRelationProp; exports.isHasManyRelationProp = isHasManyRelationProp; exports.isManyToManyRelationProp = isManyToManyRelationProp; exports.isCustomJoinClause = isCustomJoinClause; exports.SonamuQueryMode = SonamuQueryMode; exports.isKnexError = isKnexError; exports.ApiParamType = ApiParamType; exports.RenderingNode = RenderingNode; exports.TemplateOptions = TemplateOptions; exports.TemplateKey = TemplateKey; exports.GenerateOptions = GenerateOptions; exports.PathAndCode = PathAndCode; exports.getZodObjectFromApi = getZodObjectFromApi; exports.getZodObjectFromApiParams = getZodObjectFromApiParams; exports.getZodTypeFromApiParamType = getZodTypeFromApiParamType; exports.propNodeToZodTypeDef = propNodeToZodTypeDef; exports.getTextTypeLength = getTextTypeLength; exports.propToZodTypeDef = propToZodTypeDef; exports.zodTypeToZodCode = zodTypeToZodCode; exports.apiParamToTsCode = apiParamToTsCode; exports.apiParamTypeToTsType = apiParamTypeToTsType; exports.unwrapPromiseOnce = unwrapPromiseOnce; exports.serializeZodType = serializeZodType; exports.zodTypeToTsTypeDef = zodTypeToTsTypeDef; exports.registeredApis = registeredApis; exports.api = api; exports.SoException = SoException; exports.isSoException = isSoException; exports.BadRequestException = BadRequestException; exports.UnauthorizedException = UnauthorizedException; exports.NotFoundException = NotFoundException; exports.ServiceUnavailableException = ServiceUnavailableException; exports.InternalServerErrorException = InternalServerErrorException; exports.AlreadyProcessedException = AlreadyProcessedException; exports.DuplicateRowException = DuplicateRowException; exports.TargetNotFoundException = TargetNotFoundException; exports.globAsync = globAsync; exports.importMultiple = importMultiple; exports.findAppRootPath = findAppRootPath; exports.findApiRootPath = findApiRootPath; exports.nonNullable = nonNullable; exports.Entity = Entity; exports.EntityManager = EntityManager; exports.Syncer = Syncer; exports.isLocal = isLocal; exports.isRemote = isRemote; exports.isInDocker = isInDocker; exports.isDaemonServer = isDaemonServer; exports.isDevelopment = isDevelopment; exports.isStaging = isStaging; exports.isProduction = isProduction; exports.isTest = isTest; exports.DB = DB; exports.isRefField = isRefField; exports.UpsertBuilder = UpsertBuilder; exports.BaseModelClass = BaseModelClass; exports.BaseModel = BaseModel; exports.Sonamu = Sonamu; exports.Migrator = Migrator; exports.FixtureManagerClass = FixtureManagerClass; exports.FixtureManager = FixtureManager;
7446
- //# sourceMappingURL=chunk-5VT5JTY4.js.map
7761
+ //# sourceMappingURL=chunk-76VBQWGE.js.map