@timmeck/marketing-brain 0.2.1 → 0.4.0

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.
Files changed (160) hide show
  1. package/Dockerfile +22 -0
  2. package/README.md +20 -3
  3. package/dashboard.html +6 -0
  4. package/dist/cli/colors.d.ts +11 -24
  5. package/dist/cli/colors.js +3 -46
  6. package/dist/cli/colors.js.map +1 -1
  7. package/dist/cli/commands/dashboard.js +15 -0
  8. package/dist/cli/commands/dashboard.js.map +1 -1
  9. package/dist/cli/commands/peers.d.ts +2 -0
  10. package/dist/cli/commands/peers.js +38 -0
  11. package/dist/cli/commands/peers.js.map +1 -0
  12. package/dist/config.js +2 -29
  13. package/dist/config.js.map +1 -1
  14. package/dist/db/connection.d.ts +1 -2
  15. package/dist/db/connection.js +1 -18
  16. package/dist/db/connection.js.map +1 -1
  17. package/dist/hooks/post-tool-use.d.ts +2 -0
  18. package/dist/hooks/post-tool-use.js +182 -0
  19. package/dist/hooks/post-tool-use.js.map +1 -0
  20. package/dist/index.js +2 -0
  21. package/dist/index.js.map +1 -1
  22. package/dist/ipc/client.d.ts +1 -13
  23. package/dist/ipc/client.js +1 -92
  24. package/dist/ipc/client.js.map +1 -1
  25. package/dist/ipc/protocol.d.ts +1 -8
  26. package/dist/ipc/protocol.js +1 -28
  27. package/dist/ipc/protocol.js.map +1 -1
  28. package/dist/ipc/router.d.ts +2 -0
  29. package/dist/ipc/router.js +30 -0
  30. package/dist/ipc/router.js.map +1 -1
  31. package/dist/ipc/server.d.ts +1 -14
  32. package/dist/ipc/server.js +1 -129
  33. package/dist/ipc/server.js.map +1 -1
  34. package/dist/learning/confidence-scorer.d.ts +1 -5
  35. package/dist/learning/confidence-scorer.js +2 -13
  36. package/dist/learning/confidence-scorer.js.map +1 -1
  37. package/dist/learning/learning-engine.d.ts +2 -5
  38. package/dist/learning/learning-engine.js +3 -20
  39. package/dist/learning/learning-engine.js.map +1 -1
  40. package/dist/marketing-core.d.ts +2 -0
  41. package/dist/marketing-core.js +22 -2
  42. package/dist/marketing-core.js.map +1 -1
  43. package/dist/mcp/server.js +5 -60
  44. package/dist/mcp/server.js.map +1 -1
  45. package/dist/mcp/tools.js +29 -0
  46. package/dist/mcp/tools.js.map +1 -1
  47. package/dist/research/research-engine.d.ts +2 -5
  48. package/dist/research/research-engine.js +3 -24
  49. package/dist/research/research-engine.js.map +1 -1
  50. package/dist/services/analytics.service.d.ts +1 -1
  51. package/dist/services/synapse.service.d.ts +10 -10
  52. package/dist/synapses/activation.d.ts +2 -13
  53. package/dist/synapses/activation.js +2 -49
  54. package/dist/synapses/activation.js.map +1 -1
  55. package/dist/synapses/decay.d.ts +2 -11
  56. package/dist/synapses/decay.js +2 -26
  57. package/dist/synapses/decay.js.map +1 -1
  58. package/dist/synapses/hebbian.d.ts +2 -13
  59. package/dist/synapses/hebbian.js +2 -34
  60. package/dist/synapses/hebbian.js.map +1 -1
  61. package/dist/synapses/pathfinder.d.ts +2 -14
  62. package/dist/synapses/pathfinder.js +2 -49
  63. package/dist/synapses/pathfinder.js.map +1 -1
  64. package/dist/synapses/synapse-manager.d.ts +7 -23
  65. package/dist/synapses/synapse-manager.js +6 -63
  66. package/dist/synapses/synapse-manager.js.map +1 -1
  67. package/dist/types/ipc.types.d.ts +1 -11
  68. package/dist/utils/events.d.ts +4 -8
  69. package/dist/utils/events.js +2 -14
  70. package/dist/utils/events.js.map +1 -1
  71. package/dist/utils/hash.d.ts +1 -1
  72. package/dist/utils/hash.js +1 -4
  73. package/dist/utils/hash.js.map +1 -1
  74. package/dist/utils/logger.d.ts +3 -2
  75. package/dist/utils/logger.js +8 -35
  76. package/dist/utils/logger.js.map +1 -1
  77. package/dist/utils/paths.d.ts +2 -1
  78. package/dist/utils/paths.js +4 -13
  79. package/dist/utils/paths.js.map +1 -1
  80. package/eslint.config.js +14 -0
  81. package/package.json +9 -2
  82. package/.github/FUNDING.yml +0 -1
  83. package/.github/workflows/ci.yml +0 -27
  84. package/.mcp.json +0 -9
  85. package/src/api/server.ts +0 -86
  86. package/src/cli/colors.ts +0 -59
  87. package/src/cli/commands/campaign.ts +0 -66
  88. package/src/cli/commands/config.ts +0 -168
  89. package/src/cli/commands/dashboard.ts +0 -165
  90. package/src/cli/commands/doctor.ts +0 -110
  91. package/src/cli/commands/export.ts +0 -40
  92. package/src/cli/commands/import.ts +0 -84
  93. package/src/cli/commands/insights.ts +0 -44
  94. package/src/cli/commands/learn.ts +0 -24
  95. package/src/cli/commands/network.ts +0 -71
  96. package/src/cli/commands/post.ts +0 -47
  97. package/src/cli/commands/query.ts +0 -108
  98. package/src/cli/commands/rules.ts +0 -27
  99. package/src/cli/commands/start.ts +0 -100
  100. package/src/cli/commands/status.ts +0 -73
  101. package/src/cli/commands/stop.ts +0 -33
  102. package/src/cli/commands/suggest.ts +0 -64
  103. package/src/cli/ipc-helper.ts +0 -22
  104. package/src/cli/update-check.ts +0 -63
  105. package/src/config.ts +0 -110
  106. package/src/dashboard/renderer.ts +0 -136
  107. package/src/dashboard/server.ts +0 -140
  108. package/src/db/connection.ts +0 -22
  109. package/src/db/migrations/001_core_schema.ts +0 -63
  110. package/src/db/migrations/002_learning_schema.ts +0 -46
  111. package/src/db/migrations/003_synapse_schema.ts +0 -27
  112. package/src/db/migrations/004_insights_schema.ts +0 -38
  113. package/src/db/migrations/005_fts_indexes.ts +0 -77
  114. package/src/db/migrations/index.ts +0 -62
  115. package/src/db/repositories/audience.repository.ts +0 -53
  116. package/src/db/repositories/campaign.repository.ts +0 -72
  117. package/src/db/repositories/engagement.repository.ts +0 -108
  118. package/src/db/repositories/insight.repository.ts +0 -100
  119. package/src/db/repositories/post.repository.ts +0 -123
  120. package/src/db/repositories/rule.repository.ts +0 -87
  121. package/src/db/repositories/strategy.repository.ts +0 -82
  122. package/src/db/repositories/synapse.repository.ts +0 -148
  123. package/src/db/repositories/template.repository.ts +0 -76
  124. package/src/index.ts +0 -69
  125. package/src/ipc/__tests__/protocol.test.ts +0 -153
  126. package/src/ipc/client.ts +0 -110
  127. package/src/ipc/protocol.ts +0 -35
  128. package/src/ipc/router.ts +0 -126
  129. package/src/ipc/server.ts +0 -140
  130. package/src/learning/confidence-scorer.ts +0 -36
  131. package/src/learning/learning-engine.ts +0 -254
  132. package/src/marketing-core.ts +0 -285
  133. package/src/mcp/server.ts +0 -72
  134. package/src/mcp/tools.ts +0 -216
  135. package/src/research/research-engine.ts +0 -226
  136. package/src/services/analytics.service.ts +0 -73
  137. package/src/services/audience.service.ts +0 -40
  138. package/src/services/campaign.service.ts +0 -80
  139. package/src/services/insight.service.ts +0 -54
  140. package/src/services/post.service.ts +0 -116
  141. package/src/services/rule.service.ts +0 -90
  142. package/src/services/strategy.service.ts +0 -53
  143. package/src/services/synapse.service.ts +0 -32
  144. package/src/services/template.service.ts +0 -50
  145. package/src/synapses/activation.ts +0 -80
  146. package/src/synapses/decay.ts +0 -38
  147. package/src/synapses/hebbian.ts +0 -68
  148. package/src/synapses/pathfinder.ts +0 -81
  149. package/src/synapses/synapse-manager.ts +0 -115
  150. package/src/types/config.types.ts +0 -79
  151. package/src/types/ipc.types.ts +0 -8
  152. package/src/types/post.types.ts +0 -156
  153. package/src/types/synapse.types.ts +0 -43
  154. package/src/utils/__tests__/hash.test.ts +0 -39
  155. package/src/utils/__tests__/paths.test.ts +0 -70
  156. package/src/utils/events.ts +0 -44
  157. package/src/utils/hash.ts +0 -5
  158. package/src/utils/logger.ts +0 -48
  159. package/src/utils/paths.ts +0 -19
  160. package/tsconfig.json +0 -18
