@contractspec/lib.personalization 1.56.1 → 1.58.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 (58) hide show
  1. package/dist/adapter.d.ts +15 -19
  2. package/dist/adapter.d.ts.map +1 -1
  3. package/dist/adapter.js +43 -38
  4. package/dist/analyzer.d.ts +15 -19
  5. package/dist/analyzer.d.ts.map +1 -1
  6. package/dist/analyzer.js +69 -51
  7. package/dist/browser/adapter.js +46 -0
  8. package/dist/browser/analyzer.js +72 -0
  9. package/dist/browser/docs/behavior-tracking.docblock.js +97 -0
  10. package/dist/browser/docs/index.js +271 -0
  11. package/dist/browser/docs/overlay-engine.docblock.js +98 -0
  12. package/dist/browser/docs/workflow-composition.docblock.js +83 -0
  13. package/dist/browser/index.js +555 -0
  14. package/dist/browser/store.js +75 -0
  15. package/dist/browser/tracker.js +94 -0
  16. package/dist/browser/types.js +0 -0
  17. package/dist/docs/behavior-tracking.docblock.d.ts +2 -6
  18. package/dist/docs/behavior-tracking.docblock.d.ts.map +1 -1
  19. package/dist/docs/behavior-tracking.docblock.js +95 -15
  20. package/dist/docs/index.d.ts +4 -3
  21. package/dist/docs/index.d.ts.map +1 -0
  22. package/dist/docs/index.js +272 -3
  23. package/dist/docs/overlay-engine.docblock.d.ts +2 -6
  24. package/dist/docs/overlay-engine.docblock.d.ts.map +1 -1
  25. package/dist/docs/overlay-engine.docblock.js +96 -15
  26. package/dist/docs/workflow-composition.docblock.d.ts +2 -6
  27. package/dist/docs/workflow-composition.docblock.d.ts.map +1 -1
  28. package/dist/docs/workflow-composition.docblock.js +81 -15
  29. package/dist/index.d.ts +7 -7
  30. package/dist/index.d.ts.map +1 -0
  31. package/dist/index.js +555 -6
  32. package/dist/node/adapter.js +46 -0
  33. package/dist/node/analyzer.js +72 -0
  34. package/dist/node/docs/behavior-tracking.docblock.js +97 -0
  35. package/dist/node/docs/index.js +271 -0
  36. package/dist/node/docs/overlay-engine.docblock.js +98 -0
  37. package/dist/node/docs/workflow-composition.docblock.js +83 -0
  38. package/dist/node/index.js +555 -0
  39. package/dist/node/store.js +75 -0
  40. package/dist/node/tracker.js +94 -0
  41. package/dist/node/types.js +0 -0
  42. package/dist/store.d.ts +14 -18
  43. package/dist/store.d.ts.map +1 -1
  44. package/dist/store.js +74 -57
  45. package/dist/tracker.d.ts +42 -46
  46. package/dist/tracker.d.ts.map +1 -1
  47. package/dist/tracker.js +93 -91
  48. package/dist/types.d.ts +48 -51
  49. package/dist/types.d.ts.map +1 -1
  50. package/dist/types.js +1 -0
  51. package/package.json +104 -37
  52. package/dist/adapter.js.map +0 -1
  53. package/dist/analyzer.js.map +0 -1
  54. package/dist/docs/behavior-tracking.docblock.js.map +0 -1
  55. package/dist/docs/overlay-engine.docblock.js.map +0 -1
  56. package/dist/docs/workflow-composition.docblock.js.map +0 -1
  57. package/dist/store.js.map +0 -1
  58. package/dist/tracker.js.map +0 -1
