briefcase-wasm 2.4.1

WebAssembly bindings for Briefcase AI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
/**
 * Tests for WebAssembly bindings - core data models
 * These tests are designed to run in a browser environment with the WASM module loaded
 */

import { describe, it, expect, beforeAll } from '@jest/globals';

// Mock WASM module - in real tests, this would be the compiled WASM module
const mockWasm = {
    WasmInput: class {
        constructor(name, value, dataType) {
            this._name = name;
            this._value = value;
            this._dataType = dataType;
        }
        get name() { return this._name; }
        get value() { return this._value; }
        get data_type() { return this._dataType; }
        toObject() {
            return {
                name: this._name,
                value: this._value,
                data_type: this._dataType
            };
        }
    },
    WasmOutput: class {
        constructor(name, value, dataType) {
            this._name = name;
            this._value = value;
            this._dataType = dataType;
            this._confidence = null;
        }
        get name() { return this._name; }
        get value() { return this._value; }
        get data_type() { return this._dataType; }
        get confidence() { return this._confidence; }
        withConfidence(conf) { this._confidence = conf; }
        toObject() {
            const obj = {
                name: this._name,
                value: this._value,
                data_type: this._dataType
            };
            if (this._confidence !== null) {
                obj.confidence = this._confidence;
            }
            return obj;
        }
    },
    WasmModelParameters: class {
        constructor(modelName) {
            this._modelName = modelName;
            this._provider = null;
            this._parameters = {};
        }
        get model_name() { return this._modelName; }
        get provider() { return this._provider; }
        get parameters() { return this._parameters; }
        withProvider(provider) { this._provider = provider; }
        withParameter(key, value) { this._parameters[key] = value; }
    },
    WasmDecisionSnapshot: class {
        constructor(functionName) {
            this._functionName = functionName;
            this._moduleName = null;
            this._executionTimeMs = null;
            this._inputs = [];
            this._outputs = [];
            this._modelParameters = null;
            this._tags = {};
        }
        get function_name() { return this._functionName; }
        get module_name() { return this._moduleName; }
        get execution_time_ms() { return this._executionTimeMs; }
        get tags() { return this._tags; }
        withModule(name) { this._moduleName = name; }
        addInput(input) { this._inputs.push(input); }
        addOutput(output) { this._outputs.push(output); }
        withModelParameters(params) { this._modelParameters = params; }
        withExecutionTime(time) { this._executionTimeMs = time; }
        addTag(key, value) { this._tags[key] = value; }
        toObject() {
            return {
                function_name: this._functionName,
                module_name: this._moduleName,
                execution_time_ms: this._executionTimeMs,
                inputs: this._inputs.map(i => i.toObject()),
                outputs: this._outputs.map(o => o.toObject()),
                model_parameters: this._modelParameters,
                tags: this._tags
            };
        }
    },
    WasmSnapshot: class {
        constructor(snapshotType) {
            if (!['session', 'decision', 'batch'].includes(snapshotType)) {
                throw new Error(`Invalid snapshot type: ${snapshotType}`);
            }
            this._snapshotType = snapshotType;
            this._decisions = [];
        }
        get snapshot_type() { return this._snapshotType; }
        get decision_count() { return this._decisions.length; }
        addDecision(decision) { this._decisions.push(decision); }
        toObject() {
            return {
                snapshot_type: this._snapshotType,
                decisions: this._decisions.map(d => d.toObject())
            };
        }
    }
};

describe('WASM Input', () => {
    it('should create input with basic data', () => {
        const input = new mockWasm.WasmInput('test_input', 'hello world', 'string');

        expect(input.name).toBe('test_input');
        expect(input.value).toBe('hello world');
        expect(input.data_type).toBe('string');
    });

    it('should create input with JSON data', () => {
        const jsonData = { key: 'value', number: 42 };
        const input = new mockWasm.WasmInput('json_input', jsonData, 'object');

        expect(input.name).toBe('json_input');
        expect(input.value).toEqual(jsonData);
        expect(input.data_type).toBe('object');
    });

    it('should serialize to object correctly', () => {
        const input = new mockWasm.WasmInput('test', 'value', 'string');
        const obj = input.toObject();

        expect(obj).toEqual({
            name: 'test',
            value: 'value',
            data_type: 'string'
        });
    });

    it('should handle complex nested data', () => {
        const complexData = {
            metadata: {
                timestamp: Date.now(),
                source: 'api'
            },
            data: {
                features: [1, 2, 3, 4, 5],
                labels: ['a', 'b', 'c']
            }
        };

        const input = new mockWasm.WasmInput('complex', complexData, 'object');
        expect(input.value.data.features).toEqual([1, 2, 3, 4, 5]);
    });
});

