@coasys/ad4m 0.11.2-dev.2 → 0.11.2-dev.4

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.
package/lib/index.cjs CHANGED
@@ -18855,6 +18855,13 @@ class Ad4mModel {
18855
18855
  }
18856
18856
  return classCache[perspectiveID];
18857
18857
  }
18858
+ /**
18859
+ * Backwards compatibility alias for createdAt.
18860
+ * @deprecated Use createdAt instead. This will be removed in a future version.
18861
+ */
18862
+ get timestamp() {
18863
+ return this.createdAt;
18864
+ }
18858
18865
  /**
18859
18866
  * Extracts metadata from decorators for query building.
18860
18867
  *
@@ -18916,6 +18923,7 @@ class Ad4mModel {
18916
18923
  ...(options.initial !== undefined && { initial: options.initial }),
18917
18924
  ...(options.resolveLanguage !== undefined && { resolveLanguage: options.resolveLanguage }),
18918
18925
  ...(options.getter !== undefined && { getter: options.getter }),
18926
+ ...(options.surrealGetter !== undefined && { surrealGetter: options.surrealGetter }),
18919
18927
  ...(options.setter !== undefined && { setter: options.setter }),
18920
18928
  ...(options.local !== undefined && { local: options.local }),
18921
18929
  ...(options.transform !== undefined && { transform: options.transform }),
@@ -18931,7 +18939,8 @@ class Ad4mModel {
18931
18939
  name: collectionName,
18932
18940
  predicate: options.through || "",
18933
18941
  ...(options.where !== undefined && { where: options.where }),
18934
- ...(options.local !== undefined && { local: options.local })
18942
+ ...(options.local !== undefined && { local: options.local }),
18943
+ ...(options.surrealGetter !== undefined && { surrealGetter: options.surrealGetter })
18935
18944
  };
18936
18945
  }
18937
18946
  // Fallback: If both structures are empty but a JSON schema is attached, derive from it
@@ -19152,20 +19161,30 @@ class Ad4mModel {
19152
19161
  `;
19153
19162
  const links = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").querySurrealDB(linksQuery);
19154
19163
  if (links && links.length > 0) {
19164
+ let minTimestamp = null;
19155
19165
  let maxTimestamp = null;
19156
19166
  let latestAuthor = null;
19157
- // Process properties
19167
+ let originalAuthor = null;
19168
+ // Process properties (skip those with surrealGetter)
19158
19169
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
19170
+ if (propMeta.surrealGetter)
19171
+ continue; // Handle via surrealGetter evaluation
19159
19172
  const matching = links.filter((l) => l.predicate === propMeta.predicate);
19160
19173
  if (matching.length > 0) {
19161
19174
  // "Latest wins" semantics: select the last element since links are ordered ASC.
19162
19175
  // The last element has the most recent timestamp and represents the current property value.
19163
19176
  const link = matching[matching.length - 1];
19164
19177
  let value = link.target;
19165
- // Track timestamp/author
19166
- if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
19167
- maxTimestamp = link.timestamp;
19168
- latestAuthor = link.author;
19178
+ // Track timestamps/authors for createdAt and updatedAt
19179
+ if (link.timestamp) {
19180
+ if (!minTimestamp || link.timestamp < minTimestamp) {
19181
+ minTimestamp = link.timestamp;
19182
+ originalAuthor = link.author;
19183
+ }
19184
+ if (!maxTimestamp || link.timestamp > maxTimestamp) {
19185
+ maxTimestamp = link.timestamp;
19186
+ latestAuthor = link.author;
19187
+ }
19169
19188
  }
19170
19189
  // Handle resolveLanguage
19171
19190
  if (propMeta.resolveLanguage && propMeta.resolveLanguage !== 'literal') {
@@ -19201,21 +19220,44 @@ class Ad4mModel {
19201
19220
  this[propName] = value;
19202
19221
  }
19203
19222
  }
19204
- // Process collections
19223
+ // Process collections (skip those with surrealGetter)
19205
19224
  for (const [collName, collMeta] of Object.entries(metadata.collections)) {
19225
+ if (collMeta.surrealGetter)
19226
+ continue; // Handle via surrealGetter evaluation
19206
19227
  const matching = links.filter((l) => l.predicate === collMeta.predicate);
19207
19228
  // Collections preserve chronological order: links are sorted ASC by timestamp,
19208
19229
  // so the collection reflects the order in which items were added (oldest to newest).
19209
- this[collName] = matching.map((l) => l.target);
19230
+ let values = matching.map((l) => l.target);
19231
+ // Apply where.isInstance filtering if present
19232
+ if (collMeta.where?.isInstance && values.length > 0) {
19233
+ try {
19234
+ const className = typeof collMeta.where.isInstance === 'string'
19235
+ ? collMeta.where.isInstance
19236
+ : collMeta.where.isInstance.name;
19237
+ const filterMetadata = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").getSubjectClassMetadataFromSDNA(className);
19238
+ if (filterMetadata) {
19239
+ values = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").batchCheckSubjectInstances(values, filterMetadata);
19240
+ }
19241
+ }
19242
+ catch (error) {
19243
+ // Keep unfiltered values on error
19244
+ }
19245
+ }
19246
+ this[collName] = values;
19247
+ }
19248
+ // Set author and timestamps
19249
+ if (originalAuthor) {
19250
+ this.author = originalAuthor;
19210
19251
  }
19211
- // Set author and timestamp
19212
- if (latestAuthor) {
19213
- this.author = latestAuthor;
19252
+ if (minTimestamp) {
19253
+ this.createdAt = minTimestamp;
19214
19254
  }
19215
19255
  if (maxTimestamp) {
19216
- this.timestamp = maxTimestamp;
19256
+ this.updatedAt = maxTimestamp;
19217
19257
  }
19218
19258
  }
19259
+ // Evaluate SurrealQL getters
19260
+ await ctor.evaluateSurrealGettersForInstance(this, __classPrivateFieldGet(this, _Ad4mModel_perspective, "f"), metadata);
19219
19261
  }
19220
19262
  catch (e) {
19221
19263
  console.error(`SurrealDB getData also failed for ${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}:`, e);
@@ -19244,6 +19286,51 @@ class Ad4mModel {
19244
19286
  `;
19245
19287
  return fullQuery;
19246
19288
  }
19289
+ /**
19290
+ * Evaluates custom SurrealQL getters for properties and collections on a specific instance.
19291
+ * @private
19292
+ */
19293
+ static async evaluateSurrealGettersForInstance(instance, perspective, metadata) {
19294
+ const safeBaseExpression = this.formatSurrealValue(instance.baseExpression);
19295
+ // Evaluate property surrealGetters
19296
+ for (const [propName, propMeta] of Object.entries(metadata.properties)) {
19297
+ if (propMeta.surrealGetter) {
19298
+ try {
19299
+ // Replace 'Base' placeholder with actual base expression
19300
+ const query = propMeta.surrealGetter.replace(/Base/g, safeBaseExpression);
19301
+ // Query from node table to have graph traversal context
19302
+ const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
19303
+ if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null && result[0].value !== 'None' && result[0].value !== '') {
19304
+ instance[propName] = result[0].value;
19305
+ }
19306
+ }
19307
+ catch (error) {
19308
+ console.warn(`Failed to evaluate surrealGetter for ${propName}:`, error);
19309
+ }
19310
+ }
19311
+ }
19312
+ // Evaluate collection surrealGetters
19313
+ for (const [collName, collMeta] of Object.entries(metadata.collections)) {
19314
+ if (collMeta.surrealGetter) {
19315
+ try {
19316
+ // Replace 'Base' placeholder with actual base expression
19317
+ const query = collMeta.surrealGetter.replace(/Base/g, safeBaseExpression);
19318
+ // Query from node table to have graph traversal context
19319
+ const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
19320
+ if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null) {
19321
+ // Filter out 'None' from collection results
19322
+ const value = result[0].value;
19323
+ instance[collName] = Array.isArray(value)
19324
+ ? value.filter((v) => v && v !== '' && v !== 'None')
19325
+ : value;
19326
+ }
19327
+ }
19328
+ catch (error) {
19329
+ console.warn(`Failed to evaluate surrealGetter for ${collName}:`, error);
19330
+ }
19331
+ }
19332
+ }
19333
+ }
19247
19334
  /**
19248
19335
  * Generates a SurrealQL query from a Query object.
19249
19336
  *
@@ -19646,8 +19733,9 @@ WHERE ${whereConditions.join(' AND ')}
19646
19733
  fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}') AS ${collName}`);
19647
19734
  }
19648
19735
  // Always add author and timestamp fields
19649
- fields.push(`(SELECT VALUE author FROM link WHERE source = source LIMIT 1) AS author`);
19650
- fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source LIMIT 1) AS timestamp`);
19736
+ fields.push(`(SELECT VALUE author FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS author`);
19737
+ fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS createdAt`);
19738
+ fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp DESC LIMIT 1) AS updatedAt`);
19651
19739
  return fields.join(',\n ');
19652
19740
  }
19653
19741
  /**
@@ -19678,9 +19766,10 @@ WHERE ${whereConditions.join(' AND ')}
19678
19766
  const escapedPredicate = escapeSurrealString(collMeta.predicate);
19679
19767
  fields.push(`target[WHERE predicate = '${escapedPredicate}'] AS ${collName}`);
19680
19768
  }
19681
- // Always add author and timestamp fields using array::first
19769
+ // Always add author and timestamp fields
19682
19770
  fields.push(`array::first(author) AS author`);
19683
- fields.push(`array::first(timestamp) AS timestamp`);
19771
+ fields.push(`array::first(timestamp) AS createdAt`);
19772
+ fields.push(`array::last(timestamp) AS updatedAt`);
19684
19773
  return fields.join(',\n ');
19685
19774
  }
19686
19775
  /**
@@ -19779,8 +19868,10 @@ WHERE ${whereConditions.join(' AND ')}
19779
19868
  }
19780
19869
  const links = row.links || [];
19781
19870
  const instance = new this(perspective, base);
19782
- // Track the most recent timestamp and corresponding author
19871
+ // Track both earliest (createdAt) and most recent (updatedAt) timestamps
19872
+ let minTimestamp = null;
19783
19873
  let maxTimestamp = null;
19874
+ let originalAuthor = null;
19784
19875
  let latestAuthor = null;
19785
19876
  // Process each link (track index for collection ordering)
19786
19877
  for (let linkIndex = 0; linkIndex < links.length; linkIndex++) {
@@ -19790,14 +19881,22 @@ WHERE ${whereConditions.join(' AND ')}
19790
19881
  // Skip 'None' values
19791
19882
  if (target === 'None')
19792
19883
  continue;
19793
- // Track the most recent timestamp and its author
19794
- if (link.timestamp && (!maxTimestamp || link.timestamp > maxTimestamp)) {
19795
- maxTimestamp = link.timestamp;
19796
- latestAuthor = link.author;
19884
+ // Track both earliest (createdAt) and latest (updatedAt) timestamps with their authors
19885
+ if (link.timestamp) {
19886
+ if (!minTimestamp || link.timestamp < minTimestamp) {
19887
+ minTimestamp = link.timestamp;
19888
+ originalAuthor = link.author;
19889
+ }
19890
+ if (!maxTimestamp || link.timestamp > maxTimestamp) {
19891
+ maxTimestamp = link.timestamp;
19892
+ latestAuthor = link.author;
19893
+ }
19797
19894
  }
19798
- // Find matching property
19895
+ // Find matching property (skip those with surrealGetter)
19799
19896
  let foundProperty = false;
19800
19897
  for (const [propName, propMeta] of Object.entries(metadata.properties)) {
19898
+ if (propMeta.surrealGetter)
19899
+ continue; // Handle via surrealGetter evaluation
19801
19900
  if (propMeta.predicate === predicate) {
19802
19901
  // For properties, take the first value (or we could use timestamp to get latest)
19803
19902
  // Note: Empty objects {} are truthy, so we need to check for them explicitly
@@ -19867,9 +19966,11 @@ WHERE ${whereConditions.join(' AND ')}
19867
19966
  break;
19868
19967
  }
19869
19968
  }
19870
- // If not a property, check if it's a collection
19969
+ // If not a property, check if it's a collection (skip those with surrealGetter)
19871
19970
  if (!foundProperty) {
19872
19971
  for (const [collName, collMeta] of Object.entries(metadata.collections)) {
19972
+ if (collMeta.surrealGetter)
19973
+ continue; // Handle via surrealGetter evaluation
19873
19974
  if (collMeta.predicate === predicate) {
19874
19975
  // For collections, accumulate all values with their timestamps and indices for sorting
19875
19976
  if (!instance[collName]) {
@@ -19895,20 +19996,34 @@ WHERE ${whereConditions.join(' AND ')}
19895
19996
  }
19896
19997
  }
19897
19998
  }
19898
- // Set author and timestamp from the most recent link
19899
- if (latestAuthor && maxTimestamp) {
19900
- instance.author = latestAuthor;
19901
- // Convert timestamp to number (milliseconds) if it's an ISO string
19999
+ // Set author and timestamps
20000
+ if (originalAuthor) {
20001
+ instance.author = originalAuthor;
20002
+ }
20003
+ // Set createdAt from earliest timestamp
20004
+ if (minTimestamp) {
20005
+ if (typeof minTimestamp === 'string' && minTimestamp.includes('T')) {
20006
+ instance.createdAt = new Date(minTimestamp).getTime();
20007
+ }
20008
+ else if (typeof minTimestamp === 'string') {
20009
+ const parsed = parseInt(minTimestamp, 10);
20010
+ instance.createdAt = isNaN(parsed) ? minTimestamp : parsed;
20011
+ }
20012
+ else {
20013
+ instance.createdAt = minTimestamp;
20014
+ }
20015
+ }
20016
+ // Set updatedAt from most recent timestamp
20017
+ if (maxTimestamp) {
19902
20018
  if (typeof maxTimestamp === 'string' && maxTimestamp.includes('T')) {
19903
- instance.timestamp = new Date(maxTimestamp).getTime();
20019
+ instance.updatedAt = new Date(maxTimestamp).getTime();
19904
20020
  }
19905
20021
  else if (typeof maxTimestamp === 'string') {
19906
- // Try to parse as number string
19907
20022
  const parsed = parseInt(maxTimestamp, 10);
19908
- instance.timestamp = isNaN(parsed) ? maxTimestamp : parsed;
20023
+ instance.updatedAt = isNaN(parsed) ? maxTimestamp : parsed;
19909
20024
  }
19910
20025
  else {
19911
- instance.timestamp = maxTimestamp;
20026
+ instance.updatedAt = maxTimestamp;
19912
20027
  }
19913
20028
  }
19914
20029
  // Sort collections by timestamp to maintain insertion order
@@ -19932,8 +20047,10 @@ WHERE ${whereConditions.join(' AND ')}
19932
20047
  // Use original index as tiebreaker for stable sorting
19933
20048
  return a.originalIndex - b.originalIndex;
19934
20049
  });
19935
- // Replace collection with sorted values
19936
- instance[collName] = pairs.map(p => p.value);
20050
+ // Replace collection with sorted values, filtering out empty strings and None
20051
+ instance[collName] = pairs
20052
+ .map(p => p.value)
20053
+ .filter((v) => v && v !== '' && v !== 'None');
19937
20054
  // Clean up temporary arrays
19938
20055
  delete instance[timestampsKey];
19939
20056
  delete instance[indicesKey];
@@ -19955,6 +20072,40 @@ WHERE ${whereConditions.join(' AND ')}
19955
20072
  console.error(`Failed to process SurrealDB instance ${base}:`, error);
19956
20073
  }
19957
20074
  }
20075
+ // Evaluate SurrealQL getters for all instances
20076
+ for (const instance of instances) {
20077
+ await this.evaluateSurrealGettersForInstance(instance, perspective, metadata);
20078
+ }
20079
+ // Filter collections by where.isInstance if specified
20080
+ // Do this for all instances that have collections with filters
20081
+ for (const instance of instances) {
20082
+ for (const [collName, collMeta] of Object.entries(metadata.collections)) {
20083
+ if (collMeta.where?.isInstance && instance[collName]?.length > 0) {
20084
+ try {
20085
+ const targetClass = collMeta.where.isInstance;
20086
+ const subjects = instance[collName];
20087
+ // Get the class metadata from SDNA to pass to batchCheckSubjectInstances
20088
+ const targetClassName = typeof targetClass === 'string'
20089
+ ? targetClass
20090
+ : targetClass.prototype?.className || targetClass.name;
20091
+ const classMetadata = await perspective.getSubjectClassMetadataFromSDNA(targetClassName);
20092
+ if (!classMetadata) {
20093
+ continue;
20094
+ }
20095
+ // Check which subjects are instances of the target class
20096
+ const validSubjects = await perspective.batchCheckSubjectInstances(subjects, classMetadata);
20097
+ instance[collName] = validSubjects;
20098
+ }
20099
+ catch (error) {
20100
+ // On error, leave the collection unfiltered rather than breaking everything
20101
+ }
20102
+ }
20103
+ }
20104
+ }
20105
+ // Evaluate SurrealQL getters for all instances
20106
+ for (const instance of instances) {
20107
+ await this.evaluateSurrealGettersForInstance(instance, perspective, metadata);
20108
+ }
19958
20109
  // Filter by where conditions that couldn't be filtered in SQL
19959
20110
  // This includes:
19960
20111
  // - author/timestamp (computed from grouped links)