@hiliosai/sdk 0.1.4 → 0.1.6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hiliosai/sdk",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./src/index.ts"
@@ -66,6 +66,19 @@ export const CHANNELS = {
66
66
  },
67
67
  } as const;
68
68
 
69
+ /**
70
+ * Integration-specific channel names
71
+ */
72
+ export const INTEGRATION_CHANNELS = {
73
+ // Message events
74
+ MESSAGE_RECEIVED: `${NAMESPACE}.processing.message.received`,
75
+ MESSAGE_SENT: `${NAMESPACE}.processing.message.sent`,
76
+ MESSAGE_FAILED: `${NAMESPACE}.processing.message.failed`,
77
+ } as const;
78
+
79
+ export type IntegrationChannelName =
80
+ (typeof INTEGRATION_CHANNELS)[keyof typeof INTEGRATION_CHANNELS];
81
+
69
82
  /**
70
83
  * Channel Configuration Constants
71
84
  */
@@ -1,13 +1,29 @@
1
+ import type {ServiceBroker} from 'moleculer';
2
+
3
+ import type {AppContext} from '../types/context';
4
+
1
5
  /**
2
6
  * Base datasource interface that all datasources should implement
3
7
  * Provides common structure and optional lifecycle methods
4
8
  */
5
- export interface BaseDatasource {
9
+ export interface BaseDatasource<TContext = AppContext> {
6
10
  /**
7
11
  * Datasource name for identification and logging
8
12
  */
9
13
  readonly name: string;
10
14
 
15
+ /**
16
+ * Service broker instance for logging, events, and service calls
17
+ * Always available after datasource initialization
18
+ */
19
+ broker: ServiceBroker;
20
+
21
+ /**
22
+ * Current service context (only available during action execution)
23
+ * Will be undefined in lifecycle hooks or background tasks
24
+ */
25
+ context?: TContext;
26
+
11
27
  /**
12
28
  * Optional initialization method
13
29
  * Called when datasource is instantiated
@@ -48,24 +64,40 @@ export interface BaseDatasource {
48
64
  * private users: User[] = [];
49
65
  *
50
66
  * async findById(id: string): Promise<User | undefined> {
67
+ * this.broker?.logger.info('Finding user by ID:', id);
51
68
  * return this.users.find(u => u.id === id);
52
69
  * }
53
70
  *
54
- * async create(user: User): Promise<User> {
55
- * this.users.push(user);
56
- * return user;
71
+ * async healthCheck(): Promise<boolean> {
72
+ * this.broker?.logger.info('Health check for datasource', this.name);
73
+ * return true;
57
74
  * }
58
75
  * }
59
76
  * ```
60
77
  */
61
- export abstract class AbstractDatasource implements BaseDatasource {
78
+ export abstract class AbstractDatasource<TContext = AppContext>
79
+ implements BaseDatasource<TContext>
80
+ {
62
81
  abstract readonly name: string;
63
82
 
83
+ /**
84
+ * Service broker instance - injected by mixin
85
+ * Always available after initialization
86
+ */
87
+ broker!: ServiceBroker; // Using definite assignment assertion since it's injected
88
+
89
+ /**
90
+ * Current service context - injected per action
91
+ * Only available during action execution
92
+ */
93
+ context?: TContext;
94
+
64
95
  /**
65
96
  * Default health check - always returns true
66
97
  * Override for custom health check logic
67
98
  */
68
99
  async healthCheck(): Promise<boolean> {
100
+ this.broker.logger.info(`Health check for datasource - ${this.name}`);
69
101
  return true;
70
102
  }
71
103
 
@@ -0,0 +1,11 @@
1
+ // Export all Prisma extensions for easy importing
2
+ export { softDeleteExtension } from './soft-delete.extension';
3
+ export { createTenantExtension } from './tenant.extension';
4
+ export { retryExtension } from './retry.extension';
5
+
6
+ // Re-export extension interfaces
7
+ export type {
8
+ SoftDeleteExtension,
9
+ AuditTrailExtension,
10
+ TenantExtension,
11
+ } from '../prisma.datasource';
@@ -0,0 +1,91 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ /**
3
+ * Retry Extension for Prisma Transactions
4
+ * Automatically retries failed transactions with exponential backoff
5
+ *
6
+ * Usage:
7
+ * ```typescript
8
+ * import { retryExtension } from './extensions/retry.extension';
9
+ *
10
+ * class MyPrismaDS extends PrismaDatasource<PrismaClient> {
11
+ * protected applyExtensions(client: PrismaClient) {
12
+ * return client.$extends(retryExtension);
13
+ * }
14
+ * }
15
+ * ```
16
+ */
17
+
18
+ export const retryExtension = {
19
+ name: 'Retry',
20
+
21
+ client: {
22
+ async $retryTransaction<T>(
23
+ fn: (tx: any) => Promise<T>,
24
+ options: {
25
+ maxRetries?: number;
26
+ baseDelay?: number;
27
+ maxDelay?: number;
28
+ retryableErrors?: string[];
29
+ } = {}
30
+ ): Promise<T> {
31
+ const {
32
+ maxRetries = 3,
33
+ baseDelay = 100,
34
+ maxDelay = 5000,
35
+ retryableErrors = [
36
+ 'P2034', // Transaction failed due to a write conflict
37
+ 'P2002', // Unique constraint failed
38
+ 'P5000', // Raw query failed
39
+ ],
40
+ } = options;
41
+
42
+ let lastError: Error | undefined;
43
+
44
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
45
+ try {
46
+ return await (this as any).$transaction(fn, {
47
+ timeout: 10000,
48
+ maxWait: 5000,
49
+ });
50
+ } catch (error: any) {
51
+ lastError = error;
52
+
53
+ // Check if error is retryable
54
+ const isRetryable = retryableErrors.some(
55
+ (code) => error.code === code || error.message?.includes(code)
56
+ );
57
+
58
+ if (!isRetryable || attempt === maxRetries) {
59
+ throw error;
60
+ }
61
+
62
+ // Calculate delay with exponential backoff and jitter
63
+ const delay = Math.min(
64
+ baseDelay * Math.pow(2, attempt) + Math.random() * 100,
65
+ maxDelay
66
+ );
67
+
68
+ // Log retry attempt (in production, use proper logger)
69
+ if (
70
+ typeof globalThis !== 'undefined' &&
71
+ (globalThis as any).console
72
+ ) {
73
+ (globalThis as any).console.warn(
74
+ `Transaction retry ${
75
+ attempt + 1
76
+ }/${maxRetries} after ${delay}ms:`,
77
+ {
78
+ error: error.message,
79
+ code: error.code,
80
+ }
81
+ );
82
+ }
83
+
84
+ await new Promise((resolve) => setTimeout(resolve, delay));
85
+ }
86
+ }
87
+
88
+ throw lastError ?? new Error('Transaction failed after maximum retries');
89
+ },
90
+ },
91
+ };
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Soft Delete Extension for Prisma
3
+ * Automatically handles soft deletes by setting deletedAt instead of removing records
4
+ *
5
+ * Usage:
6
+ * ```typescript
7
+ * import { softDeleteExtension } from './extensions/soft-delete.extension';
8
+ *
9
+ * class MyPrismaDS extends PrismaDatasource<PrismaClient> {
10
+ * protected applyExtensions(client: PrismaClient) {
11
+ * return client.$extends(softDeleteExtension);
12
+ * }
13
+ * }
14
+ * ```
15
+ *
16
+ * Requires models to have `deletedAt DateTime?` field
17
+ */
18
+
19
+ export const softDeleteExtension = {
20
+ name: 'SoftDelete',
21
+
22
+ query: {
23
+ // Apply to all models
24
+ $allModels: {
25
+ // Override findMany to exclude soft deleted records
26
+ async findMany({args, query}: any) {
27
+ // Add deletedAt: null filter if not already specified
28
+ args.where ??= {};
29
+ if (args.where.deletedAt === undefined) {
30
+ args.where.deletedAt = null;
31
+ }
32
+ return query(args);
33
+ },
34
+
35
+ // Override findUnique to exclude soft deleted records
36
+ async findUnique({args, query}: any) {
37
+ args.where ??= {};
38
+ if (args.where.deletedAt === undefined) {
39
+ args.where.deletedAt = null;
40
+ }
41
+ return query(args);
42
+ },
43
+
44
+ // Override findFirst to exclude soft deleted records
45
+ async findFirst({args, query}: any) {
46
+ args.where ??= {};
47
+ if (args.where.deletedAt === undefined) {
48
+ args.where.deletedAt = null;
49
+ }
50
+ return query(args);
51
+ },
52
+
53
+ // Override delete to set deletedAt instead
54
+ async delete({args, query}: any) {
55
+ return query({
56
+ ...args,
57
+ data: {deletedAt: new Date()},
58
+ });
59
+ },
60
+
61
+ // Override deleteMany to set deletedAt instead
62
+ async deleteMany({args, query}: any) {
63
+ return query({
64
+ ...args,
65
+ data: {deletedAt: new Date()},
66
+ });
67
+ },
68
+ },
69
+ },
70
+
71
+ model: {
72
+ $allModels: {
73
+ // Add restore method to all models
74
+ async restore<T>(this: T, where: any): Promise<any> {
75
+ const context =
76
+ (globalThis as any).Prisma?.getExtensionContext?.(this) ?? this;
77
+
78
+ return (context as any).update({
79
+ where,
80
+ data: {deletedAt: null},
81
+ });
82
+ },
83
+
84
+ // Add findWithDeleted method to include soft deleted records
85
+ async findWithDeleted<T>(this: T, args: any): Promise<any> {
86
+ const context =
87
+ (globalThis as any).Prisma?.getExtensionContext?.(this) ?? this;
88
+
89
+ return (context as any).findMany({
90
+ ...args,
91
+ where: {
92
+ ...args.where,
93
+ // Don't filter by deletedAt
94
+ },
95
+ });
96
+ },
97
+
98
+ // Add findDeleted method to find only soft deleted records
99
+ async findDeleted<T>(this: T, args: any): Promise<any> {
100
+ const context =
101
+ (globalThis as any).Prisma?.getExtensionContext?.(this) ?? this;
102
+
103
+ return (context as any).findMany({
104
+ ...args,
105
+ where: {
106
+ ...args.where,
107
+ deletedAt: {not: null},
108
+ },
109
+ });
110
+ },
111
+ },
112
+ },
113
+ };
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Multi-Tenant Extension for Prisma
3
+ * Automatically filters queries by tenant context for multi-tenant applications
4
+ *
5
+ * Usage:
6
+ * ```typescript
7
+ * import { createTenantExtension } from './extensions/tenant.extension';
8
+ *
9
+ * class MyPrismaDS extends PrismaDatasource<PrismaClient> {
10
+ * protected applyExtensions(client: PrismaClient) {
11
+ * return client.$extends(createTenantExtension());
12
+ * }
13
+ * }
14
+ * ```
15
+ *
16
+ * Requires models to have `tenantId String` field
17
+ */
18
+
19
+ interface TenantContext {
20
+ currentTenantId: string | null;
21
+ }
22
+
23
+ export function createTenantExtension() {
24
+ const tenantContext: TenantContext = {
25
+ currentTenantId: null,
26
+ };
27
+
28
+ return {
29
+ name: 'Tenant',
30
+
31
+ client: {
32
+ // Set tenant context
33
+ $setTenant(tenantId: string) {
34
+ tenantContext.currentTenantId = tenantId;
35
+ },
36
+
37
+ // Get current tenant
38
+ $getCurrentTenant() {
39
+ return tenantContext.currentTenantId;
40
+ },
41
+
42
+ // Clear tenant context
43
+ $clearTenant() {
44
+ tenantContext.currentTenantId = null;
45
+ },
46
+ },
47
+
48
+ query: {
49
+ $allModels: {
50
+ // Automatically add tenantId filter to all read operations
51
+ async findMany({ args, query }: any) {
52
+ if (tenantContext.currentTenantId) {
53
+ args.where ??= {};
54
+ args.where.tenantId ??= tenantContext.currentTenantId;
55
+ }
56
+ return query(args);
57
+ },
58
+
59
+ async findUnique({ args, query }: any) {
60
+ if (tenantContext.currentTenantId) {
61
+ args.where ??= {};
62
+ args.where.tenantId ??= tenantContext.currentTenantId;
63
+ }
64
+ return query(args);
65
+ },
66
+
67
+ async findFirst({ args, query }: any) {
68
+ if (tenantContext.currentTenantId) {
69
+ args.where ??= {};
70
+ args.where.tenantId ??= tenantContext.currentTenantId;
71
+ }
72
+ return query(args);
73
+ },
74
+
75
+ // Automatically add tenantId to create operations
76
+ async create({ args, query }: any) {
77
+ if (tenantContext.currentTenantId) {
78
+ args.data ??= {};
79
+ args.data.tenantId ??= tenantContext.currentTenantId;
80
+ }
81
+ return query(args);
82
+ },
83
+
84
+ // Add tenantId filter to update operations
85
+ async update({ args, query }: any) {
86
+ if (tenantContext.currentTenantId) {
87
+ args.where ??= {};
88
+ args.where.tenantId ??= tenantContext.currentTenantId;
89
+ }
90
+ return query(args);
91
+ },
92
+
93
+ // Add tenantId filter to delete operations
94
+ async delete({ args, query }: any) {
95
+ if (tenantContext.currentTenantId) {
96
+ args.where ??= {};
97
+ args.where.tenantId ??= tenantContext.currentTenantId;
98
+ }
99
+ return query(args);
100
+ },
101
+ },
102
+ },
103
+ };
104
+ }
@@ -1 +1,3 @@
1
1
  export * from './base.datasource';
2
+ export * from './prisma.datasource';
3
+ export * from './extensions';