describe('WASM Output', () => {
    it('should create output with basic data', () => {
        const output = new mockWasm.WasmOutput('test_output', 'result', 'string');

        expect(output.name).toBe('test_output');
        expect(output.value).toBe('result');
        expect(output.data_type).toBe('string');
        expect(output.confidence).toBeNull();
    });

    it('should set confidence score', () => {
        const output = new mockWasm.WasmOutput('test', 'result', 'string');
        output.withConfidence(0.95);

        expect(output.confidence).toBe(0.95);
    });

    it('should serialize with confidence', () => {
        const output = new mockWasm.WasmOutput('test', 'result', 'string');
        output.withConfidence(0.85);

        const obj = output.toObject();
        expect(obj).toEqual({
            name: 'test',
            value: 'result',
            data_type: 'string',
            confidence: 0.85
        });
    });

    it('should handle array outputs', () => {
        const arrayData = ['item1', 'item2', 'item3'];
        const output = new mockWasm.WasmOutput('list', arrayData, 'array');

        expect(output.value).toEqual(arrayData);
        expect(output.data_type).toBe('array');
    });
});

describe('WASM ModelParameters', () => {
    it('should create model parameters', () => {
        const params = new mockWasm.WasmModelParameters('gpt-4');

        expect(params.model_name).toBe('gpt-4');
        expect(params.provider).toBeNull();
    });

    it('should set provider', () => {
        const params = new mockWasm.WasmModelParameters('claude-3');
        params.withProvider('anthropic');

        expect(params.provider).toBe('anthropic');
    });

    it('should add parameters', () => {
        const params = new mockWasm.WasmModelParameters('gpt-4');
        params.withParameter('temperature', 0.7);
        params.withParameter('max_tokens', 1000);

        expect(params.parameters.temperature).toBe(0.7);
        expect(params.parameters.max_tokens).toBe(1000);
    });

    it('should handle complex parameter types', () => {
        const params = new mockWasm.WasmModelParameters('custom-model');
        params.withParameter('stop_sequences', ['Human:', 'AI:']);
        params.withParameter('logit_bias', { '1234': -100, '5678': 50 });

        expect(params.parameters.stop_sequences).toEqual(['Human:', 'AI:']);
        expect(params.parameters.logit_bias).toEqual({ '1234': -100, '5678': 50 });
    });
});

describe('WASM DecisionSnapshot', () => {
    it('should create decision snapshot', () => {
        const snapshot = new mockWasm.WasmDecisionSnapshot('my_function');

        expect(snapshot.function_name).toBe('my_function');
        expect(snapshot.module_name).toBeNull();
        expect(snapshot.execution_time_ms).toBeNull();
    });

    it('should set module name', () => {
        const snapshot = new mockWasm.WasmDecisionSnapshot('my_function');
        snapshot.withModule('my_module');

        expect(snapshot.module_name).toBe('my_module');
    });

    it('should add inputs and outputs', () => {
        const snapshot = new mockWasm.WasmDecisionSnapshot('classify');

        const input = new mockWasm.WasmInput('text', 'hello', 'string');
        const output = new mockWasm.WasmOutput('label', 'greeting', 'string');

        snapshot.addInput(input);
        snapshot.addOutput(output);

        const obj = snapshot.toObject();
        expect(obj.function_name).toBe('classify');
        expect(obj.inputs).toHaveLength(1);
        expect(obj.outputs).toHaveLength(1);
    });

    it('should set model parameters', () => {
        const snapshot = new mockWasm.WasmDecisionSnapshot('generate');
        const params = new mockWasm.WasmModelParameters('gpt-4');
        params.withParameter('temperature', 0.5);

        snapshot.withModelParameters(params);

        const obj = snapshot.toObject();
        expect(obj.model_parameters).toBeDefined();
    });

    it('should set execution time', () => {
        const snapshot = new mockWasm.WasmDecisionSnapshot('my_function');
        snapshot.withExecutionTime(123.45);

        expect(snapshot.execution_time_ms).toBe(123.45);
    });

    it('should add tags', () => {
        const snapshot = new mockWasm.WasmDecisionSnapshot('my_function');
        snapshot.addTag('environment', 'production');
        snapshot.addTag('version', '1.0.0');

        expect(snapshot.tags.environment).toBe('production');
        expect(snapshot.tags.version).toBe('1.0.0');
    });

    it('should handle multiple inputs and outputs', () => {
        const snapshot = new mockWasm.WasmDecisionSnapshot('multi_io_function');

        // Add multiple inputs
        for (let i = 0; i < 3; i++) {
            const input = new mockWasm.WasmInput(`input_${i}`, `value_${i}`, 'string');
            snapshot.addInput(input);
        }

        // Add multiple outputs
        for (let i = 0; i < 2; i++) {
            const output = new mockWasm.WasmOutput(`output_${i}`, `result_${i}`, 'string');
            output.withConfidence(0.8 + i * 0.1);
            snapshot.addOutput(output);
        }

        const obj = snapshot.toObject();
        expect(obj.inputs).toHaveLength(3);
        expect(obj.outputs).toHaveLength(2);
        expect(obj.outputs[1].confidence).toBe(0.9);
    });
});