@@ -0,0 +1,555 @@
1
+ // src/adapter.ts
2
+ function insightsToOverlaySuggestion(insights, options) {
3
+ const modifications = [];
4
+ insights.suggestedHiddenFields.forEach((field) => {
5
+ modifications.push({
6
+ type: "hideField",
7
+ field,
8
+ reason: "Automatically hidden because usage is near zero"
9
+ });
10
+ });
11
+ if (insights.frequentlyUsedFields.length) {
12
+ modifications.push({
13
+ type: "reorderFields",
14
+ fields: insights.frequentlyUsedFields
15
+ });
16
+ }
17
+ if (!modifications.length) {
18
+ return null;
19
+ }
20
+ return {
21
+ overlayId: options.overlayId,
22
+ version: options.version ?? "1.0.0",
23
+ appliesTo: {
24
+ tenantId: options.tenantId,
25
+ capability: options.capability,
26
+ userId: options.userId,
27
+ role: options.role
28
+ },
29
+ modifications,
30
+ metadata: {
31
+ generatedAt: new Date().toISOString(),
32
+ automated: true
33
+ }
34
+ };
35
+ }
36
+ function insightsToWorkflowAdaptations(insights) {
37
+ return insights.workflowBottlenecks.map((bottleneck) => ({
38
+ workflow: bottleneck.workflow,
39
+ step: bottleneck.step,
40
+ note: `High drop rate (${Math.round(bottleneck.dropRate * 100)}%) detected`
41
+ }));
42
+ }
43
+
44
+ // src/analyzer.ts
45
+ var DEFAULT_THRESHOLD = 3;
46
+
47
+ class BehaviorAnalyzer {
48
+ store;
49
+ options;
50
+ constructor(store, options = {}) {
51
+ this.store = store;
52
+ this.options = options;
53
+ }
54
+ async analyze(params) {
55
+ const query = {
56
+ tenantId: params.tenantId,
57
+ userId: params.userId,
58
+ role: params.role
59
+ };
60
+ if (params.windowMs) {
61
+ query.since = Date.now() - params.windowMs;
62
+ }
63
+ const summary = await this.store.summarize(query);
64
+ return buildInsights(summary, this.options);
65
+ }
66
+ }
67
+ function buildInsights(summary, options) {
68
+ const threshold = options.fieldInactivityThreshold ?? DEFAULT_THRESHOLD;
69
+ const minSamples = options.minSamples ?? 10;
70
+ const ignoredFields = [];
71
+ const frequentlyUsedFields = [];
72
+ for (const [field, count] of Object.entries(summary.fieldCounts)) {
73
+ if (count <= threshold) {
74
+ ignoredFields.push(field);
75
+ }
76
+ if (count >= threshold * 4) {
77
+ frequentlyUsedFields.push(field);
78
+ }
79
+ }
80
+ const workflowBottlenecks = Object.entries(summary.workflowStepCounts).flatMap(([workflow, steps]) => {
81
+ const total = Object.values(steps).reduce((acc, value) => acc + value, 0);
82
+ if (!total || total < minSamples) {
83
+ return [];
84
+ }
85
+ return Object.entries(steps).filter(([, count]) => count / total < 0.4).map(([step, count]) => ({
86
+ workflow,
87
+ step,
88
+ dropRate: 1 - count / total
89
+ }));
90
+ });
91
+ const layoutPreference = detectLayout(summary);
92
+ return {
93
+ unusedFields: ignoredFields,
94
+ suggestedHiddenFields: ignoredFields.slice(0, 5),
95
+ frequentlyUsedFields: frequentlyUsedFields.slice(0, 10),
96
+ workflowBottlenecks,
97
+ layoutPreference
98
+ };
99
+ }
100
+ function detectLayout(summary) {
101
+ const fieldCount = Object.keys(summary.fieldCounts).length;
102
+ if (!fieldCount) {
103
+ return;
104
+ }
105
+ if (fieldCount >= 15) {
106
+ return "table";
107
+ }
108
+ if (fieldCount >= 8) {
109
+ return "grid";
110
+ }
111
+ return "form";
112
+ }
113
+
114
+ // src/docs/behavior-tracking.docblock.ts
115
+ import { registerDocBlocks } from "@contractspec/lib.contracts/docs";
116
+ var personalization_behavior_tracking_DocBlocks = [
117
+ {
118
+ id: "docs.personalization.behavior-tracking",
119
+ title: "Behavior Tracking",
120
+ summary: "`@contractspec/lib.personalization` provides primitives to observe how tenants/users interact with specs and turn that telemetry into personalization insights.",
121
+ kind: "reference",
122
+ visibility: "public",
123
+ route: "/docs/personalization/behavior-tracking",
124
+ tags: ["personalization", "behavior-tracking"],
125
+ body: `# Behavior Tracking
126
+
127
+ \`@contractspec/lib.personalization\` provides primitives to observe how tenants/users interact with specs and turn that telemetry into personalization insights.
128
+
129
+ ## Tracker
130
+
131
+ \`\`\`ts
132
+ import { createBehaviorTracker } from '@contractspec/lib.personalization';
133
+ import { InMemoryBehaviorStore } from '@contractspec/lib.personalization/store';
134
+
135
+ const tracker = createBehaviorTracker({
136
+ store: new InMemoryBehaviorStore(),
137
+ context: { tenantId: ctx.tenant.id, userId: ctx.identity.userId },
138
+ autoFlushIntervalMs: 5000,
139
+ });
140
+
141
+ tracker.trackFieldAccess({ operation: 'billing.createOrder', field: 'internalNotes' });
142
+ tracker.trackFeatureUsage({ feature: 'workflow-editor', action: 'opened' });
143
+ tracker.trackWorkflowStep({ workflow: 'invoice-approval', step: 'review', status: 'entered' });
144
+ \`\`\`
145
+
146
+ All events are buffered and flushed either when the buffer hits 25 entries or when \`autoFlushIntervalMs\` elapses. Tracked metrics flow to OpenTelemetry via the meter/counter built into the tracker.
147
+
148
+ ## Analyzer
149
+
150
+ \`\`\`ts
151
+ import { BehaviorAnalyzer } from '@contractspec/lib.personalization/analyzer';
152
+
153
+ const analyzer = new BehaviorAnalyzer(store, { fieldInactivityThreshold: 2 });
154
+ const insights = await analyzer.analyze({ tenantId: 'acme', userId: 'manager-42', windowMs: 7 * 24 * 60 * 60 * 1000 });
155
+
156
+ /*
157
+ {
158
+ unusedFields: ['internalNotes'],
159
+ suggestedHiddenFields: ['internalNotes'],
160
+ frequentlyUsedFields: ['customerReference', 'items'],
161
+ workflowBottlenecks: [{ workflow: 'invoice-approval', step: 'finance-review', dropRate: 0.6 }],
162
+ layoutPreference: 'table'
163
+ }
164
+ */
165
+ \`\`\`
166
+
167
+ Use the analyzer output with the overlay adapter to generate suggestions automatically.
168
+
169
+ ## Adapter
170
+
171
+ \`\`\`ts
172
+ import { insightsToOverlaySuggestion } from '@contractspec/lib.personalization/adapter';
173
+
174
+ const overlay = insightsToOverlaySuggestion(insights, {
175
+ overlayId: 'acme-order-form',
176
+ tenantId: 'acme',
177
+ capability: 'billing.createOrder',
178
+ });
179
+ \`\`\`
180
+
181
+ When the adapter returns an overlay spec, pass it to the overlay engine to register or sign it.
182
+
183
+
184
+
185
+
186
+
187
+
188
+
189
+
190
+
191
+
192
+
193
+
194
+
195
+
196
+
197
+
198
+
199
+
200
+
201
+
202
+
203
+
204
+ `
205
+ }
206
+ ];
207
+ registerDocBlocks(personalization_behavior_tracking_DocBlocks);
208
+
209
+ // src/docs/overlay-engine.docblock.ts
210
+ import { registerDocBlocks as registerDocBlocks2 } from "@contractspec/lib.contracts/docs";
211
+ var personalization_overlay_engine_DocBlocks = [
212
+ {
213
+ id: "docs.personalization.overlay-engine",
214
+ title: "Overlay Engine",
215
+ summary: "`@contractspec/lib.overlay-engine` is the canonical runtime for OverlaySpecs. It validates specs, tracks scope precedence, and exposes hooks for React renderers.",
216
+ kind: "reference",
217
+ visibility: "public",
218
+ route: "/docs/personalization/overlay-engine",
219
+ tags: ["personalization", "overlay-engine"],
220
+ body: `# Overlay Engine
221
+
222
+ \`@contractspec/lib.overlay-engine\` is the canonical runtime for OverlaySpecs. It validates specs, tracks scope precedence, and exposes hooks for React renderers.
223
+
224
+ ## Key APIs
225
+
226
+ - \`defineOverlay(spec)\` – helper to keep specs typed.
227
+ - \`OverlayRegistry\` – register signed overlays and retrieve them per context.
228
+ - \`OverlayEngine\` – apply overlays to renderable targets, emit audit events, and merge modifications deterministically.
229
+ - \`signOverlay(spec, privateKey)\` – Ed25519/RSA-PSS signer.
230
+ - \`verifyOverlaySignature(overlay)\` – verify public key signatures.
231
+ - \`useOverlay(engine, params)\` – client hook that returns \`{ target, overlaysApplied }\`.
232
+
233
+ ## Scope Precedence
234
+
235
+ Registrations are sorted by specificity:
236
+
237
+ 1. Tenant overlays
238
+ 2. Role overlays
239
+ 3. User overlays
240
+ 4. Device overlays
241
+
242
+ Less specific overlays run first; more specific overlays override later.
243
+
244
+ ## Example
245
+
246
+ \`\`\`ts
247
+ const registry = new OverlayRegistry();
248
+ const engine = new OverlayEngine({
249
+ registry,
250
+ audit: (event) => auditLogService.record(event),
251
+ });
252
+
253
+ const overlay = defineOverlay({
254
+ overlayId: 'acme-order-form',
255
+ version: '1.0.0',
256
+ appliesTo: {
257
+ capability: 'billing.createOrder',
258
+ tenantId: 'acme',
259
+ },
260
+ modifications: [
261
+ { type: 'hideField', field: 'internalNotes' },
262
+ { type: 'renameLabel', field: 'customerReference', newLabel: 'PO Number' },
263
+ ],
264
+ });
265
+
266
+ const signedOverlay = await signOverlay(overlay, privateKeyPem);
267
+ registry.register(signedOverlay);
268
+
269
+ const result = engine.apply({
270
+ target: { fields: baseFields },
271
+ capability: 'billing.createOrder',
272
+ tenantId: 'acme',
273
+ userId: 'manager-7',
274
+ });
275
+ \`\`\`
276
+
277
+ \`result.target.fields\` now carries the hidden and renamed outputs ready for rendering.
278
+
279
+
280
+
281
+
282
+
283
+
284
+
285
+
286
+
287
+
288
+
289
+
290
+
291
+
292
+
293
+
294
+
295
+
296
+
297
+
298
+
299
+
300
+ `
301
+ }
302
+ ];
303
+ registerDocBlocks2(personalization_overlay_engine_DocBlocks);
304
+
305
+ // src/docs/workflow-composition.docblock.ts
306
+ import { registerDocBlocks as registerDocBlocks3 } from "@contractspec/lib.contracts/docs";
307
+ var personalization_workflow_composition_DocBlocks = [
308
+ {
309
+ id: "docs.personalization.workflow-composition",
310
+ title: "Workflow Composition",
311
+ summary: "`@contractspec/lib.workflow-composer` composes base WorkflowSpecs with tenant/role/device-specific extensions.",
312
+ kind: "reference",
313
+ visibility: "public",
314
+ route: "/docs/personalization/workflow-composition",
315
+ tags: ["personalization", "workflow-composition"],
316
+ body: `# Workflow Composition
317
+
318
+ \`@contractspec/lib.workflow-composer\` composes base WorkflowSpecs with tenant/role/device-specific extensions.
319
+
320
+ ## Extensions
321
+
322
+ \`\`\`ts
323
+ import { WorkflowComposer } from '@contractspec/lib.workflow-composer';
324
+ import { approvalStepTemplate } from '@contractspec/lib.workflow-composer/templates';
325
+
326
+ const composer = new WorkflowComposer();
327
+
328
+ composer.register({
329
+ workflow: 'billing.invoiceApproval',
330
+ tenantId: 'acme',
331
+ priority: 10,
332
+ customSteps: [
333
+ {
334
+ after: 'validate-invoice',
335
+ inject: approvalStepTemplate({
336
+ id: 'acme-legal-review',
337
+ label: 'Legal Review (ACME)',
338
+ description: 'Tenant-specific compliance step.',
339
+ }),
340
+ transitionTo: 'final-approval',
341
+ },
342
+ ],
343
+ hiddenSteps: ['internal-audit'],
344
+ });
345
+ \`\`\`
346
+
347
+ ## Compose
348
+
349
+ \`\`\`ts
350
+ const runtimeSpec = composer.compose({
351
+ base: BaseInvoiceWorkflow,
352
+ tenantId: 'acme',
353
+ });
354
+
355
+ workflowRunner.execute(runtimeSpec, ctx);
356
+ \`\`\`
357
+
358
+ The composer uses anchor references (\`after\`/\`before\`) to place injected steps and cleans up transitions when steps are hidden.
359
+
360
+
361
+
362
+
363
+
364
+
365
+
366
+
367
+
368
+
369
+
370
+
371
+
372
+
373
+
374
+
375
+
376
+
377
+
378
+
379
+
380
+
381
+ `
382
+ }
383
+ ];
384
+ registerDocBlocks3(personalization_workflow_composition_DocBlocks);
385
+ // src/store.ts
386
+ class InMemoryBehaviorStore {
387
+ events = [];
388
+ async record(event) {
389
+ this.events.push(event);
390
+ }
391
+ async bulkRecord(events) {
392
+ this.events.push(...events);
393
+ }
394
+ async query(query) {
395
+ return filterEvents(this.events, query);
396
+ }
397
+ async summarize(query) {
398
+ const events = await this.query(query);
399
+ const summary = {
400
+ fieldCounts: {},
401
+ featureCounts: {},
402
+ workflowStepCounts: {},
403
+ totalEvents: events.length
404
+ };
405
+ events.forEach((event) => {
406
+ switch (event.type) {
407
+ case "field_access":
408
+ summary.fieldCounts[event.field] = (summary.fieldCounts[event.field] ?? 0) + 1;
409
+ break;
410
+ case "feature_usage":
411
+ summary.featureCounts[event.feature] = (summary.featureCounts[event.feature] ?? 0) + 1;
412
+ break;
413
+ case "workflow_step": {
414
+ const workflow = summary.workflowStepCounts[event.workflow] ??= {};
415
+ workflow[event.step] = (workflow[event.step] ?? 0) + 1;
416
+ break;
417
+ }
418
+ default:
419
+ break;
420
+ }
421
+ });
422
+ return summary;
423
+ }
424
+ async clear() {
425
+ this.events = [];
426
+ }
427
+ }
428
+ function filterEvents(events, query) {
429
+ return events.filter((event) => {
430
+ if (query.tenantId && event.tenantId !== query.tenantId) {
431
+ return false;
432
+ }
433
+ if (query.userId && event.userId !== query.userId) {
434
+ return false;
435
+ }
436
+ if (query.role && event.role !== query.role) {
437
+ return false;
438
+ }
439
+ if (query.since && event.timestamp < query.since) {
440
+ return false;
441
+ }
442
+ if (query.until && event.timestamp > query.until) {
443
+ return false;
444
+ }
445
+ if (query.operation && event.type === "field_access" && event.operation !== query.operation) {
446
+ return false;
447
+ }
448
+ if (query.feature && event.type === "feature_usage" && event.feature !== query.feature) {
449
+ return false;
450
+ }
451
+ if (query.workflow && event.type === "workflow_step" && event.workflow !== query.workflow) {
452
+ return false;
453
+ }
454
+ return true;
455
+ });
456
+ }
457
+
458
+ // src/tracker.ts
459
+ import { trace, metrics } from "@opentelemetry/api";
460
+ var DEFAULT_BUFFER_SIZE = 25;
461
+
462
+ class BehaviorTracker {
463
+ store;
464
+ context;
465
+ tracer = trace.getTracer("lssm.personalization", "1.0.0");
466
+ counter = metrics.getMeter("lssm.personalization", "1.0.0").createCounter("lssm.personalization.events", {
467
+ description: "Behavior events tracked for personalization"
468
+ });
469
+ buffer = [];
470
+ bufferSize;
471
+ flushTimer;
472
+ constructor(options) {
473
+ this.store = options.store;
474
+ this.context = options.context;
475
+ this.bufferSize = options.bufferSize ?? DEFAULT_BUFFER_SIZE;
476
+ if (options.autoFlushIntervalMs) {
477
+ this.flushTimer = setInterval(() => {
478
+ this.flush();
479
+ }, options.autoFlushIntervalMs);
480
+ }
481
+ }
482
+ trackFieldAccess(input) {
483
+ const event = {
484
+ type: "field_access",
485
+ operation: input.operation,
486
+ field: input.field,
487
+ timestamp: Date.now(),
488
+ ...this.context,
489
+ metadata: { ...this.context.metadata, ...input.metadata }
490
+ };
491
+ this.enqueue(event);
492
+ }
493
+ trackFeatureUsage(input) {
494
+ const event = {
495
+ type: "feature_usage",
496
+ feature: input.feature,
497
+ action: input.action,
498
+ timestamp: Date.now(),
499
+ ...this.context,
500
+ metadata: { ...this.context.metadata, ...input.metadata }
501
+ };
502
+ this.enqueue(event);
503
+ }
504
+ trackWorkflowStep(input) {
505
+ const event = {
506
+ type: "workflow_step",
507
+ workflow: input.workflow,
508
+ step: input.step,
509
+ status: input.status,
510
+ timestamp: Date.now(),
511
+ ...this.context,
512
+ metadata: { ...this.context.metadata, ...input.metadata }
513
+ };
514
+ this.enqueue(event);
515
+ }
516
+ async flush() {
517
+ if (!this.buffer.length)
518
+ return;
519
+ const events = this.buffer;
520
+ this.buffer = [];
521
+ await this.store.bulkRecord(events);
522
+ }
523
+ async dispose() {
524
+ if (this.flushTimer) {
525
+ clearInterval(this.flushTimer);
526
+ }
527
+ await this.flush();
528
+ }
529
+ enqueue(event) {
530
+ this.buffer.push(event);
531
+ this.counter.add(1, {
532
+ tenantId: this.context.tenantId,
533
+ type: event.type
534
+ });
535
+ this.tracer.startActiveSpan(`personalization.${event.type}`, (span) => {
536
+ span.setAttribute("tenant.id", this.context.tenantId);
537
+ if (this.context.userId)
538
+ span.setAttribute("user.id", this.context.userId);
539
+ span.setAttribute("personalization.event_type", event.type);
540
+ span.end();
541
+ });
542
+ if (this.buffer.length >= this.bufferSize) {
543
+ this.flush();
544
+ }
545
+ }
546
+ }
547
+ var createBehaviorTracker = (options) => new BehaviorTracker(options);
548
+ export {
549
+ insightsToWorkflowAdaptations,
550
+ insightsToOverlaySuggestion,
551
+ createBehaviorTracker,
552
+ InMemoryBehaviorStore,
553
+ BehaviorTracker,
554
+ BehaviorAnalyzer
555
+ };
@@ -0,0 +1,75 @@
1
+ // src/store.ts
2
+ class InMemoryBehaviorStore {
3
+ events = [];
4
+ async record(event) {
5
+ this.events.push(event);
6
+ }
7
+ async bulkRecord(events) {
8
+ this.events.push(...events);
9
+ }
10
+ async query(query) {
11
+ return filterEvents(this.events, query);
12
+ }
13
+ async summarize(query) {
14
+ const events = await this.query(query);
15
+ const summary = {
16
+ fieldCounts: {},
17
+ featureCounts: {},
18
+ workflowStepCounts: {},
19
+ totalEvents: events.length
20
+ };
21
+ events.forEach((event) => {
22
+ switch (event.type) {
23
+ case "field_access":
24
+ summary.fieldCounts[event.field] = (summary.fieldCounts[event.field] ?? 0) + 1;
25
+ break;
26
+ case "feature_usage":
27
+ summary.featureCounts[event.feature] = (summary.featureCounts[event.feature] ?? 0) + 1;
28
+ break;
29
+ case "workflow_step": {
30
+ const workflow = summary.workflowStepCounts[event.workflow] ??= {};
31
+ workflow[event.step] = (workflow[event.step] ?? 0) + 1;
32
+ break;
33
+ }
34
+ default:
35
+ break;
36
+ }
37
+ });
38
+ return summary;
39
+ }
40
+ async clear() {
41
+ this.events = [];
42
+ }
43
+ }
44
+ function filterEvents(events, query) {
45
+ return events.filter((event) => {
46
+ if (query.tenantId && event.tenantId !== query.tenantId) {
47
+ return false;
48
+ }
49
+ if (query.userId && event.userId !== query.userId) {
50
+ return false;
51
+ }
52
+ if (query.role && event.role !== query.role) {
53
+ return false;
54
+ }
55
+ if (query.since && event.timestamp < query.since) {
56
+ return false;
57
+ }
58
+ if (query.until && event.timestamp > query.until) {
59
+ return false;
60
+ }
61
+ if (query.operation && event.type === "field_access" && event.operation !== query.operation) {
62
+ return false;
63
+ }
64
+ if (query.feature && event.type === "feature_usage" && event.feature !== query.feature) {
65
+ return false;
66
+ }
67
+ if (query.workflow && event.type === "workflow_step" && event.workflow !== query.workflow) {
68
+ return false;
69
+ }
70
+ return true;
71
+ });
72
+ }
73
+ export {
74
+ InMemoryBehaviorStore
75
+ };
@@ -0,0 +1,94 @@
1
+ // src/tracker.ts
2
+ import { trace, metrics } from "@opentelemetry/api";
3
+ var DEFAULT_BUFFER_SIZE = 25;
4
+
5
+ class BehaviorTracker {
6
+ store;
7
+ context;
8
+ tracer = trace.getTracer("lssm.personalization", "1.0.0");
9
+ counter = metrics.getMeter("lssm.personalization", "1.0.0").createCounter("lssm.personalization.events", {
10
+ description: "Behavior events tracked for personalization"
11
+ });
12
+ buffer = [];
13
+ bufferSize;
14
+ flushTimer;
15
+ constructor(options) {
16
+ this.store = options.store;
17
+ this.context = options.context;
18
+ this.bufferSize = options.bufferSize ?? DEFAULT_BUFFER_SIZE;
19
+ if (options.autoFlushIntervalMs) {
20
+ this.flushTimer = setInterval(() => {
21
+ this.flush();
22
+ }, options.autoFlushIntervalMs);
23
+ }
24
+ }
25
+ trackFieldAccess(input) {
26
+ const event = {
27
+ type: "field_access",
28
+ operation: input.operation,
29
+ field: input.field,
30
+ timestamp: Date.now(),
31
+ ...this.context,
32
+ metadata: { ...this.context.metadata, ...input.metadata }
33
+ };
34
+ this.enqueue(event);
35
+ }
36
+ trackFeatureUsage(input) {
37
+ const event = {
38
+ type: "feature_usage",
39
+ feature: input.feature,
40
+ action: input.action,
41
+ timestamp: Date.now(),
42
+ ...this.context,
43
+ metadata: { ...this.context.metadata, ...input.metadata }
44
+ };
45
+ this.enqueue(event);
46
+ }
47
+ trackWorkflowStep(input) {
48
+ const event = {
49
+ type: "workflow_step",
50
+ workflow: input.workflow,
51
+ step: input.step,
52
+ status: input.status,
53
+ timestamp: Date.now(),
54
+ ...this.context,
55
+ metadata: { ...this.context.metadata, ...input.metadata }
56
+ };
57
+ this.enqueue(event);
58
+ }
59
+ async flush() {
60
+ if (!this.buffer.length)
61
+ return;
62
+ const events = this.buffer;
63
+ this.buffer = [];
64
+ await this.store.bulkRecord(events);
65
+ }
66
+ async dispose() {
67
+ if (this.flushTimer) {
68
+ clearInterval(this.flushTimer);
69
+ }
70
+ await this.flush();
71
+ }
72
+ enqueue(event) {
73
+ this.buffer.push(event);
74
+ this.counter.add(1, {
75
+ tenantId: this.context.tenantId,
76
+ type: event.type
77
+ });
78
+ this.tracer.startActiveSpan(`personalization.${event.type}`, (span) => {
79
+ span.setAttribute("tenant.id", this.context.tenantId);
80
+ if (this.context.userId)
81
+ span.setAttribute("user.id", this.context.userId);
82
+ span.setAttribute("personalization.event_type", event.type);
83
+ span.end();
84
+ });
85
+ if (this.buffer.length >= this.bufferSize) {
86
+ this.flush();
87
+ }
88
+ }
89
+ }
90
+ var createBehaviorTracker = (options) => new BehaviorTracker(options);
91
+ export {
92
+ createBehaviorTracker,
93
+ BehaviorTracker
94
+ };