Skip to content

feat: validate promoted properties and enhance Scriban array access - #154

Merged
AhmadRAbuhussein merged 2 commits into
releases/r8.0from
feat/validate-promoted-properties-and-fix-scriban-array-access
May 10, 2026
Merged

feat: validate promoted properties and enhance Scriban array access#154
AhmadRAbuhussein merged 2 commits into
releases/r8.0from
feat/validate-promoted-properties-and-fix-scriban-array-access

Conversation

@hamzahalq

@hamzahalq hamzahalq commented May 10, 2026

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • Bug Fixes

    • Document property validation now detects duplicate keys and enforces format-specific path syntax rules.
  • Improvements

    • Simplified template access for JSON arrays, enabling flexible field reference patterns.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 10, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@hamzahalq has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 45 minutes and 5 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d363f7c9-9972-4513-a790-3bf08ae32808

📥 Commits

Reviewing files that changed from the base of the PR and between ab7a634 and 5f7d18b.

📒 Files selected for processing (1)
  • SW.Bitween.Api/Resources/Documents/Update.cs
📝 Walkthrough

Walkthrough

This PR adds document update validation for promoted properties paths and improves Scriban template array member resolution. The first change validates promoted property keys, values, and path syntax (JSON JSONPath or XML XPath patterns) before applying updates. The second introduces a SmartArray wrapper enabling templates to access array element fields directly.

Changes

Document Promoted Properties Validation

Layer / File(s) Summary
Validation Imports
SW.Bitween.Api/Resources/Documents/Update.cs
Adds System.Text.RegularExpressions import for regex-based path validation.
Validation Logic
SW.Bitween.Api/Resources/Documents/Update.cs
Validates promoted properties: rejects empty keys/values, enforces format-specific path patterns (JSON JSONPath/identifier or XML XPath-like), and detects case-insensitive duplicate keys before update.

SmartArray Scriban Template Support

Layer / File(s) Summary
Scriban Import
SW.Bitween.NativeAdapters/JsonMapper/ScribanJsonHelper.cs
Adds Scriban.Parsing namespace for SmartArray override signature.
SmartArray Class
SW.Bitween.NativeAdapters/JsonMapper/ScribanJsonHelper.cs
Introduces SmartArray : ScriptArray that overrides member lookup to delegate to first element when base lookup fails.
JArray Conversion Integration
SW.Bitween.NativeAdapters/JsonMapper/ScribanJsonHelper.cs
Changes JSON-to-Scriban conversion to wrap JArray tokens in SmartArray instead of materializing to enumerable lists.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐰 Arrays now bow to Scriban's grace,
While paths are checked in validation's space,
Two changes blend with careful care,
Templates dance through JSON's air! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically summarizes both main changes: validation of promoted properties and enhancement of Scriban array access, matching the actual modifications in the changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/validate-promoted-properties-and-fix-scriban-array-access

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
SW.Bitween.NativeAdapters/JsonMapper/ScribanJsonHelper.cs (1)

111-131: ⚖️ Poor tradeoff

SmartArray implementation is correct but consider adding diagnostics.

The delegation logic correctly handles edge cases (empty arrays, non-object elements, existing array members). However, the implicit member delegation can make debugging difficult for template authors.

Consider adding diagnostic logging or a template context variable that tracks when delegation occurs, helping developers understand when they're accessing array.field vs array[0].field.

