@hiliosai/sdk 0.1.18 → 0.1.20

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/index.d.ts CHANGED
@@ -151,6 +151,9 @@ declare abstract class AbstractDatasource<TContext = AppContext> implements Base
151
151
  * Override to implement clearing logic
152
152
  */
153
153
  clear(): Promise<void>;
154
+ memoize<P = unknown, R = unknown>(name: string, params: P, fn: () => Promise<R>, options?: {
155
+ ttl?: number;
156
+ }): Promise<R>;
154
157
  }
155
158
 
156
159
  interface PrismaClientLike {
@@ -223,7 +226,8 @@ declare class PrismaDatasource<TPrismaClient extends PrismaClientLike = PrismaCl
223
226
  protected createClient(): TPrismaClient;
224
227
  /**
225
228
  * Apply extensions to the Prisma client
226
- * Override this method to add production extensions like soft delete, audit trails, etc.
229
+ * By default, applies tenant extension for multi-tenant support
230
+ * Override this method to add additional extensions like soft delete, audit trails, etc.
227
231
  */
228
232
  protected applyExtensions(client: TPrismaClient): TPrismaClient;
229
233
  /**
@@ -337,6 +341,13 @@ declare function createTenantExtension(): {
337
341
  $setTenant(tenantId: string): void;
338
342
  $getCurrentTenant(): string | null;
339
343
  $clearTenant(): void;
344
+ $enableBypassMode(): void;
345
+ $disableBypassMode(): void;
346
+ $enableStrictMode(): void;
347
+ $disableStrictMode(): void;
348
+ $withBypassMode<T>(fn: () => Promise<T>): Promise<T>;
349
+ $withTenant<T>(tenantId: string, fn: () => Promise<T>): Promise<T>;
350
+ $withSystemMode<T>(fn: () => Promise<T>): Promise<T>;
340
351
  };
341
352
  query: {
342
353
  $allModels: {
@@ -865,6 +876,7 @@ declare const isDev: boolean;
865
876
  declare const isTest: boolean;
866
877
  declare const isProd: boolean;
867
878
  declare const REDIS_URL: string | undefined;
879
+ declare const DEFAULT_DATASOURCE_CACHE_TTL: number;
868
880
 
869
881
  type Env = typeof env;
870
882
 
@@ -897,4 +909,4 @@ declare function DatasourceMixin(datasourceConstructors?: DatasourceConstructorR
897
909
 
898
910
  declare function omit<T extends Record<string, unknown>, K extends keyof T>(obj: T, keys: K[]): Omit<T, K>;
899
911
 
900
- export { AbstractDatasource, type ActionHandler, type ActionSchemaWithContext, type ActionWithPermissions, type AppContext, type AppMeta, type AuditTrailExtension, type BaseDatasource, type BaseSpec, CHANNELS, type CarouselItem, type ChannelSendOptions, ContextHelpersMiddleware, CreateHealthCheckMiddleware, type DatasourceConstructorRegistry, type DatasourceContext, type DatasourceInstanceRegistry, type DatasourceInstanceTypes, DatasourceMixin, type Env, HEALTH_CHECK_DEFAULTS, INTEGRATION_CHANNELS, IntegrationCapability, type IntegrationChannelName, type IntegrationConfig, type IntegrationMessageFailedPayload, type IntegrationMessageReceivedPayload, type IntegrationMessageSentPayload, IntegrationPlatform, type IntegrationRegisteredPayload, type IntegrationServiceConfig, type IntegrationServiceSchema, IntegrationStatus, type IntegrationUnregisteredPayload, MemoizeMixin, type MemoizeMixinOptions, type Message, type MessageAttachment, type MessageButton, type MessageContent, MessageContentType, type MessageDirection, type MessageParticipant, type MessageStatus, type MessageType, NAMESPACE, PERMISSIONS, type Permission, type PermissionHelpers, PermissionsMiddleware, type PlatformMessage, PrismaDatasource, REDIS_URL, ROLE_PERMISSIONS, type SendResult, type SendToChannelMethod, type ServiceActionsSchema, type ServiceConfig, type ServiceSchema, type ServiceWithDatasources, type SoftDeleteExtension, type Tenant, type TenantExtension, type User, UserRole, type WebhookEvent, createDatasourceMiddleware, createTenantExtension, defineIntegration, defineService, isDev, isProd, isTest, configs as moleculer, nodeEnv, omit, retryExtension, softDeleteExtension };
912
+ export { AbstractDatasource, type ActionHandler, type ActionSchemaWithContext, type ActionWithPermissions, type AppContext, type AppMeta, type AuditTrailExtension, type BaseDatasource, type BaseSpec, CHANNELS, type CarouselItem, type ChannelSendOptions, ContextHelpersMiddleware, CreateHealthCheckMiddleware, DEFAULT_DATASOURCE_CACHE_TTL, type DatasourceConstructorRegistry, type DatasourceContext, type DatasourceInstanceRegistry, type DatasourceInstanceTypes, DatasourceMixin, type Env, HEALTH_CHECK_DEFAULTS, INTEGRATION_CHANNELS, IntegrationCapability, type IntegrationChannelName, type IntegrationConfig, type IntegrationMessageFailedPayload, type IntegrationMessageReceivedPayload, type IntegrationMessageSentPayload, IntegrationPlatform, type IntegrationRegisteredPayload, type IntegrationServiceConfig, type IntegrationServiceSchema, IntegrationStatus, type IntegrationUnregisteredPayload, MemoizeMixin, type MemoizeMixinOptions, type Message, type MessageAttachment, type MessageButton, type MessageContent, MessageContentType, type MessageDirection, type MessageParticipant, type MessageStatus, type MessageType, NAMESPACE, PERMISSIONS, type Permission, type PermissionHelpers, PermissionsMiddleware, type PlatformMessage, PrismaDatasource, REDIS_URL, ROLE_PERMISSIONS, type SendResult, type SendToChannelMethod, type ServiceActionsSchema, type ServiceConfig, type ServiceSchema, type ServiceWithDatasources, type SoftDeleteExtension, type Tenant, type TenantExtension, type User, UserRole, type WebhookEvent, createDatasourceMiddleware, createTenantExtension, defineIntegration, defineService, isDev, isProd, isTest, configs as moleculer, nodeEnv, omit, retryExtension, softDeleteExtension };
package/dist/index.js CHANGED
@@ -249,6 +249,11 @@ var isDev = nodeEnv === "development";
249
249
  var isTest = nodeEnv === "test";
250
250
  var isProd = nodeEnv === "production";
251
251
  var REDIS_URL = env4.string("REDIS_URL");
252
+ var DEFAULT_DATASOURCE_CACHE_TTL = env4.number(
253
+ "DEFAULT_DATASOURCE_CACHE_TTL",
254
+ 60
255
+ // 60 seconds
256
+ );
252
257
  var env_default = env4;
253
258
 
254
259
  // src/errors/permission.error.ts
@@ -1389,8 +1394,176 @@ var AbstractDatasource = class {
1389
1394
  */
1390
1395
  async clear() {
1391
1396
  }
1397
+ // memoize
1398
+ async memoize(name, params, fn, options) {
1399
+ let res;
1400
+ if (!this.broker.cacher) return fn();
1401
+ const key = this.broker.cacher.defaultKeygen(
1402
+ `${this.name}:ds-${name}`,
1403
+ params ?? {},
1404
+ {},
1405
+ []
1406
+ );
1407
+ res = await this.broker.cacher.get(key);
1408
+ if (res) return res;
1409
+ res = await fn();
1410
+ this.broker.cacher.set(
1411
+ key,
1412
+ res,
1413
+ options?.ttl ?? DEFAULT_DATASOURCE_CACHE_TTL
1414
+ );
1415
+ return res;
1416
+ }
1392
1417
  };
