@coasys/ad4m 0.13.0-test-1 → 0.13.0-test-2

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 (94) hide show
  1. package/lib/index.cjs +1392 -777
  2. package/lib/index.js +1376 -775
  3. package/lib/src/Literal.js +6 -5
  4. package/lib/src/agent/AgentClient.d.ts +5 -1
  5. package/lib/src/agent/AgentClient.js +48 -2
  6. package/lib/src/expression/ExpressionRef.js +2 -2
  7. package/lib/src/language/Language.d.ts +41 -3
  8. package/lib/src/model/Ad4mModel.d.ts +28 -28
  9. package/lib/src/model/Ad4mModel.js +129 -101
  10. package/lib/src/model/Ad4mModel.test.js +1543 -535
  11. package/lib/src/model/ModelQueryBuilder.d.ts +48 -34
  12. package/lib/src/model/ModelQueryBuilder.js +163 -78
  13. package/lib/src/model/Subject.js +6 -6
  14. package/lib/src/model/decorators.d.ts +14 -8
  15. package/lib/src/model/decorators.js +41 -14
  16. package/lib/src/model/hydration-batch.d.ts +34 -0
  17. package/lib/src/model/hydration-batch.js +147 -0
  18. package/lib/src/model/hydration.d.ts +3 -3
  19. package/lib/src/model/hydration.js +106 -36
  20. package/lib/src/model/index.d.ts +4 -1
  21. package/lib/src/model/index.js +4 -1
  22. package/lib/src/model/json-schema.js +2 -2
  23. package/lib/src/model/query-cache.d.ts +30 -0
  24. package/lib/src/model/query-cache.js +66 -0
  25. package/lib/src/model/query-cache.test.d.ts +1 -0
  26. package/lib/src/model/query-cache.test.js +43 -0
  27. package/lib/src/model/query-common.d.ts +1 -1
  28. package/lib/src/model/query-common.js +1 -1
  29. package/lib/src/model/query-sparql-batch.d.ts +17 -0
  30. package/lib/src/model/query-sparql-batch.js +260 -0
  31. package/lib/src/model/query-sparql.d.ts +47 -0
  32. package/lib/src/model/query-sparql.js +336 -0
  33. package/lib/src/model/query-utils.d.ts +45 -0
  34. package/lib/src/model/query-utils.js +140 -0
  35. package/lib/src/model/relation-filtering.test.js +15 -15
  36. package/lib/src/model/sdna.js +1 -1
  37. package/lib/src/model/shacl-gen.js +42 -18
  38. package/lib/src/model/subscription-pool.d.ts +39 -0
  39. package/lib/src/model/subscription-pool.js +119 -0
  40. package/lib/src/model/types.d.ts +3 -3
  41. package/lib/src/model/types.js +1 -1
  42. package/lib/src/perspectives/PerspectiveClient.d.ts +1 -17
  43. package/lib/src/perspectives/PerspectiveClient.js +5 -57
  44. package/lib/src/perspectives/PerspectiveProxy.d.ts +51 -30
  45. package/lib/src/perspectives/PerspectiveProxy.js +224 -177
  46. package/lib/src/perspectives/PerspectiveResolver.d.ts +0 -1
  47. package/lib/src/perspectives/PerspectiveResolver.js +0 -11
  48. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +3 -3
  49. package/lib/src/perspectives/WakerSubscriptionManager.js +7 -8
  50. package/lib/src/runtime/RuntimeResolver.d.ts +11 -0
  51. package/lib/src/runtime/RuntimeResolver.js +56 -0
  52. package/lib/src/schema.gql +11 -1
  53. package/lib/src/shacl/SHACLFlow.d.ts +1 -1
  54. package/lib/src/shacl/SHACLFlow.js +9 -9
  55. package/lib/src/shacl/SHACLShape.d.ts +1 -1
  56. package/lib/src/shacl/SHACLShape.js +38 -38
  57. package/lib/src/typeDefs.js +11 -1
  58. package/lib/src/utils.d.ts +6 -6
  59. package/lib/src/utils.js +6 -6
  60. package/package.json +1 -1
  61. package/src/Literal.test.ts +10 -5
  62. package/src/Literal.ts +6 -5
  63. package/src/agent/AgentClient.ts +53 -1
  64. package/src/expression/ExpressionRef.ts +2 -2
  65. package/src/language/Language.ts +48 -3
  66. package/src/model/Ad4mModel.test.ts +1515 -565
  67. package/src/model/Ad4mModel.ts +142 -102
  68. package/src/model/ModelQueryBuilder.ts +185 -86
  69. package/src/model/Subject.ts +6 -6
  70. package/src/model/decorators.ts +51 -22
  71. package/src/model/hydration-batch.ts +205 -0
  72. package/src/model/hydration.ts +102 -39
  73. package/src/model/index.ts +4 -1
  74. package/src/model/json-schema.ts +2 -2
  75. package/src/model/query-cache.test.ts +54 -0
  76. package/src/model/query-cache.ts +79 -0
  77. package/src/model/query-common.ts +1 -1
  78. package/src/model/query-sparql-batch.ts +301 -0
  79. package/src/model/query-sparql.ts +363 -0
  80. package/src/model/{surreal-utils.ts → query-utils.ts} +40 -27
  81. package/src/model/relation-filtering.test.ts +15 -15
  82. package/src/model/sdna.ts +1 -1
  83. package/src/model/shacl-gen.ts +42 -17
  84. package/src/model/subscription-pool.ts +163 -0
  85. package/src/model/types.ts +3 -3
  86. package/src/perspectives/PerspectiveClient.ts +5 -61
  87. package/src/perspectives/PerspectiveProxy.ts +226 -181
  88. package/src/perspectives/PerspectiveResolver.ts +0 -8
  89. package/src/perspectives/WakerSubscriptionManager.ts +8 -9
  90. package/src/runtime/RuntimeResolver.ts +43 -0
  91. package/src/shacl/SHACLFlow.ts +9 -9
  92. package/src/shacl/SHACLShape.ts +39 -39
  93. package/src/utils.ts +6 -6
  94. package/src/model/query-surreal.ts +0 -280
@@ -430,16 +430,16 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
430
430
  });
431
431
  });
432
432
 
433
- describe("Ad4mModel.queryToSurrealQL()", () => {
434
- // Mock perspective proxy (minimal since queryToSurrealQL doesn't actually call it)
433
+
434
+
435
+
436
+ describe("Ad4mModel.queryToSPARQL()", () => {
435
437
  const mockPerspective = {} as any;
436
438
 
437
- // Helper function to normalize whitespace in queries for easier comparison
438
439
  function normalizeQuery(query: string): string {
439
440
  return query.replace(/\s+/g, ' ').trim();
440
441
  }
441
442
 
442
- // Test Recipe model — explicit required: true to test required-property query filters
443
443
  @Model({ name: "Recipe" })
444
444
  class Recipe extends Ad4mModel {
445
445
  @Property({ through: "recipe://name", required: true })
@@ -452,403 +452,182 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
452
452
  ingredients: string[] = [];
453
453
  }
454
454
 
455
- it("should generate basic query with no filters", async () => {
456
- const query = await Recipe.queryToSurrealQL(mockPerspective, {});
455
+ it("should generate basic SPARQL query with no filters", async () => {
456
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, {});
457
+ const norm = normalizeQuery(query);
457
458
 
458
- expect(query).toContain("id AS source");
459
- expect(query).toContain("uri AS source_uri");
460
- expect(query).toContain("FROM node");
461
- expect(query).toContain("->link AS links");
462
- expect(query).toContain("WHERE");
463
- // Should have graph traversal filters for required properties
464
- expect(query).toContain("count(->link[WHERE");
459
+ // Must be a SPARQL SELECT
460
+ expect(norm).toContain("SELECT ?source ?predicate ?target ?author ?timestamp");
461
+ // Must have conformance JOIN for required properties using direct triple patterns
462
+ expect(norm).toContain("cfTarget_name");
463
+ expect(norm).toContain("recipe://name");
465
464
  });
466
465
 
467
466
  it("should generate query with simple property filter", async () => {
468
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: "Pasta" } });
469
-
470
- // Should have graph traversal filters for required properties and user filter
471
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name']) > 0");
472
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating']) > 0");
473
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
474
- });
475
-
476
- it("should generate query with multiple property filters", async () => {
477
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: "Pasta", rating: 5 } });
478
-
479
- expect(query).toContain("WHERE");
480
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
481
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating' AND fn::parse_literal(out.uri) = 5]) > 0");
482
- expect(query).toContain("AND");
483
- });
484
-
485
- it("should handle gt operator (filtered in JavaScript, not SQL)", async () => {
486
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { gt: 4 } } });
487
-
488
- // Comparison operators for regular properties are now filtered in JavaScript post-query
489
- // The SQL just filters on the predicate existing
490
- expect(query).toContain("FROM node");
491
-
492
- // Should NOT contain comparison operators in SQL for regular properties
493
- expect(query).not.toContain("target > 4");
494
- });
495
-
496
- it("should handle lt operator (filtered in JavaScript, not SQL)", async () => {
497
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { lt: 3 } } });
498
-
499
- // Comparison operators are filtered in JavaScript post-query
500
- expect(query).toContain("FROM node");
501
- expect(query).not.toContain("target < 3");
502
- });
503
-
504
- it("should handle gte and lte operators (filtered in JavaScript, not SQL)", async () => {
505
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { gte: 3, lte: 5 } } });
506
-
507
- // Comparison operators are filtered in JavaScript post-query
508
- expect(query).toContain("FROM node");
509
- expect(query).not.toContain("target >= 3");
510
- expect(query).not.toContain("target <= 5");
511
- });
512
-
513
- it("should handle not operator with single value", async () => {
514
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { not: "Salad" } } });
515
-
516
- // Not operator uses graph traversal with count = 0
517
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Salad']) = 0");
518
- });
519
-
520
- it("should handle not operator with array (NOT IN)", async () => {
521
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { not: ["Salad", "Soup"] } } });
522
-
523
- // Not operator with array uses graph traversal with count = 0
524
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) IN ['Salad', 'Soup']]) = 0");
525
- });
526
-
527
- it("should handle between operator (filtered in JavaScript, not SQL)", async () => {
528
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { between: [3, 5] } } });
529
-
530
- // Between operator for regular properties is now filtered in JavaScript post-query
531
- expect(query).toContain("FROM node");
532
- expect(query).not.toContain("target >= 3");
533
- expect(query).not.toContain("target <= 5");
534
- });
535
-
536
- it("should handle contains operator on string property (filtered in JavaScript, not SQL)", async () => {
537
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { contains: "Past" } } });
538
-
539
- // Contains operator for regular properties is now filtered in JavaScript post-query
540
- expect(query).toContain("FROM node");
541
- expect(query).not.toContain("target CONTAINS 'Past'");
542
- });
543
-
544
- it("should handle contains operator on regular property with substring (filtered in JavaScript, not SQL)", async () => {
545
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { contains: "Salad" } } });
546
-
547
- // Contains operator is filtered in JavaScript post-query
548
- expect(query).toContain("FROM node");
549
- expect(query).not.toContain("target CONTAINS 'Salad'");
550
- });
551
-
552
- it.skip("should handle contains operator on special field (author)", async () => {
553
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { author: { contains: "alice" } } });
554
-
555
- expect(query).toContain("WHERE author CONTAINS 'alice'");
556
- // Should not use a subquery pattern
557
- expect(query).not.toContain("SELECT source FROM node");
558
- });
559
-
560
- it.skip("should handle contains operator on special field (id)", async () => {
561
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { contains: "test" } } });
562
-
563
- expect(query).toContain("WHERE source CONTAINS 'test'");
564
- });
565
-
566
- it("should handle array values (IN clause)", async () => {
567
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: ["Pasta", "Pizza"] } });
568
-
569
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) IN ['Pasta', 'Pizza']]) > 0");
570
- });
571
-
572
- it.skip("should handle special fields (author, timestamp) without subqueries", async () => {
573
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { author: "did:key:alice" } });
574
-
575
- expect(query).toContain("WHERE author = 'did:key:alice'");
576
- // Ensure it's NOT using a subquery pattern for author in WHERE clause
577
- expect(normalizeQuery(query)).not.toMatch(/WHERE.*source IN.*SELECT source FROM node.*author/);
578
- });
579
-
580
- it("should not generate ORDER BY clause in SQL (handled in JavaScript)", async () => {
581
- const query = await Recipe.queryToSurrealQL(mockPerspective, { order: { timestamp: "DESC" } });
582
-
583
- // ORDER BY is now handled in JavaScript post-query
584
- expect(query).toContain("FROM node");
585
- expect(query).not.toContain("ORDER BY");
586
- });
467
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: "Pasta" } });
468
+ const norm = normalizeQuery(query);
587
469
 
588
- it("should not generate LIMIT clause in SQL (handled in JavaScript)", async () => {
589
- const query = await Recipe.queryToSurrealQL(mockPerspective, { limit: 10 });
590
-
591
- // LIMIT is now handled in JavaScript post-query
592
- expect(query).toContain("FROM node");
593
- expect(query).not.toContain("LIMIT");
470
+ expect(norm).toContain("SELECT ?source ?predicate ?target ?author ?timestamp");
471
+ // For literal-stored properties, SPARQL only adds a JOIN (no FILTER value) — filtering is in JS
472
+ expect(norm).toContain("recipe://name");
473
+ // Value should NOT be in SPARQL — filtering happens in JS post-filter
474
+ expect(norm).toContain("?wTarget_name");
594
475
  });
595
476
 
596
- it("should not generate START clause in SQL (handled in JavaScript)", async () => {
597
- const query = await Recipe.queryToSurrealQL(mockPerspective, { offset: 20 });
477
+ it("should generate query with NOT operator", async () => {
478
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: { not: "Salad" } } });
479
+ const norm = normalizeQuery(query);
598
480
 
599
- // START/offset is now handled in JavaScript post-query
600
- expect(query).toContain("FROM node");
601
- expect(query).not.toContain("START");
481
+ // For literal-stored properties, NOT filtering is done in JS — no NOT EXISTS in SPARQL
482
+ expect(norm).toContain("recipe://name");
602
483
  });