💡 Example: Add optional delegation tracking
 public override bool TryGetValue(TemplateContext context, SourceSpan span, string member, out object? value)
 {
     if (base.TryGetValue(context, span, member, out value))
         return true;

     if (Count > 0 && this[0] is ScriptObject first)
+    {
+        // Optional: Track or log delegation for debugging
+        // context.SetValue("__delegated_member_access", true);
         return first.TryGetValue(context, span, member, out value);
+    }

     value = null;
     return false;
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@SW.Bitween.NativeAdapters/JsonMapper/ScribanJsonHelper.cs` around lines 111 -
131, Add optional diagnostics to SmartArray to make implicit delegation visible:
modify the SmartArray class (the override of TryGetValue) to record when
delegation occurs (i.e., when Count > 0 and this[0] is ScriptObject and you call
first.TryGetValue) by emitting a diagnostic via the existing logging/telemetry
mechanism or by setting a flag on the TemplateContext/ScriptObject (or pushing a
special context variable) so templates can inspect it; ensure the diagnostic is
optional/configurable (off by default) and does not change TryGetValue behavior
or return values, and reference SmartArray, TryGetValue, ScriptArray, and
ScriptObject when adding the hook so reviewers can find the change quickly.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@SW.Bitween.Api/Resources/Documents/Update.cs`:
- Around line 61-65: The current validation rejects bracket-based array access
like "items[0].name"; update the regex used in the non-'$' branch in Update.cs
(where pp.Value.Trim() is validated and the SWValidationException is thrown) to
allow square-bracket numeric indexes. Replace the existing pattern
@"^[a-zA-Z_][a-zA-Z0-9_.]*$" with a pattern that permits dot-separated
identifiers and numeric bracket access, e.g.
@"^[a-zA-Z_][a-zA-Z0-9_]*(?:(\.[a-zA-Z_][a-zA-Z0-9_]*)|(\[[0-9]+\]))*$", so
paths like items[0].name are accepted while keeping the same overall validation
and error path (the throw of SWValidationException for invalid promoted property
paths).

In `@SW.Bitween.NativeAdapters/JsonMapper/ScribanJsonHelper.cs`:
- Line 106: The conversion of JArray to SmartArray in the ToScribanValue mapping
(JArray a => new SmartArray(a.Select(ToScribanValue))) can silently drop data
when templates use member access and only the first element is returned; update
the JArray handling in ToScribanValue/ToScribanValueEnumerable to detect
multi-element arrays and either (a) wrap them in a collection type that
preserves all elements for iteration, (b) log/warn via the existing logging
facility when a SmartArray is created from an array with Count > 1, or (c) throw
a clear exception to force template authors to handle multi-element arrays
explicitly; reference JArray, SmartArray, and ToScribanValue when making the
change so reviewers can find the mapping and then add the chosen
validation/logging behavior and update any docs/comments accordingly.

---

Nitpick comments:
In `@SW.Bitween.NativeAdapters/JsonMapper/ScribanJsonHelper.cs`:
- Around line 111-131: Add optional diagnostics to SmartArray to make implicit
delegation visible: modify the SmartArray class (the override of TryGetValue) to
record when delegation occurs (i.e., when Count > 0 and this[0] is ScriptObject
and you call first.TryGetValue) by emitting a diagnostic via the existing
logging/telemetry mechanism or by setting a flag on the
TemplateContext/ScriptObject (or pushing a special context variable) so
templates can inspect it; ensure the diagnostic is optional/configurable (off by
default) and does not change TryGetValue behavior or return values, and
reference SmartArray, TryGetValue, ScriptArray, and ScriptObject when adding the
hook so reviewers can find the change quickly.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 86665962-abd6-408c-8395-96fe0199a37f

📥 Commits

Reviewing files that changed from the base of the PR and between 6dfbec7 and ab7a634.

📒 Files selected for processing (2)
  • SW.Bitween.Api/Resources/Documents/Update.cs
  • SW.Bitween.NativeAdapters/JsonMapper/ScribanJsonHelper.cs

Comment thread SW.Bitween.Api/Resources/Documents/Update.cs
{
JObject o => BuildScriptObject(o),
JArray a => a.Select(ToScribanValue).ToList(),
JArray a => new SmartArray(a.Select(ToScribanValue)),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Risk of silent data loss when accessing multi-element arrays.

Converting all JArray instances to SmartArray enables data.field syntax for array elements, but when an array contains multiple elements, only the first element is accessed. Template authors might not realize they're working with a multi-element array, leading to incomplete data processing.

Consider adding validation or logging when SmartArray member access is used on arrays with more than one element, or document this limitation prominently in template guidelines.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@SW.Bitween.NativeAdapters/JsonMapper/ScribanJsonHelper.cs` at line 106, The
conversion of JArray to SmartArray in the ToScribanValue mapping (JArray a =>
new SmartArray(a.Select(ToScribanValue))) can silently drop data when templates
use member access and only the first element is returned; update the JArray
handling in ToScribanValue/ToScribanValueEnumerable to detect multi-element
arrays and either (a) wrap them in a collection type that preserves all elements
for iteration, (b) log/warn via the existing logging facility when a SmartArray
is created from an array with Count > 1, or (c) throw a clear exception to force
template authors to handle multi-element arrays explicitly; reference JArray,
SmartArray, and ToScribanValue when making the change so reviewers can find the
mapping and then add the chosen validation/logging behavior and update any
docs/comments accordingly.

@AhmadRAbuhussein
AhmadRAbuhussein merged commit 657137d into releases/r8.0 May 10, 2026
2 checks passed
@MusaMisto
MusaMisto deleted the feat/validate-promoted-properties-and-fix-scriban-array-access branch July 2, 2026 09:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants