Skip to content
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
ad183a1
:safety_vest: enforce decodeDotInKeys and allowDots option consistenc…
techouse Aug 23, 2025
063cc5a
:bug: fix dot notation encoding in key splitter; handle top-level dot…
techouse Aug 23, 2025
c93546b
:white_check_mark: add tests for allowDots and decodeDotInKeys consis…
techouse Aug 23, 2025
9fab5d6
:white_check_mark: add comprehensive tests for encoded dot behavior i…
techouse Aug 23, 2025
50d4954
:recycle: refactor DecodeOptions to support legacy decoders and unify…
techouse Aug 23, 2025
6463554
:white_check_mark: add tests for encoded dot handling in keys and cus…
techouse Aug 23, 2025
bcbc1da
:bug: fix list limit enforcement and unify key/value decoding in parser
techouse Aug 23, 2025
8adba03
:fire: remove unused import of DecodeKind from qs.dart
techouse Aug 23, 2025
ded63d7
:bulb: update decode.dart comments to clarify key decoding and dot/br…
techouse Aug 23, 2025
8f05037
:bulb: clarify DecodeOptions docs for allowDots and decodeDotInKeys i…
techouse Aug 23, 2025
4da9a47
:recycle: simplify custom decoder handling in DecodeOptions; remove d…
techouse Aug 23, 2025
00913be
:white_check_mark: update tests to use new decoder signature with Dec…
techouse Aug 23, 2025
61e8b05
:truck: move _dotToBracketTopLevel to QS extension as static helper; …
techouse Aug 23, 2025
b102a4d
:bug: preserve leading dot in key decoding except for degenerate ".["…
techouse Aug 23, 2025
e1a29c9
:white_check_mark: add tests for leading and double dot handling with…
techouse Aug 23, 2025
e75b21d
:fire: remove legacy dynamic decoder fallback tests and helper class
techouse Aug 23, 2025
c9c6a7b
:bug: fix list limit check to account for current list length when sp…
techouse Aug 23, 2025
8f47a6a
:bug: fix parameter splitting to correctly enforce limit and wrap exc…
techouse Aug 23, 2025
5e0466d
:white_check_mark: fix custom percent-decoding logic to handle non-en…
techouse Aug 23, 2025
e6924e2
:bulb: update cleanRoot comment
techouse Aug 23, 2025
47e155b
:bulb: clarify negative listLimit behavior and list growth checks in …
techouse Aug 23, 2025
029b12f
:bulb: clarify listLimit negative value behavior and throwOnLimitExce…
techouse Aug 23, 2025
4d32fcd
:white_check_mark: improve decode tests for nested list handling, lis…
techouse Aug 23, 2025
69445f7
:bulb: update comments
techouse Aug 23, 2025
398ef76
:bulb: clarify handling of percent-encoded dots in keys and list grow…
techouse Aug 23, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
182 changes: 127 additions & 55 deletions lib/src/extensions/decode.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// ignore_for_file: deprecated_member_use_from_same_package
part of '../qs.dart';

/// Decoder: query-string → nested Dart maps/lists (Node `qs` parity)
Expand All @@ -16,17 +17,9 @@ part of '../qs.dart';
/// Implementation notes:
/// - We decode key parts lazily and then "reduce" right-to-left to build the
/// final structure in `_parseObject`.
/// - We never mutate caller-provided containers; fresh maps/lists are created.
/// - No behavioral changes are introduced here; comments only.

/// Split operation result used by the decoder helpers.
/// - `parts`: collected key segments.
/// - `exceeded`: indicates whether a configured limit was exceeded during split.
typedef SplitResult = ({List<String> parts, bool exceeded});

/// Normalizes simple dot notation to bracket notation (e.g. `a.b` → `a[b]`).
/// Only matches \nondotted, non-bracketed tokens so `a.b.c` becomes `a[b][c]`.
final RegExp _dotToBracket = RegExp(r'\.([^.\[]+)');
/// - We never mutate caller-provided containers; fresh maps/lists are allocated for merges.
/// - The implementation aims to match `qs` semantics; comments explain how each phase maps
/// to the reference behavior.