@@ -1,148 +0,0 @@
1
- import type Database from 'better-sqlite3';
2
- import type { Statement } from 'better-sqlite3';
3
- import type { SynapseRecord } from '../../types/synapse.types.js';
4
-
5
- type SynapseCreate = Omit<SynapseRecord, 'id' | 'activation_count' | 'last_activated_at' | 'created_at' | 'updated_at'>;
6
- type SynapseUpdate = Partial<Omit<SynapseRecord, 'id' | 'created_at'>>;
7
-
8
- export class SynapseRepository {
9
- private stmts: Record<string, Statement>;
10
-
11
- constructor(private db: Database.Database) {
12
- this.stmts = {
13
- create: db.prepare(`
14
- INSERT INTO synapses (source_type, source_id, target_type, target_id, synapse_type, weight, metadata)
15
- VALUES (@source_type, @source_id, @target_type, @target_id, @synapse_type, @weight, @metadata)
16
- `),
17
- getById: db.prepare('SELECT * FROM synapses WHERE id = ?'),
18
- delete: db.prepare('DELETE FROM synapses WHERE id = ?'),
19
- getOutgoing: db.prepare(
20
- 'SELECT * FROM synapses WHERE source_type = ? AND source_id = ? ORDER BY weight DESC'
21
- ),
22
- getIncoming: db.prepare(
23
- 'SELECT * FROM synapses WHERE target_type = ? AND target_id = ? ORDER BY weight DESC'
24
- ),
25
- findConnected: db.prepare(`
26
- SELECT * FROM synapses
27
- WHERE (source_type = ? AND source_id = ?) OR (target_type = ? AND target_id = ?)
28
- ORDER BY weight DESC
29
- `),
30
- findBySourceTarget: db.prepare(`
31
- SELECT * FROM synapses
32
- WHERE source_type = ? AND source_id = ? AND target_type = ? AND target_id = ? AND synapse_type = ?
33
- `),
34
- findInactiveSince: db.prepare(`
35
- SELECT * FROM synapses WHERE last_activated_at < ?
36
- `),
37
- countNodes: db.prepare(`
38
- SELECT COUNT(*) as count FROM (
39
- SELECT source_type, source_id FROM synapses
40
- UNION
41
- SELECT target_type, target_id FROM synapses
42
- )
43
- `),
44
- avgWeight: db.prepare('SELECT AVG(weight) as avg_weight FROM synapses'),
45
- countByType: db.prepare('SELECT synapse_type, COUNT(*) as count FROM synapses GROUP BY synapse_type'),
46
- totalCount: db.prepare('SELECT COUNT(*) as count FROM synapses'),
47
- topByWeight: db.prepare('SELECT * FROM synapses ORDER BY weight DESC LIMIT ?'),
48
- topDiverse: db.prepare(`
49
- SELECT * FROM (
50
- SELECT *, ROW_NUMBER() OVER (PARTITION BY synapse_type ORDER BY weight DESC) as rn
51
- FROM synapses
52
- ) WHERE rn <= ? ORDER BY weight DESC
53
- `),
54
- };
55
- }
56
-
57
- create(data: SynapseCreate): number {
58
- const result = this.stmts.create.run({
59
- source_type: data.source_type,
60
- source_id: data.source_id,
61
- target_type: data.target_type,
62
- target_id: data.target_id,
63
- synapse_type: data.synapse_type,
64
- weight: data.weight,
65
- metadata: data.metadata ?? null,
66
- });
67
- return result.lastInsertRowid as number;
68
- }
69
-
70
- getById(id: number): SynapseRecord | undefined {
71
- return this.stmts.getById.get(id) as SynapseRecord | undefined;
72
- }
73
-
74
- update(id: number, data: SynapseUpdate): boolean {
75
- const fields = Object.keys(data).filter(
76
- (key) => (data as Record<string, unknown>)[key] !== undefined
77
- );
78
- if (fields.length === 0) return false;
79
-
80
- const setClauses = fields.map((field) => `${field} = @${field}`).join(', ');
81
- const stmt = this.db.prepare(
82
- `UPDATE synapses SET ${setClauses}, updated_at = datetime('now') WHERE id = @id`
83
- );
84
- const result = stmt.run({ ...data, id });
85
- return result.changes > 0;
86
- }
87
-
88
- delete(id: number): boolean {
89
- const result = this.stmts.delete.run(id);
90
- return result.changes > 0;
91
- }
92
-
93
- getOutgoing(sourceType: string, sourceId: number): SynapseRecord[] {
94
- return this.stmts.getOutgoing.all(sourceType, sourceId) as SynapseRecord[];
95
- }
96
-
97
- getIncoming(targetType: string, targetId: number): SynapseRecord[] {
98
- return this.stmts.getIncoming.all(targetType, targetId) as SynapseRecord[];
99
- }
100
-
101
- findBySourceTarget(
102
- sourceType: string, sourceId: number,
103
- targetType: string, targetId: number,
104
- synapseType: string,
105
- ): SynapseRecord | undefined {
106
- return this.stmts.findBySourceTarget.get(
107
- sourceType, sourceId, targetType, targetId, synapseType
108
- ) as SynapseRecord | undefined;
109
- }
110
-
111
- findConnected(nodeType: string, nodeId: number): SynapseRecord[] {
112
- return this.stmts.findConnected.all(nodeType, nodeId, nodeType, nodeId) as SynapseRecord[];
113
- }
114
-
115
- findInactiveSince(cutoff: string): SynapseRecord[] {
116
- return this.stmts.findInactiveSince.all(cutoff) as SynapseRecord[];
117
- }
118
-
119
- topByWeight(limit: number): SynapseRecord[] {
120
- return this.stmts.topByWeight.all(limit) as SynapseRecord[];
121
- }
122
-
123
- topDiverse(perType: number): SynapseRecord[] {
124
- return this.stmts.topDiverse.all(perType) as SynapseRecord[];
125
- }
126
-
127
- countNodes(): number {
128
- const row = this.stmts.countNodes.get() as { count: number };
129
- return row.count;
130
- }
131
-
132
- totalCount(): number {
133
- const row = this.stmts.totalCount.get() as { count: number };
134
- return row.count;
135
- }
136
-
137
- avgWeight(): number {
138
- const row = this.stmts.avgWeight.get() as { avg_weight: number | null };
139
- return row.avg_weight ?? 0;
140
- }
141
-
142
- countByType(): Record<string, number> {
143
- const rows = this.stmts.countByType.all() as Array<{ synapse_type: string; count: number }>;
144
- const result: Record<string, number> = {};
145
- for (const row of rows) result[row.synapse_type] = row.count;
146
- return result;
147
- }
148
- }
@@ -1,76 +0,0 @@
1
- import type Database from 'better-sqlite3';
2
- import type { Statement } from 'better-sqlite3';
3
- import type { ContentTemplate, ContentTemplateCreate } from '../../types/post.types.js';
4
-
5
- export class TemplateRepository {
6
- private stmts: Record<string, Statement>;
7
-
8
- constructor(private db: Database.Database) {
9
- this.stmts = {
10
- create: db.prepare(`
11
- INSERT INTO content_templates (name, structure, example, platform)
12
- VALUES (@name, @structure, @example, @platform)
13
- `),
14
- getById: db.prepare('SELECT * FROM content_templates WHERE id = ?'),
15
- listAll: db.prepare('SELECT * FROM content_templates ORDER BY avg_engagement DESC LIMIT ?'),
16
- listByPlatform: db.prepare('SELECT * FROM content_templates WHERE platform = ? ORDER BY avg_engagement DESC LIMIT ?'),
17
- countAll: db.prepare('SELECT COUNT(*) as count FROM content_templates'),
18
- search: db.prepare(`
19
- SELECT t.* FROM content_templates t
20
- JOIN content_templates_fts f ON f.rowid = t.id
21
- WHERE content_templates_fts MATCH ?
22
- ORDER BY rank
23
- LIMIT ?
24
- `),
25
- delete: db.prepare('DELETE FROM content_templates WHERE id = ?'),
26
- };
27
- }
28
-
29
- create(data: ContentTemplateCreate): number {
30
- const result = this.stmts.create.run({
31
- name: data.name,
32
- structure: data.structure,
33
- example: data.example ?? null,
34
- platform: data.platform ?? null,
35
- });
36
- return result.lastInsertRowid as number;
37
- }
38
-
39
- getById(id: number): ContentTemplate | undefined {
40
- return this.stmts.getById.get(id) as ContentTemplate | undefined;
41
- }
42
-
43
- listAll(limit: number = 50): ContentTemplate[] {
44
- return this.stmts.listAll.all(limit) as ContentTemplate[];
45
- }
46
-
47
- listByPlatform(platform: string, limit: number = 20): ContentTemplate[] {
48
- return this.stmts.listByPlatform.all(platform, limit) as ContentTemplate[];
49
- }
50
-
51
- search(query: string, limit: number = 20): ContentTemplate[] {
52
- return this.stmts.search.all(query, limit) as ContentTemplate[];
53
- }
54
-
55
- incrementUseCount(id: number): void {
56
- this.db.prepare(
57
- `UPDATE content_templates SET use_count = use_count + 1 WHERE id = ?`
58
- ).run(id);
59
- }
60
-
61
- updateAvgEngagement(id: number, avgEngagement: number): void {
62
- this.db.prepare(
63
- `UPDATE content_templates SET avg_engagement = ? WHERE id = ?`
64
- ).run(avgEngagement, id);
65
- }
66
-
67
- countAll(): number {
68
- const row = this.stmts.countAll.get() as { count: number };
69
- return row.count;
70
- }
71
-
72
- delete(id: number): boolean {
73
- const result = this.stmts.delete.run(id);
74
- return result.changes > 0;
75
- }
76
- }
package/src/index.ts DELETED
@@ -1,69 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import { Command } from 'commander';
4
- import { startCommand } from './cli/commands/start.js';
5
- import { stopCommand } from './cli/commands/stop.js';
6
- import { statusCommand } from './cli/commands/status.js';
7
- import { doctorCommand } from './cli/commands/doctor.js';
8
- import { postCommand } from './cli/commands/post.js';
9
- import { campaignCommand } from './cli/commands/campaign.js';
10
- import { insightsCommand } from './cli/commands/insights.js';
11
- import { rulesCommand } from './cli/commands/rules.js';
12
- import { suggestCommand } from './cli/commands/suggest.js';
13
- import { dashboardCommand } from './cli/commands/dashboard.js';
14
- import { importCommand } from './cli/commands/import.js';
15
- import { exportCommand } from './cli/commands/export.js';
16
- import { learnCommand } from './cli/commands/learn.js';
17
- import { networkCommand } from './cli/commands/network.js';
18
- import { queryCommand } from './cli/commands/query.js';
19
- import { configCommand } from './cli/commands/config.js';
20
- import { checkForUpdate, getCurrentVersion } from './cli/update-check.js';
21
-
22
- const program = new Command();
23
-
24
- program
25
- .name('marketing')
26
- .description('Marketing Brain — Self-Learning Marketing Intelligence System')
27
- .version(getCurrentVersion());
28
-
29
- program.addCommand(startCommand());
30
- program.addCommand(stopCommand());
31
- program.addCommand(statusCommand());
32
- program.addCommand(doctorCommand());
33
- program.addCommand(postCommand());
34
- program.addCommand(campaignCommand());
35
- program.addCommand(insightsCommand());
36
- program.addCommand(rulesCommand());
37
- program.addCommand(suggestCommand());
38
- program.addCommand(dashboardCommand());
39
- program.addCommand(importCommand());
40
- program.addCommand(exportCommand());
41
- program.addCommand(learnCommand());
42
- program.addCommand(networkCommand());
43
- program.addCommand(queryCommand());
44
- program.addCommand(configCommand());
45
-
46
- // Hidden: MCP server (called by Claude Code)
47
- program
48
- .command('mcp-server')
49
- .description('Start MCP server (stdio transport, used by Claude Code)')
50
- .action(async () => {
51
- const { startMcpServer } = await import('./mcp/server.js');
52
- await startMcpServer();
53
- });
54
-
55
- // Hidden: run daemon in foreground
56
- program
57
- .command('daemon')
58
- .description('Run daemon in foreground')
59
- .option('-c, --config <path>', 'Config file path')
60
- .action(async (opts) => {
61
- const { MarketingCore } = await import('./marketing-core.js');
62
- const core = new MarketingCore();
63
- core.start(opts.config);
64
- });
65
-
66
- program.parse();
67
-
68
- // Non-blocking update check after command finishes
69
- checkForUpdate();
@@ -1,153 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { Buffer } from 'node:buffer';
3
- import { encodeMessage, MessageDecoder } from '../protocol.js';
4
- import type { IpcMessage } from '../../types/ipc.types.js';
5
-
6
- const makeMessage = (overrides: Partial<IpcMessage> = {}): IpcMessage => ({
7
- id: '1',
8
- type: 'request',
9
- method: 'ping',
10
- ...overrides,
11
- });
12
-
13
- describe('encodeMessage', () => {
14
- it('returns a Buffer', () => {
15
- const buf = encodeMessage(makeMessage());
16
- expect(Buffer.isBuffer(buf)).toBe(true);
17
- });
18
-
19
- it('prefixes payload with 4-byte big-endian length', () => {
20
- const msg = makeMessage();
21
- const buf = encodeMessage(msg);
22
- const payloadLength = buf.readUInt32BE(0);
23
- expect(buf.length).toBe(4 + payloadLength);
24
- });
25
-
26
- it('contains the JSON payload after the length prefix', () => {
27
- const msg = makeMessage({ id: 'test-42', method: 'hello' });
28
- const buf = encodeMessage(msg);
29
- const payloadLength = buf.readUInt32BE(0);
30
- const json = buf.subarray(4, 4 + payloadLength).toString('utf8');
31
- const parsed = JSON.parse(json);
32
- expect(parsed.id).toBe('test-42');
33
- expect(parsed.method).toBe('hello');
34
- expect(parsed.type).toBe('request');
35
- });
36
- });
37
-
38
- describe('MessageDecoder', () => {
39
- it('decodes a single complete message', () => {
40
- const decoder = new MessageDecoder();
41
- const msg = makeMessage({ id: 'a' });
42
- const encoded = encodeMessage(msg);
43
-
44
- const messages = decoder.feed(encoded);
45
- expect(messages).toHaveLength(1);
46
- expect(messages[0].id).toBe('a');
47
- });
48
-
49
- it('decodes multiple messages fed at once', () => {
50
- const decoder = new MessageDecoder();
51
- const buf = Buffer.concat([
52
- encodeMessage(makeMessage({ id: '1' })),
53
- encodeMessage(makeMessage({ id: '2' })),
54
- encodeMessage(makeMessage({ id: '3' })),
55
- ]);
56
-
57
- const messages = decoder.feed(buf);
58
- expect(messages).toHaveLength(3);
59
- expect(messages.map((m) => m.id)).toEqual(['1', '2', '3']);
60
- });
61
-
62
- it('handles partial messages across multiple feeds', () => {
63
- const decoder = new MessageDecoder();
64
- const encoded = encodeMessage(makeMessage({ id: 'split' }));
65
-
66
- // Split in the middle of the payload
67
- const mid = Math.floor(encoded.length / 2);
68
- const part1 = encoded.subarray(0, mid);
69
- const part2 = encoded.subarray(mid);
70
-
71
- const first = decoder.feed(part1);
72
- expect(first).toHaveLength(0);
73
-
74
- const second = decoder.feed(part2);
75
- expect(second).toHaveLength(1);
76
- expect(second[0].id).toBe('split');
77
- });
78
-
79
- it('handles chunk split inside the 4-byte length header', () => {
80
- const decoder = new MessageDecoder();
81
- const encoded = encodeMessage(makeMessage({ id: 'header-split' }));
82
-
83
- // Only send 2 bytes of the 4-byte header
84
- const first = decoder.feed(encoded.subarray(0, 2));
85
- expect(first).toHaveLength(0);
86
-
87
- const second = decoder.feed(encoded.subarray(2));
88
- expect(second).toHaveLength(1);
89
- expect(second[0].id).toBe('header-split');
90
- });
91
-
92
- it('returns empty array when buffer has incomplete data', () => {
93
- const decoder = new MessageDecoder();
94
- // Just 3 bytes -- not even enough for the length header
95
- const partial = Buffer.from([0x00, 0x00, 0x00]);
96
- expect(decoder.feed(partial)).toHaveLength(0);
97
- });
98
-
99
- it('reset clears internal buffer', () => {
100
- const decoder = new MessageDecoder();
101
- const encoded = encodeMessage(makeMessage({ id: 'before-reset' }));
102
-
103
- // Feed partial data, then reset
104
- decoder.feed(encoded.subarray(0, 5));
105
- decoder.reset();
106
-
107
- // Now feed a fresh complete message
108
- const messages = decoder.feed(encodeMessage(makeMessage({ id: 'after-reset' })));
109
- expect(messages).toHaveLength(1);
110
- expect(messages[0].id).toBe('after-reset');
111
- });
112
-
113
- it('preserves leftover bytes for next feed', () => {
114
- const decoder = new MessageDecoder();
115
- const msg1 = encodeMessage(makeMessage({ id: 'first' }));
116
- const msg2 = encodeMessage(makeMessage({ id: 'second' }));
117
-
118
- // Feed first message + partial second message
119
- const combined = Buffer.concat([msg1, msg2.subarray(0, 6)]);
120
- const first = decoder.feed(combined);
121
- expect(first).toHaveLength(1);
122
- expect(first[0].id).toBe('first');
123
-
124
- // Feed rest of second message
125
- const second = decoder.feed(msg2.subarray(6));
126
- expect(second).toHaveLength(1);
127
- expect(second[0].id).toBe('second');
128
- });
129
-
130
- it('round-trips all IpcMessage fields', () => {
131
- const decoder = new MessageDecoder();
132
- const msg: IpcMessage = {
133
- id: 'rt-1',
134
- type: 'response',
135
- result: { status: 'ok', data: [1, 2, 3] },
136
- };
137
- const messages = decoder.feed(encodeMessage(msg));
138
- expect(messages).toHaveLength(1);
139
- expect(messages[0]).toEqual(msg);
140
- });
141
-
142
- it('round-trips error messages', () => {
143
- const decoder = new MessageDecoder();
144
- const msg: IpcMessage = {
145
- id: 'err-1',
146
- type: 'response',
147
- error: { code: -1, message: 'something went wrong' },
148
- };
149
- const messages = decoder.feed(encodeMessage(msg));
150
- expect(messages).toHaveLength(1);
151
- expect(messages[0]).toEqual(msg);
152
- });
153
- });
package/src/ipc/client.ts DELETED
@@ -1,110 +0,0 @@
1
- import net from 'node:net';
2
- import { randomUUID } from 'node:crypto';
3
- import type { IpcMessage } from '../types/ipc.types.js';
4
- import { encodeMessage, MessageDecoder } from './protocol.js';
5
- import { getPipeName } from '../utils/paths.js';
6
-
7
- interface PendingRequest {
8
- resolve: (result: unknown) => void;
9
- reject: (err: Error) => void;
10
- timer: ReturnType<typeof setTimeout>;
11
- }
12
-
13
- export class IpcClient {
14
- private socket: net.Socket | null = null;
15
- private decoder = new MessageDecoder();
16
- private pending = new Map<string, PendingRequest>();
17
-
18
- constructor(
19
- private pipeName: string = getPipeName(),
20
- private timeout: number = 5000,
21
- ) {}
22
-
23
- connect(): Promise<void> {
24
- return new Promise((resolve, reject) => {
25
- this.socket = net.createConnection(this.pipeName, () => {
26
- resolve();
27
- });
28
-
29
- this.socket.on('data', (chunk) => {
30
- const messages = this.decoder.feed(chunk);
31
- for (const msg of messages) {
32
- this.handleMessage(msg);
33
- }
34
- });
35
-
36
- this.socket.on('error', (err) => {
37
- reject(err);
38
- for (const [id, req] of this.pending) {
39
- clearTimeout(req.timer);
40
- req.reject(new Error(`Connection error: ${err.message}`));
41
- this.pending.delete(id);
42
- }
43
- });
44
-
45
- this.socket.on('close', () => {
46
- for (const [id, req] of this.pending) {
47
- clearTimeout(req.timer);
48
- req.reject(new Error('Connection closed'));
49
- this.pending.delete(id);
50
- }
51
- this.socket = null;
52
- });
53
- });
54
- }
55
-
56
- request(method: string, params?: unknown): Promise<unknown> {
57
- return new Promise((resolve, reject) => {
58
- if (!this.socket || this.socket.destroyed) {
59
- return reject(new Error('Not connected'));
60
- }
61
-
62
- const id = randomUUID();
63
- const timer = setTimeout(() => {
64
- this.pending.delete(id);
65
- reject(new Error(`Request timeout: ${method} (${this.timeout}ms)`));
66
- }, this.timeout);
67
-
68
- this.pending.set(id, { resolve, reject, timer });
69
-
70
- const msg: IpcMessage = {
71
- id,
72
- type: 'request',
73
- method,
74
- params,
75
- };
76
- this.socket.write(encodeMessage(msg));
77
- });
78
- }
79
-
80
- disconnect(): void {
81
- for (const [id, req] of this.pending) {
82
- clearTimeout(req.timer);
83
- req.reject(new Error('Client disconnecting'));
84
- this.pending.delete(id);
85
- }
86
- this.socket?.destroy();
87
- this.socket = null;
88
- this.decoder.reset();
89
- }
90
-
91
- get connected(): boolean {
92
- return this.socket !== null && !this.socket.destroyed;
93
- }
94
-
95
- private handleMessage(msg: IpcMessage): void {
96
- if (msg.type === 'response') {
97
- const req = this.pending.get(msg.id);
98
- if (!req) return;
99
-
100
- clearTimeout(req.timer);
101
- this.pending.delete(msg.id);
102
-
103
- if (msg.error) {
104
- req.reject(new Error(msg.error.message));
105
- } else {
106
- req.resolve(msg.result);
107
- }
108
- }
109
- }
110
- }
@@ -1,35 +0,0 @@
1
- import { Buffer } from 'node:buffer';
2
- import type { IpcMessage } from '../types/ipc.types.js';
3
-
4
- export function encodeMessage(msg: IpcMessage): Buffer {
5
- const json = JSON.stringify(msg);
6
- const payload = Buffer.from(json, 'utf8');
7
- const frame = Buffer.alloc(4 + payload.length);
8
- frame.writeUInt32BE(payload.length, 0);
9
- payload.copy(frame, 4);
10
- return frame;
11
- }
12
-
13
- export class MessageDecoder {
14
- private buffer = Buffer.alloc(0);
15
-
16
- feed(chunk: Buffer): IpcMessage[] {
17
- this.buffer = Buffer.concat([this.buffer, chunk]);
18
- const messages: IpcMessage[] = [];
19
-
20
- while (this.buffer.length >= 4) {
21
- const length = this.buffer.readUInt32BE(0);
22
- if (this.buffer.length < 4 + length) break;
23
-
24
- const json = this.buffer.subarray(4, 4 + length).toString('utf8');
25
- this.buffer = this.buffer.subarray(4 + length);
26
- messages.push(JSON.parse(json) as IpcMessage);
27
- }
28
-
29
- return messages;
30
- }
31
-
32
- reset(): void {
33
- this.buffer = Buffer.alloc(0);
34
- }
35
- }