1393
1418
 
1419
+ // src/datasources/extensions/tenant.extension.ts
1420
+ function createTenantExtension() {
1421
+ const tenantContext = {
1422
+ currentTenantId: null,
1423
+ bypassMode: false,
1424
+ strictMode: false
1425
+ };
1426
+ return {
1427
+ name: "Tenant",
1428
+ client: {
1429
+ // Set tenant context
1430
+ $setTenant(tenantId) {
1431
+ tenantContext.currentTenantId = tenantId;
1432
+ tenantContext.bypassMode = false;
1433
+ },
1434
+ // Get current tenant
1435
+ $getCurrentTenant() {
1436
+ return tenantContext.currentTenantId;
1437
+ },
1438
+ // Clear tenant context
1439
+ $clearTenant() {
1440
+ tenantContext.currentTenantId = null;
1441
+ tenantContext.bypassMode = false;
1442
+ },
1443
+ // Enable bypass mode (admin operations)
1444
+ $enableBypassMode() {
1445
+ tenantContext.bypassMode = true;
1446
+ },
1447
+ // Disable bypass mode
1448
+ $disableBypassMode() {
1449
+ tenantContext.bypassMode = false;
1450
+ },
1451
+ // Enable strict mode (requires tenantId for operations)
1452
+ $enableStrictMode() {
1453
+ tenantContext.strictMode = true;
1454
+ },
1455
+ // Disable strict mode
1456
+ $disableStrictMode() {
1457
+ tenantContext.strictMode = false;
1458
+ },
1459
+ // Execute with bypass mode temporarily
1460
+ async $withBypassMode(fn) {
1461
+ const previousMode = tenantContext.bypassMode;
1462
+ tenantContext.bypassMode = true;
1463
+ try {
1464
+ return await fn();
1465
+ } finally {
1466
+ tenantContext.bypassMode = previousMode;
1467
+ }
1468
+ },
1469
+ // Execute with specific tenant temporarily
1470
+ async $withTenant(tenantId, fn) {
1471
+ const previousTenant = tenantContext.currentTenantId;
1472
+ const previousBypass = tenantContext.bypassMode;
1473
+ tenantContext.currentTenantId = tenantId;
1474
+ tenantContext.bypassMode = false;
1475
+ try {
1476
+ return await fn();
1477
+ } finally {
1478
+ tenantContext.currentTenantId = previousTenant;
1479
+ tenantContext.bypassMode = previousBypass;
1480
+ }
1481
+ },
1482
+ // Execute without tenant filtering (system operations)
1483
+ async $withSystemMode(fn) {
1484
+ const previousTenant = tenantContext.currentTenantId;
1485
+ const previousBypass = tenantContext.bypassMode;
1486
+ tenantContext.currentTenantId = null;
1487
+ tenantContext.bypassMode = true;
1488
+ try {
1489
+ return await fn();
1490
+ } finally {
1491
+ tenantContext.currentTenantId = previousTenant;
1492
+ tenantContext.bypassMode = previousBypass;
1493
+ }
1494
+ }
1495
+ },
1496
+ query: {
1497
+ $allModels: {
1498
+ // Automatically add tenantId filter to all read operations
1499
+ async findMany({ args, query }) {
1500
+ var _a;
1501
+ if (!tenantContext.bypassMode && tenantContext.currentTenantId) {
1502
+ args.where ?? (args.where = {});
1503
+ (_a = args.where).tenantId ?? (_a.tenantId = tenantContext.currentTenantId);
1504
+ } else if (tenantContext.strictMode && !tenantContext.bypassMode && !tenantContext.currentTenantId) {
1505
+ throw new Error("Tenant context required for this operation. Use $withSystemMode() for system-level operations.");
1506
+ }
1507
+ return query(args);
1508
+ },
1509
+ async findUnique({ args, query }) {
1510
+ var _a;
1511
+ if (!tenantContext.bypassMode && tenantContext.currentTenantId) {
1512
+ args.where ?? (args.where = {});
1513
+ (_a = args.where).tenantId ?? (_a.tenantId = tenantContext.currentTenantId);
1514
+ } else if (tenantContext.strictMode && !tenantContext.bypassMode && !tenantContext.currentTenantId) {
1515
+ throw new Error("Tenant context required for this operation. Use $withSystemMode() for system-level operations.");
1516
+ }
1517
+ return query(args);
1518
+ },
1519
+ async findFirst({ args, query }) {
1520
+ var _a;
1521
+ if (!tenantContext.bypassMode && tenantContext.currentTenantId) {
1522
+ args.where ?? (args.where = {});
1523
+ (_a = args.where).tenantId ?? (_a.tenantId = tenantContext.currentTenantId);
1524
+ } else if (tenantContext.strictMode && !tenantContext.bypassMode && !tenantContext.currentTenantId) {
1525
+ throw new Error("Tenant context required for this operation. Use $withSystemMode() for system-level operations.");
1526
+ }
1527
+ return query(args);
1528
+ },
1529
+ // Automatically add tenantId to create operations
1530
+ async create({ args, query }) {
1531
+ var _a;
1532
+ if (!tenantContext.bypassMode && tenantContext.currentTenantId) {
1533
+ args.data ?? (args.data = {});
1534
+ (_a = args.data).tenantId ?? (_a.tenantId = tenantContext.currentTenantId);
1535
+ } else if (tenantContext.strictMode && !tenantContext.bypassMode && !tenantContext.currentTenantId) {
1536
+ throw new Error("Tenant context required for this operation. Use $withSystemMode() for system-level operations.");
1537
+ }
1538
+ return query(args);
1539
+ },
1540
+ // Add tenantId filter to update operations
1541
+ async update({ args, query }) {
1542
+ var _a;
1543
+ if (!tenantContext.bypassMode && tenantContext.currentTenantId) {
1544
+ args.where ?? (args.where = {});
1545
+ (_a = args.where).tenantId ?? (_a.tenantId = tenantContext.currentTenantId);
1546
+ } else if (tenantContext.strictMode && !tenantContext.bypassMode && !tenantContext.currentTenantId) {
1547
+ throw new Error("Tenant context required for this operation. Use $withSystemMode() for system-level operations.");
1548
+ }
1549
+ return query(args);
1550
+ },
1551
+ // Add tenantId filter to delete operations
1552
+ async delete({ args, query }) {
1553
+ var _a;
1554
+ if (!tenantContext.bypassMode && tenantContext.currentTenantId) {
1555
+ args.where ?? (args.where = {});
1556
+ (_a = args.where).tenantId ?? (_a.tenantId = tenantContext.currentTenantId);
1557
+ } else if (tenantContext.strictMode && !tenantContext.bypassMode && !tenantContext.currentTenantId) {
1558
+ throw new Error("Tenant context required for this operation. Use $withSystemMode() for system-level operations.");
1559
+ }
1560
+ return query(args);
1561
+ }
1562
+ }
1563
+ }
1564
+ };
1565
+ }
1566
+
1394
1567
  // src/datasources/prisma.datasource.ts