603
484
 
604
- it("should generate complete query with all options (ORDER BY, LIMIT, START handled in JS)", async () => {
605
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
606
- where: { name: "Pasta", rating: { gt: 4 } },
607
- order: { timestamp: "DESC" },
608
- limit: 10,
609
- offset: 20
610
- });
485
+ it("should generate query with NOT IN operator (array)", async () => {
486
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: { not: ["Salad", "Soup"] } } });
487
+ const norm = normalizeQuery(query);
611
488
 
612
- // WHERE clause uses graph traversal filters
613
- expect(query).toContain("WHERE");
614
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
615
- // Comparison operators (gt) are filtered in JavaScript, not SQL
616
- expect(query).not.toContain("out.uri > 4");
617
- expect(query).not.toContain("target > 4");
618
- // ORDER BY, LIMIT, START are now handled in JavaScript post-query
619
- expect(query).not.toContain("ORDER BY");
620
- expect(query).not.toContain("LIMIT");
621
- expect(query).not.toContain("START");
489
+ // For literal-stored properties, NOT IN filtering is done in JS — no filter values in SPARQL
490
+ expect(norm).toContain("recipe://name");
622
491
  });
623
492
 
624
- it("should only select requested properties", async () => {
625
- const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name"] });
493
+ it("should generate query with IN clause (array values)", async () => {
494
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: ["Pasta", "Pizza"] } });
495
+ const norm = normalizeQuery(query);
626
496
 
627
- // With array::group(), all link data is selected, filtering happens in instancesFromSurrealResult
628
- expect(query).toContain("->link AS links");
629
-
497
+ // For literal-stored properties, IN filtering is done in JS — only a JOIN exists
498
+ expect(norm).toContain("recipe://name");
499
+ expect(norm).toContain("?wTarget_name");
630
500
  });
631
501
 
632
- it("should select all link data for relations", async () => {
633
- @Model({ name: "MultiRelationModel" })
634
- class MultiRelationModel extends Ad4mModel {
635
- @HasMany({ through: "test://coll1" })
636
- coll1: string[] = [];
637
-
638
- @HasMany({ through: "test://coll2" })
639
- coll2: string[] = [];
640
- }
641
-
642
- const query = await MultiRelationModel.queryToSurrealQL(mockPerspective, {});
502
+ it("should generate query with base filter", async () => {
503
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { base: "ad4m://test123" } });
504
+ const norm = normalizeQuery(query);
643
505
 
644
- // With array::group(), all link data is selected
645
- expect(query).toContain("->link AS links");
646
-
506
+ expect(norm).toContain("?source =");
507
+ expect(norm).toContain("ad4m://test123");
647
508
  });
648
509
 
649
- it("should escape single quotes in string values", async () => {
650
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: "O'Brien's Recipe" } });
651
-
652
- // Single quotes are escaped with backslash in SurrealDB
653
- expect(query).toContain("O\\'Brien\\'s Recipe");
654
- });
510
+ it("should escape special characters in SPARQL strings", async () => {
511
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: 'O\'Brien' } });
512
+ const norm = normalizeQuery(query);
655
513
 
656
- it("should handle numeric values without quotes", async () => {
657
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: 5 } });
658
-
659
- // Numeric values should not have quotes around them
660
- expect(query).toContain("fn::parse_literal(out.uri) = 5");
661
- expect(query).not.toContain("fn::parse_literal(out.uri) = '5'");
514
+ // Should not break the query
515
+ expect(norm).toContain("SELECT ?source");
662
516
  });
663
517
 
664
- it("should handle complex nested query (comparisons, ORDER BY, LIMIT handled in JS)", async () => {
665
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
666
- where: {
667
- name: "Pasta",
668
- rating: { gte: 4, lte: 5 },
669
- author: "did:key:alice"
670
- },
671
- order: { rating: "DESC" },
672
- limit: 5
673
- });
518
+ // =========================================================================
519
+ // Additional models for thorough SPARQL structure tests
520
+ // =========================================================================
674
521
 
675
- const normalized = normalizeQuery(query);
522
+ @Model({ name: "Task" })
523
+ class Task extends Ad4mModel {
524
+ @Property({ through: "task://title", resolveLanguage: "literal", required: true })
525
+ title: string = "";
676
526
 
677
- // Verify graph traversal filters are present
678
- expect(normalized).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
679
- // Comparison operators (gte, lte) are filtered in JavaScript, not SQL
680
- expect(normalized).not.toContain("out.uri >= 4");
681
- expect(normalized).not.toContain("target >= 4");
682
- expect(normalized).not.toContain("out.uri <= 5");
683
- expect(normalized).not.toContain("target <= 5");
684
- // author and timestamp filtering is done in JavaScript post-query
685
- expect(normalized).not.toContain("author = 'did:key:alice'");
527
+ @Property({ through: "task://priority", resolveLanguage: "literal" })
528
+ priority: number = 0;
686
529
 
687
- // ORDER BY and LIMIT are handled in JavaScript post-query
688
- expect(normalized).not.toContain("ORDER BY");
689
- expect(normalized).not.toContain("LIMIT");
530
+ @Property({ through: "task://done", resolveLanguage: "literal" })
531
+ done: boolean = false;
690
532
 
691
- // Verify query structure (FROM node, no GROUP BY)
692
- expect(normalized).toContain("FROM node");
693
- });
533
+ @Optional({ through: "task://description" })
534
+ description: string = "";
694
535
 
695
- it("should handle empty query object", async () => {
696
- const query = await Recipe.queryToSurrealQL(mockPerspective, {});
697
-
698
- // Should generate valid query with WHERE clause for required properties (name and rating)
699
- expect(query).toContain("id AS source");
700
- expect(query).toContain("uri AS source_uri");
701
- expect(query).toContain("FROM node");
702
-
703
- // Should have WHERE clause filtering for required properties using graph traversal
704
- expect(query).toContain("WHERE");
705
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://name']) > 0");
706
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating']) > 0");
707
- expect(query).not.toContain("ORDER BY");
708
- expect(query).not.toContain("START");
709
- });
536
+ @HasMany({ through: "task://tag" })
537
+ tags: string[] = [];
710
538
 
711
- it("should handle id special field", async () => {
712
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: "literal://test" } });
713
-
714
- expect(query).toContain("uri = 'literal://test'");
715
- });
539
+ @HasMany({ through: "task://assignee" })
540
+ assignees: string[] = [];
541
+ }
716
542
 
717
- it("should handle id special field with array (IN clause)", async () => {
718
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: ["literal://test1", "literal://test2"] } });
719
-
720
- expect(query).toContain("uri IN ['literal://test1', 'literal://test2']");
721
- });
543
+ @Model({ name: "EmptyModel" })
544
+ class EmptyModel extends Ad4mModel {
545
+ @Optional({ through: "empty://optField" })
546
+ optField: string = "";
547
+ }
722
548
 
723
- it("should handle id special field with not operator", async () => {
724
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { not: "literal://test" } } });
725
-
726
- expect(query).toContain("uri != 'literal://test'");
727
- });
549
+ // ---- Comparison operators (gt, lt, gte, lte, between, contains) ----
550
+ // These are handled in JS post-processing, NOT in SPARQL.
551
+ // The tests verify that the SPARQL still generates valid output (conformance filters)
552
+ // but does NOT inject FILTER clauses for these operators.
728
553
 
729
- it("should handle id special field with not operator and array (NOT IN)", async () => {
730
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { not: ["literal://test1", "literal://test2"] } } });
731
-
732
- expect(query).toContain("uri NOT IN ['literal://test1', 'literal://test2']");
554
+ it("should inject SPARQL FILTER for gt operator", async () => {
555
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { rating: { gt: 3 } } });
556
+ const norm = normalizeQuery(query);
557
+ expect(norm).toContain("SELECT ?source");
558
+ // gt is now handled via JS post-filter — SPARQL just joins the property
559
+ expect(norm).toContain("wTarget_cmp_rating");
733
560
  });
734
561
 
735
- it("should handle id special field with between operator", async () => {
736
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { between: ["literal://a", "literal://z"] } } } as any);
737
-
738
- const normalized = normalizeQuery(query);
739
- expect(normalized).toContain("uri >= 'literal://a' AND uri <= 'literal://z'");
562
+ it("should inject SPARQL FILTER for lt operator", async () => {
563
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { rating: { lt: 5 } } });
564
+ const norm = normalizeQuery(query);
565
+ expect(norm).toContain("SELECT ?source");
566
+ // lt is now handled via JS post-filter
567
+ expect(norm).toContain("wTarget_cmp_rating");
740
568
  });
741
569
 
742
- it("should handle id special field with gt operator", async () => {
743
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { gt: "literal://m" } } } as any);
744
-
745
- expect(query).toContain("uri > 'literal://m'");
570
+ it("should inject SPARQL FILTER for gte/lte combined", async () => {
571
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { rating: { gte: 2, lte: 8 } } });
572
+ const norm = normalizeQuery(query);
573
+ expect(norm).toContain("SELECT ?source");
574
+ // gte/lte are now handled via JS post-filter
575
+ expect(norm).toContain("wTarget_cmp_rating");
746
576
  });
747
577
 
748
- it("should handle id special field with gte and lte operators", async () => {
749
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { gte: "literal://a", lte: "literal://z" } } } as any);
750
-
751
- const normalized = normalizeQuery(query);
752
- expect(normalized).toContain("uri >= 'literal://a'");
753
- expect(normalized).toContain("uri <= 'literal://z'");
578
+ it("should inject SPARQL FILTER for between operator", async () => {
579
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { rating: { between: [1, 10] } } });
580
+ const norm = normalizeQuery(query);
581
+ expect(norm).toContain("SELECT ?source");
582
+ // between is now handled via JS post-filter
583
+ expect(norm).toContain("wTarget_cmp_rating");
754
584
  });
755
585
 
756
- it("should handle timestamp special field with gt operator (filtered in JavaScript)", async () => {
757
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { timestamp: { gt: 1234567890 } } });
758
-
759
- // timestamp filtering is done in JavaScript post-query
760
- expect(query).toContain("FROM node");
761
- expect(query).not.toContain("timestamp > 1234567890");
586
+ it("should inject SPARQL FILTER for contains operator", async () => {
587
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { where: { name: { contains: "pasta" } } });
588
+ const norm = normalizeQuery(query);
589
+ expect(norm).toContain("SELECT ?source");
590
+ // contains is now handled via JS post-filter
591
+ expect(norm).toContain("wTarget_cmp_name");
762
592
  });
763
593
 
764
- it("should handle multiple special fields (filtered in JavaScript)", async () => {
765
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
766
- where: {
767
- author: "did:key:alice",
768
- timestamp: { gt: 1000 }
769
- }
770
- });
771
-
772
- // author and timestamp filtering is done in JavaScript post-query
773
- expect(query).toContain("FROM node");
774
- expect(query).not.toContain("author = 'did:key:alice'");
775
- expect(query).not.toContain("timestamp > 1000");
776
- });
594
+ // ---- Multiple property filters combined ----
777
595
 
778
- it("should handle mixed special and regular properties", async () => {
779
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
780
- where: {
781
- name: "Pasta",
782
- author: "did:key:alice",
783
- rating: { gt: 4 }
784
- }
596
+ it("should combine multiple property equality filters with &&", async () => {
597
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, {
598
+ where: { name: "Pasta", rating: ["4", "5"] }
785
599
  });
786
-
787
- const normalized = normalizeQuery(query);
788
- // Regular properties use graph traversal filters
789
- expect(normalized).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
790
- // Comparison operators (gt) are filtered in JavaScript, not SQL
791
- expect(normalized).not.toContain("out.uri > 4");
792
- expect(normalized).not.toContain("target > 4");
793
- // author filtering is done in JavaScript post-query
794
- expect(normalized).not.toContain("author = 'did:key:alice'");
795
- });
796
-
797
- it("should handle boolean values", async () => {
798
- @Model({ name: "Task" })
799
- class Task extends Ad4mModel {
800
- @Property({ through: "task://completed" })
801
- completed: boolean = false;
802
- }
803
-
804
- const query = await Task.queryToSurrealQL(mockPerspective, { where: { completed: true } });
805
-
806
- expect(query).toContain("fn::parse_literal(out.uri) = true");
807
- });
808
-
809
- it("should handle array of numbers", async () => {
810
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: [4, 5] } });
811
-
812
- expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating' AND fn::parse_literal(out.uri) IN [4, 5]]) > 0");
600
+ const norm = normalizeQuery(query);
601
+ // Should have EXISTS blocks for both name and rating
602
+ expect(norm).toContain("recipe://name");
603
+ expect(norm).toContain("recipe://rating");
604
+ expect(norm).toContain("&&");
813
605
  });
814
606
 
815
- it("should skip unknown properties in where clause", async () => {
816
- const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { unknownProp: "value" } as any });
817
-
818
- // Should not throw error, just skip the unknown property
819
- expect(query).toContain("source");
820
-
821
- // Should not contain any condition for unknownProp
822
- expect(query).not.toContain("unknownProp");
823
- });
607
+ // ---- ORDER BY, LIMIT, OFFSET are JS post-processed ----
824
608
 
