peerpigeon 0.1.0 → 0.1.1

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.
@@ -644,6 +644,94 @@
644
644
  <h3>Storage Operations Log</h3>
645
645
  <div id="storage-log" class="storage-log"></div>
646
646
  </div>
647
+
648
+ <!-- Lexical Storage Interface -->
649
+ <div class="lexical-storage">
650
+ <h3>🔗 Lexical Storage Interface (GUN-like API)</h3>
651
+ <p class="feature-description">Chain operations like: <code>storage.get('users').get('alice').put({name: 'Alice'})</code></p>
652
+
653
+ <!-- Lexical Operations -->
654
+ <div class="lexical-operations">
655
+ <h4>Chain Operations</h4>
656
+ <div class="input-group">
657
+ <label for="lexical-path">Path (dot notation):</label>
658
+ <input type="text" id="lexical-path" placeholder="users.alice" value="demo.user1">
659
+ </div>
660
+ <div class="input-group">
661
+ <label for="lexical-data">Data (JSON):</label>
662
+ <textarea id="lexical-data" rows="3" placeholder='{"name": "Alice", "age": 30}'></textarea>
663
+ </div>
664
+ <div class="input-group">
665
+ <label for="lexical-property">Property to get:</label>
666
+ <input type="text" id="lexical-property" placeholder="name" value="name">
667
+ </div>
668
+
669
+ <div class="button-group">
670
+ <button id="lexical-put-btn" class="btn primary">Put Data</button>
671
+ <button id="lexical-get-btn" class="btn secondary">Get Property</button>
672
+ <button id="lexical-val-btn" class="btn secondary">Get Full Object</button>
673
+ <button id="lexical-update-btn" class="btn tertiary">Update</button>
674
+ <button id="lexical-delete-btn" class="btn warning">Delete</button>
675
+ </div>
676
+ </div>
677
+
678
+ <!-- Set Operations -->
679
+ <div class="lexical-sets">
680
+ <h4>Set Operations</h4>
681
+ <div class="input-group">
682
+ <label for="lexical-set-path">Set Path:</label>
683
+ <input type="text" id="lexical-set-path" placeholder="users.alice.friends" value="demo.friends">
684
+ </div>
685
+ <div class="input-group">
686
+ <label for="lexical-set-data">Set Data (JSON object):</label>
687
+ <textarea id="lexical-set-data" rows="2" placeholder='{"bob": {"name": "Bob"}, "charlie": {"name": "Charlie"}}'></textarea>
688
+ </div>
689
+
690
+ <div class="button-group">
691
+ <button id="lexical-set-btn" class="btn primary">Set Data</button>
692
+ <button id="lexical-map-btn" class="btn secondary">Map & Log</button>
693
+ </div>
694
+ </div>
695
+
696
+ <!-- Property Access Demo -->
697
+ <div class="lexical-proxy">
698
+ <h4>Property Access (Proxy)</h4>
699
+ <div class="input-group">
700
+ <label for="lexical-proxy-path">Property Path:</label>
701
+ <input type="text" id="lexical-proxy-path" placeholder="users.alice.settings.theme" value="demo.settings.theme">
702
+ </div>
703
+ <div class="input-group">
704
+ <label for="lexical-proxy-value">Value:</label>
705
+ <input type="text" id="lexical-proxy-value" placeholder="dark" value="dark">
706
+ </div>
707
+
708
+ <div class="button-group">
709
+ <button id="lexical-proxy-set-btn" class="btn primary">Set via Proxy</button>
710
+ <button id="lexical-proxy-get-btn" class="btn secondary">Get via Proxy</button>
711
+ </div>
712
+ </div>
713
+
714
+ <!-- Utility Operations -->
715
+ <div class="lexical-utils">
716
+ <h4>Utility Methods</h4>
717
+ <div class="input-group">
718
+ <label for="lexical-util-path">Path:</label>
719
+ <input type="text" id="lexical-util-path" placeholder="demo.user1" value="demo.user1">
720
+ </div>
721
+
722
+ <div class="button-group">
723
+ <button id="lexical-exists-btn" class="btn tertiary">Check Exists</button>
724
+ <button id="lexical-keys-btn" class="btn tertiary">Get Keys</button>
725
+ <button id="lexical-path-btn" class="btn tertiary">Get Path</button>
726
+ </div>
727
+ </div>
728
+
729
+ <!-- Lexical Results -->
730
+ <div class="lexical-results">
731
+ <h4>Lexical Operations Results</h4>
732
+ <div id="lexical-log" class="storage-log"></div>
733
+ </div>
734
+ </div>
647
735
  </div>
648
736
  </div>
649
737
 
@@ -916,6 +916,370 @@ export class PeerPigeonUI {
916
916
  e.target.value = '';
917
917
  });
918
918
  }