1395
1568
  var PrismaDatasource = class extends AbstractDatasource {
1396
1569
  constructor(prismaClient) {
@@ -1436,10 +1609,15 @@ var PrismaDatasource = class extends AbstractDatasource {
1436
1609
  }
1437
1610
  /**
1438
1611
  * Apply extensions to the Prisma client
1439
- * Override this method to add production extensions like soft delete, audit trails, etc.
1612
+ * By default, applies tenant extension for multi-tenant support
1613
+ * Override this method to add additional extensions like soft delete, audit trails, etc.
1440
1614
  */
1441
1615
  applyExtensions(client) {
1442
- return client;
1616
+ let extended = client;
1617
+ if (typeof client.$extends === "function") {
1618
+ extended = extended.$extends(createTenantExtension());
1619
+ }
1620
+ return extended;
1443
1621
  }
1444
1622
  /**
1445
1623
  * Get extended client with all applied extensions
@@ -1497,7 +1675,14 @@ var PrismaDatasource = class extends AbstractDatasource {
1497
1675
  async healthCheck() {
1498
1676
  try {
1499
1677
  this.broker.logger.info("Running Prisma health check");
1500
- await this.client.$queryRaw`SELECT 1`;
1678
+ const client = this.client;
1679
+ if (client.$withSystemMode) {
1680
+ await client.$withSystemMode(async () => {
1681
+ await this.client.$queryRaw`SELECT 1`;
1682
+ });
1683
+ } else {
1684
+ await this.client.$queryRaw`SELECT 1`;
1685
+ }
1501
1686
  this.broker.logger.info("Prisma health check passed");
1502
1687
  return true;
1503
1688
  } catch (error) {
@@ -1678,86 +1863,6 @@ var softDeleteExtension = {
1678
1863
  }
1679
1864
  };
1680
1865
 
1681
- // src/datasources/extensions/tenant.extension.ts
1682
- function createTenantExtension() {
1683
- const tenantContext = {
1684
- currentTenantId: null
1685
- };
1686
- return {
1687
- name: "Tenant",
1688
- client: {
1689
- // Set tenant context
1690
- $setTenant(tenantId) {
1691
- tenantContext.currentTenantId = tenantId;
1692
- },
1693
- // Get current tenant
1694
- $getCurrentTenant() {
1695
- return tenantContext.currentTenantId;
1696
- },
1697
- // Clear tenant context
1698
- $clearTenant() {
1699
- tenantContext.currentTenantId = null;
1700
- }
1701
- },
1702
- query: {
1703
- $allModels: {
1704
- // Automatically add tenantId filter to all read operations
1705
- async findMany({ args, query }) {
1706
- var _a;
1707
- if (tenantContext.currentTenantId) {
1708
- args.where ?? (args.where = {});
1709
- (_a = args.where).tenantId ?? (_a.tenantId = tenantContext.currentTenantId);
1710
- }
1711
- return query(args);
1712
- },
1713
- async findUnique({ args, query }) {
1714
- var _a;
1715
- if (tenantContext.currentTenantId) {
1716
- args.where ?? (args.where = {});
1717
- (_a = args.where).tenantId ?? (_a.tenantId = tenantContext.currentTenantId);
1718
- }
1719
- return query(args);
1720
- },
1721
- async findFirst({ args, query }) {
1722
- var _a;
1723
- if (tenantContext.currentTenantId) {
1724
- args.where ?? (args.where = {});
1725
- (_a = args.where).tenantId ?? (_a.tenantId = tenantContext.currentTenantId);
1726
- }
1727
- return query(args);
1728
- },
1729
- // Automatically add tenantId to create operations
1730
- async create({ args, query }) {
1731
- var _a;
1732
- if (tenantContext.currentTenantId) {
1733
- args.data ?? (args.data = {});
1734
- (_a = args.data).tenantId ?? (_a.tenantId = tenantContext.currentTenantId);
1735
- }
1736
- return query(args);
1737
- },
1738
- // Add tenantId filter to update operations
1739
- async update({ args, query }) {
1740
- var _a;
1741
- if (tenantContext.currentTenantId) {
1742
- args.where ?? (args.where = {});
1743
- (_a = args.where).tenantId ?? (_a.tenantId = tenantContext.currentTenantId);
1744
- }
1745
- return query(args);
1746
- },
1747
- // Add tenantId filter to delete operations
1748
- async delete({ args, query }) {
1749
- var _a;
1750
- if (tenantContext.currentTenantId) {
1751
- args.where ?? (args.where = {});
1752
- (_a = args.where).tenantId ?? (_a.tenantId = tenantContext.currentTenantId);
1753
- }
1754
- return query(args);
1755
- }
1756
- }
1757
- }
1758
- };
1759
- }
1760
-
1761
1866
  // src/datasources/extensions/retry.extension.ts
1762
1867
  var retryExtension = {
1763
1868
  name: "Retry",
@@ -1812,4 +1917,4 @@ var retryExtension = {
1812
1917
  }
1813
1918
  };
1814
1919
 
1815
- export { AbstractDatasource, CHANNELS, ContextHelpersMiddleware, CreateHealthCheckMiddleware, DatasourceMixin, HEALTH_CHECK_DEFAULTS, INTEGRATION_CHANNELS, IntegrationCapability, IntegrationPlatform, IntegrationStatus, MemoizeMixin, MessageContentType, NAMESPACE, PERMISSIONS, PermissionsMiddleware, PrismaDatasource, REDIS_URL, ROLE_PERMISSIONS, UserRole, createDatasourceMiddleware, createTenantExtension, defineIntegration, defineService, env_default as env, isDev, isProd, isTest, moleculer_default as moleculer, nodeEnv, omit, retryExtension, softDeleteExtension };
1920
+ export { AbstractDatasource, CHANNELS, ContextHelpersMiddleware, CreateHealthCheckMiddleware, DEFAULT_DATASOURCE_CACHE_TTL, DatasourceMixin, HEALTH_CHECK_DEFAULTS, INTEGRATION_CHANNELS, IntegrationCapability, IntegrationPlatform, IntegrationStatus, MemoizeMixin, MessageContentType, NAMESPACE, PERMISSIONS, PermissionsMiddleware, PrismaDatasource, REDIS_URL, ROLE_PERMISSIONS, UserRole, createDatasourceMiddleware, createTenantExtension, defineIntegration, defineService, env_default as env, isDev, isProd, isTest, moleculer_default as moleculer, nodeEnv, omit, retryExtension, softDeleteExtension };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hiliosai/sdk",
3
- "version": "0.1.18",
3
+ "version": "0.1.20",
4
4
  "type": "module",
5
5
  "license": "UNLICENSED",
6
6
  "main": "./dist/index.js",
@@ -31,4 +31,4 @@
31
31
  "bun-types": "latest"
32
32
  },
33
33
  "prettier": "@hiliosai/prettier"
34
- }
34
+ }