825
- it.skip("should skip unknown properties in select clause", async () => {
826
- const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name", "unknownProp"] as any });
827
-
828
- // Should include name using aggregation
829
- expect(query).toContain("array::first(target[WHERE predicate = 'recipe://name']) AS name");
830
- // Should not error on unknownProp, just skip it
831
- expect(query).not.toContain("unknownProp");
609
+ it("should not include ORDER BY in SPARQL (JS post-processed)", async () => {
610
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { order: { name: "ASC" } });
611
+ const norm = normalizeQuery(query);
612
+ expect(norm).toContain("SELECT ?source");
613
+ expect(norm).not.toContain("ORDER BY");
832
614
  });
833
615
 
834
- it("should handle order by regular property (handled in JavaScript)", async () => {
835
- const query = await Recipe.queryToSurrealQL(mockPerspective, { order: { name: "ASC" } });
836
-
837
- // ORDER BY is now handled in JavaScript post-query
838
- expect(query).toContain("FROM node");
839
- expect(query).not.toContain("ORDER BY");
616
+ it("should not include LIMIT in SPARQL (JS post-processed)", async () => {
617
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { limit: 10 });
618
+ const norm = normalizeQuery(query);
619
+ expect(norm).toContain("SELECT ?source");
620
+ expect(norm).not.toContain("LIMIT");
840
621
  });
841
622
 
842
- it("should generate query with only properties specified", async () => {
843
- const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name", "rating"] });
844
-
845
- // With array::group(), all link data is selected, filtering happens in instancesFromSurrealResult
846
- expect(query).toContain("->link AS links");
847
-
623
+ it("should not include OFFSET in SPARQL (JS post-processed)", async () => {
624
+ const query = await (Recipe as any).queryToSPARQL(mockPerspective, { offset: 5 });
625
+ const norm = normalizeQuery(query);
626
+ expect(norm).toContain("SELECT ?source");
627
+ expect(norm).not.toContain("OFFSET");
848
628
  });
849
629
  });
850
-
851
- describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", () => {
630
+ describe("Ad4mModel.instancesFromQueryResult() and SPARQL integration", () => {
852
631
  // Test Recipe model
853
632
  @Model({ name: "Recipe" })
854
633
  class Recipe extends Ad4mModel {
@@ -862,9 +641,9 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
862
641
  ingredients: string[] = [];
863
642
  }
864
643
 
865
- // Mock perspective with both querySurrealDB and infer methods
644
+ // Mock perspective with both querySparql and infer methods
866
645
  const mockPerspective = {
867
- querySurrealDB: jest.fn(),
646
+ querySparql: jest.fn(),
868
647
  infer: jest.fn(),
869
648
  uuid: 'test-perspective-uuid',
870
649
  stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
@@ -874,18 +653,18 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
874
653
  jest.clearAllMocks();
875
654
  });
876
655
 
877
- it("should convert empty SurrealDB results correctly", async () => {
878
- const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, []);
656
+ it("should convert empty query results correctly", async () => {
657
+ const result = await Recipe.instancesFromQueryResult(mockPerspective, {}, []);
879
658
 
880
659
  expect(result.results).toEqual([]);
881
660
  expect(result.totalCount).toBe(0);
882
661
  });
883
662
 
884
- it("should convert SurrealDB results to model instances", async () => {
885
- const surrealResults = [
663
+ it("should convert query results to model instances", async () => {
664
+ const queryResults = [
886
665
  {
887
666
  source: "node:abc123",
888
- source_uri: "literal://recipe1",
667
+ source_uri: "literal:recipe1",
889
668
  links: [
890
669
  { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
891
670
  { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
@@ -896,7 +675,7 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
896
675
  },
897
676
  {
898
677
  source: "node:def456",
899
- source_uri: "literal://recipe2",
678
+ source_uri: "literal:recipe2",
900
679
  links: [
901
680
  { predicate: "recipe://name", target: "Pizza", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
902
681
  { predicate: "recipe://rating", target: "4", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
@@ -907,7 +686,7 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
907
686
  }
908
687
  ];
909
688
 
910
- const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, surrealResults);
689
+ const result = await Recipe.instancesFromQueryResult(mockPerspective, {}, queryResults);
911
690
 
912
691
  expect(result.results).toHaveLength(2);
913
692
  expect(result.totalCount).toBe(2);
@@ -925,10 +704,10 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
925
704
  });
926
705
 
927
706
  it("should filter properties when query specifies properties", async () => {
928
- const surrealResults = [
707
+ const queryResults = [
929
708
  {
930
709
  source: "node:abc123",
931
- source_uri: "literal://recipe1",
710
+ source_uri: "literal:recipe1",
932
711
  links: [
933
712
  { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
934
713
  { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
@@ -938,10 +717,10 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
938
717
  }
939
718
  ];
940
719
 
941
- const result = await Recipe.instancesFromSurrealResult(
720
+ const result = await Recipe.instancesFromQueryResult(
942
721
  mockPerspective,
943
722
  { properties: ["name"] },
944
- surrealResults
723
+ queryResults
945
724
  );
946
725
 
947
726
  expect(result.results).toHaveLength(1);
@@ -956,10 +735,10 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
956
735
  });
957
736
 
958
737
  it("should filter properties when query specifies properties", async () => {
959
- const surrealResults = [
738
+ const queryResults = [
960
739
  {
961
740
  source: "node:abc123",
962
- source_uri: "literal://recipe1",
741
+ source_uri: "literal:recipe1",
963
742
  links: [
964
743
  { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
965
744
  { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
@@ -969,10 +748,10 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
969
748
  }
970
749
  ];
971
750
 
972
- const result = await Recipe.instancesFromSurrealResult(
751
+ const result = await Recipe.instancesFromQueryResult(
973
752
  mockPerspective,
974
753
  { properties: ["name"] },
975
- surrealResults
754
+ queryResults
976
755
  );
977
756
 
978
757
  expect(result.results).toHaveLength(1);
@@ -983,7 +762,7 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
983
762
  });
984
763
 
985
764
  it("should handle results missing base field", async () => {
986
- const surrealResults = [
765
+ const queryResults = [
987
766
  {
988
767
  links: [
989
768
  { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
@@ -993,40 +772,35 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
993
772
  } as any
994
773
  ];
995
774
 
996
- const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, surrealResults);
775
+ const result = await Recipe.instancesFromQueryResult(mockPerspective, {}, queryResults);
997
776
 
998
777
  // Should filter out the invalid result (or handle gracefully)
999
778
  expect(result.results).toHaveLength(0);
1000
779
  expect(result.totalCount).toBe(0);
1001
780
  });
1002
781
 
1003
- it("should use SurrealDB by default in findAll()", async () => {
1004
- const surrealResults = [
1005
- {
1006
- source: "node:abc123",
1007
- source_uri: "literal://recipe1",
1008
- links: [
1009
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1010
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1011
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1012
- ]
1013
- }
782
+ it("should use SPARQL when engine is 'sparql' in findAll()", async () => {
783
+ // Raw SPARQL rows (flat) — groupSPARQLResults will group them
784
+ const queryResults = [
785
+ { source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
786
+ { source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
787
+ { source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1014
788
  ];
1015
789
 
1016
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
790
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
1017
791
 
1018
- const results = await Recipe.findAll(mockPerspective, {});
792
+ const results = await Recipe.findAll(mockPerspective, {}, 'sparql');
1019
793
 
1020
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
794
+ expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
1021
795
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1022
796
  expect(results).toHaveLength(1);
1023
797
  expect(results[0].name).toBe("Pasta");
1024
798
  });
1025
799
 
1026
- it("should use Prolog when useSurrealDB is false in findAll()", async () => {
800
+ it("should use Prolog when engine is prolog in findAll()", async () => {
1027
801
  const prologResults = [{
1028
802
  AllInstances: [
1029
- ["literal://recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
803
+ ["literal:recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
1030
804
  ],
1031
805
  TotalCount: 1
1032
806
  }];
@@ -1036,118 +810,99 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
1036
810
  const results = await Recipe.findAll(mockPerspective, {}, false);
1037
811
 
1038
812
  expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1039
- expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
813
+ expect(mockPerspective.querySparql).not.toHaveBeenCalled();
1040
814
  expect(results).toHaveLength(1);
1041
815
  });
1042
816
 
1043
- it("should use SurrealDB by default in findAllAndCount()", async () => {
1044
- const surrealResults = [
1045
- {
1046
- source: "node:abc123",
1047
- source_uri: "literal://recipe1",
1048
- links: [
1049
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1050
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1051
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1052
- ]
1053
- }
817
+ it("should use SPARQL when engine is 'sparql' in findAllAndCount()", async () => {
818
+ const queryResults = [
819
+ { source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
820
+ { source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
821
+ { source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1054
822
  ];
1055
823
 
1056
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
824
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
1057
825
 
1058
- const { results, totalCount } = await Recipe.findAllAndCount(mockPerspective, {});
826
+ const { results, totalCount } = await Recipe.findAllAndCount(mockPerspective, {}, 'sparql');
1059
827
 
1060
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
828
+ expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
1061
829
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1062
830
  expect(results).toHaveLength(1);
1063
831
  expect(totalCount).toBe(1);
1064
832
  });
1065
833
 
1066
- it("should use SurrealDB by default in paginate()", async () => {
1067
- const surrealResults = [
1068
- {
1069
- source: "node:abc123",
1070
- source_uri: "literal://recipe1",
1071
- links: [
1072
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1073
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1074
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1075
- ]
1076
- }
834
+ it("should use SPARQL when engine is 'sparql' in paginate()", async () => {
835
+ const queryResults = [
836
+ { source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
837
+ { source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
838
+ { source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1077
839
  ];
1078
840
 
1079
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
841
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
1080
842
 
1081
- const page = await Recipe.paginate(mockPerspective, 10, 1, {});
843
+ const page = await Recipe.paginate(mockPerspective, 10, 1, {}, 'sparql');
1082
844
 
1083
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
845
+ expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
1084
846
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1085
847
  expect(page.results).toHaveLength(1);
1086
848
  expect(page.pageSize).toBe(10);
1087
849
  expect(page.pageNumber).toBe(1);
1088
850
  });
1089
851
 
1090
- it("should use SurrealDB by default in count()", async () => {
852
+ it("should use SPARQL when engine is 'sparql' in count()", async () => {
1091
853
  // Since count() uses result.length and GROUP BY returns one row per source,
1092
854
  // mock 5 recipe sources
1093
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1094
- source: `node:abc${i+1}`,
1095
- source_uri: `literal://recipe${i+1}`,
1096
- links: [
1097
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1098
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1099
- ]
1100
- }));
855
+ const queryResults = [
856
+ ...Array.from({ length: 5 }, (_, i) => [
857
+ { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
858
+ { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
859
+ ]).flat()
860
+ ];
1101
861
 
1102
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
862
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
1103
863
 
1104
- const count = await Recipe.count(mockPerspective, {});
864
+ const count = await Recipe.count(mockPerspective, {}, 'sparql');
1105
865
 
1106
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
866
+ expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
1107
867
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1108
868
  expect(count).toBe(5);
1109
869
  });
1110
870
 
1111
- it("should use Prolog when useSurrealDB is false in count()", async () => {
871
+ it("should use Prolog when engine is prolog in count()", async () => {
1112
872
  const prologResults = [{ TotalCount: 10 }];
1113
873
  mockPerspective.infer.mockResolvedValue(prologResults);
1114
874
 
1115
875
  const count = await Recipe.count(mockPerspective, {}, false);
1116
876
 
1117
877
  expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1118
- expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
878
+ expect(mockPerspective.querySparql).not.toHaveBeenCalled();
1119
879
  expect(count).toBe(10);
1120
880
  });
1121
881
 
1122
- it("should use SurrealDB by default in ModelQueryBuilder.get()", async () => {
1123
- const surrealResults = [
1124
- {
1125
- source: "node:abc123",
1126
- source_uri: "literal://recipe1",
1127
- links: [
1128
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1129
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1130
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1131
- ]
1132
- }
882
+ it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.get()", async () => {
883
+ const queryResults = [
884
+ { source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
885
+ { source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
886
+ { source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1133
887
  ];
1134
888
 
1135
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
889
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
1136
890
 
1137
891
  const results = await Recipe.query(mockPerspective)
1138
892
  .where({ name: "Pasta" })
893
+ .engine('sparql')
1139
894
  .get();
1140
895
 
1141
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
896
+ expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
1142
897
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1143
898
  expect(results).toHaveLength(1);
1144
899
  expect(results[0].name).toBe("Pasta");
1145
900
  });
1146
901
 
1147
- it("should use Prolog when useSurrealDB(false) in ModelQueryBuilder.get()", async () => {
902
+ it("should use Prolog when.engine('prolog') in ModelQueryBuilder.get()", async () => {
1148
903
  const prologResults = [{
1149
904
  AllInstances: [
1150
- ["literal://recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
905
+ ["literal:recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
1151
906
  ],
1152
907
  TotalCount: 1
1153
908
  }];
@@ -1156,55 +911,49 @@ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", ()
1156
911
 
1157
912
  const results = await Recipe.query(mockPerspective)
1158
913
  .where({ name: "Pasta" })
1159
- .useSurrealDB(false)
914
+ .engine('prolog')
1160
915
  .get();
1161
916
 
1162
917
  expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1163
- expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
918
+ expect(mockPerspective.querySparql).not.toHaveBeenCalled();
1164
919
  expect(results).toHaveLength(1);
1165
920
  });
1166
921
 
1167
- it("should use SurrealDB by default in ModelQueryBuilder.count()", async () => {
922
+ it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.count()", async () => {
1168
923
  // count() counts the number of rows returned by the query (one row per source)
1169
- const surrealResults = Array.from({ length: 3 }, (_, i) => ({
1170
- source: `node:abc${i+1}`,
1171
- source_uri: `literal://recipe${i+1}`,
1172
- links: [
1173
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1174
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1175
- ]
1176
- }));
1177
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
924
+ const queryResults = [
925
+ ...Array.from({ length: 3 }, (_, i) => [
926
+ { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
927
+ { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
928
+ ]).flat()
929
+ ];
930
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
1178
931
 
1179
932
  const count = await Recipe.query(mockPerspective)
1180
933
  .where({ rating: { gt: 4 } })
934
+ .engine('sparql')
1181
935
  .count();
1182
936
 
1183
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
937
+ expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
1184
938
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1185
939
  expect(count).toBe(3);
1186
940
  });
1187
941
 
1188
- it("should use SurrealDB by default in ModelQueryBuilder.paginate()", async () => {
1189
- const surrealResults = [
1190
- {
1191
- source: "node:abc123",
1192
- source_uri: "literal://recipe1",
1193
- links: [
1194
- { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1195
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1196
- { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1197
- ]
1198
- }
942
+ it("should use SPARQL when engine is 'sparql' in ModelQueryBuilder.paginate()", async () => {
943
+ const queryResults = [
944
+ { source: "literal:recipe1", predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
945
+ { source: "literal:recipe1", predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
946
+ { source: "literal:recipe1", predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1199
947
  ];
1200
948
 
1201
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
949
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
1202
950
 
1203
951
  const page = await Recipe.query(mockPerspective)
1204
952
  .where({ rating: { gt: 3 } })
953
+ .engine('sparql')
1205
954
  .paginate(10, 1);
1206
955
 
1207
- expect(mockPerspective.querySurrealDB).toHaveBeenCalledTimes(1);
956
+ expect(mockPerspective.querySparql).toHaveBeenCalledTimes(1);
1208
957
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1209
958
  expect(page.results).toHaveLength(1);
1210
959
  expect(page.pageSize).toBe(10);
@@ -1228,7 +977,7 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
1228
977
 
1229
978
  // Mock perspective
1230
979
  const mockPerspective = {
1231
- querySurrealDB: jest.fn(),
980
+ querySparql: jest.fn(),
1232
981
  infer: jest.fn(),
1233
982
  uuid: 'test-perspective-uuid',
1234
983
  stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
@@ -1238,159 +987,143 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
1238
987
  jest.clearAllMocks();
1239
988
  });
1240
989
 
1241
- it("should apply JS-level filtering for gt operator on properties in SurrealDB count()", async () => {
1242
- // Mock SurrealDB results: 5 recipes with ratings 1, 2, 3, 4, 5
1243
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1244
- source: `node:abc${i+1}`,
1245
- source_uri: `literal://recipe${i+1}`,
1246
- links: [
1247
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1248
- { predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1249
- ]
1250
- }));
990
+ it("should apply JS-level filtering for gt operator on properties in SPARQL count()", async () => {
991
+ // Mock query results: 5 recipes with ratings 1, 2, 3, 4, 5
992
+ const queryResults = [
993
+ ...Array.from({ length: 5 }, (_, i) => [
994
+ { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
995
+ { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
996
+ ]).flat()
997
+ ];
1251
998
 
1252
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
999
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
1253
1000
 
1254
1001
  // Count recipes with rating > 3 (should match 2 recipes: rating 4 and 5)
1255
- const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } });
1002
+ const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } }, 'sparql');
1256
1003
 
1257
1004
  // Verify count matches the number of instances that would be returned by findAll
1258
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { gt: 3 } } });
1005
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { gt: 3 } } }, 'sparql');
1259
1006
 
1260
1007
  expect(count).toBe(2);
1261
1008
  expect(count).toBe(findAllResults.length);
1262
1009
  });
1263
1010
 
1264
- it("should apply JS-level filtering for between operator on properties in SurrealDB count()", async () => {
1265
- // Mock SurrealDB results: 5 recipes with ratings 1, 2, 3, 4, 5
1266
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1267
- source: `node:abc${i+1}`,
1268
- source_uri: `literal://recipe${i+1}`,
1269
- links: [
1270
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1271
- { predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1272
- ]
1273
- }));
1011
+ it("should apply JS-level filtering for between operator on properties in SPARQL count()", async () => {
1012
+ // Mock query results: 5 recipes with ratings 1, 2, 3, 4, 5
1013
+ const queryResults = [
1014
+ ...Array.from({ length: 5 }, (_, i) => [
1015
+ { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1016
+ { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1017
+ ]).flat()
1018
+ ];
1274
1019
 
1275
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1020
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
1276
1021
 
1277
1022
  // Count recipes with rating between 2 and 4 (should match 3 recipes: rating 2, 3, 4)
1278
- const count = await Recipe.count(mockPerspective, { where: { rating: { between: [2, 4] } } });
1023
+ const count = await Recipe.count(mockPerspective, { where: { rating: { between: [2, 4] } } }, 'sparql');
1279
1024
 
1280
1025
  // Verify count matches the number of instances that would be returned by findAll
1281
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { between: [2, 4] } } });
1026
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { between: [2, 4] } } }, 'sparql');
1282
1027
 
1283
1028
  expect(count).toBe(3);
1284
1029
  expect(count).toBe(findAllResults.length);
1285
1030
  });
1286
1031
 
1287
- it("should apply JS-level filtering for timestamp gt operator in SurrealDB count()", async () => {
1288
- // Mock SurrealDB results: 5 recipes with different timestamps
1289
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1290
- source: `node:abc${i+1}`,
1291
- source_uri: `literal://recipe${i+1}`,
1292
- links: [
1293
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1294
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1295
- ]
1296
- }));
1032
+ it("should apply JS-level filtering for timestamp gt operator in SPARQL count()", async () => {
1033
+ // Mock query results: 5 recipes with different timestamps
1034
+ const queryResults = [
1035
+ ...Array.from({ length: 5 }, (_, i) => [
1036
+ { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1037
+ { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1038
+ ]).flat()
1039
+ ];
1297
1040
 
1298
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1041
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
1299
1042
 
1300
1043
  // Count recipes with timestamp > 2023-01-03 (should match 2 recipes: 2023-01-04 and 2023-01-05)
1301
1044
  const targetTimestamp = new Date("2023-01-03T00:00:00Z").getTime();
1302
- const count = await Recipe.count(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } });
1045
+ const count = await Recipe.count(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } }, 'sparql');
1303
1046
 
1304
1047
  // Verify count matches the number of instances that would be returned by findAll
1305
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } });
1048
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } }, 'sparql');
1306
1049
 
1307
1050
  expect(count).toBe(2);
1308
1051
  expect(count).toBe(findAllResults.length);
1309
1052
  });
1310
1053
 
1311
- it("should apply JS-level filtering for timestamp between operator in SurrealDB count()", async () => {
1312
- // Mock SurrealDB results: 5 recipes with different timestamps
1313
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1314
- source: `node:abc${i+1}`,
1315
- source_uri: `literal://recipe${i+1}`,
1316
- links: [
1317
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1318
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1319
- ]
1320
- }));
1054
+ it("should apply JS-level filtering for timestamp between operator in SPARQL count()", async () => {
1055
+ // Mock query results: 5 recipes with different timestamps
1056
+ const queryResults = [
1057
+ ...Array.from({ length: 5 }, (_, i) => [
1058
+ { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1059
+ { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1060
+ ]).flat()
1061
+ ];
1321
1062
 
1322
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1063
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
1323
1064
 
1324
1065
  // Count recipes with timestamp between 2023-01-02 and 2023-01-04
1325
1066
  const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1326
1067
  const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
1327
1068
  const count = await Recipe.count(mockPerspective, {
1328
1069
  where: { timestamp: { between: [startTimestamp, endTimestamp] } }
1329
- });
1070
+ }, 'sparql');
1330
1071
 
1331
1072
  // Verify count matches the number of instances that would be returned by findAll
1332
1073
  const findAllResults = await Recipe.findAll(mockPerspective, {
1333
1074
  where: { timestamp: { between: [startTimestamp, endTimestamp] } }
1334
- });
1075
+ }, 'sparql');
1335
1076
 
1336
1077
  expect(count).toBe(3);
1337
1078
  expect(count).toBe(findAllResults.length);
1338
1079
  });
1339
1080
 
1340
- it("should apply JS-level filtering for author filtering in SurrealDB count()", async () => {
1341
- // Mock SurrealDB results: 3 recipes by Alice and 2 by Bob
1342
- const surrealResults = [
1343
- ...Array.from({ length: 3 }, (_, i) => ({
1344
- source: `node:abc${i+1}`,
1345
- source_uri: `literal://recipe${i+1}`,
1346
- links: [
1347
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1348
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1349
- ]
1350
- })),
1351
- ...Array.from({ length: 2 }, (_, i) => ({
1352
- source: `node:def${i+4}`,
1353
- source_uri: `literal://recipe${i+4}`,
1354
- links: [
1355
- { predicate: "recipe://name", target: `Recipe ${i+4}`, author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
1356
- { predicate: "recipe://rating", target: "5", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" }
1357
- ]
1358
- }))
1081
+ it("should apply JS-level filtering for author filtering in SPARQL count()", async () => {
1082
+ // Mock query results: 3 recipes by Alice and 2 by Bob
1083
+ const queryResults = [
1084
+ ...Array.from({ length: 3 }, (_, i) => [
1085
+ { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1086
+ { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1087
+ ]).flat(),
1088
+ ...Array.from({ length: 2 }, (_, i) => [
1089
+ { source: `literal:recipe${i+4}`, predicate: "recipe://name", target: `Recipe ${i+4}`, author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
1090
+ { source: `literal:recipe${i+4}`, predicate: "recipe://rating", target: "5", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" }
1091
+ ]).flat()
1359
1092
  ];
1360
1093
 
1361
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1094
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
1362
1095
 
1363
1096
  // Count recipes by Alice (should match 3 recipes)
1364
- const count = await Recipe.count(mockPerspective, { where: { author: "did:key:alice" } });
1097
+ const count = await Recipe.count(mockPerspective, { where: { author: "did:key:alice" } }, 'sparql');
1365
1098
 
1366
1099
  // Verify count matches the number of instances that would be returned by findAll
1367
- const findAllResults = await Recipe.findAll(mockPerspective, { where: { author: "did:key:alice" } });
1100
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { author: "did:key:alice" } }, 'sparql');
1368
1101
 
1369
1102
  expect(count).toBe(3);
1370
1103
  expect(count).toBe(findAllResults.length);
1371
1104
  });
1372
1105
 
1373
1106
  it("should apply JS-level filtering in ModelQueryBuilder.count() with gt operator", async () => {
1374
- // Mock SurrealDB results: 5 recipes with ratings 1, 2, 3, 4, 5
1375
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1376
- source: `node:abc${i+1}`,
1377
- source_uri: `literal://recipe${i+1}`,
1378
- links: [
1379
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1380
- { predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1381
- ]
1382
- }));
1107
+ // Mock query results: 5 recipes with ratings 1, 2, 3, 4, 5
1108
+ const queryResults = [
1109
+ ...Array.from({ length: 5 }, (_, i) => [
1110
+ { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1111
+ { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: `${i+1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1112
+ ]).flat()
1113
+ ];
1383
1114
 
1384
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1115
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
1385
1116
 
1386
1117
  // Count recipes with rating > 3 using ModelQueryBuilder
1387
1118
  const count = await Recipe.query(mockPerspective)
1388
1119
  .where({ rating: { gt: 3 } })
1120
+ .engine('sparql')
1389
1121
  .count();
1390
1122
 
1391
1123
  // Verify count matches the number of instances that would be returned by get()
1392
1124
  const getResults = await Recipe.query(mockPerspective)
1393
1125
  .where({ rating: { gt: 3 } })
1126
+ .engine('sparql')
1394
1127
  .get();
1395
1128
 
1396
1129
  expect(count).toBe(2);
@@ -1398,17 +1131,15 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
1398
1131
  });
1399
1132
 
1400
1133
  it("should apply JS-level filtering in ModelQueryBuilder.count() with timestamp between", async () => {
1401
- // Mock SurrealDB results: 5 recipes with different timestamps
1402
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1403
- source: `node:abc${i+1}`,
1404
- source_uri: `literal://recipe${i+1}`,
1405
- links: [
1406
- { predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1407
- { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1408
- ]
1409
- }));
1134
+ // Mock query results: 5 recipes with different timestamps
1135
+ const queryResults = [
1136
+ ...Array.from({ length: 5 }, (_, i) => [
1137
+ { source: `literal:recipe${i+1}`, predicate: "recipe://name", target: `Recipe ${i+1}`, author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` },
1138
+ { source: `literal:recipe${i+1}`, predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i+1}T00:00:00Z` }
1139
+ ]).flat()
1140
+ ];
1410
1141
 
1411
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1142
+ mockPerspective.querySparql.mockResolvedValue(queryResults);
1412
1143
 
1413
1144
  const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1414
1145
  const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
@@ -1416,11 +1147,13 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
1416
1147
  // Count using ModelQueryBuilder
1417
1148
  const count = await Recipe.query(mockPerspective)
1418
1149
  .where({ timestamp: { between: [startTimestamp, endTimestamp] } })
1150
+ .engine('sparql')
1419
1151
  .count();
1420
1152
 
1421
1153
  // Verify count matches the number of instances that would be returned by get()
1422
1154
  const getResults = await Recipe.query(mockPerspective)
1423
1155
  .where({ timestamp: { between: [startTimestamp, endTimestamp] } })
1156
+ .engine('sparql')
1424
1157
  .get();
1425
1158
 
1426
1159
  expect(count).toBe(3);
@@ -1434,7 +1167,7 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
1434
1167
  const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } }, false);
1435
1168
 
1436
1169
  expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1437
- expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1170
+ expect(mockPerspective.querySparql).not.toHaveBeenCalled();
1438
1171
  expect(count).toBe(2);
1439
1172
  });
1440
1173
 
@@ -1452,8 +1185,1225 @@ describe("Ad4mModel.count() with advanced where conditions", () => {
1452
1185
  );
1453
1186
 
1454
1187
  expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1455
- expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1188
+ expect(mockPerspective.querySparql).not.toHaveBeenCalled();
1456
1189
  expect(count).toBe(3);
1457
1190
  });
1458
1191
  });
1459
1192
 
1193
+
1194
+ // ──────────────────────────────────────────────────────────
1195
+ // Batch SPARQL query builder tests
1196
+ // ──────────────────────────────────────────────────────────
1197
+
1198
+ import { buildBatchSPARQLQuery } from "./query-sparql-batch";
1199
+
1200
+ describe("buildBatchSPARQLQuery", () => {
1201
+ @Model({ name: "Author" })
1202
+ class Author extends Ad4mModel {
1203
+ @Property({ through: "author://name", required: true })
1204
+ name!: string;
1205
+ }
1206
+
1207
+ @Model({ name: "Book" })
1208
+ class Book extends Ad4mModel {
1209
+ @Property({ through: "book://title", required: true })
1210
+ title!: string;
1211
+
1212
+ @HasMany(() => Author, { through: "book://author" })
1213
+ authors!: Author[];
1214
+ }
1215
+
1216
+ it("should generate UNION branches for depth 0 and depth 1 includes", () => {
1217
+ const metadata = Book.getModelMetadata();
1218
+ const query = { include: { authors: true } };
1219
+ const sparql = buildBatchSPARQLQuery(metadata, query, Book);
1220
+
1221
+ expect(sparql).toContain("?depth");
1222
+ expect(sparql).toContain("?parentBase");
1223
+ expect(sparql).toContain("?relationName");
1224
+ expect(sparql).toContain("UNION");
1225
+ expect(sparql).toContain("BIND(\"0\" AS ?depth)");
1226
+ expect(sparql).toContain("BIND(\"1\" AS ?depth)");
1227
+ expect(sparql).toContain("book://author");
1228
+ });
1229
+
1230
+ it("should include parent filter when query.parent is specified", () => {
1231
+ const metadata = Book.getModelMetadata();
1232
+ const query = {
1233
+ parent: { id: "flux://library1", predicate: "library://books" },
1234
+ include: { authors: true },
1235
+ };
1236
+ const sparql = buildBatchSPARQLQuery(metadata, query, Book);
1237
+
1238
+ expect(sparql).toContain("flux://library1");
1239
+ expect(sparql).toContain("library://books");
1240
+ });
1241
+
1242
+ it("should include where filter for simple equality", () => {
1243
+ const metadata = Book.getModelMetadata();
1244
+ const query = {
1245
+ where: { title: "My Book" },
1246
+ include: { authors: true },
1247
+ };
1248
+ const sparql = buildBatchSPARQLQuery(metadata, query, Book);
1249
+
1250
+ // For literal-stored properties, SPARQL only has a JOIN (no FILTER value) — filtering in JS
1251
+ expect(sparql).toContain("book://title");
1252
+ expect(sparql).toContain("root_wTarget_eq_title");
1253
+ });
1254
+
1255
+ it("should throw when include is empty", () => {
1256
+ const metadata = Book.getModelMetadata();
1257
+ expect(() => buildBatchSPARQLQuery(metadata, {}, Book)).toThrow("requires query.include");
1258
+ });
1259
+ });
1260
+
1261
+ describe("SPARQL comparison filters", () => {
1262
+ @Model({ name: "Item" })
1263
+ class Item extends Ad4mModel {
1264
+ @Property({ through: "item://price", required: true })
1265
+ price!: string;
1266
+
1267
+ @Property({ through: "item://name", required: true })
1268
+ name!: string;
1269
+ }
1270
+
1271
+ it("should generate gt filter", async () => {
1272
+ const mockPersp = { getLinks: jest.fn().mockResolvedValue([]) } as any;
1273
+ const query = await (Item as any).queryToSPARQL(mockPersp, { where: { price: { gt: 10 } } });
1274
+ // gt is now JS post-filter — SPARQL just joins the property
1275
+ expect(query).toContain("item://price");
1276
+ });
1277
+
1278
+ it("should generate between filter", async () => {
1279
+ const mockPersp = { getLinks: jest.fn().mockResolvedValue([]) } as any;
1280
+ const query = await (Item as any).queryToSPARQL(mockPersp, { where: { price: { between: [5, 20] } } });
1281
+ // between is now JS post-filter
1282
+ expect(query).toContain("item://price");
1283
+ });
1284
+
1285
+ it("should generate contains filter", async () => {
1286
+ const mockPersp = { getLinks: jest.fn().mockResolvedValue([]) } as any;
1287
+ const query = await (Item as any).queryToSPARQL(mockPersp, { where: { name: { contains: "widget" } } });
1288
+ // contains is now JS post-filter
1289
+ expect(query).toContain("item://name");
1290
+ });
1291
+ });
1292
+
1293
+ // ──────────────────────────────────────────────────────────
1294
+ // SPARQL Direct Triple Pattern & IRI Tests
1295
+ // ──────────────────────────────────────────────────────────
1296
+
1297
+ import { buildSPARQLQuery, groupSPARQLResults, formatSPARQLValue, buildSPARQLGetDataQuery } from "./query-sparql";
1298
+
1299
+ describe("SPARQL direct triple pattern generation", () => {
1300
+ @Model({ name: "Channel" })
1301
+ class Channel extends Ad4mModel {
1302
+ @Flag({ through: "flux://entry_type", value: "flux://channel" })
1303
+ type: string = "";
1304
+
1305
+ @Property({ through: "flux://name", resolveLanguage: "literal", required: true })
1306
+ name: string = "";
1307
+
1308
+ @Optional({ through: "flux://description" })
1309
+ description: string = "";
1310
+
1311
+ @HasMany({ through: "flux://has_message" })
1312
+ messages: string[] = [];
1313
+ }
1314
+
1315
+ const mockPersp = {} as any;
1316
+
1317
+ it("generates direct triple pattern with ?source ?predicate ?target", async () => {
1318
+ const query = await (Channel as any).queryToSPARQL(mockPersp, {});
1319
+ // Must use direct triple pattern, not link-node reification
1320
+ expect(query).toContain("?source ?predicate ?target");
1321
+ expect(query).not.toContain("rdf:type");
1322
+ expect(query).not.toContain("ad4m:Link");
1323
+ });
1324
+
1325
+ it("generates Flag filter as ?source <predicate> <value>", async () => {
1326
+ const query = await (Channel as any).queryToSPARQL(mockPersp, {});
1327
+ expect(query).toContain("<flux://entry_type>");
1328
+ expect(query).toContain("<flux://channel>");
1329
+ });
1330
+
1331
+ it("generates Property binding as ?source <predicate> ?varName", async () => {
1332
+ const query = await (Channel as any).queryToSPARQL(mockPersp, {});
1333
+ expect(query).toContain("<flux://name>");
1334
+ expect(query).toMatch(/\?source\s+<flux:\/\/name>\s+\?cfTarget_name/);
1335
+ });
1336
+
1337
+ it("uses GRAPH ?linkGraph pattern for author/timestamp", async () => {
1338
+ const query = await (Channel as any).queryToSPARQL(mockPersp, {});
1339
+ expect(query).toContain("GRAPH ?linkGraph { ?source ?predicate ?target . }");
1340
+ expect(query).toContain("?linkGraph <ad4m://ontology/author> ?author");
1341
+ expect(query).toContain("?linkGraph <ad4m://ontology/timestamp> ?timestamp");
1342
+ });
1343
+
1344
+ it("does NOT contain RDF-star BIND(<< >> AS ?ann) pattern", async () => {
1345
+ const query = await (Channel as any).queryToSPARQL(mockPersp, {});
1346
+ expect(query).not.toContain("BIND(<<");
1347
+ expect(query).not.toContain("?ann ");
1348
+ });
1349
+
1350
+ it("uses FILTER(isIRI(?source)) to exclude non-IRI subjects", async () => {
1351
+ const query = await (Channel as any).queryToSPARQL(mockPersp, {});
1352
+ expect(query).toContain("FILTER(isIRI(?source)");
1353
+ });
1354
+ });
1355
+
1356
+ describe("SPARQL IRI formatting", () => {
1357
+ it("wraps AD4M URIs in angle brackets", () => {
1358
+ const query = buildSPARQLGetDataQuery("ad4m://test123");
1359
+ expect(query).toContain("<ad4m://test123>");
1360
+ });
1361
+
1362
+ it("wraps literal: URIs in angle brackets", () => {
1363
+ const query = buildSPARQLGetDataQuery("literal:string:foo");
1364
+ expect(query).toContain("<literal:string:foo>");
1365
+ });
1366
+
1367
+ it("wraps flux:// URIs in angle brackets", () => {
1368
+ const query = buildSPARQLGetDataQuery("flux://has_channel");
1369
+ expect(query).toContain("<flux://has_channel>");
1370
+ });
1371
+
1372
+ it("wraps did:key URIs in angle brackets", () => {
1373
+ const query = buildSPARQLGetDataQuery("did:key:z6MkhaXg");
1374
+ expect(query).toContain("<did:key:z6MkhaXg>");
1375
+ });
1376
+ });
1377
+
1378
+ describe("groupSPARQLResults", () => {
1379
+ it("groups flat rows by source URI", () => {
1380
+ const rows = [
1381
+ { source: "ad4m://a", predicate: "p1", target: "t1", author: "auth1", timestamp: "ts1" },
1382
+ { source: "ad4m://a", predicate: "p2", target: "t2", author: "auth1", timestamp: "ts1" },
1383
+ { source: "ad4m://b", predicate: "p1", target: "t3", author: "auth2", timestamp: "ts2" },
1384
+ ];
1385
+ const grouped = groupSPARQLResults(rows);
1386
+ expect(grouped).toHaveLength(2);
1387
+
1388
+ const aGroup = grouped.find(g => g.source_uri === "ad4m://a");
1389
+ expect(aGroup).toBeDefined();
1390
+ expect(aGroup!.links).toHaveLength(2);
1391
+
1392
+ const bGroup = grouped.find(g => g.source_uri === "ad4m://b");
1393
+ expect(bGroup).toBeDefined();
1394
+ expect(bGroup!.links).toHaveLength(1);
1395
+ });
1396
+
1397
+ it("returns empty array for empty input", () => {
1398
+ expect(groupSPARQLResults([])).toEqual([]);
1399
+ });
1400
+
1401
+ it("preserves metadata in grouped links", () => {
1402
+ const rows = [
1403
+ { source: "x", predicate: "p", target: "t", author: "did:key:z6Mk", timestamp: "2024-01-01T00:00:00Z" },
1404
+ ];
1405
+ const grouped = groupSPARQLResults(rows);
1406
+ expect(grouped[0].links[0].author).toBe("did:key:z6Mk");
1407
+ expect(grouped[0].links[0].timestamp).toBe("2024-01-01T00:00:00Z");
1408
+ });
1409
+ });
1410
+
1411
+ describe("formatSPARQLValue", () => {
1412
+ it("wraps strings in double quotes", () => {
1413
+ expect(formatSPARQLValue("hello")).toBe('"hello"');
1414
+ });
1415
+
1416
+ it("escapes special characters", () => {
1417
+ expect(formatSPARQLValue('say "hi"')).toBe('"say \\"hi\\""');
1418
+ });
1419
+
1420
+ it("converts numbers to quoted strings", () => {
1421
+ expect(formatSPARQLValue(42)).toBe('"42"');
1422
+ });
1423
+ });
1424
+
1425
+ // ──────────────────────────────────────────────────────────
1426
+ // Comprehensive SPARQL migration unit tests
1427
+ // ──────────────────────────────────────────────────────────
1428
+
1429
+ import { matchesCondition, hydrateFromLinks } from "./hydration";
1430
+ import { Literal } from "../Literal";
1431
+
1432
+ // Helper: create literal URLs using JSON encoding (which handles all types including booleans)
1433
+ function literalUrl(value: any): string {
1434
+ if (typeof value === 'string') return Literal.from(value).toUrl();
1435
+ // Use JSON encoding for numbers and booleans since Literal.get() doesn't handle boolean: prefix
1436
+ return `literal:json:${encodeURIComponent(JSON.stringify(value))}`;
1437
+ }
1438
+
1439
+ describe("matchesCondition()", () => {
1440
+ // Simple equality
1441
+ it("simple string equality — match", () => {
1442
+ expect(matchesCondition("hello", "hello")).toBe(true);
1443
+ });
1444
+ it("simple string equality — mismatch", () => {
1445
+ expect(matchesCondition("hello", "world")).toBe(false);
1446
+ });
1447
+ it("simple boolean equality — true", () => {
1448
+ expect(matchesCondition(true, true)).toBe(true);
1449
+ });
1450
+ it("simple boolean equality — false", () => {
1451
+ expect(matchesCondition(false, false)).toBe(true);
1452
+ });
1453
+ it("boolean mismatch", () => {
1454
+ expect(matchesCondition(true, false)).toBe(false);
1455
+ });
1456
+ it("simple number equality", () => {
1457
+ expect(matchesCondition(42, 42)).toBe(true);
1458
+ });
1459
+ it("number mismatch", () => {
1460
+ expect(matchesCondition(42, 99)).toBe(false);
1461
+ });
1462
+
1463
+ // Array IN clause
1464
+ it("array IN clause — value present", () => {
1465
+ expect(matchesCondition("a", ["a", "b", "c"])).toBe(true);
1466
+ });
1467
+ it("array IN clause — value absent", () => {
1468
+ expect(matchesCondition("d", ["a", "b", "c"])).toBe(false);
1469
+ });
1470
+
1471
+ // NOT operator
1472
+ it("not operator with string", () => {
1473
+ expect(matchesCondition("bob", { not: "alice" })).toBe(true);
1474
+ expect(matchesCondition("alice", { not: "alice" })).toBe(false);
1475
+ });
1476
+ it("not operator with array (NOT IN)", () => {
1477
+ expect(matchesCondition("a", { not: ["b", "c"] })).toBe(true);
1478
+ expect(matchesCondition("b", { not: ["b", "c"] })).toBe(false);
1479
+ });
1480
+
1481
+ // Comparison operators
1482
+ it("gt", () => {
1483
+ expect(matchesCondition(10, { gt: 5 })).toBe(true);
1484
+ expect(matchesCondition(5, { gt: 5 })).toBe(false);
1485
+ });
1486
+ it("gte", () => {
1487
+ expect(matchesCondition(5, { gte: 5 })).toBe(true);
1488
+ expect(matchesCondition(4, { gte: 5 })).toBe(false);
1489
+ });
1490
+ it("lt", () => {
1491
+ expect(matchesCondition(3, { lt: 5 })).toBe(true);
1492
+ expect(matchesCondition(5, { lt: 5 })).toBe(false);
1493
+ });
1494
+ it("lte", () => {
1495
+ expect(matchesCondition(5, { lte: 5 })).toBe(true);
1496
+ expect(matchesCondition(6, { lte: 5 })).toBe(false);
1497
+ });
1498
+ it("combined gt + lt (range)", () => {
1499
+ expect(matchesCondition(5, { gt: 3, lt: 7 })).toBe(true);
1500
+ expect(matchesCondition(3, { gt: 3, lt: 7 })).toBe(false);
1501
+ expect(matchesCondition(7, { gt: 3, lt: 7 })).toBe(false);
1502
+ });
1503
+
1504
+ // Between
1505
+ it("between — inclusive range", () => {
1506
+ expect(matchesCondition(5, { between: [3, 7] })).toBe(true);
1507
+ expect(matchesCondition(3, { between: [3, 7] })).toBe(true);
1508
+ expect(matchesCondition(7, { between: [3, 7] })).toBe(true);
1509
+ expect(matchesCondition(2, { between: [3, 7] })).toBe(false);
1510
+ expect(matchesCondition(8, { between: [3, 7] })).toBe(false);
1511
+ });
1512
+
1513
+ // Contains
1514
+ it("contains with string", () => {
1515
+ expect(matchesCondition("hello world", { contains: "world" })).toBe(true);
1516
+ expect(matchesCondition("hello world", { contains: "xyz" })).toBe(false);
1517
+ });
1518
+ it("contains with array", () => {
1519
+ expect(matchesCondition(["a", "b", "c"], { contains: "b" })).toBe(true);
1520
+ expect(matchesCondition(["a", "b", "c"], { contains: "d" })).toBe(false);
1521
+ });
1522
+
1523
+ // Edge cases
1524
+ it("returns false for undefined value with equality check", () => {
1525
+ expect(matchesCondition(undefined, "hello")).toBe(false);
1526
+ });
1527
+ it("returns false for empty string when condition is non-empty", () => {
1528
+ expect(matchesCondition("", "Recipe 2")).toBe(false);
1529
+ });
1530
+ it("returns true for undefined with not operator", () => {
1531
+ expect(matchesCondition(undefined, { not: "hello" })).toBe(true);
1532
+ });
1533
+ });
1534
+
1535
+ describe("hydrateFromLinks()", () => {
1536
+ // Create a mock perspective that won't be called for literal properties
1537
+ const mockPerspective = {} as any;
1538
+
1539
+ @Model({ name: "HydrationTest" })
1540
+ class HydrationTest extends Ad4mModel {
1541
+ @Property({ through: "test://name", resolveLanguage: "literal" })
1542
+ name: string = "";
1543
+
1544
+ @Property({ through: "test://score", resolveLanguage: "literal" })
1545
+ score: number = 0;
1546
+
1547
+ @Property({ through: "test://active", resolveLanguage: "literal" })
1548
+ active: boolean = false;
1549
+ }
1550
+
1551
+ const metadata = HydrationTest.getModelMetadata();
1552
+
1553
+ it("hydrates all properties when requestedProperties is undefined", async () => {
1554
+ const instance = new HydrationTest(mockPerspective) as any;
1555
+ const links = [
1556
+ { predicate: "test://name", target: literalUrl("Alice"), author: "did:test", timestamp: "1000" },
1557
+ { predicate: "test://score", target: literalUrl(42), author: "did:test", timestamp: "1000" },
1558
+ { predicate: "test://active", target: literalUrl(true), author: "did:test", timestamp: "1000" },
1559
+ ];
1560
+ await hydrateFromLinks(instance, links, metadata, mockPerspective, undefined);
1561
+ expect(instance.name).toBe("Alice");
1562
+ expect(instance.score).toBe(42);
1563
+ expect(instance.active).toBe(true);
1564
+ });
1565
+
1566
+ it("hydrates only requested properties when requestedProperties is provided", async () => {
1567
+ const instance = new HydrationTest(mockPerspective) as any;
1568
+ const links = [
1569
+ { predicate: "test://name", target: literalUrl("Alice"), author: "did:test", timestamp: "1000" },
1570
+ { predicate: "test://score", target: literalUrl(42), author: "did:test", timestamp: "1000" },
1571
+ { predicate: "test://active", target: literalUrl(true), author: "did:test", timestamp: "1000" },
1572
+ ];
1573
+ await hydrateFromLinks(instance, links, metadata, mockPerspective, ["name"]);
1574
+ expect(instance.name).toBe("Alice");
1575
+ // score and active should remain at defaults since not requested
1576
+ expect(instance.score).toBe(0);
1577
+ expect(instance.active).toBe(false);
1578
+ });
1579
+
1580
+ it("hydrates where-clause + projection properties when both are in requestedProperties", async () => {
1581
+ const instance = new HydrationTest(mockPerspective) as any;
1582
+ const links = [
1583
+ { predicate: "test://name", target: literalUrl("Recipe 2"), author: "did:test", timestamp: "1000" },
1584
+ { predicate: "test://active", target: literalUrl(true), author: "did:test", timestamp: "1000" },
1585
+ ];
1586
+ // Simulate merged hydration props: projection ["active"] + where clause props ["name"]
1587
+ await hydrateFromLinks(instance, links, metadata, mockPerspective, ["active", "name"]);
1588
+ expect(instance.name).toBe("Recipe 2");
1589
+ expect(instance.active).toBe(true);
1590
+ });
1591
+
1592
+ it("sets author and timestamps from links", async () => {
1593
+ const instance = new HydrationTest(mockPerspective) as any;
1594
+ const links = [
1595
+ { predicate: "test://name", target: literalUrl("Bob"), author: "did:author1", timestamp: "1000" },
1596
+ { predicate: "test://score", target: literalUrl(10), author: "did:author2", timestamp: "2000" },
1597
+ ];
1598
+ await hydrateFromLinks(instance, links, metadata, mockPerspective);
1599
+ expect(instance.author).toBe("did:author1");
1600
+ expect(instance.createdAt).toBe(1000);
1601
+ expect(instance.updatedAt).toBe(2000);
1602
+ });
1603
+
1604
+ it("handles empty links array", async () => {
1605
+ const instance = new HydrationTest(mockPerspective) as any;
1606
+ await hydrateFromLinks(instance, [], metadata, mockPerspective);
1607
+ expect(instance.name).toBe("");
1608
+ expect(instance.score).toBe(0);
1609
+ });
1610
+ });
1611
+
1612
+ describe("instancesFromQueryResult — where + properties interaction", () => {
1613
+ const mockPerspective = {
1614
+ get: jest.fn().mockResolvedValue([]),
1615
+ querySparql: jest.fn().mockResolvedValue([]),
1616
+ getExpression: jest.fn().mockResolvedValue(null),
1617
+ } as any;
1618
+
1619
+ @Model({ name: "Recipe" })
1620
+ class Recipe extends Ad4mModel {
1621
+ @Property({ through: "recipe://name", resolveLanguage: "literal", required: true })
1622
+ name: string = "";
1623
+
1624
+ @Property({ through: "recipe://booleanTest", resolveLanguage: "literal" })
1625
+ booleanTest: boolean = false;
1626
+
1627
+ @Property({ through: "recipe://score", resolveLanguage: "literal" })
1628
+ score: number = 0;
1629
+ }
1630
+
1631
+ it("should filter by where clause property even when not in properties projection", async () => {
1632
+ // Simulate SPARQL result with two recipes
1633
+ const grouped = [
1634
+ {
1635
+ source_uri: "expr:recipe1",
1636
+ links: [
1637
+ { predicate: "recipe://name", target: literalUrl("Recipe 1"), author: "did:test", timestamp: "1000" },
1638
+ { predicate: "recipe://booleanTest", target: literalUrl(true), author: "did:test", timestamp: "1000" },
1639
+ ],
1640
+ },
1641
+ {
1642
+ source_uri: "expr:recipe2",
1643
+ links: [
1644
+ { predicate: "recipe://name", target: literalUrl("Recipe 2"), author: "did:test", timestamp: "1000" },
1645
+ { predicate: "recipe://booleanTest", target: literalUrl(false), author: "did:test", timestamp: "1000" },
1646
+ ],
1647
+ },
1648
+ ];
1649
+
1650
+ const query = { where: { name: "Recipe 2" }, properties: ["booleanTest"] };
1651
+ const { results } = await Recipe.instancesFromQueryResult(mockPerspective, query, grouped);
1652
+
1653
+ expect(results.length).toBe(1);
1654
+ expect((results[0] as any).booleanTest).toBe(false);
1655
+ // name should be deleted after filtering since it wasn't in properties projection
1656
+ expect((results[0] as any).name).toBeUndefined();
1657
+ });
1658
+
1659
+ it("should delete unrequested properties AFTER where-filtering", async () => {
1660
+ const grouped = [
1661
+ {
1662
+ source_uri: "expr:recipe1",
1663
+ links: [
1664
+ { predicate: "recipe://name", target: literalUrl("Recipe 1"), author: "did:test", timestamp: "1000" },
1665
+ { predicate: "recipe://score", target: literalUrl(99), author: "did:test", timestamp: "1000" },
1666
+ ],
1667
+ },
1668
+ ];
1669
+
1670
+ const query = { where: { name: "Recipe 1" }, properties: ["score"] };
1671
+ const { results } = await Recipe.instancesFromQueryResult(mockPerspective, query, grouped);
1672
+
1673
+ expect(results.length).toBe(1);
1674
+ expect((results[0] as any).score).toBe(99);
1675
+ // name was used for filtering but should be deleted from final result
1676
+ expect((results[0] as any).name).toBeUndefined();
1677
+ });
1678
+
1679
+ it("should return all properties when no projection is specified", async () => {
1680
+ const grouped = [
1681
+ {
1682
+ source_uri: "expr:recipe1",
1683
+ links: [
1684
+ { predicate: "recipe://name", target: literalUrl("Test"), author: "did:test", timestamp: "1000" },
1685
+ { predicate: "recipe://booleanTest", target: literalUrl(true), author: "did:test", timestamp: "1000" },
1686
+ { predicate: "recipe://score", target: literalUrl(50), author: "did:test", timestamp: "1000" },
1687
+ ],
1688
+ },
1689
+ ];
1690
+
1691
+ const query = { where: { name: "Test" } };
1692
+ const { results } = await Recipe.instancesFromQueryResult(mockPerspective, query, grouped);
1693
+
1694
+ expect(results.length).toBe(1);
1695
+ expect((results[0] as any).name).toBe("Test");
1696
+ expect((results[0] as any).booleanTest).toBe(true);
1697
+ expect((results[0] as any).score).toBe(50);
1698
+ });
1699
+ });
1700
+
1701
+ describe("groupSPARQLResults()", () => {
1702
+ it("groups rows by source", () => {
1703
+ const rows = [
1704
+ { source: "a", predicate: "p1", target: "t1", author: "auth", timestamp: "ts1" },
1705
+ { source: "a", predicate: "p2", target: "t2", author: "auth", timestamp: "ts2" },
1706
+ { source: "b", predicate: "p1", target: "t3", author: "auth", timestamp: "ts3" },
1707
+ ];
1708
+ const grouped = groupSPARQLResults(rows);
1709
+ expect(grouped.length).toBe(2);
1710
+ const groupA = grouped.find(g => g.source_uri === "a")!;
1711
+ const groupB = grouped.find(g => g.source_uri === "b")!;
1712
+ expect(groupA.links.length).toBe(2);
1713
+ expect(groupB.links.length).toBe(1);
1714
+ });
1715
+
1716
+ it("handles empty input", () => {
1717
+ expect(groupSPARQLResults([])).toEqual([]);
1718
+ });
1719
+
1720
+ it("preserves link metadata", () => {
1721
+ const rows = [
1722
+ { source: "x", predicate: "pred", target: "tgt", author: "did:auth", timestamp: "2024-01-01" },
1723
+ ];
1724
+ const grouped = groupSPARQLResults(rows);
1725
+ expect(grouped[0].links[0]).toEqual({
1726
+ predicate: "pred",
1727
+ target: "tgt",
1728
+ author: "did:auth",
1729
+ timestamp: "2024-01-01",
1730
+ });
1731
+ });
1732
+ });
1733
+
1734
+ describe("buildSPARQLQuery edge cases", () => {
1735
+ @Model({ name: "FlagModel" })
1736
+ class FlagModel extends Ad4mModel {
1737
+ @Flag({ through: "flag://type", value: "flag://FlagModel" })
1738
+ type: string = "";
1739
+
1740
+ @Property({ through: "flag://name", resolveLanguage: "literal", required: true })
1741
+ name: string = "";
1742
+ }
1743
+
1744
+ @Model({ name: "NoFlagModel" })
1745
+ class NoFlagModel extends Ad4mModel {
1746
+ @Property({ through: "noflag://title", resolveLanguage: "literal" })
1747
+ title: string = "";
1748
+ }
1749
+
1750
+ it("adds conformance JOIN for flag + required properties", () => {
1751
+ const metadata = FlagModel.getModelMetadata();
1752
+ const allRelsMeta = {} as any;
1753
+ const sparql = buildSPARQLQuery(metadata, allRelsMeta, {}, FlagModel);
1754
+ // Should contain flag triple pattern
1755
+ expect(sparql).toContain("<flag://type>");
1756
+ expect(sparql).toContain("<flag://FlagModel>");
1757
+ // Should contain required property pattern
1758
+ expect(sparql).toContain("<flag://name>");
1759
+ });
1760
+
1761
+ it("uses structural subquery when no conformance patterns exist", () => {
1762
+ const metadata = NoFlagModel.getModelMetadata();
1763
+ const allRelsMeta = {} as any;
1764
+ const sparql = buildSPARQLQuery(metadata, allRelsMeta, {}, NoFlagModel);
1765
+ // Should contain structural subquery with DISTINCT
1766
+ expect(sparql).toContain("SELECT DISTINCT ?source");
1767
+ expect(sparql).toContain("<noflag://title>");
1768
+ });
1769
+
1770
+ it("adds JOIN for where-clause on literal-stored fields", () => {
1771
+ const metadata = FlagModel.getModelMetadata();
1772
+ const allRelsMeta = {} as any;
1773
+ const sparql = buildSPARQLQuery(metadata, allRelsMeta, { where: { name: "test" } }, FlagModel);
1774
+ // Where clause should add a join pattern for name
1775
+ expect(sparql).toContain("flag://name");
1776
+ });
1777
+
1778
+ it("handles where: {id: 'specific-id'} with FILTER on ?source", () => {
1779
+ const metadata = FlagModel.getModelMetadata();
1780
+ const allRelsMeta = {} as any;
1781
+ const sparql = buildSPARQLQuery(metadata, allRelsMeta, { where: { id: "expr:123" } as any }, FlagModel);
1782
+ // Should filter by source
1783
+ expect(sparql).toContain("expr:123");
1784
+ });
1785
+ });
1786
+
1787
+ describe("sparse fieldset property deletion timing", () => {
1788
+ const mockPerspective = {
1789
+ get: jest.fn().mockResolvedValue([]),
1790
+ querySparql: jest.fn().mockResolvedValue([]),
1791
+ getExpression: jest.fn().mockResolvedValue(null),
1792
+ } as any;
1793
+
1794
+ @Model({ name: "TimingTest" })
1795
+ class TimingTest extends Ad4mModel {
1796
+ @Property({ through: "timing://a", resolveLanguage: "literal" })
1797
+ a: string = "";
1798
+
1799
+ @Property({ through: "timing://b", resolveLanguage: "literal" })
1800
+ b: string = "";
1801
+
1802
+ @Property({ through: "timing://c", resolveLanguage: "literal" })
1803
+ c: string = "";
1804
+ }
1805
+
1806
+ it("where-clause properties are available during filtering but deleted after", async () => {
1807
+ const grouped = [
1808
+ {
1809
+ source_uri: "expr:1",
1810
+ links: [
1811
+ { predicate: "timing://a", target: literalUrl("match"), author: "did:test", timestamp: "1000" },
1812
+ { predicate: "timing://b", target: literalUrl("keep"), author: "did:test", timestamp: "1000" },
1813
+ { predicate: "timing://c", target: literalUrl("ignore"), author: "did:test", timestamp: "1000" },
1814
+ ],
1815
+ },
1816
+ {
1817
+ source_uri: "expr:2",
1818
+ links: [
1819
+ { predicate: "timing://a", target: literalUrl("no-match"), author: "did:test", timestamp: "1000" },
1820
+ { predicate: "timing://b", target: literalUrl("skip"), author: "did:test", timestamp: "1000" },
1821
+ { predicate: "timing://c", target: literalUrl("skip"), author: "did:test", timestamp: "1000" },
1822
+ ],
1823
+ },
1824
+ ];
1825
+
1826
+ // properties projection asks for "b" only, where clause filters on "a"
1827
+ const query = { where: { a: "match" }, properties: ["b"] };
1828
+ const { results } = await TimingTest.instancesFromQueryResult(mockPerspective, query, grouped);
1829
+
1830
+ // Only the matching instance should survive
1831
+ expect(results.length).toBe(1);
1832
+ // "b" was requested — should be present
1833
+ expect((results[0] as any).b).toBe("keep");
1834
+ // "a" was used for filtering but not in projection — should be deleted
1835
+ expect((results[0] as any).a).toBeUndefined();
1836
+ // "c" was not requested — should be deleted
1837
+ expect((results[0] as any).c).toBeUndefined();
1838
+ });
1839
+
1840
+ it("properties not in projection are undefined after instancesFromQueryResult", async () => {
1841
+ const grouped = [
1842
+ {
1843
+ source_uri: "expr:1",
1844
+ links: [
1845
+ { predicate: "timing://a", target: literalUrl("val-a"), author: "did:test", timestamp: "1000" },
1846
+ { predicate: "timing://b", target: literalUrl("val-b"), author: "did:test", timestamp: "1000" },
1847
+ { predicate: "timing://c", target: literalUrl("val-c"), author: "did:test", timestamp: "1000" },
1848
+ ],
1849
+ },
1850
+ ];
1851
+
1852
+ const query = { properties: ["a"] };
1853
+ const { results } = await TimingTest.instancesFromQueryResult(mockPerspective, query, grouped);
1854
+
1855
+ expect(results.length).toBe(1);
1856
+ expect((results[0] as any).a).toBe("val-a");
1857
+ expect((results[0] as any).b).toBeUndefined();
1858
+ expect((results[0] as any).c).toBeUndefined();
1859
+ });
1860
+ });
1861
+
1862
+ // ── Batch hydration for reverse relations (3.4) ─────────────────────────────
1863
+ describe("Batch hydration for reverse relations", () => {
1864
+ it("batch hydration should correctly group targets by parent instance ID", () => {
1865
+ // Test the grouping logic used in batch SPARQL hydration
1866
+ const sparqlResults = [
1867
+ { target: "inst:1", source: "child:a" },
1868
+ { target: "inst:1", source: "child:b" },
1869
+ { target: "inst:2", source: "child:c" },
1870
+ { target: "inst:3", source: "child:d" },
1871
+ { target: "inst:3", source: "child:e" },
1872
+ { target: "inst:3", source: "child:f" },
1873
+ ];
1874
+
1875
+ const reverseLinksMap = new Map<string, string[]>();
1876
+ for (const row of sparqlResults) {
1877
+ if (!reverseLinksMap.has(row.target)) reverseLinksMap.set(row.target, []);
1878
+ reverseLinksMap.get(row.target)!.push(row.source);
1879
+ }
1880
+
1881
+ expect(reverseLinksMap.get("inst:1")).toEqual(["child:a", "child:b"]);
1882
+ expect(reverseLinksMap.get("inst:2")).toEqual(["child:c"]);
1883
+ expect(reverseLinksMap.get("inst:3")).toEqual(["child:d", "child:e", "child:f"]);
1884
+ });
1885
+
1886
+ it("batch hydration should handle empty relation sets without error", () => {
1887
+ const sparqlResults: any[] = [];
1888
+ const reverseLinksMap = new Map<string, string[]>();
1889
+ for (const row of sparqlResults) {
1890
+ if (!reverseLinksMap.has(row.target)) reverseLinksMap.set(row.target, []);
1891
+ reverseLinksMap.get(row.target)!.push(row.source);
1892
+ }
1893
+
1894
+ expect(reverseLinksMap.size).toBe(0);
1895
+ expect(reverseLinksMap.get("nonexistent") || []).toEqual([]);
1896
+ });
1897
+
1898
+ it("batch hydration should return identical results to N+1 hydration (grouping equivalence)", () => {
1899
+ // Simulate N+1: each instance queries separately
1900
+ const instances = [{ id: "inst:1" }, { id: "inst:2" }];
1901
+ const allLinks = [
1902
+ { data: { source: "child:a", predicate: "rel://has", target: "inst:1" } },
1903
+ { data: { source: "child:b", predicate: "rel://has", target: "inst:1" } },
1904
+ { data: { source: "child:c", predicate: "rel://has", target: "inst:2" } },
1905
+ ];
1906
+
1907
+ // N+1 approach
1908
+ const n1Results = new Map<string, string[]>();
1909
+ for (const inst of instances) {
1910
+ const links = allLinks.filter(l => l.data.target === inst.id);
1911
+ n1Results.set(inst.id, links.map(l => l.data.source));
1912
+ }
1913
+
1914
+ // Batch approach
1915
+ const batchResults = new Map<string, string[]>();
1916
+ const sparqlRows = allLinks.map(l => ({ target: l.data.target, source: l.data.source }));
1917
+ for (const row of sparqlRows) {
1918
+ if (!batchResults.has(row.target)) batchResults.set(row.target, []);
1919
+ batchResults.get(row.target)!.push(row.source);
1920
+ }
1921
+
1922
+ // Results should be identical
1923
+ for (const inst of instances) {
1924
+ expect(batchResults.get(inst.id)).toEqual(n1Results.get(inst.id));
1925
+ }
1926
+ });
1927
+
1928
+ it("batch hydration with nested includes should use batched queries at each level", () => {
1929
+ // This test verifies the structure: nested includes result in multiple
1930
+ // batch operations, one per relation depth level
1931
+ const depth0Rows = [
1932
+ { target: "root:1", source: "mid:a" },
1933
+ { target: "root:1", source: "mid:b" },
1934
+ ];
1935
+ const depth1Rows = [
1936
+ { target: "mid:a", source: "leaf:x" },
1937
+ { target: "mid:b", source: "leaf:y" },
1938
+ ];
1939
+
1940
+ // Group each level
1941
+ const level0Map = new Map<string, string[]>();
1942
+ for (const r of depth0Rows) {
1943
+ if (!level0Map.has(r.target)) level0Map.set(r.target, []);
1944
+ level0Map.get(r.target)!.push(r.source);
1945
+ }
1946
+
1947
+ const level1Map = new Map<string, string[]>();
1948
+ for (const r of depth1Rows) {
1949
+ if (!level1Map.has(r.target)) level1Map.set(r.target, []);
1950
+ level1Map.get(r.target)!.push(r.source);
1951
+ }
1952
+
1953
+ expect(level0Map.get("root:1")).toEqual(["mid:a", "mid:b"]);
1954
+ expect(level1Map.get("mid:a")).toEqual(["leaf:x"]);
1955
+ expect(level1Map.get("mid:b")).toEqual(["leaf:y"]);
1956
+ });
1957
+ });
1958
+
1959
+ // ── Push-down FILTER for literal equality (3.5) ──────────────────────────────
1960
+ describe("Push-down FILTER for literal equality", () => {
1961
+ const mockPerspective = {} as any;
1962
+
1963
+ @Model({ name: "FilterTest" })
1964
+ class FilterTest extends Ad4mModel {
1965
+ @Property({ through: "ft://name", required: true })
1966
+ name: string = "";
1967
+ @Property({ through: "ft://rating", required: true })
1968
+ rating: number = 0;
1969
+ }
1970
+
1971
+ const normalizeQuery = (q: string) => q.replace(/\s+/g, " ").trim();
1972
+
1973
+ it("SPARQL query for where: { name: 'Alice' } should add JOIN but NOT parse_literal FILTER", async () => {
1974
+ const query = await (FilterTest as any).queryToSPARQL(mockPerspective, { where: { name: "Alice" } });
1975
+ const norm = normalizeQuery(query);
1976
+ // JOIN pattern exists (ensures property is present for JS post-filter)
1977
+ expect(norm).toContain("?wTarget_name");
1978
+ // No parse_literal FILTER — custom fn:: functions aren't valid in parsed SPARQL
1979
+ expect(norm).not.toContain("fn::parse_literal");
1980
+ });
1981
+
1982
+ it("SPARQL query for where: { name: ['Alice', 'Bob'] } should add JOIN but NOT parse_literal FILTER", async () => {
1983
+ const query = await (FilterTest as any).queryToSPARQL(mockPerspective, { where: { name: ["Alice", "Bob"] } });
1984
+ const norm = normalizeQuery(query);
1985
+ expect(norm).toContain("?wTarget_name");
1986
+ expect(norm).not.toContain("fn::parse_literal");
1987
+ });
1988
+
1989
+ it("SPARQL query for where: { rating: { gt: 5 } } should NOT include parse_literal FILTER", async () => {
1990
+ const query = await (FilterTest as any).queryToSPARQL(mockPerspective, { where: { rating: { gt: 5 } } });
1991
+ const norm = normalizeQuery(query);
1992
+ expect(norm).not.toContain("fn::parse_literal");
1993
+ });
1994
+
1995
+ it("literal property where clause adds JOIN for JS post-filter", async () => {
1996
+ const query = await (FilterTest as any).queryToSPARQL(mockPerspective, { where: { name: "Alice" } });
1997
+ const norm = normalizeQuery(query);
1998
+ expect(norm).toContain("?wTarget_name");
1999
+ });
2000
+ });
2001
+
2002
+ // ── Lightweight fingerprint (3.7) ────────────────────────────────────────────
2003
+ describe("Lightweight fingerprint optimization", () => {
2004
+ // Replicate the buildFingerprint logic for testing
2005
+ const buildFingerprint = (results: any[]) => {
2006
+ if (results.length === 0) return '0:';
2007
+ const ids = results.map((r: any) => r.id || '').sort().join(',');
2008
+ const ts = results.map((r: any) => r.updatedAt || r.timestamp || '').join(',');
2009
+ return `${results.length}:${ids}:${ts}`;
2010
+ };
2011
+
2012
+ const base = [
2013
+ { id: "a", updatedAt: "100" },
2014
+ { id: "b", updatedAt: "200" },
2015
+ ];
2016
+
2017
+ it("lightweight fingerprint should detect instance addition", () => {
2018
+ const fp1 = buildFingerprint(base);
2019
+ const fp2 = buildFingerprint([...base, { id: "c", updatedAt: "300" }]);
2020
+ expect(fp1).not.toBe(fp2);
2021
+ });
2022
+
2023
+ it("lightweight fingerprint should detect instance removal", () => {
2024
+ const fp1 = buildFingerprint(base);
2025
+ const fp2 = buildFingerprint([base[0]]);
2026
+ expect(fp1).not.toBe(fp2);
2027
+ });
2028
+
2029
+ it("lightweight fingerprint should detect timestamp change", () => {
2030
+ const fp1 = buildFingerprint(base);
2031
+ const fp2 = buildFingerprint([{ id: "a", updatedAt: "999" }, base[1]]);
2032
+ expect(fp1).not.toBe(fp2);
2033
+ });
2034
+
2035
+ it("lightweight fingerprint should NOT false-positive for identical sets", () => {
2036
+ const fp1 = buildFingerprint(base);
2037
+ const fp2 = buildFingerprint([...base]); // same data, new array
2038
+ expect(fp1).toBe(fp2);
2039
+ });
2040
+ });
2041
+
2042
+ // ── Native SPARQL getter evaluation ──────────────────────────────────────────
2043
+ describe("Native SPARQL getter evaluation", () => {
2044
+ const { evaluateCustomGettersForInstance } = require("./hydration");
2045
+
2046
+ const mockPerspective = {
2047
+ getLinks: jest.fn().mockResolvedValue([]),
2048
+ querySparql: jest.fn(),
2049
+ get: jest.fn().mockResolvedValue([]),
2050
+ };
2051
+
2052
+ beforeEach(() => {
2053
+ jest.clearAllMocks();
2054
+ });
2055
+
2056
+ it("should execute SELECT getter directly via querySparql", async () => {
2057
+ const metadata = {
2058
+ properties: {
2059
+ replyingTo: {
2060
+ predicate: "flux://has_reply",
2061
+ getter: 'SELECT ?target WHERE { ?target <flux://has_reply> ?source . } LIMIT 1',
2062
+ type: "string",
2063
+ }
2064
+ },
2065
+ relations: {},
2066
+ };
2067
+
2068
+ mockPerspective.querySparql.mockResolvedValue([
2069
+ { target: { value: "literal:string:msg123" } }
2070
+ ]);
2071
+
2072
+ const instance = { id: "test://msg1", replyingTo: undefined };
2073
+ await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
2074
+
2075
+ expect(mockPerspective.querySparql).toHaveBeenCalledWith(
2076
+ expect.stringContaining("SELECT ?target WHERE")
2077
+ );
2078
+ expect(instance.replyingTo).toBe("literal:string:msg123");
2079
+ });
2080
+
2081
+ it("should execute ASK getter and return boolean", async () => {
2082
+ const metadata = {
2083
+ properties: {
2084
+ isPopular: {
2085
+ predicate: "flux://is_popular",
2086
+ getter: 'ASK WHERE { SELECT (COUNT(DISTINCT ?reactor) AS ?count) WHERE { ?reactor <flux://reaction> ?source . } HAVING(?count > 5) }',
2087
+ type: "boolean",
2088
+ readOnly: true,
2089
+ }
2090
+ },
2091
+ relations: {},
2092
+ };
2093
+
2094
+ mockPerspective.querySparql.mockResolvedValue(true);
2095
+
2096
+ const instance = { id: "test://msg1", isPopular: false };
2097
+ await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
2098
+
2099
+ expect(mockPerspective.querySparql).toHaveBeenCalledWith(
2100
+ expect.stringContaining("ASK WHERE")
2101
+ );
2102
+ expect(instance.isPopular).toBe(true);
2103
+ });
2104
+
2105
+ it("should replace ?source with instance ID in SPARQL getter", async () => {
2106
+ const metadata = {
2107
+ properties: {
2108
+ author: {
2109
+ predicate: "test://author",
2110
+ getter: 'SELECT ?target WHERE { ?source <test://author> ?target . }',
2111
+ type: "string",
2112
+ }
2113
+ },
2114
+ relations: {},
2115
+ };
2116
+
2117
+ mockPerspective.querySparql.mockResolvedValue([
2118
+ { target: { value: "did:key:abc123" } }
2119
+ ]);
2120
+
2121
+ const instance = { id: "test://post1", author: undefined };
2122
+ await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
2123
+
2124
+ expect(mockPerspective.querySparql).toHaveBeenCalledWith(
2125
+ expect.stringContaining("<test://post1>")
2126
+ );
2127
+ expect(mockPerspective.querySparql).not.toHaveBeenCalledWith(
2128
+ expect.stringContaining("?source")
2129
+ );
2130
+ });
2131
+
2132
+ it("should handle empty SPARQL results gracefully", async () => {
2133
+ const metadata = {
2134
+ properties: {
2135
+ replyingTo: {
2136
+ predicate: "flux://has_reply",
2137
+ getter: 'SELECT ?target WHERE { ?target <flux://has_reply> ?source . } LIMIT 1',
2138
+ type: "string",
2139
+ }
2140
+ },
2141
+ relations: {},
2142
+ };
2143
+
2144
+ mockPerspective.querySparql.mockResolvedValue([]);
2145
+
2146
+ const instance = { id: "test://msg1", replyingTo: "original" };
2147
+ await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
2148
+
2149
+ // Should not overwrite with undefined
2150
+ expect(instance.replyingTo).toBe("original");
2151
+ });
2152
+
2153
+ it("should handle SPARQL getter errors without crashing", async () => {
2154
+ const metadata = {
2155
+ properties: {
2156
+ broken: {
2157
+ predicate: "test://broken",
2158
+ getter: 'SELECT ?target WHERE { INVALID SPARQL }',
2159
+ type: "string",
2160
+ }
2161
+ },
2162
+ relations: {},
2163
+ };
2164
+
2165
+ mockPerspective.querySparql.mockRejectedValue(new Error("SPARQL parse error"));
2166
+
2167
+ const instance = { id: "test://msg1", broken: undefined };
2168
+ const consoleSpy = jest.spyOn(console, "warn").mockImplementation();
2169
+ await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
2170
+ consoleSpy.mockRestore();
2171
+
2172
+ // Should not throw, should warn
2173
+ expect(instance.broken).toBeUndefined();
2174
+ });
2175
+
2176
+ it("should execute SPARQL getter for relations", async () => {
2177
+ const metadata = {
2178
+ properties: {},
2179
+ relations: {
2180
+ tags: {
2181
+ predicate: "test://has_tag",
2182
+ getter: 'SELECT ?target WHERE { ?source <test://has_tag> ?target . }',
2183
+ direction: "forward",
2184
+ }
2185
+ },
2186
+ };
2187
+
2188
+ mockPerspective.querySparql.mockResolvedValue([
2189
+ { target: { value: "tag:a" } },
2190
+ { target: { value: "tag:b" } },
2191
+ ]);
2192
+
2193
+ const instance = { id: "test://post1", tags: [] };
2194
+ await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
2195
+
2196
+ expect(instance.tags).toEqual(["tag:a", "tag:b"]);
2197
+ });
2198
+
2199
+ it("should warn for legacy SurrealDB-style getter syntax instead of converting", async () => {
2200
+ const metadata = {
2201
+ properties: {
2202
+ legacy: {
2203
+ predicate: "test://legacy",
2204
+ getter: "(<-link[WHERE predicate = 'test://legacy'].in.uri)[0]",
2205
+ type: "string",
2206
+ }
2207
+ },
2208
+ relations: {},
2209
+ };
2210
+
2211
+ const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
2212
+
2213
+ const instance = { id: "test://msg1", legacy: undefined };
2214
+ await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
2215
+
2216
+ // Should NOT call querySparql — legacy getters are no longer converted
2217
+ expect(mockPerspective.querySparql).not.toHaveBeenCalled();
2218
+ // Should warn about unsupported syntax
2219
+ expect(warnSpy).toHaveBeenCalledWith(
2220
+ expect.stringContaining("Unsupported legacy getter syntax")
2221
+ );
2222
+ // Value should remain undefined
2223
+ expect(instance.legacy).toBeUndefined();
2224
+
2225
+ warnSpy.mockRestore();
2226
+ });
2227
+ });
2228
+
2229
+ // ── Subscribe callback timing ──────────────────────────────────────────
2230
+ describe("ModelQueryBuilder subscribe callback timing", () => {
2231
+ it("subscribe should not invoke callback synchronously before Promise resolves", async () => {
2232
+ // This test verifies that the initial callback from subscribe() is deferred
2233
+ // via queueMicrotask, preventing Preact/React hook lifecycle violations
2234
+ // when subscribe() is called from useEffect.
2235
+
2236
+ const mockPerspective = {
2237
+ getLinks: jest.fn().mockResolvedValue([]),
2238
+ subscribeQuery: jest.fn().mockResolvedValue({
2239
+ result: '[]',
2240
+ onResult: jest.fn(),
2241
+ dispose: jest.fn(),
2242
+ }),
2243
+ querySparql: jest.fn().mockResolvedValue('[]'),
2244
+ } as any;
2245
+
2246
+ const { Ad4mModel, Model, Property, Flag } = require("./index");
2247
+
2248
+ @Model({ name: "TimingTest" })
2249
+ class TimingTest extends Ad4mModel {
2250
+ @Flag({ through: "test://type", value: "test://timing" })
2251
+ type: string = "test://timing";
2252
+ @Property({ through: "test://name" })
2253
+ name: string = "";
2254
+ }
2255
+
2256
+ let callbackInvokedBeforeResolve = false;
2257
+ let promiseResolved = false;
2258
+
2259
+ const query = TimingTest.query(mockPerspective);
2260
+ const promise = query.subscribe((results: any[]) => {
2261
+ if (!promiseResolved) {
2262
+ callbackInvokedBeforeResolve = true;
2263
+ }
2264
+ });
2265
+
2266
+ // At this point the Promise hasn't resolved yet
2267
+ // The callback should NOT have fired synchronously
2268
+ expect(callbackInvokedBeforeResolve).toBe(false);
2269
+
2270
+ await promise;
2271
+ promiseResolved = true;
2272
+
2273
+ // After the microtask queue drains, the callback should fire
2274
+ await new Promise(r => setTimeout(r, 10));
2275
+ // The callback was deferred — it fires after the Promise resolves
2276
+ });
2277
+ });
2278
+
2279
+ // ============================================================================
2280
+ // Performance Optimisation Tests
2281
+ // ============================================================================
2282
+
2283
+ import { getCachedResult, setCachedResult, clearQueryCache, queryCacheSize } from "./query-cache";
2284
+ import { clearSubscriptionPool, subscriptionPoolSize } from "./subscription-pool";
2285
+ import { getPropertiesMetadata, getRelationsMetadata, getMemoizedSHACL } from "./decorators";
2286
+
2287
+ describe("QueryCache", () => {
2288
+ beforeEach(() => clearQueryCache());
2289
+
2290
+ it("should return undefined for cache miss", () => {
2291
+ expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBeUndefined();
2292
+ });
2293
+
2294
+ it("should return cached result within TTL", () => {
2295
+ const result = [{ s: "test" }];
2296
+ setCachedResult("uuid1", "SELECT ?s WHERE {}", result);
2297
+ expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBe(result);
2298
+ });
2299
+
2300
+ it("should expire after TTL", async () => {
2301
+ setCachedResult("uuid1", "SELECT ?s WHERE {}", [{ s: "test" }], 50);
2302
+ await new Promise(r => setTimeout(r, 60));
2303
+ expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBeUndefined();
2304
+ });
2305
+
2306
+ it("should cache independently per perspective", () => {
2307
+ setCachedResult("uuid1", "SELECT ?s WHERE {}", "result1");
2308
+ setCachedResult("uuid2", "SELECT ?s WHERE {}", "result2");
2309
+ expect(getCachedResult("uuid1", "SELECT ?s WHERE {}")).toBe("result1");
2310
+ expect(getCachedResult("uuid2", "SELECT ?s WHERE {}")).toBe("result2");
2311
+ });
2312
+
2313
+ it("should cache independently per query", () => {
2314
+ setCachedResult("uuid1", "query1", "r1");
2315
+ setCachedResult("uuid1", "query2", "r2");
2316
+ expect(getCachedResult("uuid1", "query1")).toBe("r1");
2317
+ expect(getCachedResult("uuid1", "query2")).toBe("r2");
2318
+ });
2319
+
2320
+ it("should clear all entries", () => {
2321
+ setCachedResult("uuid1", "q1", "r1");
2322
+ setCachedResult("uuid2", "q2", "r2");
2323
+ expect(queryCacheSize()).toBe(2);
2324
+ clearQueryCache();
2325
+ expect(queryCacheSize()).toBe(0);
2326
+ });
2327
+ });
2328
+
2329
+ describe("SHACL Memoisation", () => {
2330
+ it("should memoise generateSHACL() per class", () => {
2331
+ @Model({ name: "MemoTest1" })
2332
+ class MemoTest1 extends Ad4mModel {
2333
+ @Property({ through: "test://name" })
2334
+ name: string = "";
2335
+ }
2336
+
2337
+ const result1 = (MemoTest1 as any).generateSHACL();
2338
+ const result2 = (MemoTest1 as any).generateSHACL();
2339
+ expect(result1).toBe(result2); // Same reference = memoised
2340
+ });
2341
+
2342
+ it("should memoise getPropertiesMetadata per class", () => {
2343
+ @Model({ name: "PropMemoTest" })
2344
+ class PropMemoTest extends Ad4mModel {
2345
+ @Property({ through: "test://x" })
2346
+ x: string = "";
2347
+ }
2348
+
2349
+ const r1 = getPropertiesMetadata(PropMemoTest);
2350
+ const r2 = getPropertiesMetadata(PropMemoTest);
2351
+ expect(r1).toBe(r2); // Same reference
2352
+ });
2353
+
2354
+ it("should memoise getRelationsMetadata per class", () => {
2355
+ @Model({ name: "RelMemoTest" })
2356
+ class RelMemoTest extends Ad4mModel {
2357
+ @HasMany({ through: "test://items" })
2358
+ items: string[] = [];
2359
+ }
2360
+
2361
+ const r1 = getRelationsMetadata(RelMemoTest);
2362
+ const r2 = getRelationsMetadata(RelMemoTest);
2363
+ expect(r1).toBe(r2); // Same reference
2364
+ });
2365
+
2366
+ it("should return different results for different classes", () => {
2367
+ @Model({ name: "ClassA" })
2368
+ class ClassA extends Ad4mModel {
2369
+ @Property({ through: "test://a" })
2370
+ a: string = "";
2371
+ }
2372
+
2373
+ @Model({ name: "ClassB" })
2374
+ class ClassB extends Ad4mModel {
2375
+ @Property({ through: "test://b" })
2376
+ b: string = "";
2377
+ }
2378
+
2379
+ const propsA = getPropertiesMetadata(ClassA);
2380
+ const propsB = getPropertiesMetadata(ClassB);
2381
+ expect(propsA).not.toBe(propsB);
2382
+ expect(propsA).toHaveProperty("a");
2383
+ expect(propsB).toHaveProperty("b");
2384
+ });
2385
+ });
2386
+
2387
+ describe("Lazy Conformance Filters", () => {
2388
+ it("should defer conformance filter resolution until property access", () => {
2389
+ @Model({ name: "LazyTarget2" })
2390
+ class LazyTarget2 extends Ad4mModel {
2391
+ @Flag({ through: "test://type", value: "test://lazy" })
2392
+ type: string = "test://lazy";
2393
+ @Property({ through: "test://name", required: true })
2394
+ name: string = "";
2395
+ }
2396
+
2397
+ @Model({ name: "LazyParent2" })
2398
+ class LazyParent2 extends Ad4mModel {
2399
+ @HasMany(() => LazyTarget2, { through: "test://children" })
2400
+ children: string[] = [];
2401
+ }
2402
+
2403
+ // generateSHACL was called during @Model — the shape exists
2404
+ const shacl = (LazyParent2 as any).generateSHACL();
2405
+ expect(shacl).toBeDefined();
2406
+ expect(shacl.shape).toBeDefined();
2407
+ expect(shacl.name).toBe("LazyParent2");
2408
+ });
2409
+ });