919
+
920
+ // Setup Lexical Storage Interface
921
+ this.setupLexicalStorageControls();
922
+ }
923
+
924
+ setupLexicalStorageControls() {
925
+ // Chain Operations
926
+ const lexicalPutBtn = document.getElementById('lexical-put-btn');
927
+ const lexicalGetBtn = document.getElementById('lexical-get-btn');
928
+ const lexicalValBtn = document.getElementById('lexical-val-btn');
929
+ const lexicalUpdateBtn = document.getElementById('lexical-update-btn');
930
+ const lexicalDeleteBtn = document.getElementById('lexical-delete-btn');
931
+
932
+ // Set Operations
933
+ const lexicalSetBtn = document.getElementById('lexical-set-btn');
934
+ const lexicalMapBtn = document.getElementById('lexical-map-btn');
935
+
936
+ // Property Access
937
+ const lexicalProxySetBtn = document.getElementById('lexical-proxy-set-btn');
938
+ const lexicalProxyGetBtn = document.getElementById('lexical-proxy-get-btn');
939
+
940
+ // Utility Operations
941
+ const lexicalExistsBtn = document.getElementById('lexical-exists-btn');
942
+ const lexicalKeysBtn = document.getElementById('lexical-keys-btn');
943
+ const lexicalPathBtn = document.getElementById('lexical-path-btn');
944
+
945
+ // Chain Operations Event Handlers
946
+ if (lexicalPutBtn) {
947
+ lexicalPutBtn.addEventListener('click', async () => {
948
+ const path = document.getElementById('lexical-path')?.value?.trim();
949
+ const data = document.getElementById('lexical-data')?.value?.trim();
950
+
951
+ if (!path || !data) {
952
+ this.addLexicalLogEntry('❌ Error: Both path and data are required');
953
+ return;
954
+ }
955
+
956
+ try {
957
+ const parsedData = JSON.parse(data);
958
+ const lex = this.mesh.distributedStorage.lexical();
959
+ const pathParts = path.split('.');
960
+
961
+ let current = lex;
962
+ for (const part of pathParts) {
963
+ current = current.get(part);
964
+ }
965
+
966
+ await current.put(parsedData);
967
+ this.addLexicalLogEntry(`✅ Put data at path: ${path}`);
968
+ } catch (error) {
969
+ this.addLexicalLogEntry(`❌ Error: ${error.message}`);
970
+ }
971
+ });
972
+ }
973
+
974
+ if (lexicalGetBtn) {
975
+ lexicalGetBtn.addEventListener('click', async () => {
976
+ const path = document.getElementById('lexical-path')?.value?.trim();
977
+ const property = document.getElementById('lexical-property')?.value?.trim();
978
+
979
+ if (!path || !property) {
980
+ this.addLexicalLogEntry('❌ Error: Both path and property are required');
981
+ return;
982
+ }
983
+
984
+ try {
985
+ const lex = this.mesh.distributedStorage.lexical();
986
+ const pathParts = path.split('.');
987
+
988
+ let current = lex;
989
+ for (const part of pathParts) {
990
+ current = current.get(part);
991
+ }
992
+
993
+ const value = await current.get(property).val();
994
+ this.addLexicalLogEntry(`📄 ${path}.${property}: ${JSON.stringify(value)}`);
995
+ } catch (error) {
996
+ this.addLexicalLogEntry(`❌ Error: ${error.message}`);
997
+ }
998
+ });
999
+ }
1000
+
1001
+ if (lexicalValBtn) {
1002
+ lexicalValBtn.addEventListener('click', async () => {
1003
+ const path = document.getElementById('lexical-path')?.value?.trim();
1004
+
1005
+ if (!path) {
1006
+ this.addLexicalLogEntry('❌ Error: Path is required');
1007
+ return;
1008
+ }
1009
+
1010
+ try {
1011
+ const lex = this.mesh.distributedStorage.lexical();
1012
+ const pathParts = path.split('.');
1013
+
1014
+ let current = lex;
1015
+ for (const part of pathParts) {
1016
+ current = current.get(part);
1017
+ }
1018
+
1019
+ const value = await current.val();
1020
+ this.addLexicalLogEntry(`📄 Full object at ${path}: ${JSON.stringify(value, null, 2)}`);
1021
+ } catch (error) {
1022
+ this.addLexicalLogEntry(`❌ Error: ${error.message}`);
1023
+ }
1024
+ });
1025
+ }
1026
+
1027
+ if (lexicalUpdateBtn) {
1028
+ lexicalUpdateBtn.addEventListener('click', async () => {
1029
+ const path = document.getElementById('lexical-path')?.value?.trim();
1030
+ const data = document.getElementById('lexical-data')?.value?.trim();
1031
+
1032
+ if (!path || !data) {
1033
+ this.addLexicalLogEntry('❌ Error: Both path and data are required');
1034
+ return;
1035
+ }
1036
+
1037
+ try {
1038
+ const parsedData = JSON.parse(data);
1039
+ const lex = this.mesh.distributedStorage.lexical();
1040
+ const pathParts = path.split('.');
1041
+
1042
+ let current = lex;
1043
+ for (const part of pathParts) {
1044
+ current = current.get(part);
1045
+ }
1046
+
1047
+ await current.update(parsedData);
1048
+ this.addLexicalLogEntry(`✅ Updated data at path: ${path}`);
1049
+ } catch (error) {
1050
+ this.addLexicalLogEntry(`❌ Error: ${error.message}`);
1051
+ }
1052
+ });
1053
+ }
1054
+
1055
+ if (lexicalDeleteBtn) {
1056
+ lexicalDeleteBtn.addEventListener('click', async () => {
1057
+ const path = document.getElementById('lexical-path')?.value?.trim();
1058
+
1059
+ if (!path) {
1060
+ this.addLexicalLogEntry('❌ Error: Path is required');
1061
+ return;
1062
+ }
1063
+
1064
+ try {
1065
+ const lex = this.mesh.distributedStorage.lexical();
1066
+ const pathParts = path.split('.');
1067
+
1068
+ let current = lex;
1069
+ for (const part of pathParts) {
1070
+ current = current.get(part);
1071
+ }
1072
+
1073
+ await current.delete();
1074
+ this.addLexicalLogEntry(`✅ Deleted data at path: ${path}`);
1075
+ } catch (error) {
1076
+ this.addLexicalLogEntry(`❌ Error: ${error.message}`);
1077
+ }
1078
+ });
1079
+ }
1080
+
1081
+ // Set Operations Event Handlers
1082
+ if (lexicalSetBtn) {
1083
+ lexicalSetBtn.addEventListener('click', async () => {
1084
+ const path = document.getElementById('lexical-set-path')?.value?.trim();
1085
+ const data = document.getElementById('lexical-set-data')?.value?.trim();
1086
+
1087
+ if (!path || !data) {
1088
+ this.addLexicalLogEntry('❌ Error: Both path and data are required');
1089
+ return;
1090
+ }
1091
+
1092
+ try {
1093
+ const parsedData = JSON.parse(data);
1094
+ const lex = this.mesh.distributedStorage.lexical();
1095
+ const pathParts = path.split('.');
1096
+
1097
+ let current = lex;
1098
+ for (const part of pathParts) {
1099
+ current = current.get(part);
1100
+ }
1101
+
1102
+ await current.set(parsedData);
1103
+ this.addLexicalLogEntry(`✅ Set data at path: ${path}`);
1104
+ } catch (error) {
1105
+ this.addLexicalLogEntry(`❌ Error: ${error.message}`);
1106
+ }
1107
+ });
1108
+ }
1109
+
1110
+ if (lexicalMapBtn) {
1111
+ lexicalMapBtn.addEventListener('click', async () => {
1112
+ const path = document.getElementById('lexical-set-path')?.value?.trim();
1113
+
1114
+ if (!path) {
1115
+ this.addLexicalLogEntry('❌ Error: Path is required');
1116
+ return;
1117
+ }
1118
+
1119
+ try {
1120
+ const lex = this.mesh.distributedStorage.lexical();
1121
+ const pathParts = path.split('.');
1122
+
1123
+ let current = lex;
1124
+ for (const part of pathParts) {
1125
+ current = current.get(part);
1126
+ }
1127
+
1128
+ const mapResults = [];
1129
+ const unsubscribe = current.map().on((value, key) => {
1130
+ mapResults.push({ key, value });
1131
+ this.addLexicalLogEntry(`🗺️ Map result - ${key}: ${JSON.stringify(value)}`);
1132
+ });
1133
+
1134
+ // Stop mapping after a short delay
1135
+ setTimeout(() => {
1136
+ if (unsubscribe) unsubscribe();
1137
+ this.addLexicalLogEntry(`✅ Map operation completed with ${mapResults.length} results`);
1138
+ }, 1000);
1139
+ } catch (error) {
1140
+ this.addLexicalLogEntry(`❌ Error: ${error.message}`);
1141
+ }
1142
+ });
1143
+ }
1144
+
1145
+ // Property Access Event Handlers
1146
+ if (lexicalProxySetBtn) {
1147
+ lexicalProxySetBtn.addEventListener('click', async () => {
1148
+ const path = document.getElementById('lexical-proxy-path')?.value?.trim();
1149
+ const value = document.getElementById('lexical-proxy-value')?.value?.trim();
1150
+
1151
+ if (!path || !value) {
1152
+ this.addLexicalLogEntry('❌ Error: Both path and value are required');
1153
+ return;
1154
+ }
1155
+
1156
+ try {
1157
+ const lex = this.mesh.distributedStorage.lexical();
1158
+ const pathParts = path.split('.');
1159
+
1160
+ // Use proxy property access
1161
+ let current = lex;
1162
+ for (const part of pathParts.slice(0, -1)) {
1163
+ current = current[part];
1164
+ }
1165
+
1166
+ const lastPart = pathParts[pathParts.length - 1];
1167
+ await current[lastPart].put(value);
1168
+
1169
+ this.addLexicalLogEntry(`✅ Set via proxy: ${path} = ${value}`);
1170
+ } catch (error) {
1171
+ this.addLexicalLogEntry(`❌ Error: ${error.message}`);
1172
+ }
1173
+ });
1174
+ }
1175
+
1176
+ if (lexicalProxyGetBtn) {
1177
+ lexicalProxyGetBtn.addEventListener('click', async () => {
1178
+ const path = document.getElementById('lexical-proxy-path')?.value?.trim();
1179
+
1180
+ if (!path) {
1181
+ this.addLexicalLogEntry('❌ Error: Path is required');
1182
+ return;
1183
+ }
1184
+
1185
+ try {
1186
+ const lex = this.mesh.distributedStorage.lexical();
1187
+ const pathParts = path.split('.');
1188
+
1189
+ // Use proxy property access
1190
+ let current = lex;
1191
+ for (const part of pathParts.slice(0, -1)) {
1192
+ current = current[part];
1193
+ }
1194
+
1195
+ const lastPart = pathParts[pathParts.length - 1];
1196
+ const value = await current[lastPart].val();
1197
+
1198
+ this.addLexicalLogEntry(`📄 Proxy get ${path}: ${JSON.stringify(value)}`);
1199
+ } catch (error) {
1200
+ this.addLexicalLogEntry(`❌ Error: ${error.message}`);
1201
+ }
1202
+ });
1203
+ }
1204
+
1205
+ // Utility Operations Event Handlers
1206
+ if (lexicalExistsBtn) {
1207
+ lexicalExistsBtn.addEventListener('click', async () => {
1208
+ const path = document.getElementById('lexical-util-path')?.value?.trim();
1209
+
1210
+ if (!path) {
1211
+ this.addLexicalLogEntry('❌ Error: Path is required');
1212
+ return;
1213
+ }
1214
+
1215
+ try {
1216
+ const lex = this.mesh.distributedStorage.lexical();
1217
+ const pathParts = path.split('.');
1218
+
1219
+ let current = lex;
1220
+ for (const part of pathParts) {
1221
+ current = current.get(part);
1222
+ }
1223
+
1224
+ const exists = await current.exists();
1225
+ this.addLexicalLogEntry(`🔍 ${path} exists: ${exists}`);
1226
+ } catch (error) {
1227
+ this.addLexicalLogEntry(`❌ Error: ${error.message}`);
1228
+ }
1229
+ });
1230
+ }
1231
+
1232
+ if (lexicalKeysBtn) {
1233
+ lexicalKeysBtn.addEventListener('click', async () => {
1234
+ const path = document.getElementById('lexical-util-path')?.value?.trim();
1235
+
1236
+ if (!path) {
1237
+ this.addLexicalLogEntry('❌ Error: Path is required');
1238
+ return;
1239
+ }
1240
+
1241
+ try {
1242
+ const lex = this.mesh.distributedStorage.lexical();
1243
+ const pathParts = path.split('.');
1244
+
1245
+ let current = lex;
1246
+ for (const part of pathParts) {
1247
+ current = current.get(part);
1248
+ }
1249
+
1250
+ const keys = await current.keys();
1251
+ this.addLexicalLogEntry(`🔑 Keys at ${path}: [${keys.join(', ')}]`);
1252
+ } catch (error) {
1253
+ this.addLexicalLogEntry(`❌ Error: ${error.message}`);
1254
+ }
1255
+ });
1256
+ }
1257
+
1258
+ if (lexicalPathBtn) {
1259
+ lexicalPathBtn.addEventListener('click', async () => {
1260
+ const path = document.getElementById('lexical-util-path')?.value?.trim();
1261
+
1262
+ if (!path) {
1263
+ this.addLexicalLogEntry('❌ Error: Path is required');
1264
+ return;
1265
+ }
1266
+
1267
+ try {
1268
+ const lex = this.mesh.distributedStorage.lexical();
1269
+ const pathParts = path.split('.');
1270
+
1271
+ let current = lex;
1272
+ for (const part of pathParts) {
1273
+ current = current.get(part);
1274
+ }
1275
+
1276
+ const fullPath = current.getPath();
1277
+ this.addLexicalLogEntry(`🛤️ Full storage path: ${fullPath}`);
1278
+ } catch (error) {
1279
+ this.addLexicalLogEntry(`❌ Error: ${error.message}`);
1280
+ }
1281
+ });
1282
+ }
919
1283
  }
920
1284
 
921
1285
  async handleStorageStore(isUpdate = false) {
@@ -1006,6 +1370,23 @@ export class PeerPigeonUI {
1006
1370
  }
1007
1371
  }
1008
1372
 
1373
+ addLexicalLogEntry(message) {
1374
+ const logElement = document.getElementById('lexical-log');
1375
+ if (!logElement) return;
1376
+
1377
+ const entry = document.createElement('div');
1378
+ entry.className = 'log-entry';
1379
+ entry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
1380
+
1381
+ logElement.appendChild(entry);
1382
+ logElement.scrollTop = logElement.scrollHeight;
1383
+
1384
+ // Keep only last 100 entries
1385
+ while (logElement.children.length > 100) {
1386
+ logElement.removeChild(logElement.firstChild);
1387
+ }
1388
+ }
1389
+
1009
1390
  updateStorageStatus() {
1010
1391
  if (!this.mesh.distributedStorage) {
1011
1392
  document.getElementById('storage-status').textContent = 'Not Available';
@@ -387,20 +387,154 @@ class StorageTest {
387
387
  }
388
388
 
389
389
  async testStorageToggle() {
390
- await this.runTest('Storage Enable/Disable', async () => {
391
- // Test disable
392
- await this.storage.disable();
390
+ await this.runTest('Storage Toggle', async () => {
391
+ const key = 'test-toggle';
392
+ const value = { test: true };
393
+
394
+ // Store when enabled
395
+ await this.storage.store(key, value);
396
+ let retrieved = await this.storage.retrieve(key);
397
+ if (JSON.stringify(retrieved) !== JSON.stringify(value)) {
398
+ throw new Error('Failed to store when enabled');
399
+ }
400
+
401
+ // Disable storage
402
+ this.storage.disable();
393
403
  if (this.storage.isEnabled()) {
394
404
  throw new Error('Storage should be disabled');
395
405
  }
396
406
 
397
- // Test enable
398
- await this.storage.enable();
407
+ // Operations should fail or return null when disabled
408
+ const disabledResult = await this.storage.store('disabled-key', { test: true });
409
+ if (disabledResult !== false) {
410
+ throw new Error('Store should fail when disabled');
411
+ }
412
+
413
+ // Re-enable storage
414
+ this.storage.enable();
399
415
  if (!this.storage.isEnabled()) {
400
416
  throw new Error('Storage should be enabled');
401
417
  }
402
418
 
403
- console.log(' Storage successfully toggled enabled/disabled');
419
+ // Should work again
420
+ retrieved = await this.storage.retrieve(key);
421
+ if (JSON.stringify(retrieved) !== JSON.stringify(value)) {
422
+ throw new Error('Failed to retrieve after re-enabling');
423
+ }
424
+
425
+ console.log(' Storage toggle functionality verified');
426
+ });
427
+ }
428
+
429
+ async testLexicalInterface() {
430
+ await this.runTest('Lexical Interface - Basic Operations', async () => {
431
+ const lex = this.storage.lexical();
432
+
433
+ // Test basic put/get
434
+ const user = lex.get('users').get('alice');
435
+ await user.put({ name: 'Alice', age: 30, city: 'New York' });
436
+
437
+ const name = await user.get('name').val();
438
+ if (name !== 'Alice') {
439
+ throw new Error(`Expected 'Alice', got '${name}'`);
440
+ }
441
+
442
+ const age = await user.get('age').val();
443
+ if (age !== 30) {
444
+ throw new Error(`Expected 30, got ${age}`);
445
+ }
446
+
447
+ // Test object reconstruction
448
+ const fullUser = await user.val();
449
+ if (!fullUser || fullUser.name !== 'Alice' || fullUser.age !== 30 || fullUser.city !== 'New York') {
450
+ throw new Error('Object reconstruction failed');
451
+ }
452
+
453
+ console.log(' Basic lexical operations verified');
454
+ });
455
+
456
+ await this.runTest('Lexical Interface - Set Operations', async () => {
457
+ const lex = this.storage.lexical();
458
+ const friends = lex.get('users').get('bob').get('friends');
459
+
460
+ // Test set operations
461
+ await friends.set({
462
+ alice: { name: 'Alice', status: 'online' },
463
+ charlie: { name: 'Charlie', status: 'offline' }
464
+ });
465
+
466
+ // Verify set data was stored
467
+ const setData = await this.storage.retrieve('users:bob:friends:_set');
468
+ if (!setData || !setData.alice || !setData.charlie) {
469
+ throw new Error('Set data not stored correctly');
470
+ }
471
+
472
+ console.log(' Set operations verified');
473
+ });
474
+
475
+ await this.runTest('Lexical Interface - Property Access', async () => {
476
+ const lex = this.storage.lexical();
477
+
478
+ // Test proxy-based property access
479
+ const settings = lex.users.alice.settings;
480
+ await settings.put({ theme: 'dark', language: 'en' });
481
+
482
+ const theme = await settings.theme.val();
483
+ if (theme !== 'dark') {
484
+ throw new Error(`Expected 'dark', got '${theme}'`);
485
+ }
486
+
487
+ console.log(' Property access verified');
488
+ });
489
+
490
+ await this.runTest('Lexical Interface - Update and Delete', async () => {
491
+ const lex = this.storage.lexical();
492
+ const profile = lex.get('profiles').get('user1');
493
+
494
+ // Test update
495
+ await profile.put({ name: 'John', age: 25 });
496
+ await profile.update({ age: 26, city: 'Boston' });
497
+
498
+ const updatedProfile = await profile.val();
499
+ if (updatedProfile.age !== 26 || updatedProfile.city !== 'Boston' || updatedProfile.name !== 'John') {
500
+ throw new Error('Update operation failed');
501
+ }
502
+
503
+ // Test delete
504
+ await profile.delete();
505
+ const deletedProfile = await profile.val();
506
+ if (deletedProfile !== null) {
507
+ throw new Error('Delete operation failed');
508
+ }
509
+
510
+ console.log(' Update and delete operations verified');
511
+ });
512
+
513
+ await this.runTest('Lexical Interface - Utility Methods', async () => {
514
+ const lex = this.storage.lexical();
515
+ const testObj = lex.get('test').get('object');
516
+
517
+ await testObj.put({ prop1: 'value1', prop2: 'value2', prop3: 'value3' });
518
+
519
+ // Test exists
520
+ const exists = await testObj.exists();
521
+ if (!exists) {
522
+ throw new Error('exists() should return true');
523
+ }
524
+
525
+ // Test keys
526
+ const keys = await testObj.keys();
527
+ if (!keys.includes('prop1') || !keys.includes('prop2') || !keys.includes('prop3')) {
528
+ throw new Error('keys() did not return expected keys');
529
+ }
530
+
531
+ // Test getPath
532
+ const path = testObj.getPath();
533
+ if (path !== 'test:object') {
534
+ throw new Error(`Expected path 'test:object', got '${path}'`);
535
+ }
536
+
537
+ console.log(' Utility methods verified');
404
538
  });
405
539
  }
406
540
 
@@ -427,6 +561,7 @@ class StorageTest {
427
561
  await this.testBackupAndRestore();
428
562
  await this.testStatistics();
429
563
  await this.testStorageToggle();
564
+ await this.testLexicalInterface();
430
565
  await this.testCleanup();
431
566
 
432
567
  this.printSummary();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "peerpigeon",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "WebRTC-based peer-to-peer mesh networking library with intelligent routing and signaling server",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -1,5 +1,6 @@
1
1
  import { EventEmitter } from './EventEmitter.js';
2
2
  import DebugLogger from './DebugLogger.js';
3
+ import { createLexicalInterface } from './LexicalStorageInterface.js';
3
4
 
4
5
  // Dynamic import for unsea to handle both Node.js and browser environments
5
6
  let unsea = null;
@@ -403,6 +404,10 @@ export class DistributedStorageManager extends EventEmitter {
403
404
  * @returns {Promise<boolean>} Success status
404
405
  */
405
406
  async store(key, value, options = {}) {
407
+ if (!this.enabled) {
408
+ return false;
409
+ }
410
+
406
411
  if (!this.webDHT) {
407
412
  throw new Error('WebDHT not available - ensure it is enabled in mesh configuration');
408
413
  }
@@ -1698,4 +1703,20 @@ export class DistributedStorageManager extends EventEmitter {
1698
1703
 
1699
1704
  return results;
1700
1705
  }
1706
+
1707
+ /**
1708
+ * Get a lexical interface for GUN-like chaining
1709
+ * @returns {Proxy} Lexical interface
1710
+ */
1711
+ lexical() {
1712
+ return createLexicalInterface(this);
1713
+ }
1714
+
1715
+ /**
1716
+ * Alias for lexical() - more GUN-like naming
1717
+ * @returns {Proxy} Lexical interface
1718
+ */
1719
+ gun() {
1720
+ return this.lexical();
1721
+ }
1701
1722
  }
@@ -0,0 +1,332 @@
1
+ import { EventEmitter } from './EventEmitter.js';
2
+ import DebugLogger from './DebugLogger.js';
3
+
4
+ /**
5
+ * Lexical Storage Interface - GUN-like chaining API for DistributedStorageManager
6
+ *
7
+ * Usage:
8
+ * const user = storage.get('users').get('alice');
9
+ * await user.put({name: 'Alice', age: 30});
10
+ * const name = await user.get('name').val();
11
+ *
12
+ * user.get('friends').set({bob: true, charlie: true});
13
+ * user.get('friends').map().on((friend, key) => console.log(key, friend));
14
+ */
15
+ export class LexicalStorageInterface extends EventEmitter {
16
+ constructor(distributedStorage, path = []) {
17
+ super();
18
+ this.debug = DebugLogger.create('LexicalStorageInterface');
19
+ this.storage = distributedStorage;
20
+ this.path = path.slice(); // Create a copy of the path
21
+ this.subscriptions = new Map();
22
+ this._isMap = false;
23
+ }
24
+
25
+ /**
26
+ * Navigate to a key (creates a new interface instance)
27
+ * @param {string} key - The key to navigate to
28
+ * @returns {LexicalStorageInterface} New interface for the key
29
+ */
30
+ get(key) {
31
+ const newInterface = new LexicalStorageInterface(this.storage, [...this.path, key]);
32
+ return newInterface;
33
+ }
34
+
35
+ /**
36
+ * Store data at the current path
37
+ * @param {any} value - Value to store
38
+ * @param {Object} options - Storage options
39
+ * @returns {Promise<LexicalStorageInterface>} This interface for chaining
40
+ */
41
+ async put(value, options = {}) {
42
+ const fullKey = this.path.join(':');
43
+
44
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
45
+ // For objects, store each property as a separate key
46
+ const promises = Object.entries(value).map(([prop, val]) => {
47
+ const propKey = `${fullKey}:${prop}`;
48
+ return this.storage.store(propKey, val, options);
49
+ });
50
+ await Promise.all(promises);
51
+
52
+ // Also store the object structure for reference
53
+ await this.storage.store(fullKey, { _keys: Object.keys(value), _type: 'object' }, options);
54
+ } else {
55
+ // For primitives, store directly
56
+ await this.storage.store(fullKey, value, options);
57
+ }
58
+
59
+ // Emit change event
60
+ this.emit('put', { key: fullKey, value });
61
+
62
+ return this;
63
+ }
64
+
65
+ /**
66
+ * Retrieve the current value
67
+ * @param {Object} options - Retrieval options
68
+ * @returns {Promise<any>} The stored value
69
+ */
70
+ async val(options = {}) {
71
+ const fullKey = this.path.join(':');
72
+ const value = await this.storage.retrieve(fullKey, options);
73
+
74
+ // If it's an object structure, reconstruct it
75
+ if (value && typeof value === 'object' && value._keys && value._type === 'object') {
76
+ const reconstructed = {};
77
+ const promises = value._keys.map(async (key) => {
78
+ const keyValue = await this.storage.retrieve(`${fullKey}:${key}`, options);
79
+ reconstructed[key] = keyValue;
80
+ });
81
+ await Promise.all(promises);
82
+ return reconstructed;
83
+ }
84
+
85
+ return value;
86
+ }
87
+
88
+ /**
89
+ * Set multiple key-value pairs (like GUN's set)
90
+ * @param {Object} obj - Object with key-value pairs to set
91
+ * @param {Object} options - Storage options
92
+ * @returns {Promise<LexicalStorageInterface>} This interface for chaining
93
+ */
94
+ async set(obj, options = {}) {
95
+ const fullKey = this.path.join(':');
96
+
97
+ // Store each entry with a unique ID
98
+ const promises = Object.entries(obj).map(([key, value]) => {
99
+ const setKey = `${fullKey}:${key}`;
100
+ return this.storage.store(setKey, value, options);
101
+ });
102
+
103
+ await Promise.all(promises);
104
+
105
+ // Update the set index
106
+ const existingSet = await this.storage.retrieve(`${fullKey}:_set`) || {};
107
+ const updatedSet = { ...existingSet, ...obj };
108
+ await this.storage.store(`${fullKey}:_set`, updatedSet, options);
109
+
110
+ // Emit set event
111
+ this.emit('set', { key: fullKey, values: obj });
112
+
113
+ return this;
114
+ }
115
+
116
+ /**
117
+ * Map over a set (like GUN's map)
118
+ * @returns {LexicalStorageInterface} New interface for mapping
119
+ */
120
+ map() {
121
+ const mapInterface = new LexicalStorageInterface(this.storage, this.path);
122
+ mapInterface._isMap = true;
123
+ return mapInterface;
124
+ }
125
+
126
+ /**
127
+ * Subscribe to changes (like GUN's on)
128
+ * @param {Function} callback - Callback for changes
129
+ * @returns {Function} Unsubscribe function
130
+ */
131
+ on(callback) {
132
+ const fullKey = this.path.join(':');
133
+
134
+ if (this._isMap) {
135
+ // For maps, listen to set changes
136
+ const setKey = `${fullKey}:_set`;
137
+
138
+ const handleChange = async () => {
139
+ const setData = await this.storage.retrieve(setKey);
140
+ if (setData) {
141
+ Object.entries(setData).forEach(([key, value]) => {
142
+ callback(value, key);
143
+ });
144
+ }
145
+ };
146
+
147
+ // Subscribe to the set key using storage's subscription mechanism
148
+ if (this.storage.subscribe) {
149
+ this.storage.subscribe(setKey).then(() => {
150
+ this.storage.on('dataUpdated', (event) => {
151
+ if (event.key === setKey) {
152
+ handleChange();
153
+ }
154
+ });
155
+ });
156
+ }
157
+
158
+ // Initial call
159
+ handleChange();
160
+
161
+ return () => {
162
+ if (this.storage.unsubscribe) {
163
+ this.storage.unsubscribe(setKey);
164
+ }
165
+ };
166
+ } else {
167
+ // For regular keys, listen to direct changes
168
+ if (this.storage.subscribe) {
169
+ this.storage.subscribe(fullKey).then((currentValue) => {
170
+ callback(currentValue, fullKey);
171
+ });
172
+
173
+ this.storage.on('dataUpdated', (event) => {
174
+ if (event.key === fullKey) {
175
+ this.storage.retrieve(fullKey).then(value => {
176
+ callback(value, fullKey);
177
+ });
178
+ }
179
+ });
180
+ }
181
+
182
+ return () => {
183
+ if (this.storage.unsubscribe) {
184
+ this.storage.unsubscribe(fullKey);
185
+ }
186
+ };
187
+ }
188
+ }
189
+
190
+ /**
191
+ * Once - listen for a single change
192
+ * @param {Function} callback - Callback for the change
193
+ * @returns {Promise} Promise that resolves with the value
194
+ */
195
+ async once(callback) {
196
+ return new Promise((resolve) => {
197
+ const unsubscribe = this.on((value, key) => {
198
+ if (callback) callback(value, key);
199
+ unsubscribe();
200
+ resolve(value);
201
+ });
202
+ });
203
+ }
204
+
205
+ /**
206
+ * Delete the current path
207
+ * @returns {Promise<boolean>} Success status
208
+ */
209
+ async delete() {
210
+ const fullKey = this.path.join(':');
211
+
212
+ // If it's an object, delete all its properties first
213
+ const value = await this.storage.retrieve(fullKey);
214
+ if (value && typeof value === 'object' && value._keys && value._type === 'object') {
215
+ const deletePromises = value._keys.map(key => {
216
+ const propKey = `${fullKey}:${key}`;
217
+ return this.storage.delete(propKey);
218
+ });
219
+ await Promise.all(deletePromises);
220
+ }
221
+
222
+ const result = await this.storage.delete(fullKey);
223
+
224
+ // Emit delete event
225
+ this.emit('delete', { key: fullKey });
226
+
227
+ return result;
228
+ }
229
+
230
+ /**
231
+ * Update with merge semantics
232
+ * @param {any} value - Value to merge
233
+ * @param {Object} options - Update options
234
+ * @returns {Promise<LexicalStorageInterface>} This interface for chaining
235
+ */
236
+ async update(value, options = {}) {
237
+ const fullKey = this.path.join(':');
238
+ const currentValue = await this.storage.retrieve(fullKey);
239
+
240
+ let mergedValue;
241
+ if (typeof value === 'object' && value !== null && !Array.isArray(value) &&
242
+ typeof currentValue === 'object' && currentValue !== null && !Array.isArray(currentValue)) {
243
+ // Handle object reconstruction first
244
+ if (currentValue._keys && currentValue._type === 'object') {
245
+ const reconstructed = {};
246
+ const promises = currentValue._keys.map(async (key) => {
247
+ const keyValue = await this.storage.retrieve(`${fullKey}:${key}`, options);
248
+ reconstructed[key] = keyValue;
249
+ });
250
+ await Promise.all(promises);
251
+ mergedValue = { ...reconstructed, ...value };
252
+ } else {
253
+ mergedValue = { ...currentValue, ...value };
254
+ }
255
+ } else {
256
+ mergedValue = value;
257
+ }
258
+
259
+ // Use put instead of update to ensure proper object decomposition
260
+ await this.put(mergedValue, options);
261
+
262
+ // Emit update event
263
+ this.emit('update', { key: fullKey, value: mergedValue });
264
+
265
+ return this;
266
+ }
267
+
268
+ /**
269
+ * Create a proxied interface that allows property access
270
+ * @returns {Proxy} Proxied interface
271
+ */
272
+ proxy() {
273
+ return new Proxy(this, {
274
+ get(target, prop) {
275
+ // If it's a method, return it bound
276
+ if (typeof target[prop] === 'function') {
277
+ return target[prop].bind(target);
278
+ }
279
+
280
+ // If it's a property access, create a new get() call
281
+ if (typeof prop === 'string' && !prop.startsWith('_') && prop !== 'constructor') {
282
+ return target.get(prop).proxy();
283
+ }
284
+
285
+ return target[prop];
286
+ }
287
+ });
288
+ }
289
+
290
+ /**
291
+ * Get the current path as a string
292
+ * @returns {string} The path
293
+ */
294
+ getPath() {
295
+ return this.path.join(':');
296
+ }
297
+
298
+ /**
299
+ * Check if a value exists at the current path
300
+ * @returns {Promise<boolean>} Whether the value exists
301
+ */
302
+ async exists() {
303
+ const fullKey = this.path.join(':');
304
+ const value = await this.storage.retrieve(fullKey);
305
+ return value !== null && value !== undefined;
306
+ }
307
+
308
+ /**
309
+ * Get all keys under the current path (for object-like structures)
310
+ * @returns {Promise<string[]>} Array of keys
311
+ */
312
+ async keys() {
313
+ const fullKey = this.path.join(':');
314
+ const value = await this.storage.retrieve(fullKey);
315
+
316
+ if (value && typeof value === 'object' && value._keys && value._type === 'object') {
317
+ return value._keys;
318
+ }
319
+
320
+ return [];
321
+ }
322
+ }
323
+
324
+ /**
325
+ * Create a lexical interface for the distributed storage
326
+ * @param {DistributedStorageManager} distributedStorage
327
+ * @returns {Proxy} Proxied lexical interface
328
+ */
329
+ export function createLexicalInterface(distributedStorage) {
330
+ const lexicalInterface = new LexicalStorageInterface(distributedStorage);
331
+ return lexicalInterface.proxy();
332
+ }