/// Internal decoding surface grouped under the `QS` extension.
///
Expand All @@ -50,7 +43,7 @@ extension _$Decode on QS {
if (val is String && val.isNotEmpty && options.comma && val.contains(',')) {
final List<String> splitVal = val.split(',');
if (options.throwOnLimitExceeded &&
currentListLength + splitVal.length > options.listLimit) {
(currentListLength + splitVal.length) > options.listLimit) {
throw RangeError(
'List limit exceeded. '
'Only ${options.listLimit} element${options.listLimit == 1 ? '' : 's'} allowed in a list.',
Expand All @@ -61,7 +54,7 @@ extension _$Decode on QS {

// Guard incremental growth of an existing list as we parse additional items.
if (options.throwOnLimitExceeded &&
currentListLength + 1 > options.listLimit) {
currentListLength >= options.listLimit) {
throw RangeError(
'List limit exceeded. '
'Only ${options.listLimit} element${options.listLimit == 1 ? '' : 's'} allowed in a list.',
Expand All @@ -73,7 +66,8 @@ extension _$Decode on QS {

/// Tokenizes the raw query-string into a flat key→value map before any
/// structural reconstruction. Handles:
/// - query prefix removal (`?`), percent-decoding via `options.decoder`
/// - query prefix removal (`?`), and kind‑aware decoding via `DecodeOptions.decodeKey` /
/// `DecodeOptions.decodeValue` (by default these percent‑decode)
/// - charset sentinel detection (`utf8=`) per `qs`
/// - duplicate key policy (combine/first/last)
/// - parameter and list limits with optional throwing behavior
Expand All @@ -99,15 +93,15 @@ extension _$Decode on QS {
final List<String> allParts = cleanStr.split(options.delimiter);
late final List<String> parts;
if (limit != null && limit > 0) {
final int takeCount = options.throwOnLimitExceeded ? limit + 1 : limit;
final int count =
allParts.length < takeCount ? allParts.length : takeCount;
parts = allParts.sublist(0, count);
if (options.throwOnLimitExceeded && allParts.length > limit) {
throw RangeError(
'Parameter limit exceeded. Only $limit parameter${limit == 1 ? '' : 's'} allowed.',
);
}
parts = allParts.sublist(
0,
allParts.length < limit ? allParts.length : limit,
);
} else {
parts = allParts;
}
Expand Down Expand Up @@ -145,15 +139,14 @@ extension _$Decode on QS {

late final String key;
dynamic val;
// Decode key/value using key-aware decoder, no %2E protection shim.
// Decode key/value via DecodeOptions.decodeKey/decodeValue (kind-aware).
if (pos == -1) {
// Decode bare key (no '=') using key-aware decoder
key = options.decoder(part, charset: charset, kind: DecodeKind.key);
// Decode bare key (no '=') using key-aware decoding
key = options.decodeKey(part, charset: charset) ?? '';
val = options.strictNullHandling ? null : '';
} else {
// Decode key slice using key-aware decoder; values decode as value kind
key = options.decoder(part.slice(0, pos),
charset: charset, kind: DecodeKind.key);
// Decode the key slice as a key; values decode as values
key = options.decodeKey(part.slice(0, pos), charset: charset) ?? '';
// Decode the substring *after* '=', applying list parsing and the configured decoder.
val = Utils.apply<dynamic>(
_parseListValue(
Expand All @@ -163,8 +156,7 @@ extension _$Decode on QS {
? (obj[key] as List).length
: 0,
),
(dynamic v) =>
options.decoder(v, charset: charset, kind: DecodeKind.value),
(dynamic v) => options.decodeValue(v as String?, charset: charset),
);
}

Expand Down Expand Up @@ -206,6 +198,9 @@ extension _$Decode on QS {
/// - When `allowEmptyLists` is true, an empty string (or `null` under
/// `strictNullHandling`) under a `[]` segment yields an empty list.
/// - `listLimit` applies to explicit numeric indices as an upper bound.
/// - Keys arrive already decoded (top‑level encoded dots become literal `.` before we get here).
/// Whether top‑level dots split was decided earlier by `_splitKeyIntoSegments` (based on
/// `allowDots`). Numeric list indices are only honored for *bracketed* numerics like `[3]`.
static dynamic _parseObject(
List<String> chain,
dynamic val,
Expand Down Expand Up @@ -255,8 +250,9 @@ extension _$Decode on QS {
: Utils.combine([], leaf);
} else {
obj = <String, dynamic>{};
// Normalize bracketed segments ("[k]") and optionally decode `%2E` → '.'
// when `decodeDotInKeys` is enabled.
// Normalize bracketed segments ("[k]"). Keys have already been percent‑decoded earlier by
// `decodeKey`, so `%2E/%2e` are not present here; dot‑notation splitting (if any) already
// happened in `_splitKeyIntoSegments`.
final String cleanRoot = root.startsWith('[') && root.endsWith(']')
? root.slice(1, root.length - 1)
: root;
Expand Down Expand Up @@ -313,20 +309,22 @@ extension _$Decode on QS {
}

/// Splits a key like `a[b][0][c]` into `['a', '[b]', '[0]', '[c]']` with:
/// - dot-notation normalization (`a.b` → `a[b]`) when `allowDots` is true
/// - dotnotation normalization (`a.b` → `a[b]`) when `allowDots` is true (runs before splitting)
/// - depth limiting (depth=0 returns the whole key as a single segment)
/// - bracket group balancing, preserving unterminated tails as a single
/// remainder segment unless `strictDepth` is enabled (then it throws)
/// - balanced bracket grouping; an unterminated `[` causes the *entire key* to be treated as a
/// single literal segment (matching `qs`)
/// - when there are additional groups/text beyond `maxDepth`:
/// • if `strictDepth` is true, we throw;
/// • otherwise the remainder is wrapped as one final bracket segment (e.g., `"[rest]"`)
static List<String> _splitKeyIntoSegments({
required String originalKey,
required bool allowDots,
required int maxDepth,
required bool strictDepth,
}) {
// Optionally normalize `a.b` to `a[b]` before splitting.
final String key = allowDots
? originalKey.replaceAllMapped(_dotToBracket, (m) => '[${m[1]}]')
: originalKey;
final String key =
allowDots ? _dotToBracketTopLevel(originalKey) : originalKey;

// Depth==0 → do not split at all (reference `qs` behavior).
if (maxDepth <= 0) {
Expand All @@ -335,67 +333,141 @@ extension _$Decode on QS {

final List<String> segments = [];

// Extract the parent token (before the first '['), if any.
// Parent token before the first '[' (may be empty when key starts with '[')
final int first = key.indexOf('[');
final String parent = first >= 0 ? key.substring(0, first) : key;
if (parent.isNotEmpty) segments.add(parent);

final int n = key.length;
int open = first;
int depth = 0;
int collected = 0;
int lastClose = -1;

while (open >= 0 && depth < maxDepth) {
// Balance nested brackets inside this group: "[ ... possibly [] ... ]"
while (open >= 0 && collected < maxDepth) {
int level = 1;
int i = open + 1;
int close = -1;

// Balance nested '[' and ']' within this group.
while (i < n) {
final int ch = key.codeUnitAt(i);
if (ch == 0x5B) {
// '['
final int cu = key.codeUnitAt(i);
if (cu == 0x5B) {
level++;
} else if (ch == 0x5D) {
// ']'
} else if (cu == 0x5D) {
level--;
if (level == 0) {
close = i;
break;
}
}
// Advance inside the current bracket group until it balances.
i++;
}

if (close < 0) {
// Unterminated group, stop collecting groups
break;
// Unterminated group: treat the entire key as a single literal segment (qs semantics).
return <String>[key];
}

segments.add(key.substring(open, close + 1)); // includes enclosing [ ]
depth++;
segments
.add(key.substring(open, close + 1)); // balanced group, includes [ ]
lastClose = close;
collected++;

// find next group, starting after this one
// Find the next '[' after this balanced group.
open = key.indexOf('[', close + 1);
}

// If additional groups remain beyond the allowed depth, either throw or
// stash the remainder as a single segment, per `strictDepth`.
if (open >= 0) {
// We still have remainder starting with '['
// Trailing text after the last balanced group → one final bracket segment (unless it's just '.').
if (lastClose >= 0 && lastClose + 1 < n) {
final String remainder = key.substring(lastClose + 1);
if (remainder != '.') {
if (strictDepth && open >= 0) {
throw RangeError(
'Input depth exceeded $maxDepth and strictDepth is true');
}
segments.add('[$remainder]');
}
} else if (open >= 0) {
// There are more groups beyond the collected depth.
if (strictDepth) {
throw RangeError(
'Input depth exceeded $maxDepth and strictDepth is true');
}
// Stash the remainder as a single segment (qs behavior)
// Wrap the remaining bracket groups as a single literal segment.
// Example: key="a[b][c][d]", depth=2 → segment="[[c][d]]" which becomes "[c][d]" later.
segments.add('[${key.substring(open)}]');
}

return segments;
}

/// Convert top‑level dots to bracket segments (depth‑aware).
/// - Only dots at depth == 0 split.
/// - Dots inside `[...]` are preserved.
/// - Degenerate cases are preserved and do not create empty segments:
/// * leading '.' (e.g., ".a") keeps the dot literal,
/// * double dots ("a..b") keep the first dot literal,
/// * trailing dot ("a.") keeps the trailing dot (which is ignored by the splitter).
/// - Percent‑encoded dots are not handled here because keys have already been decoded by
/// `DecodeOptions.decodeKey` (defaulting to percent‑decoding).
static String _dotToBracketTopLevel(String s) {
if (s.isEmpty || !s.contains('.')) return s;
final StringBuffer sb = StringBuffer();
int depth = 0;
int i = 0;
while (i < s.length) {
final ch = s[i];
if (ch == '[') {
depth++;
sb.write(ch);
i++;
} else if (ch == ']') {
if (depth > 0) depth--;
sb.write(ch);
i++;
} else if (ch == '.') {
if (depth == 0) {
final bool hasNext = i + 1 < s.length;
final String next = hasNext ? s[i + 1] : '\u0000';

// preserve a *leading* '.' as a literal, unless it's the ".[" degenerate.
if (i == 0 && (!hasNext || next != '[')) {
sb.write('.');
i++;
} else if (hasNext && next == '[') {
// Degenerate ".[" → skip the dot so "a.[b]" behaves like "a[b]".
i++; // consume the '.'
} else if (!hasNext || next == '.') {
// Preserve literal dot for trailing/duplicate dots.
sb.write('.');
i++;
} else {
// Normal split: convert a.b → a[b] at top level.
final int start = ++i;
int j = start;
while (j < s.length && s[j] != '.' && s[j] != '[') {
j++;
}
sb.write('[');
sb.write(s.substring(start, j));
sb.write(']');
i = j;
}
} else {
// Inside brackets, keep '.' as content.
sb.write('.');
i++;
}
} else {
sb.write(ch);
i++;
}
}
return sb.toString();
}

/// Normalizes the raw query-string prior to tokenization:
/// - Optionally drops a single leading `?` (when `ignoreQueryPrefix` is set).
/// - Optionally drops exactly one leading `?` (when `ignoreQueryPrefix` is true).
/// - Rewrites percent-encoded bracket characters (%5B/%5b → '[', %5D/%5d → ']')
/// in a single pass for faster downstream bracket parsing.
static String _cleanQueryString(
Expand Down
Loading