describe('WASM Snapshot', () => {
    it('should create snapshot with valid type', () => {
        const snapshot = new mockWasm.WasmSnapshot('session');

        expect(snapshot.snapshot_type).toBe('session');
        expect(snapshot.decision_count).toBe(0);
    });

    it('should throw error for invalid type', () => {
        expect(() => {
            new mockWasm.WasmSnapshot('invalid_type');
        }).toThrow();
    });

    it('should add decisions', () => {
        const snapshot = new mockWasm.WasmSnapshot('batch');
        const decision = new mockWasm.WasmDecisionSnapshot('test_func');

        snapshot.addDecision(decision);

        expect(snapshot.decision_count).toBe(1);
    });

    it('should handle multiple decisions', () => {
        const snapshot = new mockWasm.WasmSnapshot('batch');

        for (let i = 0; i < 5; i++) {
            const decision = new mockWasm.WasmDecisionSnapshot(`func_${i}`);
            snapshot.addDecision(decision);
        }

        expect(snapshot.decision_count).toBe(5);
    });

    it('should serialize properly', () => {
        const snapshot = new mockWasm.WasmSnapshot('decision');
        const decision = new mockWasm.WasmDecisionSnapshot('test_func');

        snapshot.addDecision(decision);

        const obj = snapshot.toObject();
        expect(obj.snapshot_type).toBe('decision');
        expect(obj.decisions).toHaveLength(1);
        expect(obj.decisions[0].function_name).toBe('test_func');
    });
});

describe('WASM Integration Tests', () => {
    it('should handle complete AI workflow', () => {
        // Create decision snapshot
        const decision = new mockWasm.WasmDecisionSnapshot('text_classification');
        decision.withModule('nlp_service');

        // Add input
        const inputText = new mockWasm.WasmInput('text', 'This is a great product!', 'string');
        decision.addInput(inputText);

        // Add model parameters
        const params = new mockWasm.WasmModelParameters('bert-base-uncased');
        params.withProvider('huggingface');
        params.withParameter('max_length', 512);
        decision.withModelParameters(params);

        // Add output
        const outputLabel = new mockWasm.WasmOutput('sentiment', 'positive', 'string');
        outputLabel.withConfidence(0.92);
        decision.addOutput(outputLabel);

        // Set execution time and tags
        decision.withExecutionTime(45.2);
        decision.addTag('model_version', 'v2.1');
        decision.addTag('environment', 'staging');

        // Create session snapshot
        const session = new mockWasm.WasmSnapshot('session');
        session.addDecision(decision);

        // Verify everything
        expect(session.decision_count).toBe(1);
        expect(decision.function_name).toBe('text_classification');
        expect(decision.module_name).toBe('nlp_service');
        expect(decision.execution_time_ms).toBe(45.2);

        // Test serialization
        const sessionObj = session.toObject();
        expect(sessionObj.decisions).toHaveLength(1);

        const decisionObj = decision.toObject();
        expect(decisionObj.inputs).toHaveLength(1);
        expect(decisionObj.outputs).toHaveLength(1);
        expect(decisionObj.model_parameters).toBeDefined();
        expect(decisionObj.tags.model_version).toBe('v2.1');
    });

    it('should handle browser-specific data types', () => {
        // Test with File-like objects
        const fileInput = new mockWasm.WasmInput('file', new Blob(['content']), 'file');
        expect(fileInput.value).toBeInstanceOf(Blob);

        // Test with ArrayBuffer
        const buffer = new ArrayBuffer(8);
        const bufferInput = new mockWasm.WasmInput('buffer', buffer, 'binary');
        expect(bufferInput.value).toBeInstanceOf(ArrayBuffer);

        // Test with Date objects
        const now = new Date();
        const dateInput = new mockWasm.WasmInput('timestamp', now, 'datetime');
        expect(dateInput.value).toBeInstanceOf(Date);
    });

    it('should handle large datasets', () => {
        const snapshot = new mockWasm.WasmSnapshot('batch');

        // Add many decisions
        for (let i = 0; i < 100; i++) {
            const decision = new mockWasm.WasmDecisionSnapshot(`batch_func_${i}`);
            const input = new mockWasm.WasmInput('data', `input_${i}`, 'string');
            const output = new mockWasm.WasmOutput('result', `output_${i}`, 'string');

            decision.addInput(input);
            decision.addOutput(output);
            snapshot.addDecision(decision);
        }

        expect(snapshot.decision_count).toBe(100);

        // Serialization should work efficiently
        const startTime = Date.now();
        const obj = snapshot.toObject();
        const endTime = Date.now();

        expect(obj.decisions).toHaveLength(100);
        expect(endTime - startTime).toBeLessThan(100); // Should be fast
    });

    it('should maintain data integrity across serialization', () => {
        const original = new mockWasm.WasmDecisionSnapshot('integrity_test');

        // Add various data types
        original.addInput(new mockWasm.WasmInput('string', 'test', 'string'));
        original.addInput(new mockWasm.WasmInput('number', 42, 'number'));
        original.addInput(new mockWasm.WasmInput('boolean', true, 'boolean'));
        original.addInput(new mockWasm.WasmInput('array', [1, 2, 3], 'array'));
        original.addInput(new mockWasm.WasmInput('object', {a: 1, b: 2}, 'object'));

        const output = new mockWasm.WasmOutput('result', {score: 0.95, label: 'positive'}, 'object');
        output.withConfidence(0.95);
        original.addOutput(output);

        original.addTag('test', 'value');
        original.withExecutionTime(100.5);

        // Serialize and verify
        const serialized = original.toObject();

        expect(serialized.inputs).toHaveLength(5);
        expect(serialized.outputs).toHaveLength(1);
        expect(serialized.execution_time_ms).toBe(100.5);
        expect(serialized.tags.test).toBe('value');
        expect(serialized.outputs[0].confidence).toBe(0.95);
    });

    it('should be compatible with JSON serialization', () => {
        const decision = new mockWasm.WasmDecisionSnapshot('json_test');
        decision.addInput(new mockWasm.WasmInput('data', 'test', 'string'));
        decision.addOutput(new mockWasm.WasmOutput('result', 'success', 'string'));

        const snapshot = new mockWasm.WasmSnapshot('session');
        snapshot.addDecision(decision);

        // Convert to plain object and serialize as JSON
        const obj = snapshot.toObject();
        const json = JSON.stringify(obj);
        const parsed = JSON.parse(json);

        expect(parsed.snapshot_type).toBe('session');
        expect(parsed.decisions).toHaveLength(1);
        expect(parsed.decisions[0].function_name).toBe('json_test');
    });

    it('should handle memory-efficient operations', () => {
        // Test that operations don't cause memory leaks
        const createSnapshot = () => {
            const snapshot = new mockWasm.WasmSnapshot('session');
            const decision = new mockWasm.WasmDecisionSnapshot('memory_test');

            // Add some data
            for (let i = 0; i < 10; i++) {
                decision.addInput(new mockWasm.WasmInput(`input_${i}`, `value_${i}`, 'string'));
            }

            snapshot.addDecision(decision);
            return snapshot.toObject();
        };

        // Create many snapshots
        for (let i = 0; i < 50; i++) {
            createSnapshot();
        }

        // Should complete without issues
        expect(true).toBe(true);
    });
});

export default {};