saropa_dart_utils 2.2.1
saropa_dart_utils: ^2.2.1 copied to clipboard
280+ extension methods and utilities for Flutter/Dart. Null-safe string, DateTime, List, Map, and number operations that eliminate boilerplate.
Changelog #
pub.dev - saropa_dart_utils
Published version: See field version in pubspec.yaml
Full release history: https://saropa.com/developers/saropa-dart-utils/changelog/
2.2.1 #
A small housekeeping release: the example app now requires material_ui 1.12.0 or newer, and the library, scanner and extension code are the same as in 2.2.0. log
Maintenance
- Publish: dependency constraints are checked —
scripts/publish.pyraises constraints inexample/pubspec.yamlthat are behind the root pubspec, and blocks the release when a runtime dependency changed since the previous tag and the release's changelog section does not name it with its new version. The example now requiresmaterial_ui: ^1.12.0. Test:scripts/tests/test_dependency_sync.py.
2.2.0 #
Scanner commands work on Windows again: scans, repeated-code search and fixes no longer fail with a SIGTERM error, and "Refresh Catalog" no longer reports a missing library folder. The last-weekday-of-month helpers, nextDay/prevDay, isDateAfterToday, isTomorrow/isYesterday/isOlderThanYesterday and nth-weekday range checks now stay on the correct date across daylight-saving changes, and a new addCalendarDays moves a date by whole days without that drift, while startOfDayInKind gives a date's midnight without turning UTC into local. Relative date buckets no longer count a day short after clocks spring forward, and day lists that keep the time of day recover after a clock-change gap. Negative durations format with a minus sign, splitByMonth keeps UTC input in UTC, two cron step forms parse correctly, and closing a resource pool disposes every idle resource even when one disposer fails. Flattening a hierarchy with circular or conflicting parent links now reports an error instead of losing items, and new helpers list the problem ids without raising an error or repair the data. Quiet hours no longer end in the past when clocks fall back, isDateAfterToday given a UTC now uses the UTC day, and stepping back through business days gets past a date a time zone skipped. After an install or update the extension now checks that the scanner can run on your machine and tells you only if it cannot. log
Added #
- Scanner: every finding states why — messages carry a
Why:reason in VS Code Problems, CLI, markdown and SARIF output, and false rule text about day arithmetic is corrected. Details: tool/scanner/CHANGELOG.md. DateTime.startOfDayInKind(date_time_calendar_day_extensions.dart) — midnight of the value's calendar date, keeping UTC as UTC and local as local;startOfDayandtoDateOnly()always return local. Exported from the package entry point. Test:test/datetime/date_time_calendar_day_extensions_test.dart.repairHierarchy(hierarchy_repair_utils.dart) — returns a cleaned copy of a node list thatvalidateHierarchyreports as valid andflattenHierarchyaccepts: one node per id in first-appearance order, the first listed parent for conflicting ids, cycle members and self-parents turned into roots, other parent links kept. Nodes that need no change are returned as the original objects. The optionalcycleBreak: HierarchyCycleBreak.singleLinkinstead cuts one link per cycle, making only the member that appears first in the input a root; the default,everyMember, detaches all members. Exported byhierarchy_utils.dartand the package entry point. Test:test/graph/hierarchy_repair_utils_test.dart.validateHierarchyandHierarchyValidation(hierarchy_validation_utils.dart) — a non-throwing check that returns the idsflattenHierarchyrejects, ascycleIds,selfParentIds,cycleDescendantIdsandconflictingIds, with anisValidgetter.flattenHierarchyuses it, so the two cannot disagree. Exported byhierarchy_utils.dartand the package entry point. Test:test/graph/hierarchy_validation_utils_test.dart.DateTime.addCalendarDays(int days)(date_time_calendar_day_extensions.dart) — moves a date by calendar days, keeping the wall-clock time and UTC/local kind; unlikeadd(Duration(days: n))and the Jiffy-basedaddDays, a local midnight stays at midnight across a DST change. Exported from the package entry point. Test:test/datetime/date_time_calendar_day_extensions_test.dart.TtlCacheinjectable clock (ttl_cache.dart) — a new optionalnowargument supplies the time used to stamp and expire entries; it defaults toDateTime.now, so existing callers are unaffected. Test:test/caching/ttl_cache_test.dart.- Extension: startup self-check — after an install or update,
saropa_scan doctorruns in the background until the extension version has an answer. A success settles it and writes one log line. A failure may be passing (an offlinepub get, antivirus holding a new binary), so it is retried on later activations, at least 5 minutes apart; the third failure settles the version and shows one warning with "Show Log" (the run log), "Set Up" and "Copy Diagnostics". A scanner that gives no answer within 120 seconds counts as a failure. Windows opened together do not both check: the claim is a lock file in extension storage, created exclusively and expiring after 5 minutes. A cancel, a busy scanner, or discovery still unfinished after 10 minutes (an unanswered consent dialog, for example) leaves the question open. It waits for the scanner discovery the extension already starts and adds no prompt of its own, and does nothing in an untrusted workspace (it runs when trust is granted). A project whose config breaksdoctordoes not count as a broken machine when--versionstill answers. A setup warning already on screen suppresses the self-check warning only when it explains the same failure (no scanner package or no Dart). Tests:extension/src/test/self-check*.test.ts,extension/src/test/claim-lock.test.ts. - Extension: "Copy Diagnostics" on scanner warnings — copies the warning, the failure behind it, a fresh
doctorreport (or its error), the scanner origin and version, the extension version and the OS and architecture to the clipboard, with the home directory replaced by~(also where it is percent-encoded, written in the other Unicode normalization form, given as a Windows short name or reached through a link), the account name by<user>(very short and ordinary names are kept) and recognizable secrets (known token formats, URL and header credentials,password=-style pairs, private keys) by<redacted>, then confirms. Cancelling also ends the wait for a scanner discovery that is still pending. A button on a scanner warning whose action fails now shows an error. Tests:extension/src/test/copy-diagnostics.test.ts,extension/src/test/scanner-diagnostics.test.ts,extension/src/test/redaction.test.ts,extension/src/test/scanner-warning.test.ts.
Changed #
material_uiconstraint raised to^1.12.0(was^1.11.0).- Version impact —
flattenHierarchynow throwingArgumentErrorfor input it used to accept is a behavior change, andvalidateHierarchy,HierarchyValidation,repairHierarchyandHierarchyCycleBreakare new public API. - Extension: "scanner cannot be set up" and "setup was declined" warnings now offer "Show Log", "Set Up" and "Copy Diagnostics"; when an untrusted workspace is what blocks setup, "Manage Workspace Trust" takes the place of "Set Up". The failed-build warning offers "Show Log" and "Copy Diagnostics". The download consent prompt and its confirmation are translatable.
- Extension: a download that fails after "Set Up Scanner" or "Download scanner" shows a warning with the reason (a missing release manifest included), "Show Log" and "Copy Diagnostics"; a download tried unasked is only logged. Tests:
extension/src/test/cli-download-offer.test.ts,extension/src/test/cli-manager-download.test.ts. - Extension: a built scanner that fails its launch check is no longer used. Setup moves on to the download or the
dart runfallback, and later windows skip the binary (the file is kept) until "Set Up Scanner" sees it run or the bundled source changes. Test:extension/src/test/cli-manager-rejected-build.test.ts. - Extension: "scanner is set up" appears only after the newly built binary has run; one that does not run shows the failure warning alone.
- Extension: "Set Up Scanner" launches the scanner before naming it as the one in use. When it does not run (a wrong
saropaUtils.cli.path, a damaged bundled, PATH, downloaded or built binary), the warning names what repairs that origin and offers "Show Log" and "Copy Diagnostics". On thedart runfallback it first asks, naming the command and folder, then allows 5 minutes with a cancel button. In an untrusted workspace nothing is launched and the warning says trust is needed. Tests:extension/src/test/cli-verify.test.ts,extension/src/test/cli-manager-verify.test.ts,extension/src/test/cli-manager-fallback.test.ts. - Extension: a
doctorrun that exits with an error and prints no report now fails with the scanner's error output, also for exit code 1, which used to pass as an empty result. Test:extension/src/test/doctor-exit.test.ts.
Fixed #
- Extension: "Copy Diagnostics" left quoted values after credential flags (
--password "x",--token 'y') in the copied text. Test:extension/src/test/redaction.test.ts. - Extension: "Copy Diagnostics" mangled paths that merely contain the home directory — with a home of
/root,/srv/app/root/libbecame/srv/app~/lib. A home path now has to start at a boundary;file://and percent-encoded forms still match. Test:extension/src/test/redaction.test.ts. - Extension: setup that ended without a scanner file advised deleting the folder
.— it now says that no scanner file was found, and launches nothing. Tests:extension/src/test/cli-verify.test.ts,extension/src/test/cli-manager-download.test.ts. - Extension: non-ASCII scanner output could be corrupted when a character arrived split between two chunks. Test:
extension/src/test/scanner-spawn.test.ts. - Extension: doctor version facts were lost behind
dart runbuild notices, and the "Catalog refresh failed" notification could not be translated — the version check reads the report the same way "Doctor" does, and the failure text is a literalvscode.l10n.tmessage with a placeholder. - Extension: "Doctor" failed with the raw JSON report when it found blockers — the scanner exits 2 in that case and the extension accepted only 0 and 1. A printed report is now shown whatever the exit code. Test:
extension/src/test/doctor-exit.test.ts. - Extension: the "Refresh Catalog" notice could not be collected for translation — the text reached
vscode.l10n.tthrough a constant. It is now a literal inextension/src/cli/scanner-notices.ts. Tests:extension/src/test/refresh-catalog-command.test.ts,extension/src/test/l10n-literals.test.ts. flattenHierarchysilently dropped nodes (hierarchy_utils.dart) — behavior change: it now throwsArgumentError, naming the ids, for nodes unreachable from a root (parent cycle, self-parent, and their descendants) and for one id listed with different parents (null and''both mean no parent). A repeated root is now emitted once, like a repeated child (previously once per listing, with its subtree each time). Output order for other valid input is unchanged. The walk is now iterative and builds a child map once (O(n)), and the dartdoc no longer claims a cycle causes unbounded recursion.MonthWeekdayUtils.lastWeekdayOfMonthcould return the wrong date across a DST change — it stepped back with fixed 24-hourDurations on a localDateTime, so in a time zone that switches late in a month the result landed at 01:00, or at 23:00 on the previous day. It now uses calendar fields and returns local midnight. This also covers thelast*helpers ofDayInMonthCalculationsthat delegate to it. Test:test/datetime/month_weekday_utils_test.dart.- Scanner:
scan,dupesandfixfailed on Windows withSignalException: Failed to listen for SIGTERM(errno 50) — Windows cannot watch SIGTERM, and the refusal arrives as a stream error that the surroundingtrynever caught. Signal wiring now lives intool/scanner/lib/src/signals.dart(watchStopSignals): SIGINT only on Windows, SIGINT and SIGTERM elsewhere, with registration errors ignored.watchuses the same helper, so it now also stops cleanly on SIGTERM outside Windows. Test:tool/scanner/test/platform/signals_test.dart. - Scanner: stopping
watchwaited for the running rescan, and SIGTERM exited 130 — a stop signal now cancels the rescan in flight, partial findings are not cached, and the exit code is 143 for SIGTERM and 130 for SIGINT. Test:tool/scanner/test/commands_wow/watch_stop_test.dart. - Extension: "Refresh Catalog" failed with
Cannot find the library lib/ directory— a scanner with nosaropa_dart_utilslibrary source within reach (a compiled executable, for example) cannot regenerate the catalog. The command now says so and writes the loaded catalog summary to the output channel; a scanner run from asaropa_dart_utilssource checkout still regenerates it. Tests:extension/src/test/catalog-refresh.test.ts,tool/scanner/test/cli_core/catalog_refresh_refusal_test.dart. nextDay/prevDaycould return the wrong day across DST — they stepped 24 elapsed hours, soDateTime(2026, 11, 1).nextDay()returned Nov 1 in US Eastern andprevDayskipped a 23-hour day. They now step by calendar day. Behavior change: withisStartOfDay: falsethe result keeps the wall-clock time (previously it was exactly 24 hours away, an hour off across a DST change).generateDayListinherits the fix. Behavior change: with the defaultisStartOfDay: truea UTC input now returns UTC midnight (previously local midnight of the UTC date, a different instant). Test:test/datetime/dst_day_step_regression_test.dart.isTomorrow,isYesterdayandisOlderThanYesterdaymisjudged DST days — they stepped 24 elapsed hours, so in US EasternDateTime(2026, 11, 2).isTomorrow(now: DateTime(2026, 11, 1))was false,isYesterdayskipped a 23-hour day, andisOlderThanYesterdayput the start of yesterday an hour off (00:30 on a 25-hour yesterday counted as older). They now step by calendar day. Behavior change:isOlderThanTodayandisOlderThanYesterdaywith a UTCnownow use UTC midnight as the boundary (previously local midnight of the UTC date, off by the local offset). Test:test/datetime/relative_predicate_dst_test.dart.expandRecurrenceweekly rules kept a shifted time after a DST gap — once a weekly occurrence fell in a spring-forward gap (02:30 became 03:30), every later week stayed at 03:30. Weekly occurrences now take their time of day fromstart, like the other frequencies. Test:test/datetime/recurrence_dst_test.dart.relativeDateBucketcounted one day short across a spring-forward change — it measured elapsed time between local midnights, so in US Eastern Mar 8, 2026 seen from Mar 9 wastoday. Calendar days are now counted. Test:test/datetime/relative_date_bucket_utils_test.dart.generateDayList(isStartOfDay: false)kept a shifted time after a clock-change gap — 02:30 became 03:30 on the spring-forward day and stayed there for every later day. Each day now takes its time of day from the start value. Test:test/datetime/dst_day_step_regression_test.dart.prevDaycould return the input date where a zone skipped a whole date (Pacific/Apia, Dec 30, 2011) — it now steps over the missing date. Found by code reading; only a run under that zone can detect it (test/datetime/skipped_midnight_zone_test.dart).isDateAfterTodayandlastWeekdayOfMonthin zones that skip midnight — where today's midnight (or the month's last midnight) does not exist, the 01:00 stand-in was carried to the next (or earlier) day, putting the boundary or result at 01:00. Both now return to midnight after stepping. Found by code reading; the tests intest/datetime/skipped_midnight_zone_test.dartcan only detect it under such a zone.isDateAfterTodaymisjudged times on DST days — on a 25-hour day 23:30 counted as after today, and after a 23-hour day 00:30 the next day did not. Today now ends at the next local midnight. Test:test/datetime/dst_day_step_regression_test.dart.DateTimeRange.isNthDayOfMonthInRangecould skip a month — when the month's last day was a 23-hour spring-forward day (Europe/London, Mar 31, 2024), the computed month end fell on the previous day and a range starting on that last day missed the month. Test:test/datetime/dst_day_step_regression_test.dart.QuietHours.quietUntilcould return a time before its input — in the repeated fall-back hour the window end resolved to the first occurrence of its wall time. It now returns the second occurrence when the first is not after the input. Test:test/datetime/quiet_hours_utils_test.dart.isDateAfterTodaywith a UTCnowended today at local midnight — behavior change: today now ends at midnight innow's kind (UTC midnight for a UTCnow). A localnowis unchanged. Test:test/datetime/date_time_comparison_extensions_test.dart.- Backward business-day steps could not pass a skipped date —
BusinessCalendar.previousBusinessDay,BusinessCalendar.addBusinessDaysand the weekend-onlyaddBusinessDays(negative counts) rebuilt the same day where a zone dropped a whole date (Pacific/Apia, Dec 30, 2011), looping forever or counting that day twice. They now step withprevDay. Not reproduced: the tests intest/datetime/skipped_midnight_zone_test.dartonly bite in that zone. splitByMonthreturned local boundaries for UTC input — behavior change: boundaries now follow the kind ofstart(UTC in, UTC out). Local input is unchanged. Whenendis the other kind it is converted to the same instant instart's kind first, so the result never mixes UTC and local values. Month ends are built at midnight from calendar fields, so a zone that skips midnight on the 1st no longer gives a 01:00 month end. Test:test/datetime/dst_day_step_regression_test.dart.formatDurationwrapped negative durations —-90 minprinted23h 30m. Behavior change: negatives now print the magnitude with a leading minus (-1h 30m); a negative that shows only the zero label stays0s. A sub-second duration withisIncludeMillisecondsno longer prints a stray zero label:500 msis500ms(was0s 500ms) and-500 msis-500ms. Test:test/datetime/duration_format_parse_test.dart.CronSchedule.tryParsestep forms — behavior change:a/1now meansathrough the field maximum, as documented fora/n(previously justa), and an out-of-range step start such as60/5inside a list (1,60/5) now rejects the expression instead of being dropped. Test:test/parsing/cron_utils_test.dart.ResourcePool.closestopped disposing after one disposer threw — later idle resources leaked. Behavior change: every idle resource is now disposed, then the first disposer error is rethrown. Test:test/async/resource_pool_close_test.dart.mostOccurrences/leastOccurrencesthrew aTypeErrorondouble.nan(double_iterable_extensions.dart, iterable_extensions.dart) — a default map gave each NaN its own unreachable key, so reading the counts failed. All NaN values now count as one value, also inList.topOccurrenceandcountBy. Theint,double,bool,enumand generic versions read the iterable once, so a lazy source (map,where, a generator) runs its callbacks once. Behavior change: ties now go to the value seen first (previouslyHashMaporder). Tests:test/double/double_iterable_extensions_test.dart,test/int/int_iterable_extensions_test.dart,test/iterable/iterable_extensions_test.dart,test/bool/bool_iterable_extensions_test.dart,test/enum/enum_iterable_extensions_test.dart,test/list/list_extensions_test.dart.groupByandgroupByTransformreturned a map whose entries threw when a key was NaN — every NaN key now lands in one group. Tests:test/iterable/iterable_extensions_test.dart,test/iterable/iterable_group_by_extensions_test.dart.isqrtoverflowed at the 64-bit maximum, soisPrime(9223372036854775807)returnedtrue(num_more_extensions.dart) —isqrt(9223372036854775807)was negative, andnum_prime_utils.darthad a private copy with the same defect (2^63-1 is composite). The copy is gone:isPrimeandprimeFactorscallisqrt, andisqrtdivides with~/instead of>>, which truncates to 32 bits on the web. Tests:test/num/num_more_extensions_test.dart,test/num/num_prime_factorial_modulo_lerp_test.dart.averageread a lazy source twice, so the sum and the count could come from different data. Test:test/num/num_iterable_extensions_test.dart.- String helpers split emoji or dropped text by mixing UTF-16 offsets with character indexes —
capitalize,upperCaseFirstChar,lowerCaseFirstChar,titleCaseandJsonTypeUtilsword capitalization now take the whole first character ('👋ab'.capitalize()keeps the emoji;'e'+ U+0301 becomes'E'+ U+0301). Cuts atindexOf/lastIndexOfoffsets now use the same offsets ingetEverythingBefore,getEverythingAfter,getEverythingAfterLast,removeLastOccurrence,removeWrappingChar,removeStart,removeLeadingAndTrailing,stripSubstring, thebetweenhelpers,truncateWithEllipsisPreserveWords,pluralize, key-value parsing,parseNestedQuery,parseListFromString,parsePortFromHostPort,parseHexToBytes,applyPatch,MyersDiffUtils.diffLines,parseSearchQueryandLevenshteinUtils.fuzzyContains('👋a-b'.getEverythingBefore('-')was'👋a-', now'👋a').getRandomCharreturns a whole character.isPalindrome,commonPrefixandcommonSuffixcompare whole characters, so'👋a👋'is a palindrome and['👋a', '👍b'].commonPrefix()is''instead of half an emoji. Tests:test/string/*_test.dartfor each file,test/list/list_string_extensions_test.dart,test/parsing/parse_list_utils_test.dart,test/parsing/parsing_more_utils_test.dart,test/json/json_type_utils_test.dart,test/niche/niche_more_utils_test.dart. - Size arguments and insert positions now count characters (grapheme clusters) — behavior change:
insert(position),replaceLastNCharacters,trimWithEllipsis,collapseMultilineString(crop length),breakLongWords,chunkText(maxChars,overlap),characterNgrams,excerptAround(contextChars) andsafeHtmlExcerpt(maxLength) previously measured UTF-16 code units but cut by character, which kept the wrong text when emoji were present;collapseMultilineStringcould loop forever on emoji. An emoji or a letter with a combining mark now counts as one. endsWithAnymatched only one-character suffixes — behavior change: each entry is compared as a whole suffix ('file.dart'.endsWithAny(['.dart'])is nowtrue), and empty entries never match (a manualany((e) => s.endsWith(e))treats''as a match). Test:test/string/string_analysis_extensions_test.dart.DateTimeUtils.firstDayNextMonthcould return the 1st of the same month in a zone whose clocks fall back late in the month; it now builds the date from calendar fields.DateTimeUtils.tomorrowcalled just after midnight on a 25-hour day returned today; it now steps one calendar day. Test:test/datetime/date_time_utils_test.dart.- URL helpers left a bare
?or#— behavior change:removeQueryremoves the?(and, by default, the#),stripFragmentandbuildUriremove the#, andaddQueryParameteranduriWithQueryParamsdrop the?when no parameter is left. Tests:test/url/url_extensions_test.dart,test/url/url_build_utils_test.dart,test/url/path_query_untested_test.dart. isValidIpv4andparsePortFromHostPortaccepted non-decimal input — behavior change: each IPv4 part must be one to three ASCII digits (signs, spaces and0xrejected; leading zeros still accepted), and a port must be ASCII digits only (' 80','+80','0x50'now returnnull). Test:test/parsing/parsing_more_utils_test.dart.- Scanner: rules that offered a fix as safe when it could fail to compile or change behavior —
iterable.countWhere(nullable elements),string.splitIntoLines,datetime.isYesterday/isTomorrow(DST),url.removeQueryandurl.stripFragmentare nowreview;string.isEqualsskips null-aware operands andmap.ensureKeyskips awaited values; six rules named extensions that do not exist. Rule reasons were updated for the library fixes above. Details: tool/scanner/CHANGELOG.md.
Maintenance
- Release test selection includes split test files — a changed source file now also selects the
<name>_<part>_test.dartfiles beside its mirrored test that import it. Test:scripts/tests/test_test_selection.py. - Scanner skips
lib/src— package-internal declarations are left out of the generated catalog, the util index, verification import lookup and the test index, so no match can suggest apackage:saropa_dart_utils/src/import. The util index format is now 2, so cached format 1 indexes are rebuilt; the shippedlibindex.json, which holds nolib/srcmember, was relabeled and re-embedded. Tests:tool/scanner/test/catalog/package_private_test.dart,tool/scanner/test/libmatch/libmatch_test.dart. - Capabilities generator and audit skip
lib/src— package-internal files are left out ofCAPABILITIES.mdand are no longer reported by the audit as missing from the package entry point. Tests:test/tool/gen_capabilities_test.dart,scripts/tests/test_audit_exports.py. JsonUtils: suppressed fouravoid_stack_trace_in_productionfalse positives — the flagged calls aredart:developerlog(), which is not user-visible output. Stack traces are kept; no behavior change.Base64Utils,allSettled,retryTimes: suppressed the same false positive on their fourdart:developerlog()calls. It occurs only in a scan without--resolve; the note injson_utils.dartstates when to remove the ignores. Comment-only change.- Stale lint ignore report — new
scripts/check_stale_ignores.pystripssaropa_lints/ignores in a temporary copy, scans it with and without--resolve, and lists the ignores that suppress nothing or name no installed rule. It runs as a non-blocking step in therelease_gateworkflow. Tests:scripts/tests/test_stale_ignores.py. - Removed 93 stale
saropa_lintsignores listed by that check, across 43 Dart files, with the comments that only justified them; rationales that describe code behavior (calendar rollover, deliberate fallbacks) remain as plain comments. Comment-only; no behavior change. - Scanner tests:
watchcancellation covers the pooled path with 4 workers and stops each scan from inside the engine instead of from a timer; the extension-constant check is skipped, with a reason, when theextension/folder is absent. - Lint cleanup — resolved
avoid_datetime_constructor(intentional rollovers carry a reasoned ignore),move_variable_closer_to_its_usage(ResourcePool.close,formatDuration, the cron field parser) anddocument_analyzer_ignore_rationale(JsonUtils). No behavior change. - Tests: pinned DST cases for
lastWeekdayOfMonthand a millisecond case forformatDuration— the DST cases can only detect a regression in a time zone with the matching transition; under UTC they pass with or without the fix. Theciworkflow now runstest/datetimea second time withTZ=Europe/Londonso CI exercises the European cases. - Tests:
ResourcePool.close— disposal of every idle resource, failure of all waiting borrowers, and a secondclose/acquirewhile the first close is still disposing. Test:test/async/resource_pool_close_test.dart. - Recurrence iterator uses
addCalendarDays— its private_addDayscopy had the same contract and was removed. The copies inbusiness_calendar_utils.dart,quiet_hours_utils.dartandsla_calculator_utils.dartstay because they reset every step to midnight, whichaddCalendarDaysdoes not; a comment on each says why. No behavior change. addMonthsdocumented and pinned as the calendar-month step — it already clamps to the target month's last day and keeps the time of day and UTC/local kind, so no separateaddCalendarMonthswas added. Documentation and tests only. Test:test/datetime/add_months_calendar_contract_test.dart.- Same-kind date truncation uses
startOfDayInKind— replaces the private copies behindnextDay/prevDayand inquiet_hours_utils.dartandsla_calculator_utils.dart. Copies that always return local or always UTC are unchanged. The swap itself changes no behavior. - Tests: zones that skip midnight —
test/datetime/skipped_midnight_zone_test.dartpins days in America/Havana, America/Santiago, America/Asuncion, Asia/Beirut and Pacific/Apia. It passes trivially elsewhere, and no CI job sets one of those zones. addCalendarDaysdocuments nonexistent wall times — a time inside a spring-forward gap resolves as theDateTimeconstructor resolves it (02:30 becomes 03:30 on the Dart VM). Test:test/datetime/date_time_calendar_day_extensions_test.dart.- Lint ignores: added the
saropa_lints/prefix to theavoid_datetime_constructorignores inmonth_weekday_utils.dart,month_weekday_named_extensions.dartandperiod_split_utils.dart, clearingrequire_ignore_comment_plugin_prefix. Comment-only change. - Extension: the default
dart runscanner command is one exported constant (DEFAULT_SCAN_COMMAND), checked againstpackage.json. The CLI manager and self-check test suites are split into smaller files with shared helpers underextension/src/test/helpers/. - Publish tests: concurrent runs no longer collide in Flutter's kernel cache — the release test runner's parallel
flutter testprocesses copied onto one file underbuild/test_cache/, failing a suite load withPathExistsException(errno 183) and leaving the process hung. Each worker slot now passes its own--dart-define=SAROPA_TEST_SLOT, which gives it a separate cache file. Test:scripts/tests/test_test_runner.py. - Tests:
TtlCacheexpiry runs on a virtual clock — real delays made "re-setting a key refreshes its expiry" fail on a busy machine; the exact expiry instant is now pinned too. A further test covers expiry on the default clock. - Publish tests: a retried batch counts only its final attempt — failures and test counts from the discarded attempt no longer remain, so a batch that passes on retry is not listed as failed, and the retry's raw output is no longer hidden. The kernel cache
PathExistsExceptioncopy failure is now retried. Test:scripts/tests/test_test_runner.py. - Publish tests: parallel runs are guarded — only one test runner can use a checkout at a time; the first test file runs alone so the shared
build/unit_test_assetsis built before the fan-out; file collisions are recognized by exception class or error number plus the shared build path, not by SDK wording; the stall watchdog also kills the process tree on macOS and Linux and says so when it cannot; a script test reads the local Flutter tool source and fails if the kernel cache naming assumption stops holding. Tests:scripts/tests/. - Publish tests: a retry no longer hides first-attempt failures — the failed tests and raw output of a retried batch are listed in the final report without failing the run, and the
RETRYline names the trigger. A watchdog kill is recorded even when buffered output follows it, and a manual cleanup message appears if the output stays open afterward. An empty test selection fails with a message instead of crashing, and only lock contention is reported as a busy checkout. Tests:scripts/tests/test_test_runner.py,test_run_lock.py,test_process_tree.py,test_flutter_clash.py. - README code cards retaken — all 12 cards under
assets/cards/regenerated withscripts/make_cards.pyand checked against the library's real output; newscripts/modules/cards_browser.pypicks the first headless browser that renders (installed Edge returned nothing). Test:test/readme_examples_test.dart. Not yet viewed on GitHub or pub.dev. - Publish: version files sync to the changelog —
scripts/publish.pyraisespubspec.yaml,extension/package.jsonand the root version fields ofextension/package-lock.jsonto the highest of the topCHANGELOG.mdrelease and those files, instead of failingextension-lockstepon a lagging file. Versions compare by semver order and are never lowered; a version with no top changelog entry still fails. Test:scripts/tests/test_version_sync.py.
2.1.2 #
Release pipeline fixes only: the 2.1.1 publish was blocked by a CI formatting check, so this release carries the same features with a working publish. log
Maintenance
- CI: format check resolves scanner packages first —
publish.ymlrunsdart pub getintool/scannerbeforedart format --set-exit-if-changed .. Without it,package:lintscould not be resolved, the nestedtool/scanner/analysis_options.yamlwas ignored, and 251 scanner files were reformatted at the root page width, failing the 2.1.1 publish. - Publish: test runner stall watchdog —
scripts/modules/test_runner.pykills a test batch that prints nothing for 240 s and retries it once, instead of hanging the whole publish (three batches sat idle for 22 minutes while the same files passed alone in 11 s). A second stall is reported as a failure. - Publish: Abort / Retry / Ignore on every failing step — a failed step no longer ends the run; the script asks whether to abort, retry or ignore, and ignored steps are listed in the release summary.
- Publish: extension
.vsixis built in the project root —<root>/saropa-utils-<version>.vsixinstead ofextension/;*.vsixis gitignored at the root. - Extension version kept in lockstep —
extension/package.jsonbumped withpubspec.yaml(2.1.2).
2.1.1 #
Locally built extension packages now include the scanner, so there is nothing to set up by hand. The Saropa Utils findings list now has its own icon in the Activity Bar instead of hiding inside the Explorer. log
Fixed #
- Extension: local .vsix builds shipped without the scanner —
extension/bin/<platform-arch>/was only filled by the CI release workflow.vscode:prepublishnow runsextension/scripts/bundle_scanner.py(npm run bundle-scanner), which compilestool/scannerfor the host platform and skips when a content hash of the scanner sources plus thedart --versiontext matches a sidecar.hashfile next to the exe (mtime is no longer used, so deleted files and SDK upgrades trigger a rebuild). Coversnpm run vsix*and the release script. - Extension: "Find opportunities" failed with
Could not find package saropa_scan— thedart run saropa_scan:saropa_scanfallback ran in the workspace root, where the package cannot be resolved. WithsaropaUtils.scannerPathempty it now runs in<workspace>/tool/scannerwhen that folder has apubspec.yaml(fallbackScannerCwd). Ifdart runstill cannot find the package, the error now names thesaropaUtils.scannerPathandsaropaUtils.cli.pathsettings. The fallback folder is only used when itspubspec.yamldeclaresname: saropa_scan, so an unrelatedtool/scannerpackage no longer hijacks the working directory. - Scanner: shared JSON readers
jsonReq<T>/jsonOpt<T>(json_access.dart) — one lint-clean place for decoded-JSON map reads (require_null_safe_json_access).jsonReqcheckscontainsKeythenis Tand throws aFormatExceptionnaming the key and actual type (was a bareTypeError);jsonOptreturns null on missing or wrong type.reverse_suggest.dartnow usesjsonReqfor its 17 former inline casts (replaces the private_req). - Scanner: all
require_null_safe_json_accesssites converted — every flagged literal-keym['k'] as Tread acrosstool/scanner/libnow goes through the sharedjsonReq/jsonOpt(map reads) orArgResults.option()/.flag()/.multiOption()(CLI args). Behavior: a missing/mistyped required key now raisesFormatException(wasTypeError); config fields holding a wrong type fall back to their defaults instead of throwing; a CLI option with no value reads as an empty string instead of throwing. - Extension: every scanner command now shares one working-directory rule — "Find repeated code", fix, doctor, explain and exclude edits all pick the
dart runfolder through a single helper (resolveRunCwd), so none can drift from "Find opportunities". Installs built before this fix (such as the 2.1.0 VSIX) must be rebuilt and reinstalled to pick it up. - Extension: the scanner now sets itself up — when no scanner binary is bundled, on PATH or downloaded, the first scan in a trusted workspace asks "Set up scanner (compile from source shipped with the extension)?" and then compiles it with the local Dart SDK (
dart pub get+dart compile exe) from<extension>/scanner-src, in a cancellable progress notification with a visible success or failure message. The binary is cached in extension storage (cli/built-<source hash>/) and rebuilt only when the bundled source changes; the answer is remembered per source. The build is tried before the GitHub download, so a missingscanner-v<version>release (404) no longer ends setup. When setup is impossible, the message names exactly what is missing (for example "Dart SDK not found on PATH") instead of failing withCould not find package saropa_scan. New handlersaropaUtils.setupScannerre-runs setup and clears earlier "no" answers (pure logic inextension/src/cli/cli-build.ts, text incli-setup-messages.tsviavscode.l10n.t). - Extension: security hardening of scanner build-from-source — a review of the first version found that an opened folder could influence what gets compiled and run. Now: (1) nothing is probed, offered or built until the workspace is trusted, and granting trust re-runs setup; (2) only the scanner source shipped inside the extension (
<extension>/scanner-src) is ever built, never a workspacetool/scanner; when it is not bundled the message says "scanner source not bundled with this extension"; (3) the cache key is a SHA-256 of the source content (pubspec.yaml,pubspec.lock,lib/,bin/), so a same-version source with different code can neither reuse nor poison another build, and any source change rebuilds once; (4) the build runs in a private copy under extension storage, so nothing is written into a user repo or the extension folder; (5) each build uses its own random work dir and one atomic rename, and a finished build that another window may be running is never deleted; (6) consent is stored per source hash; (7) the compile output path is a short relative ASCII path, so a Flutterdart.bataccepts it even when the storage path has non-ASCII characters or(x86). Tests:extension/src/test/cli-build.test.ts,extension/src/test/cli-manager.test.ts.
Changed #
- Scanner: all
int.parse/double.parse/DateTime.parseintool/scanner/lib/srcreplaced withtryParse— (prefer_try_parse_for_dynamic_data). Rounding goes through oneroundTohelper (src/round_to.dart); regex-matched digit groups skip/return null on overflow;ulfcommand options and corrupt lease/index JSON throwFormatExceptionwith a message; bench/corpus CLI args (bench/src/cli_args.dart) throwArgumentErrornaming the flag and quoting the bad value, and theirfallbackapplies only when the flag is absent. Valid input behaves as before. - CI: scanner source reaches the released VSIX —
extension.ymlandrelease-scanner.ymlnow runactions/setup-pythonbeforevsce package, sovscode:prepublish(python scripts/bundle_scanner.py) always runs and copiestool/scannerintoextension/scanner-srceven withSAROPA_SKIP_SCANNER_BUNDLE=1. - Extension: scanner source ships in the VSIX —
bundle_scanner.pynow always mirrorstool/scanner(pubspec.yaml,pubspec.lock,lib/,bin/) intoextension/scanner-src(gitignored, included in the package), even whenSAROPA_SKIP_SCANNER_BUNDLE=1or no Dart SDK is present, so the extension can build the scanner from<extension>/scanner-src.assets/is left out because the exe and source builds use the catalog embedded inlib/. - Extension: host-only exe bundling made explicit —
bundle_scanner.pywarns whentool/scannerhas uncommitted changes (it builds the working tree), skips writing the host exe whenSAROPA_VSCE_TARGETnames a different platform, and prints which targets have no bundled exe. Thevsce packagesteps inextension.ymlandrelease-scanner.ymlnow setSAROPA_SKIP_SCANNER_BUNDLE=1, so the script docstring claim is true. - Extension: "Set Up Scanner" is now a declared command —
saropaUtils.setupScanner(handler already existed) is contributed inpackage.jsonwith title keycommand.setupScanner.titleand sits in the findings view overflow menu (overflow@5), so the Command Palette and the view menu can re-run scanner setup. The manifest test now pins the Activity Bar container structure (viewsContainers.activitybaridsaropaUtils,views.saropaUtilsholdssaropaUtils.findings) instead of the old Explorer placement. - Extension: more actions surfaced in the findings view — the empty-state welcome now offers Scan Workspace, Find opportunities, Find repeated code, Fix all safe, Check package versions, Open report and Open Settings (text in
viewsWelcome.emptyinpackage.nls.json). The view title bar now shows Scan Workspace, Find opportunities, Find repeated code and Fix all safe as icons ahead of Group by, Open report and Open Settings (navigation@1-@7). Overflow keeps Open HTML report, Refresh catalog, Show run log and Check package versions (overflow@1-@4). Rationale: scans were buried in overflow although they are the first thing a new user needs;package.jsoncannot hold comments, so the reasoning is recorded here. Each command already had a codicon, so nocontributes.commandschange. - Extension: findings view moved to its own Activity Bar container —
saropaUtils.findingswas a collapsed section under Explorer, easy to miss. It now lives in a dedicatedsaropaUtilscontainer (contributes.viewsContainers.activitybar, title keyviewContainer.saropaUtils.title, iconmedia/icon-activitybar.svg, a single-colorcurrentColorSVG as the Activity Bar requires). The view keeps its id, name,saropaUtils.isDartProjectgate and welcome text, sosaropaUtils.findings.focusstill works."visibility": "collapsed"was dropped because a container's only view cannot be meaningfully collapsed.
2.1.0 #
Changelog links and the package homepage now point to saropa.com, and there is a new optional saropa_scan tool and "Saropa Utils" VS Code extension that find code you could replace with this library. log
Added #
- Release script: the test step now runs only tests affected since the last release (full suite on config/helper/barrel changes or unmapped files), in parallel batches with live progress; new
--full-testsand--test-workers Nflags - Release script: never prompts (no
input(), no [y/N], no retry/abort/ignore menus). A failing step is recorded and every independent step still runs; steps that depend on a failed one are skipped with the reason, and a final summary lists OK/WARN/FAILED/SKIPPED with exact re-run commands (exit code stays non-zero on any failure). Former prompts are now flags or automatic rules:--audit-only,--skip-audit,--strict-audit,--bump patch|minor|major,--allow-missing-intro. The "Saropa Utils" extension is built to one path,extension/saropa-utils-<version>.vsix(gitignored, printed in the output and summary), that exact file is published withvsce publish --packagePath, and the upload runs in parallel with the pub.dev wait (output prefixed[ext]) unless--skip-extension, so it may go live before pub.dev finishes; both results are reported separately - Extension: the README/CHANGELOG copy bundled in the extension drops SVG images from untrusted hosts (the coverage badge), which
vsce packagerejects; the root README keeps them - Release script: the documentation step skips
dart docwhen no doc input changed since the last successful run and shows live progress; new--full-docsflag - Optional
saropa_scantool in the repository (not part of the published package): finds hand-written code that asaropa_dart_utilscall replaces, finds repeated code worth extracting (useful with or without this package), and applies fixes with undo. A companion VS Code extension, "Saropa Utils", shows both results and can suggest adding or upgradingsaropa_dart_utils. See the README section "Finding opportunities with saropa_scan" - "Saropa Utils" VS Code extension now has its own store icon (a dart in a target, in the same style as the other Saropa extensions) and a matching sidebar glyph
- "Saropa Utils" VS Code extension version now matches the package version (2.1.0), is kept equal by a manifest test, and no longer has its own README or changelog (its docs are the "VS Code extension" section of README.md and the
Extension:entries here) - Extension: findings view in the Explorer (groupable by util member, rule, folder or kind) with two peer groups, "saropa_dart_utils opportunities" and "Repeated code"; Problems panel entries with quick fixes (replace, replace all in file or workspace for safe fixes, ignore a rule here); status bar (
12 utils · 5 repeated); Report screen with two peer sections, filters, adoption trend and JSON, Markdown or CSV export; "Doctor" and "Explain This Finding"; "Add to Exclude List" and "Edit Exclude List"; scan on save for the saved file - Extension: version sync detects
saropa_dart_utilsin every pubspec (hosted, path, git, dev dependency, override, pub workspaces, melos) with the resolved version frompubspec.lock, compares it with the scanner catalog version, and offers "Add saropa_dart_utils" / "Upgrade to - Extension: findings that need a newer
saropa_dart_utilsare marked "needs upgrade to >= x" and offer "Upgrade package then replace" - Extension: scanner discovery via
cli.path, bundled platform binary, PATH, cached download, verified on-demand download (URL, size and SHA-256 shown; checked before first run), thendart run; one scan at a time per window, polite mode (--priority low --jobs auto --lock wait), exit code 75 backoff, scans wait while the machine is busy, child processes are killed as a group on cancel or window close - Extension: versioned API (
apiVersion1, withgetUtilsVersionInfo()and optionalneedsUpgrade/rooton findings) for other Saropa extensions; limited support for untrusted workspaces; settingscli.path,politeMode,scanOnSave.includeRepeatedCode,versionNudge.enabled,versionCheck.pubDev
Changed #
- Extension: renamed from "Saropa Dart Scanner" to "Saropa Utils" (id
saropa.saropa-utils); commands, views, context keys and settings use thesaropaUtils.prefix. Settings still written undersaropaScanner.*are read as a fallback when the new key was never set (user settings only for machine-scoped keys); old command ids are not aliased - Extension: "Find opportunities to use saropa_dart_utils" is the first command, "Find repeated code" its peer, "Scan Workspace (both)" runs both; default grouping is by util member; scan on save runs only the fast utils scan (
scanOnSave.includeRepeatedCodeturns repeated-code analysis on); the Report leads with "N opportunities to use saropa_dart_utils" - Release
[log]links inCHANGELOG.mdandCHANGELOG_HISTORY.mdopen the saropa.com changelog pages instead of GitHub, andCHANGELOG.mdlinks to the full release history - Package homepage is now
https://saropa.com/developers/ allSettled,retryTimes,Base64Utils.compressText/decompressTextand theJsonUtilsdecode helpers report failures throughdart:developerlog()with the error and stack trace attached, instead of printing them withdebugPrint- README shows code-card screenshots for String, DateTime, List, Number, Map and Async, and its examples use the real
toUnique()andAsyncSemaphoreUtilsnames - README examples use real API names (
addNotNull,isCaseSensitive,intToHex(),firstCharacter(),CommonRandom) and correct output comments; every README code block was compiled and run
Fixed #
- Extension: activation no longer crashes in a real Extension Host (a variable was used before it was declared)
- Extension (Windows): command paths such as
C:\Program Files (x86)\...or containing%,!,^,{}are accepted (no shell is used); the legacydartfallback works under Flutter (dart.exeon PATH, then the Flutter SDK'sdart.exe, elsedart.batthroughcmd.exewith every token allowlist-checked); the busy-machine check works (CPU usage is sampled, sinceos.loadavg()is always 0); process-tree kill usestaskkill /T /F;Pathis found when the env var is not spelledPATH - Extension: exclude globs match case-insensitively on Windows and macOS; quick fixes insert text with the document's line ending (CRLF files no longer get bare LF); workspace-relative paths compare drive letters and case correctly on Windows
- Extension: packaging scripts
vsix:win32-x64,vsix:linux-x64,vsix:linux-arm64,vsix:darwin-x64,vsix:darwin-arm64andvsix:universal parseRrulerejects out-of-rangeUNTILdate or time fields with aFormatExceptioninstead of rolling over into a different datetimeboxno longer leaks an unhandled async error on timeout or when the wrapped function throws
Security #
- Extension:
changedSince,fix.git,fix.commitPer,fix.commentandcli.pathare machine-scoped so a repository cannot set them;changedSincemust be a plain git ref (no leading-) and is passed as--changed-since=<ref>, exclude globs as--exclude=<glob>, and a file path starting with-is prefixed with./
Internal #
-
DateConstants.unixEpochDateis built withDateTime.fromMillisecondsSinceEpoch(0, isUtc: true); the value is the same UTC instant as before -
Lint cleanup: indexed loops rewritten, redundant ignores removed, and
saropa_lintsfalse positives documented on their ignores -
Re-enabled two skipped
timeboxtests -
Replaced
addAllaccumulators with collection literals (mapBatched,SpatialGrid,TrieUtils), made the trie delete helper return void, removed a try/catch that could never fire infindUnicodeClassType, and fixed other code behind lint ignores so the ignores could be deleted -
The publish script writes saropa.com
[log]links and, on a major bump, retargets the previous major's links to itsN.x/page -
Upgraded the
saropa_lintsdev dependency to 17.10.0 or later, reused an already-built month start in the nth-weekday range check, and added date-arithmetic comments -
The publish audit's duplicate-class check now ignores private (
_-prefixed) classes and thetool/andtest/directories, which cannot collide in the published API, and counts a class once per file
Maintenance
- New
tool/scannerpackage (saropa_scan0.1.0,publish_to: none) with its own changelog, user guide and ademoproject that exists only to be scanned - New
extension/VS Code extension "Saropa Utils" 2.1.0 (saropa.saropa-utils, settings prefixsaropaUtils.) with no README or changelog of its own:scripts/publish.py(shared helperscripts/modules/extension.py) publishes the extension after pub.dev (--skip-extension/--extension-only, version must equal pubspec) and copies the rootREADME.mdandCHANGELOG.mdintoextension/(gitignored) from thevscode:prepublishhook, rewriting relative links to absolute GitHub URLs; run once in a real VS Code 1.105 Extension Host viacode-server(extension/test-host/), not in the desktop app, not on Windows or macOS; the scanner download flow and release pipeline are untested - CI workflows
scanner.yml,extension.ymlandrelease-scanner.yml(scanner build matrix, extension packaging, draft GitHub Release; nothing is published automatically) analysis_options.yamlexcludestool/scanner/demo/**;.pubignoreexcludes/extension/and/.saropa_scan/(/tool/was already excluded);.gitignoreignoresextension/bin/- Bug reports
BUG-001(README code-card screenshots),BUG-004,BUG-005andBUG-006filed from running the scanner on this library - Added
esbuild,jsonl,sarif,vitestandvsixtocspell.json - New
release.ymlworkflow publishes the extension VSIXes built byrelease-scanner.ymlto Open VSX using trusted publishing (OIDC, noOVSX_PATsecret); it runs after a successfulscanner-v*tag run or by manual dispatch with a run id. The Open VSX publisher is registered against the file namerelease.yml, so do not rename it or add an environment
2.0.0 #
The library now uses the material_ui package instead of flutter/material, so date range, time of day and color extensions accept material_ui types. log
Added #
String.preventOrphansLastGap({int minWrapChars = 4}): fuses only the last gap with a non-breaking space when the last word or the one before it is shorter thanminWrapChars;preventOrphansis unchangedStreamDebounceUtils: stream-based debounce transformer for event streams
Changed #
- Imports
package:material_ui/material_ui.dartinstead ofpackage:flutter/material.dart;DateTimeRange,TimeOfDay,ColorandMaterialColorextensions now use the material_ui types - Minimum Flutter is now 3.47.0 and minimum Dart is now 3.13.0
Breaking #
- Extensions no longer accept the types from
package:flutter/material.dart; they take the material_ui types - Minimum Flutter 3.47.0 / Dart 3.13.0
Migration #
- Replace
package:flutter/material.dartimports withpackage:material_ui/material_ui.dartand addmaterial_ui: ^1.11.0to your dependencies - Upgrade to Flutter 3.47.0+ / Dart 3.13.0+
- Apps still on
package:flutter/material.dartshould stay on 1.6.x
Fixed #
- Suppressed 10
unused_resultanalyzer false positives where@useResult-annotated members are correctly consumed in compound boolean expressions (&&/||) but the Dart analyzer does not track usage through boolean operators - Updated VS Code
dart.analysisExcludedFoldersto include all folders listed inanalysis_options.yamlexcludes (.dart_tool,.github,.vscode,assets,build,example,scripts,tool) pluscoverageanddoc
Internal #
material_ui: added^1.11.0environment.sdk:>=3.9.0 <4.0.0->>=3.13.0 <4.0.0;environment.flutter:>=3.41.4->>=3.47.0analyzer(dev):>=11.0.0 <13.0.0->^14.7.0saropa_lints(dev):>=13.12.7 <17.0.0->^17.1.0- Removed invalid
finalmodifier on 7 parameters (rejected by the Dart 3.14 toolchain) - Filed
unused_resultanddeprecated_member_usetransitive false positives tosaropa_lints/bugs/
1.6.3 #
Audit-tooling fix only — no library changes. log
Internal #
Tooling
- Declaration parser in the publish audit (scripts/modules/audit.py) no longer misreads
const-list elements as declarations. A multi-line constructor call used as a list element (e.g.CrashFamilyCoverage(inside<CrashFamilyCoverage>[ … ]) opens a paren list that does not close on its own line, which the parser accepted as an undocumented declaration — falsely flagging the first entry ofkCrashCoverageAuditandkRuleRemediationsunder both "missing doc header" and "sparse code comments". Both_iter_declsand_method_rangesnow skip any line that begins while(/[nesting is still open (a<T>[ … ]literal or a split argument list);{is excluded so class/function bodies do not suppress the real members inside them.
1.6.2 #
Release-tooling hardening plus release-build input validation. The tooling work future-proofs the publish flow so a saropa_lints rule newly promoted to WARNING is caught before tagging instead of failing the tag-triggered publish one warning at a time (the v1.6.0 experience). The validation work converts assert-guarded preconditions on public-API input to if-throw guards so they hold in release builds, not just debug — a codebase-review sweep found that the dangerous subset degraded to a silent divide-by-zero, hang, or wrong result in production. log
Changed #
stableHashandHyperLogLogUtilsare now web-safe (stable_hash_utils.dart, hyperloglog_utils.dart) — both relied on 64-bit integer wrap that the web's 53-bit-doubleintmodel lacks (and shift operators truncate to 32 bits there), sostableHashproduced a different digest on web than the VM and the HLL estimate collapsed on web. The 64-bit FNV-1a multiply and the splitmix64 hash mixing / register-index-and-rank extraction are now computed in 32-bit limbs (16-bit split multiplies keep every intermediate under 2^53), so results are identical on every platform. The VM output is unchanged — the limb arithmetic reproduces the exact mod-2^64 result, verified against a BigInt ground truth over 200k (stableHash) and 500k (HLL) random inputs, so previously persistedstableHashdigests stay valid.stableHashgains a pinned-digest regression test.- Release-build precondition enforcement (18 files) — converted silent-failure
assertpreconditions on public-API input toif-throw guards (ArgumentError, orRangeErrorfor index/range args) so they run in every build, extending the v1.6.0FenwickTree/rolling_correlationprecedent to the rest of the library. Constructors validate through a static helper invoked in the initializer list, which keeps the throw out of the constructor body (soavoid_exception_in_constructorstays satisfied) and runs before any field initializer that would divide by the value.- Divide-by-zero / NaN:
SpatialGrid(cellSize),TimeDecayCounter(halfLifeMillis),TokenBucketRateLimiter(tokensPerSecond, capacity),binByWidth(bins, max > min),RateLimitSchedule(period),SlidingWindowRateLimiter(limit, window),TimeSeriesBuffer(bucketSizeMs, rawCapacity). - Hang / deadlock:
TaskScheduler(concurrency),BoundedWorkQueue(maxSize),ResourcePool(maxSize). - Silently-wrong result:
LruCache/MruCache/SizeLimitCachesize bounds;SegmentTree.update/query/valueAt(a negative index maps to a valid slot and corrupts the wrong leaf rather than throwing);IntervalEntry/IntervalTree.queryRange/hasOverlap(low > high);MultiIndexCollection(empty indexers);BkTree.search(negativemaxDistance);giniCoefficient(negative values). - Intentionally unchanged: the
constconstructorsQuietWindow,OpenWindow,RecurrenceSpeckeep theirasserts — aconstconstructor cannot throw and droppingconstwould be breaking;quantileBoundaries/binCountsalready degrade gracefully (return[]onbins < 2). - The matching precondition tests now expect
ArgumentError/RangeErrorinstead ofAssertionError.
- Divide-by-zero / NaN:
safeTempNamenow uses a cryptographically secure RNG (safe_temp_name_utils.dart) — was backed by a seedableRandom(), whose sequence is reproducible, so the generated temp-file names were predictable; an attacker who can guess the name can win a temp-file race or pre-create it. Switched toRandom.secure(). Also throwsArgumentErroron a non-positivelength(was silently returning an empty, always-colliding name).Map.getRandomListExceptaccepts an optionalRandom(map_extensions.dart) — previously shuffled with a fresh, non-injectableRandom(), making the result non-reproducible and untestable. Now takes an optionalrandom(defaults toRandom()), matching the injectable-RNG convention used elsewhere in the library. Backward-compatible (new optional parameter).hasInvalidUnicode/removeInvalidUnicodenow detect the real replacement character (string_analysis_extensions.dart) — the constant was56327(0xDC07, a lone low surrogate), not U+FFFD (65533) as the dartdoc said, so an actual�was never matched or removed. Fixed to65533; both methods now work as documented.- More grapheme-vs-code-unit slicing fixes (the same class as v1.6.0's
removeLastChar):removeFirstLastCharandremoveMatchingWrappingBrackets(string_manipulation_extensions.dart) counted code units but sliced with the grapheme-indexedsubstringSafe, so astral content shifted the result ('a😀b'.removeFirstLastChar()returned'😀b';'(😀)'kept the trailing bracket). Both now count graphemes, matchingremoveLastChars.removePrefix/removeSuffix(string_lower_extensions.dart) fed a code-unitprefix.length/suffix.lengthintosubstringSafe, dropping the wrong span when the prefix/suffix or content held astral chars ('😀ab'.removePrefix('😀')→'b'). Switched to code-unitsubstring, consistent withstartsWith/endsWith.
AsyncSemaphoreUtils.release()guards over-release (async_semaphore_utils.dart) — arelease()with no matchingacquire()(and no waiter) silently pushed_availableabovepermits, permanently letting the semaphore admit more thanpermitsconcurrent holders. It now throwsStateErrorinstead of corrupting the permit count.int.ordinal()— correct suffix for*11/*12/*13and negatives (int_string_extensions.dart) — the "teen" check was an absolute11..19window, so111.ordinal()returned'111st'(should be'111th'); likewise112/113/1011/213. And% 10on a negative gave the wrong suffix ((-21).ordinal()→'-21th'). Now tests the last two digits (11–13→th) and usesabs()for the ones digit, so111→'111th',101→'101st',(-21)→'-21st'. The class doc already promised negative support.flattenHierarchyno longer drops orphan-parent nodes (hierarchy_utils.dart) — a node whoseparentIdreferenced an id absent from the input was never a root and never reached by recursion, so it and its entire subtree silently vanished from the result. Such nodes are now treated as roots (level 0).formatNumberLocaleclampsdecimalPlaces(num_locale_utils.dart) —decimalPlaces > 20madetoStringAsFixedthrowRangeError. Now clamped to 20, matchingformatDouble.retryWithBackoffclamps the exponential shift (retry_utils.dart) —1 << (attempt - 1)was unclamped, so a largemaxAttemptsoverflowed the web's 32-bit shift and produced a wrong (small/negative) delay. Now clamped to<< 30, matchingexponential_backoff_utils/retry_policy_utils.
Deprecated #
String?.isNullOrEmptyandString?.isNotNullOrEmpty(string_nullable_extensions.dart) — convenient shorthand, but both defeat Dart's null promotion: the analyzer cannot see the opaque getter impliesthis != null, so afterif (text.isNullOrEmpty) return;(or insideif (text.isNotNullOrEmpty) { … }) the variable stays nullable and callers are pushed toward!. Prefer the long formstext == null || text.isEmptyandtext != null && text.isNotEmpty, which the analyzer understands and which promotetextto non-null in the guarded scope. Kept for source compatibility; deprecated to steer new code.
Added #
debounceCancelable/throttleCancelable(debounce_utils.dart, throttle_utils.dart) — variants ofdebounce/throttlethat return aCancelableCallback(a handle you invoke like a function and can alsocancel()). The plaindebounce/throttleclosures expose no cancel, so a pending timer fires even after the owner (e.g. a widget/controller) is disposed — a use-after-dispose and a Timer leak. The cancelable variants let callers drop the pending invocation on teardown. Non-breaking: the existingdebounce/throttleare unchanged; their docs now point to the cancelable variants.kRuleRemediationsrule-to-remediation mapping (rule_remediation_map.dart) — aconstdata table joining asaropa_lintscrash-prevention rule id to thesaropa_dart_utilspublic symbol that removes the runtime failure it flags (e.g.avoid_unsafe_reduce→sumBy,avoid_path_traversal→isPathSafe,geocoding_unchecked_first→firstWhereOrElse). This is the Saropa Suite Integration plan's R1 deliverable — the data that lets a sibling tool's quick fix upgrade from "enable rule X" to "enable rule X and useYfrom saropa_dart_utils." Ownership settled 2026-06-14 against the sibling changelogs: Lints owns rule→crash-signature, this package owns rule→util-symbol, joined onruleId. Every mapped symbol is pinned by a test that exercises it in compiled code, so alib/rename breaks the build rather than shipping a dead suggestion.kCrashCoverageAuditcrash-family remediation coverage audit (crash_coverage_audit.dart) — the Suite Integration plan's R3 deliverable. For each of the 12 stable crash families the suite recognizes at runtime (Log Capture'sCRASH_SIGNATURE_IDS), records whether this package covers it (coveredwith the owned symbol — e.g.state-error-no-element→singleOrNull,range-error-index→getOrNull,type-error-cast→castOrNull,format-exception→toIntNullable,concurrent-modification→forEachSnapshot) or is not remediable by a utility (notApplicable, e.g.late-init,out-of-memory,anr). No open gaps. Pinned by a test that asserts the family-id set equals the suite contract (a new upstream family fails until triaged) and exercises everycoveredsymbol in compiled code.List.forEachSnapshot(list_mutate_during_iteration_extensions.dart) — runs an action for each element of a point-in-time snapshot of the list, so the body may safely add to or remove from the list during iteration withoutConcurrentModificationError. Closes the suite'sconcurrent-modificationcrash family (R3 follow-up). Documents the snapshot semantics (added elements are not visited this pass; a removed element is still visited if it was present at snapshot time) and points pure conditional removal at the built-inremoveWhere.
Security #
isPathSafedirectory-traversal bypass fixed (path_validator_utils.dart) — the escape check measured depth from the filesystem root (depth < 0) while depth started at the root's own depth, so a path could climbrootParts.lengthlevels above the supplied root and still be reported safe.isPathSafe('../secret', 'home/user')returnedtruethough it resolves tohome/secret(outside the root). Now rejects the moment the path climbs above the root directory itself. If you relied on this for sandboxing, re-test: some previously-"safe" paths are now correctly unsafe.
Fixed #
pathExtension/pathWithoutExtensiononly treat a dot in the final segment as an extension (path_extension_utils.dart) — searching the whole path made a dot in a directory name look like the extension:pathExtension('/a.b/file')returned'b/file'andpathWithoutExtension('/a.b/c')returned'/a.b/c'→'/a'. Both now confine the dot search to the basename (and ignore a leading-dot dotfile).pathChangeExtensioninherits the fix.Map.renameKey/renameKeysno longer lose data or drop null values (map_more_extensions.dart) — they mutated the copy while iterating it, so a chained rename ({'a':'b','b':'c'}) overwrote'b'before renaming it ({'a':1,'b':2}→{'c':1}, value2lost); and anif (v != null)guard silently dropped entries whose value was null. Both now rebuild into a fresh map in one pass, preserving null values; a genuine target collision resolves last-wins (documented).JsonUtils.cleanJsonResponsestrips outer quotes around astral content (json_utils.dart) — used the grapheme-indexedsubstringSafewith a code-unit length, so a quoted value containing a non-BMP grapheme (e.g."🎉") kept its closing quote and then failed to decode. Switched to code-unitsubstring.formatFileSize(..., decimals: 0)keeps integer-part zeros (pad_format_utils.dart) —9728(9.5 KB) rounded to"10", and the unconditional0+$trailing-zero strip turned it into"1 KB". The strip now runs only after a decimal point.Map.deepMergereturns a fully independent result (map_deep_merge_extensions.dart) — nested maps/lists carried through unchanged were shared by reference with the inputs, so mutating the merged map mutated the receiver orother(also affectedcopyWithDefaults). Carried-through values are now deep-cloned.parseIpv4rejects non-canonical octets (ip_cidr_utils.dart) —int.tryParseaccepted a leading sign, surrounding whitespace, and leading zeros ('+1',' 1','01'), soparseIpv4('+1.2.3.4')parsed. Octets must now match a canonical decimal form (no sign/whitespace/leading-zero) — closes an octal-vs-decimal parser differential that can bypass IP allow/deny lists.isImageUri/fileExtensionuse code-unit slicing (url_extensions.dart) — fed a code-unitlastIndexOf('.')into the grapheme-indexedsubstringSafe, returning a wrong extension for filenames with astral characters. Switched to code-unitsubstring.parseQueryStringdecodes+as space (url_query_utils.dart) —Uri.decodeComponentdoes not translate+, so form/browser-produced query strings (a=hello+world) kept the literal+. Now+→space (a literal+arrives as%2B, sobuildQueryStringround-trips are unaffected).num.isNotZeroOrNegative/isZeroOrNegativehandle NaN (num_extensions.dart) —this != 0 && !isNegativeclassifiedNaNas positive. Rewritten asthis > 0/this <= 0, soNaNis correctly neither.roundToSignificantDigitsis correct at exact powers of ten (num_format_extensions.dart) — the decimal exponent was derived from a floatlog10that is fuzzy at powers of ten (e.g.log10(1000)≈ 2.9999997), mis-sizing the scale. Now nudges the exponent to the true integer with apowcomparison.FenwickTree(size)enforcessize >= 0in release (fenwick_tree_utils.dart) — the constructor used a release-strippedassert;size == -1slipped pastList.filled(0)into an unusable tree. Now throwsArgumentErrorvia a static validator (v1.6.0 fixed only the methods).prettyPrintindents entries correctly (debug_utils.dart) — keys/items were prefixed with the parent level's pad, so they were one level too shallow (top-level entries had no indent). Entries are now indented one level deeper than the closing brace.rangeDoubleavoids float drift and a zero-step infinite loop (debug_utils.dart) — computedx += step(accumulating error, so a0.1step could drop/add the endpoint) and would loop forever forstep == 0. Now guardsstep == 0and computes each element asstart + i*step.
Internal #
Tooling
- CI: added a standalone
release_gateworkflow (.github/workflows/release_gate.yml) that runsdart pub publish --dry-runon every push/PR to main — the same command the tag-triggeredpublish.ymlenforces (it runsdart analyzeinternally and exits 65 on any warning). Blocking warnings now surface at PR time, before the irreversible version tag, instead of one-per-tag-round. It is a separate workflow rather than a job inci(main.yaml) because that workflow is disabled, which would have made the gate inert. - Release script (
scripts/modules/workflow.py): the local analysis gate now fails on WARNING-severity findings, not just errors. Becausedart pub publishexits 65 on a single warning, a warning that previously passed this gate still blocked the publish; matching the semantics locally catches it before tagging. pubspec.yaml: pinnedsaropa_lintsto exact13.12.7(was^13.12.7). A caret range let CI's fresh resolve pull a newer patch that promoted a rule to WARNING while the older local lock showed nothing — the version drift behind the whack-a-mole.- Doc-header audit (scripts/modules/audit.py) no longer false-flags a public member as "missing doc header" when a multi-line annotation sits between its dartdoc and the declaration. The upward walk that looks for the
///block now tracks paren depth, so the interior lines of a split@Deprecated( 'msg' 'msg' )(which end with', not@/)/,) are skipped to the opening@Name(instead of aborting the walk. This was reporting the deprecatedisNullOrEmpty/isNotNullOrEmptygetters as undocumented when both carry full dartdoc. suggest_saropa_utilsscanner (tool/suggest_saropa_utils_lib.dart) rebuilt against the reallib/API. Removed detectors that recommended utils that do not exist (orZero,orNow,toIntOr, the misspellednotNullOrEmpty) — they suggested non-compiling code — and detectors that pushed the null-promotion-defeatingisNullOrEmpty/isNotNullOrEmpty/isNullOrZerogetters. Replaced with 45 detectors each audited for a real, flow-analysis-safe target (capitalize,takeLast,dropLast,lastOrNull,ensurePrefix/ensureSuffix,countWhere,whereNotNull,containsAny,getEverythingBefore/After,compressSpaces,orEmpty,isSameDay,startOfDay/endOfDay,addDays/addHours/addMinutes/addMonths/addYears,isLeapYear,isWeekend,flatten,none,containsAll,sumBy,invert,isNumeric,isPalindrome,removeAll,wordCount,percentageOf,lerp,isInteger, …), plus a reverse detector that flags use of the deprecated getters and points back at the explicit form.
Documentation
- Doc accuracy:
hexToInt(hex_utils.dart) no longer claims it "Prints a warning to the debug console" — it returnsnulland prints nothing (the v1.6.0 cleanup fixed only the example, not the prose).varint(varint_utils.dart) now documents that values beyond 32 bits round-trip only on the Dart VM — on web,intis a 53-bit double and the shift operators truncate to 32 bits. toPercentage(double_extensions.dart) doc examples used the wrong parameter name (roundDown:→doRoundDown:); they now compile.topKIndices(top_k_heap_utils.dart) doc corrected: it keeps the k best in a bounded sorted buffer, not a binary heap.withTimeout(timeout_policy_utils.dart) documents that anullfallback is read as "no fallback" (rethrow), so a nullableTcannot usenullas the recovery value — use the required-fallbacktimeout_fallback_utilsinstead.sanitizeHtml/stripHtmlTags(html_sanitizer_utils.dart) docs corrected: it is an HTML-to-plain-text reducer, NOT an allowlist sanitizer (the old doc claimed "allowlist tags/attributes" it never implemented). Added a caveat that its regex tag-stripping is not a security sanitizer and must not be used to produce HTML for re-insertion.
Refactoring
_satisfiesCaret(dependency_resolver_utils.dart) rewritten from a nested ternary to a chained conditional (project style rule). No behavior change.
Tests
suggest_saropa_utilsscanner — coverage expanded from ~17 to 98 cases (suggest_saropa_utils_test.dart) — one positive test per detector confirming it fires on its canonical hand-rolled snippet, real-world variant cases (capitalize via string interpolation and viasubstring(0, 1), extra-whitespacesublist,this-receiverlastOrNull, parenless leap-year), false-positive guards (correct long-form guards, already-using-the-util, literal-boundsublist,wherewithout.length, unguarded division,anywithout negation), and scanner edge cases (empty/whitespace input, multi-hit lines, 1-based line numbers). The expansion caught a real defect: thecountWheredetector's regex stopped at the first)and so never matched a lambda predicate (.where((e) => …).length) — fixed to allow one level of nested parens. Thecapitalizedetector was broadened to also recognize the string-interpolation andsubstring(0, 1)forms found in common Dart idioms.splitCapitalizedUnicodeminLengthmerging now covered (string_text_extensions_test.dart) — the merge branch (the method's most complex path: fuse adjacent parts shorter thanminLength) had no tests. Added 10 cases pinning the real behavior:minLength: 1is a no-op, partial vs full fusion, a part already at the floor staying split, thestraße/ÖsterreichUnicode merge, thesplitNumbersdigit-to-letter split ('Area51TestSite'→['Area', '51', 'Test', 'Site'], four parts — the library's regex separates digit-from-letter, unlike the originating app copy), andsplitBySpacerunning after the merge so it is not subject tominLength. Closes the coverage gap from the 1.6.x utility migration harvested out of Saropa Contacts.- Direct coverage for the named weekday-of-month wrappers (month_weekday_named_extensions_test.dart) —
firstThursday/firstFriday/firstSaturday/secondFriday/secondSaturday/lastFriday/lastSaturdaypreviously had no test naming them directly (their contract was only covered transitively through the bulk non-null sweep). Added one sample-date case per wrapper pinning both the resolved date and itsweekday, so a regression in a single wrapper's ordinal/weekday argument is caught by name. - Rule-to-remediation mapping pinning test (rule_remediation_map_test.dart) — exercises each
kRuleRemediationssymbol in compiled code (an empty-collectionsumBy, a no-matchfirstWhereOrElse, a traversalisPathSafe, etc.), so a renamed or unexported symbol fails the build. Also asserts two-way drift fails (a mapped symbol with no probe, or a probe for an unmapped symbol), rule ids are unique, all fields are non-empty, and everysourcenames a.dartfile. - Crash-coverage audit pinning test (crash_coverage_audit_test.dart) — asserts
kCrashCoverageAudit's family-id set equals the suite'sCRASH_SIGNATURE_IDScontract (an added/removed upstream family fails the test until reconciled), exercises everycoveredsymbol in compiled code, enforces the status invariants (coveredcarries symbol+source, others carry neither), and pins the open-gap set to empty so a coverage regression or a new uncovered family is noticed. forEachSnapshotedge-case tests (list_mutate_during_iteration_extensions_test.dart) — removal during iteration without throwing, the contrasting plainfor-inthat DOES throwConcurrentModificationError, added elements not visited this pass (bounded against an infinite loop), a removed element still visited if present at snapshot time, plus empty / single / no-mutation / nullable-element cases.- Release-audit cleanup ahead of tagging 1.6.2:
formatNumberLocale(num_locale_utils.dart) — reworded thedecimalPlaces-clamp comment so it no longer reads as commented-out code (it contained aname(args)call form that trippedprefer_no_commented_out_code). No behavior change.AsyncSemaphoreUtilstests (async_semaphore_utils_test.dart) — suppressedprefer_setup_teardownwith a rationale comment: each test constructs its semaphore with the permit count that IS the scenario under test (1 to serialize, 2 to bound concurrency), so a sharedsetUp()would hide the parameter each case exercises.
1.6.1 - 2026-06-12 #
Clears every pub.dev "Pass static analysis" point deduction (was 40/50): the seven dangling library doc comments pana reported plus the other eleven plugin findings it counts in the same check. dart analyze is now fully clean. log
Fixed #
stats/rolling_correlation_utils.dart: replaced two release-strippedasserts withif-throw guards (nowArgumentError) so equal-length andwindow >= 2preconditions are enforced in release builds, not just debug.collections/skip_list_utils.dart: replaced a!null-assertion inaddwith an explicit invariant guard that throwsStateError, and switched three[0]reads tofirstOrNull(added thepackage:collectionimport) so neither the unsafe-collection nor null-assertion lint fires.
Internal #
Lint
- Added
library;after the dangling file-level doc comment in:base64/gzip_codec_io.dart,base64/gzip_codec_stub.dart,object/pipe_compose_utils.dart,object/pipe_utils.dart,object/shallow_copy_utils.dart,testing/debug_utils.dart,url/url_encode_utils.dart. - Reworded three explanatory comments (
num/num_more_extensions.dart,datetime/date_time_week_extensions.dart,validation/jwt_structure_utils.dart) so no line begins with anidentifier.membertoken, which the commented-out-code lint misread as dead code. No code or behavior change.
Tests
parsing/varint_utils_test.dart:expect(encoded.length, 10)→expect(encoded, hasLength(10))for a proper matcher and clearer failure output.
Refactoring
collections/fenwick_tree_utils.dart:valueAtconverted to an expression body (=>).
1.6.0 - 2026-06-12 #
Adds 35 advanced utilities from the roadmap — order-statistic trees, multi-source graph search, time-series analytics, calendar/billing helpers, and async cancellation; then a second batch of range-query trees, approximate string search, spatial indexing, async write caches, graph simplification/serialization, and rate-limited scheduling — plus a null-year-tolerant day-count helper. Then a full-project correctness audit of all 476 library files: ~40 algorithm/crash/concurrency bug fixes (incl. a semaphore permit race and two process hangs), ~30 documentation-accuracy corrections, 40 new regression tests, and a per-method audit-date stamp on every method. All fixes preserve existing signatures (backward-compatible). log
Internal #
Lint, docs, and tooling
-
Added a tree-shaking checklist to the README Installation section — documents that the barrel import (
saropa_dart_utils.dart) costs the same shipped size as leaf imports (AOT/dart compile jskeep only reachable code), that extensions shake per method, that the package adds novm:entry-point/dart:mirrors/eager top-level side effects, and the two caveats (tree-shaking is release-build only;pub getdownload size is separate from app-binary size). -
Rewrote
HebrewDateConverter.getMonthNameleap-year branch as a Dart 3switchexpression (hebrew_date_converter.dart) — clearsprefer_returning_conditional_expressions(saropa_lints) without introducing the nested ternary the project'sdart.mdbans. Behavior unchanged (all 100 converter tests pass): the default arm covers both the 1-5 and 8+ direct-index months; 6 → Adar I, 7 → Adar II. -
Suppressed a
prefer_setup_teardown(saropa_lints) false positive in color_light_test.dart with a documented// ignore:— the flagged per-group arrange is a known false positive fixed upstream in saropa_lints 13.12.4 (raises the duplicate threshold when a file-levelsetUpalready exists); the project pins 13.12.3, so the fix has not arrived. Tests stay explicit per the project's clarity-over-DRY testing rule. -
Suppressed
require_timezone_display(saropa_lints) in the twointlclock-rendering files (date_time_intl_time_display_extensions.dart, date_time_intl_display_render.dart) with a documented// ignore_for_filereason. These are locale clock-rendering primitives where the caller owns the timezone-display decision; two flagged sites are provable false positives (aDateFormat.jm()read only for its.patternstring and never formatted, and a seconds-onlyDateFormat('ss')whose field is timezone-invariant). Filed upstream as a saropa_lints false-positive bug report. -
Suppressed
prefer_correct_callback_field_name(saropa_lints) in backtracking_utils.dart with a documented// ignore_for_filereason. The four flagged fields (choices,apply,isComplete,isValid) are pure strategy callbacks — a candidate generator, a state transform, and two predicates — not UI event handlers, so theonXxxconvention the rule enforces would misname them; they are also public fields of a published API, so renaming would be breaking. -
Suppressed an
avoid_accessing_collections_by_constant_index(saropa_lints) false positive in skip_list_utils.dartvalueswith a documented inline// ignore:reason. The flaggednode.forward[0]is the level-0 successor link in the iterator's list walk —nodeis reassigned every iteration, so it is a genuine traversal, not the wasteful fixed-element re-read the rule assumes. This was the lone Warning-severity issue that failed thedart pub publish --dry-runanalyze gate and blocked the v1.6.0 publish (exit 65);.firstwas rejected as the alternative because it trades the warning foravoid_unsafe_collection_methods. -
Added
/build/to .pubignore. A root.pubignoreoverrides.gitignorefor pub, so.gitignore'sbuild/rule stopped applying and the CI runner'sflutter testartifacts (a 64 MBtest_cachedill plus native/unit-test assets) were bundled into the published tarball, bloating the v1.6.0 archive to 21 MB. Excluding/build/ships the package substantially lighter. -
Fixed a flaky test in common_random_test.dart that intermittently failed the publish
Run testsgate. "unique instances with default seed" compared a singlenextInt(100)from two RNGs, which collide ~1% of the time even when seeded differently — a latent ~1% spurious-failure rate. It now compares a 10-draw sequence (collision probability 100^-10) and delays 2 ms (not 1) to reliably cross a millisecond seed boundary. Library behavior unchanged; the test was at fault. -
Disabled the
avoid_string_substring(saropa_lints) rule in analysis_options.yaml and analysis_options_custom.yaml. A newersaropa_lints(pulled by the CI fresh-resolve, since the lock is untracked) promoted this heuristic to WARNING severity, which failsdart pub publish --dry-runwith exit 65. The library has 49 deliberate, bounds-checkedsubstring()calls across parsers, hex/color, and URL templates where indices come fromRegExpmatch offsets or prior length checks — all provably in-range. Auditing/suppressing each site individually is impractical and the rule adds no safety here, so it is disabled project-wide; re-enable with a per-site audit if desired. This was the recurring blocker that failed the v1.6.0 publish across multiple retries (each dry-run surfaced a different substring site). -
Expanded the dartdoc on
MapExtensions.countItems<K, V>(map_extensions.dart) to enterprise-grade: documents the post-deduplicationSetcount, lazy-iterable materialization, content-irrelevance (emoji/combining-mark/nulleach count as one element), order-independence, and non-mutation, plus a worked example. No behavior change. -
Removed the duplicated per-member
/// Hex range:doc comments fromUnicodeClassType(unicode_class_type.dart), bringing the file under the 200-line limit (346 → 147). The inclusive code-point ranges already live once inunicodeClassRanges(unicode_class_blocks.dart) — the single sourcefindUnicodeClassTypeactually reads — so the enum docs were a drift risk. The enum header now points auditors to that table. No enum members changed (105, same order); no behavior change. -
Cleared the open
saropa_lintsanalysis-server diagnostics across eight files, all behavior-preserving (analyze + affected suites green):ColorUtils.getColor(material_color_utils.dart) now reads the non-nullableMaterialColor.shadeNNNgetters instead ofcolor[NNN]!, removing all tenavoid_null_assertionhits and the null-assertion caveat from its dartdoc; threeif/elsevalue-returns inHebrewDateConverter(hebrew_date_converter.dart) collapse to single (non-nested) conditional expressions; thetwoDigitshelper comment inDurationClockFormatExtensions(duration_clock_format_extensions.dart) becomes a///doc comment; four prose WHY-comments thatprefer_no_commented_out_codemisread as code (they led withtoInt()/sublist(...)/?./ a bare// Tens./// Units.label) were reworded, not deleted, in hebrew_date_converter.dart, double_aspect_ratio_extensions.dart, list_string_extensions.dart, and text_direction_parse_utils.dart. Two adjacent diagnostics were deliberately left as-is because resolving them conflicts with this project's own.claude/rules: collapsing the remainingmonth==6branch would force a nested ternary (banned bydart.md), and furthersetUpextraction in the lighten suite would force unrelated tests to share state (againsttesting.md's "Clarity Over DRY").
Fixed #
-
FenwickTreebounds checks now enforce in release builds (fenwick_tree_utils.dart) —update,prefixSum, andrangeSumguarded their index/range arguments withassert, which the Dart compiler strips from release builds (avoid_assert_in_production). In production a negativeindexpassed toupdatewould makei & -i == 0and spin the update loop forever (a hang, not a no-op); an out-of-range index toprefixSum/rangeSumwould return a silently wrong sum. All three now throwRangeErrorso the checks run in every build.valueAt's redundant assert is removed (it delegates to the now-validatedrangeSum). The two bounds tests now expectRangeErrorinstead ofAssertionError. -
removeLastChar()/removeLastChars(count)now count by grapheme cluster (string_manipulation_extensions.dart) — both methods bounded by code-unitString.lengthbut sliced with the grapheme-indexedsubstringSafe, an incoherent hybrid: it subtracted a code-unit count from a code-unit length, then used the result as a grapheme index. The visible effect depended on how many code units each trailing grapheme spanned — e.g.'a😀'.removeLastChar()returned'a😀'unchanged (the emoji's two code units left the grapheme index past the end), and the dartdoc's "counts UTF-16 code units / can split a cluster" claim was the opposite of what the code did. Both now count user-perceived characters: thecountargument is a count of visible characters, a trailing emoji or base+combining-mark sequence is removed whole, and the dartdoc matches.'a😀'.removeLastChars(1)→'a'; decomposed'Café'.removeLastChars(1)drops the whole accented cluster →'Caf'. Pure-ASCII behavior is unchanged. The three pre-existing emoji/combining-mark tests are rewritten to pin the coherent grapheme results, plus a newremoveLastCharemoji case. -
pathRelativenow emits leading..for up-traversal (path_join_utils.dart) —pathRelative('a/b/c', 'a/b/d')returned'd'instead of'../d'. The function computed the correct climb-out segments but joined them throughpathJoin, which treats a leading..as a pop with nothing above it and discards it. It now joins the already-clean segments directly, so any relative path that must ascend out ofbaseis correct ('a/b/c/d'→'a/x'yields'../../../x', pure ascent yields'../..'). Identical paths still yield'';pathJoin/pathNormalizepop semantics are unchanged for their other callers. Pinned by three new up-traversal tests. -
Project audit pass 7 — caching / int / double / json / bool / base64 + singletons (~43 files):
formatPrecision(double_extensions.dart) clampsprecisionto 0–20 (the rangetoStringAsFixedaccepts) instead of throwing a RangeError on a negative or >20 value.- Doc accuracy:
toBoolJson(json_type_utils.dart) documented as a truthy coercion that returnsfalse(notnull) for unrecognized non-null input — only anullargument yieldsnull(matching its tested behavior);int.ordinalexample114th(was101th);hexToIntexamples drop the false "prints a warning" claim;double.leastOccurrencescomment fixed (was a copy-paste of "highest"). - The cache implementations (LRU/MRU/TTL/size-limit/write-through), UUID v4 version/variant bits, HTML entity decoding, color packing/WCAG, and base64 round-trips were all audited and verified correct.
- 1 new regression test; per-method audit-date stamps across all files.
-
Project audit pass 6 — iterable / map / list / validation / url / object / niche (97 files):
jwtPayload(jwt_structure_utils.dart): two fixes — the base64url padding calc appended a spurious====block when the payload length was already a multiple of 4 (rejecting otherwise-valid tokens), and the bytes were decoded as raw code units instead of UTF-8 (mojibake for multi-byte claims). Now(block - len%block) % blockpadding andutf8.decode.mapDiff(map_diff_utils.dart): a genuinely-nullvalue (nullable V) is now reported as added/changed/removed instead of being skipped as if absent (key-presence based, not value-null based).lastWhereOrElse(iterable_first_last_extensions.dart) andrunLengthEncode(run_length_utils.dart): a matched/prevnull(nullable T) is no longer mistaken for "no match"/"no run" — the?? orElseandprev == nullsentinels are replaced.truncateToByteLength(niche_more_utils.dart): counts UTF-8 bytes per RUNE, so a non-BMP emoji is 4 bytes (not 6) and is never split into an invalid surrogate half.unflattenKeys(map_flatten_extensions.dart) andsetNested(map_nested_extensions.dart): a scalar/branch key collision now actually stops instead of writing the leaf into the wrong (outer) map.- Guards:
takeLast(negative n → empty, was RangeError);randomAlphanumeric(non-positive length → '', was a crash);parseQueryString(malformed percent-escape → literal text, was FormatException);getRandomListExcept(negative count clamped);shapeString(result never exceeds maxLength, was returning'...'for maxLength 2). - Doc accuracy:
map_initials_sortexample corrected;list_top_k"(partial sort)" → full-sort note;truncateToByteLengthdoc updated to code-point boundaries. - 5 new regression-test groups; per-method audit-date stamps across all 97 files.
-
Project audit pass 5 — string corrections (lib/string, 78 files):
SoundexUtils.encode(soundex_utils.dart) now treats vowels (A,E,I,O,U,Y) as adjacency-breakers (resetting the run) while H/W stay transparent — same-coded consonants separated by a vowel are re-coded, soGauss→G200instead ofG000.substituteTemplate(string_template_extensions.dart) does a single regex pass so a value containing another key's placeholder is not re-substituted (was chainedreplaceAll).markdownToPlainText(markdown_plain_utils.dart) strips image syntaxbefore the link rule, so it no longer leaves a stray leading!.chunkText(text_chunk_utils.dart) forces at least one char of forward progress, sooverlap >= maxCharsterminates instead of looping forever / overflowing the buffer.parseSearchQuery(search_query_parser_utils.dart) skips a bare-token instead of emitting an empty negated term.extractUrlsWithContext(url_extract_utils.dart) trims trailing sentence punctuation the greedy match swallowed (https://a.com.→https://a.com), leaving brackets intact for paren-bearing URLs.- Doc accuracy:
truncateMiddleandredactPhoneexample outputs corrected;String.reverseddocumented as rune-based (breaks grapheme clusters);template_engine_utilsno longer claims conditionals;textFingerprintdocumented as an order-sensitive identity hash, NOT a simhash (its Hamming distance is not a similarity measure). - 6 new regression-test groups; per-method audit-date stamps across all 78 files.
-
Project audit pass 4 — async & parsing corrections (lib/async 34, lib/parsing 37):
AsyncSemaphoreUtils(async_semaphore_utils.dart) fixed a permit double-counting race:releaseincremented_availableeven when handing the permit directly to a waiter while the wokenacquiredecremented again, so a fast-path acquirer in the wake-up gap could admit a second holder and drive the count negative.releasenow hands off without touching the pool.- Hang guards:
mapBatched(batch_async_utils.dart) treats a non-positive batch size as 1 instead of looping forever;raceFirst(race_cancel_utils.dart) fails fast on an empty producer list instead of returning a never-completing future;retryWithJitter(retry_policy_utils.dart) guards a zero jitter (nextInt(0)RangeError) and clamps the backoff shift;bufferCount/windowCountclamp a non-positive count to 1. SemverUtils.compareTo(semver_utils.dart) now compares pre-release identifiers per semver §11 (numeric-vs-numeric numerically, numeric below alphanumeric, longer ranks higher) instead of a plain string compare that madealpha.2 > alpha.10.encodeVarint/decodeVarint(varint_utils.dart) round-trip negative and >2^35 values: encode uses a logical shift + mask test (negatives emit the full 10-byte form), decode's cap is raised to 64 bits.parseHexColor(hex_color_utils.dart) rejects an embedded non-hex char instead of stripping it and parsing the coincidentally-valid remainder (#a1z2c3d→ null).parseChangelogSections(changelog_section_utils.dart) slices with code-unitsubstring, not the grapheme-indexedsubstringSafe, so emoji/non-BMP content no longer misaligns section bodies.parseNestedQuery(nested_query_parser_utils.dart) skips a scalar/nested key collision (a=1&a[b]=2) instead of leaking the nested leaf to the root.- Doc accuracy:
CircuitBreakerUtilsdocumented as two-state (no real half-open gating);memoizeFuturenotes failures are cached permanently;compareVersionswarns it ignores pre-release suffixes;raceFirstheader no longer claims it cancels losers. - 5 new regression-test groups; per-method audit-date stamps across all 71 files.
-
Project audit pass 3 — datetime corrections (lib/datetime, 57 files):
- Two unbounded-loop guards:
expandRecurrence(recurrence_iterator_utils.dart) now abandons an impossible rule (e.g.FREQ=YEARLY;BYMONTH=2;BYMONTHDAY=30) after a long empty run instead of hanging even under.take(n);fillMissing(timeseries_gap_utils.dart) returns the input sorted for a non-positive interval instead of spinning forever / OOM. - DST / calendar-field correctness:
heatmapGrid/_weekStart(calendar_heatmap_utils.dart),dayOfYear/numOfWeeks(and thusweekOfYear/weekNumber) (date_time_calendar_extensions.dart),getNthWeekdayOfMonthInYear(date_time_extensions.dart), andsplitByMonth(period_split_utils.dart) now step dates with calendar fields / UTC date-only endpoints instead ofDuration(days:n)on local time, which drifted off midnight (and one day off, fordayOfYear) across DST transitions. parseIsoWeekString(date_time_week_extensions.dart) now rejects a week the year does not have (e.g.2025-W53) by validating the week's Thursday-year, instead of returning a date in the following ISO year.isAnnualDateInRange(date_time_comparison_extensions.dart) no longer matches a Feb-29 annual date against Mar 1 in non-leap years (DateTime silently rolls Feb 29 over).- Doc accuracy:
getEmojiDayOrNightno longer claims error-handling/logging it does not do;convertDaysToYearsAndMonthsexamples corrected (365 days is 11 months, not 1 year;45with remaining days is15, not14). - 6 new regression tests; per-method audit-date stamps across all 57 files.
- Two unbounded-loop guards:
-
Project audit pass 2 — collections corrections (lib/collections, 64 files):
kmeans2D(kmeans_utils.dart) now seeds centroids with maximin (greedy k-means++) spreading instead of placing all k atpoints[0]— the old seeding collapsed the output to at most two clusters for any k because identical centroids never diverge under Lloyd's algorithm.bucketByTime(time_bucket_utils.dart) andTimeSeriesBuffer(timeseries_buffer_utils.dart) now FLOOR the epoch-to-bucket division instead of truncating toward zero, so pre-1970 (negative-epoch) timestamps land in the correct bucket.bucketByTimealso returns empty for a non-positive bucket width instead of dividing by zero.BloomFilterUtils(bloom_filter_utils.dart) sizes the bit array withdart:math.loginstead of a hand-rolled natural-log approximation that mis-sized the filter.DifferenceArrayUtils.addRange(difference_array_utils.dart) now ignores a reversed range (l > r) as a no-op instead of silently corrupting the recovered array.- Doc accuracy:
StreamQuantileUtilsdocumented as the exact O(n) estimator it is (not the "P²-style fixed-memory" the title implied; removed the dead no-op buffer sort);PriorityMapUtilsdocumented as draining buckets in priority-insertion order, NOT by comparing key value;toColumnardocumented as using the first row's keys as the schema;topKIndicesdocumented as returning an unspecified order;pivot_unpivot_utilsnotesunpivotis not implemented. - 4 new regression tests; per-method audit-date stamps across all 64 files.
-
Project audit pass 1 — graph & num algorithm corrections (stats/graph/num categories):
floydWarshall(floyd_warshall_utils.dart) now seeds the distance matrix with the minimum edge weight per(i, j), not the last one — parallel edges in a multigraph and positive self-loops no longer overwrite a shorter distance or the diagonal0.dagSchedule(dag_scheduler_utils.dart) now appliespriorityas a tiebreaker among nodes that are simultaneously ready (priority-aware Kahn), instead of sorting the whole topological order by priority — the old form could place a dependency after its dependent, breaking topology.douglasPeuckerIndices(line_simplify_utils.dart) perpendicular distance now divides by the chord length (sqrt(dx²+dy²)), not the squared length —epsilonis once again a true distance tolerance; the degenerate zero-length chord uses Euclidean distance.dijkstraDistances/dijkstraWithParents/astar/bfs/dfs/criticalPathDistancesnow guard an empty graph or out-of-range start/source/goal instead of throwingRangeError(astar returnsnull, matching its no-path contract).nextPowerOfTwo(num_more_extensions.dart) bit-smear now reaches>> 32, fixing wrong results for 64-bit inputs above 2³².lcm(math_utils.dart) divides before multiplying to avoid 64-bit overflow on large operands.- Doc accuracy:
outlierIndicesByMADno longer claims the modified z-score cutoff (it omits the 0.6745 constant — now documented);divideSafedrops the impossible "or null" divisor note;NumUtils.generateIntListdrops the "prints a warning" claim (it does not print). - 6 new regression tests pin the corrected behaviors. Per-method audit-date stamps added across stats/graph/num doc headers.
-
List<String>helper tests pinned to real Dart casing/trim behavior (list_string_extensions_test.dart) — corrected two test expectations that asserted behavior Dart does not have, plus the matching source dartdoc. (1) The eszett case test claimed['straße'].toUpperCase()yields['STRASSE'], but Dart'sString.toUpperCase()is a 1:1 code-point map that leaves'ß'unchanged ('STRAßE'); the test and theListStringExtensions.toUpperCasedartdoc (which wrongly stated'ß'->'SS') now state the real no-expansion behavior. (2) TheremoveTrimmedEmpty(trim: false)test expected[' a ', ' ']to drop the whitespace-only' ', contradicting the documentednullIfEmpty(trimFirst:false)contract (and the sibling tests at the same group) under whichtrim:falsedrops only a literal''and keeps' '; the test now asserts both entries survive. Source behavior was correct in both cases — only the wrong expectations and the stale dartdoc changed. -
ComputeStreamTransformernon-sendable-closure test no longer hangs the suite (compute_stream_transformer_test.dart) — the test passed a closure capturing aStreamController(a non-sendable native receive port) throughcompute()and asserted the stream surfaced an error. That "non-sendable closure rejects" behavior is a real-isolate (on-device) contract that is unobservable in the Flutter test VM: sending such a closure leaves a dangling_RawReceivePortthat never closes, so the test isolate could not quiesce and the case ran to the 30-second timeout — the platform sensitivity the spec already flags. Reworked the test to assert the observable, supported half of the contract (a top-levelComputeCallbackcomputes correctly) and documented why the closure-rejection path is intentionally not exercised here. Source unchanged — it already propagates compute failures correctly (covered by the passingonError/ rethrow tests). -
DateTime.getSimpleRelativeDay/getRelativeDayResultnow count whole calendar days across a DST spring-forward (simple_relative_day_utils.dart) — the date-only normalize built LOCAL midnights, so on a spring-forward day (e.g. Mar 10→11 2024 in a US zone, a 23-hour local day)difference().inDaystruncated a genuine one-calendar-day gap to0, misbucketing tomorrow as today. The normalizer now builds UTC midnight from the calendar fields, so two normalized dates are always an exact multiple of 24 hours apart and the day count is correct regardless of DST or the receiver's UTC-vs-local kind. -
String.removeEndnow strips a code-unit suffix that falls inside a grapheme cluster (string_manipulation_extensions.dart) —removeEndmatched the suffix with UTF-16endsWithbut sliced with the grapheme-awaresubstringSafe, which reinterpreted the code-unit cut indexlength - end.lengthas a grapheme index and refused to split a base+combining-mark cluster, leaving the suffix un-stripped. So('e' + U+0301).removeEnd(U+0301)returned the unchanged'é'instead of'e'. Switched the slice to plainString.substring— afterendsWithis true the cut point is a guaranteed-valid code-unit boundary, so it never throws — making the strip consistent with the documented UTF-16 code-unit contractremoveEndNullableinherits. ASCII/BMP suffixes are unaffected. -
TextDirectionParseUtils.tryParsenow rejects a BOM-prefixed token (text_direction_parse_utils.dart) — Dart'sString.trim()strips U+FEFF (BOM / zero-width no-break space) as whitespace, so'ltr'was incorrectly parsing asltrinstead ofnull. The SPEC pins BOM as NOT whitespace (it is a formatting char, unlike NBSP / thin / ideographic space, which stay trimmed), so a private_trimhelper now re-attaches any leading/trailing BOM thattrim()removed, keeping the token unrecognized while preserving real-Unicode-whitespace trimming. Aligns the source with the existing zero-width-space (U+200B) handling. -
DateTime.toDateFormatnow returns''for an invalid pattern (date_time_intl_display_extensions.dart) — the documented "invalid pattern →'', never throws" contract relied solely on a try/catch, but intl'sDateFormatdoes NOT throw on an unrecognized field letter such as'q': it echoes the letter as literal text ('q'.toDateFormat('q')returned'q'), so the catch never fired. Added an up-front_patternHasUnknownFieldguard that rejects any unquoted ASCII letter outside intl's implemented field set (GyMkSEahKHcLQdDmsvzZ, sourced from intl's own pattern matcher), returning''before formatting. Letters inside single-quoted literal sections are exempt, so a literal pattern like'q'(quoted) still renders. -
Corrected the
compareAgesinstant-equality test (date_time_compare_age_extensions_test.dart) so it constructs the UTC and local operands from ONE instant (utc.toLocal()) instead of buildingDateTime.utc(2020, 1, 1)andDateTime(2020, 1, 1)independently. The old form assumed they were the same moment, butDateTime(...)is wall-clock local time — a different absolute instant fromDateTime.utc(...)on any host not at UTC+0 — so the instant-basedcompareTocorrectly returned-1, failing the assertion. The source comparator was correct; the test fixture was wrong. -
Corrected the
ColorUtils.getColorshade500 test (material_color_utils_test.dart) so it compares ARGB values (toARGB32()) instead of objects.getColor(shade500, Colors.red)returns the plainColorat[500]; the old assertion compared it to theColors.redMaterialColorobject, which never equals a plainColorbecause the two are different runtime types even when the tone is identical. Now both sides are reduced to theirtoARGB32()integer (replacing the deprecated.value), matching the spec intent that shade500 is the swatch's primary tone. The source was correct; the test fixture was wrong. -
Fixed
findUnicodeClassType(value, ignoreWhitespace: false)(unicode_class_utils.dart) to classify whitespace runes into their Unicode block instead of returningnull. The function calledvalue.trim()unconditionally, and Dart'strim()strips Unicode space separators (NBSP U+00A0, en-space U+2002, ideographic space U+3000, ogham space U+1680), so a whitespace-only string was emptied before the scan ran — makingignoreWhitespace: falseunreachable for exactly those runes. The trim now only runs whenignoreWhitespaceistrue; when the caller opts in to classifying whitespace, the original string reaches the rune loop, so NBSP →Latin1Supplement, en-space →GeneralPunctuation, and ideographic space →CJKSymbolsAndPunctuationas the spec's Bulletproofing list requires. The defaultignoreWhitespace: truepath is unchanged. -
Corrected two
HebrewDateConvertertest expectations (hebrew_date_converter_test.dart) against SPEC-datetime-hebrew-converter.md. (1) The cross-cycle leap-boundary test asserted 5774→5777 as the last-leap/first-leap pair, but the closed-form(year*7+1)%19 < 7(used by the test's own far-future case and the source) places the seventh and final leap of a 19-year cycle at cycle-position 19, making 5776 the last leap and 5779 the first of the next cycle; 5774 is position 17 (the sixth leap). (2) The proleptic-day-before-epoch test (DateTime(-3760, 9, 6), JD 347997) expected month 13/day 29, but Hebrew year 0 is a degenerate proleptic year (its molad-derived length is 321 days, not a real 383–385-day leap year), so the month-walk lands on month 11, day 25 — the test now pins the algorithm's actual floor output. The source was correct in both cases; the test expectations were wrong.
Added #
Roadmap batch — 25 advanced, tree-shakeable utilities (each its own file + full test suite; 276 new tests):
FenwickTree(fenwick_tree_utils.dart, roadmap #483) — Binary Indexed Tree for O(log n) point updates and prefix/range sums overnum; 1-based internal tree behind a 0-based public API, withFenwickTree.fromListbulk build.MinMaxHeap<T>(min_max_heap_utils.dart, roadmap #499) — double-ended priority queue (min-max heap) giving O(1)min/maxpeek and O(log n)removeMin/removeMaxfrom a single backing array, withminOrNull/maxOrNullfor the empty case.SkipList<T>(skip_list_utils.dart, roadmap #502) — probabilistic ordered set withcontains/add/remove, ascendingvalues, andfloor/ceilingorder-statistic lookups; injectableRandomfor deterministic tests.clusterBySimilarity/dedupBySimilarity(similarity_dedup_utils.dart, roadmap #461) — single-link (transitive) near-duplicate clustering via union-find over a caller-supplied similarity predicate, preserving first-seen order.weightedSubset(constrained_subset_utils.dart, roadmap #476) — weighted random subset selection without replacement (Efraimidis–Spirakis) honoring exclusion sets and non-positive-weight skipping; injectableRandom.clusterIntoSessions/sessionsWithBounds(session_clustering_utils.dart, roadmap #485) — gap-based sessionization of timestamped items (clickstream/login/GPS bursts); sorts input and splits on gaps exceedingmaxGap, optionally returning each session's start/end bounds.BacktrackingSolver<State, Choice>(backtracking_utils.dart, roadmap #486) — generic depth-first backtracking with pruning callbacks and a solutionlimit;solveFirst/solveAll(verified on N-Queens and subset-sum).permutations/combinations/cartesianProduct/powerSet(lazy_combinatorics_utils.dart, roadmap #488) — lazysync*combinatorics that yield fresh lists on demand, so huge spaces are enumerable without materializing them.ItemSimilarityModel<T>(item_similarity_utils.dart, roadmap #490) — co-occurrence item-to-item recommender; Jaccard similarity over per-item basket sets with rankedrecommend(item, topN).multiSourceBfsDistances/multiSourceBfsNearest(multi_source_bfs_utils.dart, roadmap #535) — single-sweep multi-source BFS giving each node its hop distance to (and identity of) the nearest seed;-1sentinel for unreachable nodes.pageRank(pagerank_utils.dart, roadmap #541) — power-iteration PageRank with dangling-node mass redistribution and tolerance-based early stop; scores sum to ~1.enumeratePaths(path_enumeration_utils.dart, roadmap #543) — all simple (no repeated node) paths between two nodes with an optionalmaxDepthedge cap.reachabilitySets/reachabilityMatrix/canReach(reachability_utils.dart, roadmap #551) — transitive closure; a node reaches itself only when it lies on a cycle.cusumChangePoints(change_point_cusum_utils.dart, roadmap #568) — two-sided CUSUM change-point detection with configurable threshold/drift, resetting on each detection.giniCoefficient(gini_utils.dart, roadmap #573) — inequality metric in [0,1] via the sorted-rank formula;0for equal distributions, NaN for empty, asserts non-negative inputs.rollingCorrelation(rolling_correlation_utils.dart, roadmap #577) — Pearson correlation over a sliding window of two equal-length series; NaN where a window has zero variance.binByWidth/quantileBoundaries/binByBoundaries/binCounts(data_binning_utils.dart, roadmap #585) — equal-width, quantile, and custom-boundary binning with out-of-range clamping and frequency counts.billingDateInMonth/nextBillingDate/billingSchedule/currentCycle(billing_cycle_utils.dart, roadmap #609) — monthly billing anniversaries with end-of-month clamping (anchor 31 → Feb 28/29) and cycle-bounds resolution.RecurrenceSpec+RecurrenceFrequency+humanizeRecurrence(humanize_recurrence_utils.dart, roadmap #599) — human-readable recurrence text ("every 2 weeks on Tuesday", "every 2nd Tuesday of the month") with a correct English-ordinal helper.dailyCounts/heatmapGrid/heatmapStats(calendar_heatmap_utils.dart, roadmap #603) — GitHub-style heatmap data: per-day event counts, a week-aligned grid over a date range, and max/total/active-day stats.findGaps/fillMissing/forwardFill(timeseries_gap_utils.dart, roadmap #606) — detect missing samples in a roughly-regular series (tolerance-based), generate the complete regular grid, and forward-fill null values.parseCacheControl/parseMaxAge/parseETag/parseRetryAfterSeconds(http_header_parse_utils.dart, roadmap #632) — dependency-free parsing of common HTTP caching headers (directive map, weak/strong ETag, numeric Retry-After).stableHash/canonicalString(stable_hash_utils.dart, roadmap #649) — order-stable structural checksum (FNV-1a 64-bit, sorted map keys, order-preserving lists) rendered as a fixed 16-char lowercase hex; no crypto dependency.flattenMap/explode(flatten_explode_utils.dart, roadmap #648) — flatten nested maps/lists into dotted/indexed keys and explode an array field into one row per element for tabular/BI export.CancellationToken/CancellationException/runCancellable(cancellation_token_utils.dart, roadmap #674) — cooperative cancellation: idempotentcancel,throwIfCancelled,whenCancelledfuture, fire-onceonCancelcallbacks, and a task-vs-cancellation race helper.
Roadmap batch 2 — 10 more advanced, tree-shakeable utilities (each its own file + full test suite; 80 new tests):
-
SegmentTree(segment_tree_utils.dart, roadmap #495) — iterative segment tree for O(log n) range sum / min / max with O(log n) point updates;SegmentTree.sum/.min/.maxnamed constructors with identity-aware empty handling. -
BkTree(bk_tree_utils.dart, roadmap #493) — metric-tree index for approximate string matching:search(query, maxDistance)prunes via the triangle inequality (default Damerau–Levenshtein, injectable metric), set-semantics inserts. -
SpatialGrid<T>(spatial_grid_utils.dart, roadmap #506) — uniform-grid spatial index for 2D points; O(1)insertandqueryRadius(x, y, r)that scans only overlapping cells then filters by true Euclidean distance. -
TimeSeriesBuffer+TimeBucket(timeseries_buffer_utils.dart, roadmap #510) — bounded series that keeps the last N raw points verbatim and folds evicted points into fixed-width count/sum/min/max/mean buckets for raw-recent + aggregated-history views. -
WriteThroughStore<K, V>/WriteBackStore<K, V>(write_through_cache.dart, roadmap #508) — async cache wrappers that coordinate writes to a backing store (the read-throughWriteThroughCache#523 does not): write-through persists on everyput; write-back buffers dirty keys and coalesces them onflush. -
MruCache<K, V>(mru_cache.dart, roadmap #509) — fixed-capacity cache with most-recently-used eviction (the right policy for cyclic scans) plus per-key access-frequency tracking viafrequencyOf. -
simplifyDegree2Chains(graph_simplify_utils.dart, roadmap #545) — contracts maximal chains of degree-2 pass-through nodes in an undirected graph into single junction-to-junction edges; preserves anchorless pure cycles so connectivity is never lost. -
serializeAdjacency/parseAdjacency(graph_serialize_utils.dart, roadmap #554) — loss-free compact text codec (0>1,2;1;2>0) for directed adjacency-list graphs; nodart:convertdependency, preserves neighbor order and isolated nodes. -
diffCalendars+CalendarEvent(calendar_diff_utils.dart, roadmap #608) — classifies two event snapshots (keyed by id) into added / removed / changed, where "changed" compares start, end, and title; the core of sync reconciliation and "what changed" UIs. -
RateLimitSchedule(rate_limit_schedule_utils.dart, roadmap #612) — shapes requested event times to honor a rolling-window quota (max N per period) plus a minimum cooldown, pushing rather than dropping events to the earliest compliant instant. -
findUnicodeClassType(String)+UnicodeClassTypeenum +isUnicodeWhitespace(int)(unicode_class_utils.dart, unicode_class_type.dart) — script/block detector that inspects a string's runes and returns the Unicode named block (BasicLatin,Cyrillic,Arabic,CJKUnifiedIdeographs,Hiragana,HangulSyllables,CurrencySymbols,Arrows, ...) the first qualifying rune falls into, mirroring the .NET "Supported Named Blocks" table across the Basic Multilingual Plane (U+0000–U+FFFF). Useful for language/script detection, input validation, sort-bucket selection, and font-fallback decisions. Options:ignoreBasicLatinskips the Latin block so a Latin-prefixed string reports the trailing non-Latin script;firstCharOnly(defaulttrue) classifies only the first qualifying rune vs. scanning to the first non-ignored match;ignoreWhitespace(defaulttrue) skips whitespace runes. Returnsnullfor an empty/whitespace-only string, for unassigned gaps between blocks, and for astral-plane runes above U+FFFF (most emoji) — the function is BMP-only and the three surrogate enum blocks are unreachable from valid Dart strings. Never throws (best-effort contract; any failure degrades tonull). The companionisUnicodeWhitespace(int rune)is the pure-Dart whitespace predicate (ASCII controls plus the Unicode space separatorstrimdoes not always strip, e.g. narrow no-break space, ideographic space) replacing the originalquiver.isWhitespacedependency, and the backingunicodeClassRangestable is exposed for meta-tests asserting it stays sorted, non-overlapping, and one-entry-per-enum-value. Pure Dart, no Flutter or external dependencies. -
String?.compareStringFolded()/foldedCompare()/List<String>.sortedFolded()(string_folded_compare_extensions.dart) — diacritic-folding sort comparator. Folds Latin diacritics and ligatures (á→a,ß→ss,æ→ae) so accented names interfile with their base letter instead of sorting afterzby code unit; case-insensitive by default, with an optionalnaturalnumeric mode (img2beforeimg10), null grouping (nullsLast), and a deterministic raw-string tie-break so two distinct strings that fold to the same key ("Foo"vs"fóò") never compare equal — safe as aSplayTreeMapcomparator (a0compare silently drops a key). Composes the existingremoveDiacritics()andnaturalCompare(); pure Dart, no new dependencies. Latin-focused: non-Latin scripts (CJK, Cyrillic, ...) pass through and order by code point; NOT locale-aware ICU collation. -
DateTimeIntlDisplayExtensionsonDateTime(date_time_intl_display_extensions.dart) — locale-correct date/time display viaintlskeletons (yMMMd,MMMEd,jm,Hms, ...), the one opt-in module inlib/datetime/that pulls theintldependency (the rest stays intl-free by design). Unlike the fixed-layoutDateFormatNamespresets, these REORDER components per locale (en_US "Jan 15, 1945", fr_FR "15 janv. 1945", ja_JP "1945年1月15日") and auto-detect each locale's 12h/24h clock from thejmskeleton. Members:dateDisplay(abbreviated/full month, optional English ordinal, current-year suppression),makeDisplayDate(weekday + year,year > 0guard for placeholder dates),makeDisplayTime(locale clock with minute-eliding and a U+00A0 non-breaking clock so "8:31 PM" never wraps),utcTimeDisplay(fixed presets via the newUtcTimeDisplayEnum),fullDateDisplay,formatByLocale,toDateFormat(explicit pattern + millisecond suffix), andgetUtcOffset(pure-DartUTC+5/UTC±0/UTC+5:30). All display methods catch and degrade (null/'') rather than throw on an unloaded locale. The top-levelformatUtcOffset(Duration, {verbose})formats a fixed offset deterministically (no host-TZ read) for testability. Callers formatting non-English locales must callinitializeDateFormatting()once per process first. Requires theintlpackage (re-enabled inpubspec.yaml). -
String.removeEndNullable(String? find)(string_manipulation_extensions.dart) — nullable-aware companion toremoveEnd, sitting beside it onStringManipulationExtensions. Returns the receiver unchanged whenfindisnullor empty (nothing to strip); returnsnullonly for the empty-receiver-with-a-real-suffix case (an empty source cannot carry the requested suffix, sonullmarks "no source" distinctly from'"stripped to nothing"); otherwise delegates toremoveEnd, so a whole-string match strips to'(notnull) and only ONE trailing occurrence is removed. Matching is case-sensitive UTF-16 code-unit suffix matching (not grapheme-aware), so a surrogate-pair emoji or whole combining mark strips cleanly while a bare combining mark off a cluster can split it. Pure Dart, no Flutter or external dependencies. -
bool.compareTo(bool other)(bool_sort_extensions.dart) — adds theBoolSortingHelperextension so aboolcan be used as a sort key.booldoes not implementComparableindart:core, so[true, false].sort()throws; this fills the gap with aComparable.compareTo-shaped comparator (truesorts BEFOREfalse, the "flagged first" convention): returns0for equal values,-1when this istrueandotherisfalse, and1for the reverse. Drops intoitems.sort((a, b) => a.isPinned.compareTo(b.isPinned))or any tie-break comparator. Pure Dart, no Flutter or external dependencies; the closed two-value domain has no failure path. -
FilterValue<T>(filter_value.dart) — optional-write wrapper forcopyWithparameters that need three intents instead of two:FilterValue.unset()(the const default) keeps the current value,FilterValue(v)overrides withv, andFilterValue(null)explicitly clears to null — the case the?? this.fieldidiom can't express and that the*ForceNullcompanion-parameter workaround doubled the parameter surface to express.resolve(current)performs the keep-vs-override decision in one call; the wrapper holds its value by reference (no copy) and defines nooperator ==. Pure Dart, zero dependencies. -
DateTime.toAnnualDate/DateTime.toDayRange()(date_time_bounds_extensions.dart) — two members added toDateTimeBoundsExtensions.toAnnualDatepins month/day to sentinel year 0 (the canonical recurring-annual-date form for birthdays/anniversaries) — the blessed producer for the existingDateTimeComparisonExtensions.isAnnualDateInRangeconsumer, dropping time-of-day and surviving Feb 29 (year 0 is a leap year).toDayRange()returns the full local calendar day as aDateTimeRangeby composing the existingstartOfDay/endOfDaygetters, so the end is microsecond-precise (23:59:59.999999), not millisecond-truncated, with a single source of truth for the bounds. -
DateTimeUtils.monthDayCountSafe({int? year, required int month})(date_time_utils.dart) — null-year-tolerant, non-throwing companion tomonthDayCount. Whenyearis null, February returns 28 (a leap year cannot be resolved without the year); a known leap year still yields 29. An out-of-rangemonth(0,13,-1, very large ints) returns 30 instead of throwing, so callers holding partial date parts get a defined value. Negative years follow the proleptic Gregorian leap rule. Backed by newDateConstants.daysInThirtyOneDayMonth/daysInThirtyDayMonth. -
Duration.displayTime()/Duration.formatDuration()/Duration.reverse()(duration_clock_format_extensions.dart) — a newDurationClockFormatExtensionswith three pure-Dart formatters.displayTime()renders a stopwatch/media clock string ('HH:MM:SS.mmm', or'MM:SS.mmm'withshowHours: false) and never rolls hours into days, soDuration(hours: 25)shows'25:00:00.000'— distinct from the day-aware top-levelformatDuration(d, ...)it sits alongside.formatDuration()renders a comma-joined human list of non-zero units down to microseconds ('1 hr, 2 mins, 3 secs, 4 ms, 5 μs'), returning'Instantaneous'forDuration.zero, with optionalshowLeadingZerosand short/longshortFormwords (microsecond short form is the Greek muμs).reverse()returns the sign-negated duration. Reuses the library'sString.pluralize; no Flutter, nointl. -
Uint8List.toIntList()/List<int>.toUint8List()(uint8list_extensions.dart) — two reciprocal byte/integer bridges in new extensionsUint8ListExtensionandIntListExtension.toIntList()copies a fixed-lengthUint8Listinto a fresh growable, independentList<int>(the form binary APIs — file bytes, crypto output, network frames, image decoders — need when they must append or mutate).toUint8List()copies anyList<int>into a fresh fixed-lengthUint8ListviaUint8List.fromList, storing each element modulo 256 (low 8 bits):256 → 0,257 → 1,-1 → 255, and even platform-max/min ints reduce to their low byte without throwing — narrowing that holds for typed-data sources (Int8List/Int16List) too. Both directions produce independent buffers, so post-conversion mutation never crosses over. Pure Dart (dart:typed_dataonly), no Flutter, no external packages. -
StopRangeenum (gradient_stop_range.dart) — four named easing categories (easeIn,easeOut,easeInOut,linear) mapped via.stopsto a fresh normalized two-elementList<double>in the 0..1 range ([0, 0.5],[0.5, 1],[0.25, 0.75],[0, 1]). Drops straight into any stops-accepting gradient API (FlutterGradient.stops, a CSS/SVG string builder, a custom shader). Pure Dart, no Flutter or external dependencies; each read returns an independent list so caller mutation can't corrupt the constants. -
double.toAspectRatio()(double_aspect_ratio_extensions.dart) — converts a decimal ratio (e.g. an image'swidth / height) into a GCD-simplified integer pair(int, int)?, quantizing the fractional part to three decimal places (× 1000) and reducing viaIntUtils.findGreatestCommonDenominator. Pure Dart, no dependencies; reuses the package'shasDecimalsgetter and GCD utility. Whole numbers return(1, value); the tuple order is(denominator-side, value-side), locked by a regression test. Returnsnullfor NaN,±Infinity, and negative fractional input — the non-finite guard keeps the integral path from throwingUnsupportedErrorontoInt(). The 3-decimal quantization truncates toward zero and is intentionally lossy, so canonical small ratios such as16:9are not recovered (16 / 9→(1000, 1777)). -
DarkColorsenum +DarkColorsUtils.darkColorMap(dark_colors.dart) — 20-value enum (Red…Black) mapped to fixed, fully-opaque Material 700Colorconstants (e.g.Red → 0xFFD32F2F). A brand-agnostic palette of legible-on-light dark colors for category tags, avatar backgrounds, chart series, and labels. Compile-timeconstdata table; every swatch is distinct, alpha0xFF, and verified by tests to clear a 3.0 WCAG contrast floor against white (cross-checked via the package's owncontrastRatio). Enum order is index-stable (Red= 0,Black= 19) so values persisted by index never silently remap. Flutter-typed (needsColor); kept in its own file so the pure-Dartcolor_utils.dartmath stays Flutter-free. -
SimpleRelativeDayenum +DateTime.getSimpleRelativeDay()/getRelativeDayResult()(simple_relative_day_utils.dart) — calendar-day relative classifier that buckets a date against a referencenowintotoday/yesterday/tomorrow/beforeYesterday/afterTomorrow/lastWeekday/nextWeekday(±3..±13 days) /lastMonth/nextMonth, returningnullfor dates outside the ~2-month window (same month beyond ±2 weeks, or more than one calendar month away) so callers get a typed label only when one is useful. Covers BOTH past and future at single-day resolution — net-new alongside the past-only stringrelativeDateBucketand the free-textrelativeTimeString. Time-of-day is dropped (calendar days, not 24-hour spans) via an internal kind-preserving date-only normalize, so a 23:59-vs-00:01 pair reads as one day and a DST short day still counts whole days; the month delta folds the year ((year*12 + month)) so Dec→Jan reads as next month.getRelativeDayResulttakes a caller-suppliedweekdayFormatterfor the "Last/Next [Weekday]" label so the core staysintl-free and never touches app locale state — the formatter is invoked at most once and only for weekday buckets (a throwing formatter propagates rather than being swallowed). The four unreachableThisWeek/LastWeek/NextWeek/ThisMonthvalues from the source app were dropped at inclusion (the classifier never emitted them). Pure Dart, no Flutter, no external packages. -
num.formatNumber({format, locale})(num_intl_format_extensions.dart) — a newNumIntlFormatExtensionsthat renders anynumwith CLDR-accurate, locale-aware grouping/decimal separators by delegating tointl'sNumberFormat(format, locale).format(this).formatis an arbitrary ICU number pattern (default'#,##0'; e.g.'#,##0.00'two decimals,'##,##,##0'Indian 2-2-3 grouping,'#,##0;(#,##0)'parenthesized negatives,'#,##0%'which scales the receiver by 100,'00000'zero-pad).localeis a BCP-47 string ('de_DE'produces'1.234','es_ES'produces'1.234.567','fr_FR'groups with U+202F a NARROW no-break space, not U+00A0); when null it follows the process-globalIntl.defaultLocale. This is the CLDR-accurate counterpart to the dependency-freeformatNumberLocalefree function (which inserts hand-supplied separator strings with no locale data and cannot express non-3-digit grouping or decimal-comma locales) — both are kept, trading theintldependency against accuracy. Rounding is half-up (2.5produces'3');double.infinity/negativeInfinity/nanrender the locale symbols (infinity, minus-infinity, NaN),-0.0is preserved as'-0', and an unknown/emptylocalethrowsArgumentErrorrather than silently falling back. Opt-in module pulling the already-presentintldependency, mirroringdate_time_intl_display_extensions.dart. -
DayInMonthCalculations(month_weekday_named_extensions.dart) — named, readability-focused wrappers over the existingMonthWeekdayUtilscore for the exact phrasings DST and public-holiday rule tables are written in:firstMonday/secondMonday/thirdMonday,firstThursday/firstFriday/firstSaturday/firstSunday,secondFriday/secondSaturday/secondSunday,thirdSaturday/thirdSunday, pluslastMonday/lastThursday/lastFriday/lastSaturday/lastSunday. Every 1st/2nd/3rd/4th andlast*occurrence is non-null (a calendar invariant —thirdSaturday/thirdSundaycorrected from the over-cautious nullable original to matchthirdMonday); an out-of-rangemonththrows a namedStateErrorrather than returning a plausible-but-wrong neighboring-month date, and the genuinely-absent-able 5th-occurrence query stays onMonthWeekdayUtils.nthWeekdayOfMonth. AddsdaysInFebruary(year)(leap-aware via the day-0-of-March trick, correct for ÷4/÷100/÷400, year 0, and negative years), plusfirstDayOfMonth(year, month)andlastDay(year, month)month-boundary helpers (the latter handles the December month-13 roll-over). All results are local midnightDateTime. Pure Dart, no Flutter, no external packages. -
RelativeTimeUtils(date_time_relative_predicate_extensions.dart) —DateTimeextension with four net-new calendar-day predicates plus a descriptive relative-time formatter.isTomorrow/isYesterdaycompare date-only viaisSameDateOnly(time-of-day irrelevant, so 23:59 vs 00:01 of the adjacent day still matches);isOlderThanToday/isOlderThanYesterdayuse exclusive start-of-day instant boundaries viaisBefore(the exact midnight returnsfalse, one microsecond earliertrue). Each takes an optionalnowfor deterministic tests. The two families intentionally diverge on UTC-vs-local (field comparison vs instant comparison) and are documented as not-DST-safe across a transition (the fixed 24h add/subtract).relativeTime({now, isDescriptive, isDescriptiveTimeSuffix, roundUp})returns verbose ("a moment ago","about an hour from now","23 years ago") or terse ("now","~1h","2y") phrasing, with an optionalago/from nowsuffix and floor-vs-round numeric units. Year-level spans use date-based calendar arithmetic (subtract years, back off one if the anniversary has not yet passed) instead ofdays / 365.25, fixing the off-by-one near anniversary boundaries (a2000-12-31birthday reads23 yearson2024-06-15, not24). Pure Dart; depends only onisSameDateOnlyandString.pluralize. The existing top-levelrelativeTimeStringis untouched — this is a distinct, additive API with a different output dialect. -
Map<String, V>.sortMap()(map_initials_sort_extensions.dart) —InitialsSortingUtilsextension returning aSplayTreeMap<String, V>ordered "letters before numbers" (from SPEC-sort-utils.md): letter-initial keys sort alphabetically and come first, number-initial keys follow with PURE integers in numeric order so'10'sorts after'2'(not before, the lexicographic trap). Letter detection is ASCII-only ([a-zA-Z]), so accented/non-Latin/emoji/symbol/empty initials fall to aString.compareTolexicographic fallback — documented and tested. Fixes a latent correctness bug in the source: two distinct pure-int keys of equal value ('007'vs'7') madeint.compareToreturn0, which would silently DROP one entry from theSplayTreeMap; a lexicographic tie-break now retains every entry. Signed ('-5') andint-overflowing ('99999999999999999999') keys correctly fall through to lexicographic without throwing. Pure Dart (dart:collectiononly), no Flutter or external packages. -
sortNullableStringListInPlace(List<String?>)(list_nullable_string_sort_extensions.dart) — top-level helper that sorts aList<String?>in place, case-insensitively, withnulls grouped to the front, returningtrueon success (thefalsebranch is defensive — the comparison cannot throw forString?). Delegates to the library's existingcompareStringNullable(single source of truth for null-aware string ordering) rather than re-implementing the lowercase/null-coalescing, and wraps the comparison so callers avoid the extension-on-List<String?>lint at each call site. Comparison is lowercased UTF-16 code-unit order, NOT locale-aware:'é'(U+00E9) sorts after'z', andnull/''both collate as the empty string. Pure Dart, no Flutter or external packages. -
compareAges(DateTime? a, DateTime? b, {bool ascending = true})(date_time_compare_age_extensions.dart) — nulls-LAST nullableDateTimecomparator with a direction flag, the counterpart tocompareDateTimeNullable(which placesnullFIRST and has no direction option). Twonulls are equal (0); a singlenullsorts LAST in BOTH directions because the null branches return1/-1BEFORE theascendingmultiplier is applied (a regression that reordered them would float nulls to the top — pinned by tests). Non-null values compare by absolute instant (DateTime.compareTo), so UTC-vs-local of the same moment is equal, DST transitions and calendar boundaries are irrelevant to ordering, and a one-microsecond difference is not truncated. Pure Dart, no Flutter or external packages. -
MaterialShade/MaterialShadeName/MaterialShadeLevels(color/material_shade.dart) — Flutter-scoped type-safe model of the tenMaterialColorintensities (50–900).valuegives the swatch index integer (Colors.blue[shade.value]),onShadereturns the contrast-correct foreground (black on the50–400band, white on500–900) per Material accessibility convention so callers never recompute luminance, anddisplayName/displayNameAnnotatedgive UI labels ("Shade 500", with(Lightest)/(Middle)/(Darkest)on the band endpoints, plain ASCII space so persisted/compared labels stay stable).MaterialShadeLevelsexposes the canonicallightShades/darkShades/ combinedshadesconst lists plus a seededrandomShade({bool? isLightBackground, int? seed})that draws from the high-contrast band for the given background —isLightBackground: truedeliberately yields a DARK shade for a light background. The picker reuses the library ownIterable.randomElement(the app-internalRandomList.randomItemdependency was dropped). -
ComputeStreamTransformer<TInput, TOutput>(async/compute_stream_transformer.dart) — genericStreamTransformerBasethat runs each incoming event through Flutter'scompute()(a one-shot background isolate) and emits the result, keeping CPU-bound per-event work (model mapping, parsing, serialization, byte decoding) off the UI thread. A thin, type-parametric wrapper overstream.asyncMap((d) => compute(fn, d)):asyncMapawaits each computation before pulling the next event, so output order always equals input order even when a later payload computes faster.computeFunctionmust be a top-level/static function (acomputerequirement — capturing closures cannot be sent to an isolate) and its payload must be isolate-sendable. The optionalonErrorrecovers a compute failure into a fallback value (one fallback per failing event, no collapsing) instead of erroring the stream; a SOURCE-stream error is forwarded untouched because it is not a compute failure, and a throwingonErrorsurfaces its error rather than swallowing it. On webcompute()runs inline (no real isolate) but still produces correct results. Flutter-typed (needspackage:flutter/foundation.dart); the app-specific contact-conversion specializations from the source were dropped as proprietary. -
String.toColor/Color.toHex/Color.darken/Color.lighten/Color.readableOn(flutter/color_extensions.dart) -- FlutterColor<-> hex-string conversion plus HSL lightness adjustment and a WCAG-contrast convergence helper (from SPEC-color-utils.md).String.toColor()parses a 6-digitRRGGBB(forced opaque) or 8-digitAARRGGBBhex string --#optional, case-insensitive, whitespace-trimmed -- returningnullfor empty/wrong-length/non-hex input (a0xprefix, leading sign, 3-digit shorthand, full-width or Arabic-Indic digits all yieldnull; embedded#is stripped everywhere).Color.toHex({includeAlpha})formats as uppercase, zero-padded, fixed-width#AARRGGBB/#RRGGBB, clamping wide-gamut channels above1.0so the width never breaks.darken/lightenadjust HSL lightness preserving hue/saturation/alpha and return the color unchanged for out-of-range,NaN, or infinite amounts (lenient, no-throw contract).readableOn(background, {minRatio = 4.5, step = 0.04, maxSteps = 16})darkens (light bg) or lightens (dark bg) the foreground until it clears the WCAG target, capped bymaxStepsso an unreachable pair (mid-gray on mid-gray, identical fg/bg,step == 0) returns best-effort instead of spinning. Flutter-typed; kept in its ownlib/flutter/file so the pure-Dartniche/color_utils.dartint-channel math stays Flutter-free. -
TextDirectionParseUtils.tryParse+TextWritingDirectionenum (string/text_direction_parse_utils.dart) — pure-Dart parser for the universal CSS/HTML/Unicodeltr/rtldirection tokens, returning a package-localenum TextWritingDirection { ltr, rtl }(from SPEC-string-text-direction.md). The Flutter-typedTextDirectionform from the source app was deliberately NOT ported — returningdart:ui'sTextDirectionfor a one-line wrapper would pull Flutter into this otherwise Flutter-free package; callers map to the framework type at the UI boundary.tryParseis case-insensitive and strips only LEADING/TRAILING whitespace viaString.trim()— which also strips Unicode whitespace (U+00A0 NBSP, thin space, ideographic space) but NOT zero-width chars (U+200B, U+FEFF BOM) or the direction marks themselves (LRM U+200E, RLM U+200F), all of which therefore yieldnull. No substring or partial matching ('ltrx','l t r','ltr;'→ null) and no Unicode normalization/folding (full-width'ltr', accented'ĺtr', emoji → null). ASCII-only lowercasing makes the result locale-independent (no Turkish-I pitfall). Total function: returnsnull(never throws) for null, empty, whitespace-only, numeric strings, control characters, and arbitrarily long junk. Pure Dart, no Flutter, no external packages. -
List<String>.joinWithFinal/anyContains/removeTrimmedEmpty/firstNotEqualTo/toLowerCase/toUpperCase, plusList<String?>.toLowerCase/toUpperCase/removeNullsAndTrimmedEmpty(list/list_string_extensions.dart) — seven members added to the existingListStringExtensionsplus a newNullableListStringExtensions on List<String?>(from SPEC-string-list-helpers.md).joinWithFinal({separator, finalSeparator})joins a list into a British-style sentence with a distinct final connector (['a','b','c']->'a, b and c') — distinct fromjoinDisplayList's Oxford-comma form: it adds no comma before the connector and does no trim/dedupe, so a blank entry survives (['a','','c']->'a, and c'); returnsnullfor empty and the sole item for length 1.anyContains(check, {caseSensitive})is true when any element containscheckas a substring (null/emptycheckor empty list ->false; case-insensitive lowercases both sides once).removeTrimmedEmpty({trim})drops entries empty after trimming and returnsnull(never[]) so a caller distinguishes "no items" from a result; withtrim: falseonly literally empty strings are dropped (a' 'survives).firstNotEqualTo(value)returns the first element not equal tovalue(case-sensitive), or the first element whenvalueis null, elsenull.toLowerCase/toUpperCaseare invariant-culture element-wise mappings (Turkish'i'->'I', German'ß'->'SS', emoji round-trip unchanged). The nullable variants drop nulls via core-DartnonNullsfirst. Pure Dart; reusespackage:collection(firstOrNull/firstWhereOrNull) and the library's ownString.nullIfEmpty(trimFirst:)/List.nullIfEmpty(). -
ColorUtils(flutter/material_color_utils.dart) — three Flutter Material palette helpers with no app-domain knowledge (from SPEC-color-material.md).materialColorsis the canonical ordered, duplicate-free, immutableconstlist of the 19 primaryMaterialColorswatches (Colors.red…Colors.blueGrey) for indexing a fixed palette (charts, avatars, tags, deterministic per-index colors).getWhiteContrastColor(int)maps ANY int — negatives, values past 99, andintmin/max — deterministically to one of 100 fully-opaque colors biased to contrast against white, normalizing via((n % 100) + 100) % 100so the0–9palette indices stay in range on the VM and on web (JS-double ints) alike, then alpha-blending a tens-digit primary over a ones-digit secondary; every result is alpha1.0and clears a measured WCAG contrast floor against white (lightest blend ≈1.22).getColor(MaterialShade, MaterialColor)is a typed, exhaustive-switch swatch accessor replacing the stringlycolor[500]!. Reuses the sharedMaterialShadefromlib/color/material_shade.dartrather than redefining it. Flutter-typed (needsColor/MaterialColor); no external packages. -
HebrewDateConverter(datetime/hebrew_date_converter.dart) — net-new Gregorian→Hebrew (Jewish) lunisolar calendar converter and formatter (from SPEC-datetime-hebrew-converter.md), the library's first non-Gregorian calendar system. Implements the fixed arithmetic Hebrew calendar from "Calendrical Calculations" (Reingold & Dershowitz) via a Julian-Day-Number bridge: deterministic, offline, nointl, no I/O.fromGregorian(DateTime)returns a plain({int year, int month, int day})record (Hebrew year 57xx, month 1–13 in display order, day 1–30);isHebrewLeapYear/monthsInHebrewYear(12 or 13) /daysInHebrewYear(353–355 regular, 383–385 leap) /daysInHebrewMonth(29 or 30, with variable-length Cheshvan/Kislev and the four Rosh-Hashanah postponement rules) expose the calendar arithmetic.getMonthName(month, year, {useHebrew})resolves the leap-year Adar I / Adar II split (and plain Adar in a regular year) in English transliteration or Hebrew script;formatDayHebrew/formatYearHebrewrender gematria numerals (with the 15→ט״ו / 16→ט״ז substitutions that avoid spelling a divine name, and the thousands digit elided for years);format/formatDayMonthcompose the full strings ('1 Tishrei 5785'or'א׳ תִּשְׁרֵי תשפ״ה'). Civil-date mapping by design: only the input's year/month/day are read — time-of-day, UTC/local flag, and sunset are ignored, so an eveningDateTimeis NOT advanced to the next Hebrew day.abstract finalnamespace, all static; pure Dart, onlypackage:meta(@useResult).
Internal #
Tests
- Full
String.removeEndNullablecoverage (string_manipulation_extensions_test.dart) implementing the sample cases and every bulletproofing gap from SPEC-string-misc-helpers.md: the null/empty-find no-op branches; the empty-receiver null-vs-empty split across {null, empty, non-empty} find; whole-string match to'(not null); suffix-longer-than-receiver and find-contains-receiver-plus-more no-match; single trailing occurrence of a repeated suffix; case-sensitivity; multi-byte accented-letter and surrogate-pair emoji suffixes (asserting no lone surrogate remains); a bare combining-mark strip documenting UTF-16 (non-grapheme) matching; and ASCII + non-breaking-space whitespace suffixes. - Code-point guard coverage for the
StringExtensionstypographic constants (string_special_chars_test.dart) implementing the sample value-assertion tests and every bulletproofing gap from SPEC-string-special-chars.md: exact code point per constant (smart quotes, non-breaking space/hyphen, Unicode/soft hyphen, zero-width space, Hangul-fillerblank, ellipsis, double chevron, apostrophe, bullet); single-rune guarantee for every glyph (plus an explicit LF-not-CRLF check onnewLine); UTF-8 encode/decode round-trip for all 18 members (guarding a re-encode flattening a smart quote to ASCII or losing the zero-width space); distinctness (nonBreakingSpace!= regular space,zeroWidthnon-empty,blanksurvivingtrim()); alias integrity (dot == bullet,lineBreak == newLine,apostrophe == accentedQuoteClosingboth U+2019);dotJoinerexact space+bullet+space shape; and const-evaluability proven by aconstlist fixture plus thecommonWordEndingsconst-list embedding. No source change — the constants already ship instring_extensions.dart. - Full coverage for the Flutter
Colorextensions (color_to_color_test.dart, color_to_hex_test.dart, color_light_test.dart, color_readable_test.dart) implementing the sample cases and every bulletproofing gap from SPEC-color-utils.md:toColorwhitespace/tab/newline/non-breaking-space, internal whitespace, multiple/embedded#,0x-prefix, leading sign, full-width and Arabic-Indic digits, 3-digit shorthand, wrong-length, all-zero/all-F, and null-safe call sites;toHexzero-padding, half-channel and 0.5 rounding boundaries, wide-gamut>1.0clamp, uppercase and fixed-width assertions, and full round-trips;darken/lightenNaN/+/-infinity/out-of-range no-op, epsilon near-no-op, pure black/white floors, grayscale no-NaN, transparent-alpha preservation, and the clamp-breaks-true-inverse boundary;readableOnunreachable best-effort (minRatio21, identical fg/bg), trivially-satisfiedminRatio <= 1,maxSteps0/negative,step0/NaN/negative termination, the 0.45 luminance split direction, and foreground-alpha preservation. - Full coverage for
ComputeStreamTransformer(compute_stream_transformer_test.dart) implementing every sample case plus every item in the SPEC-stream-compute-transformer.md bulletproofing list: in-order mapping, single event, empty source, order preservation under varied latency, nullTInput/TOutputround-trip, rethrow-on-error withoutonError(asserting pre-error values still emit),onErrorfallback (including when the FIRST event throws and for consecutive errors with one fallback each), a throwingonErrorsurfacing on the stream, a 100k-element large payload, Unicode/non-breaking-space/ellipsis/emoji string integrity, numeric extremes (0, negative,±Infinity,NaNviaisNaN,double.maxFinite,intnear 2^53), source-stream error passing through untouched despiteonError, broadcast-source no-replay behavior, cancellation mid-stream emitting nothing further, andonDonefiring after an error. - Hardened
MapExtensions.countItemscoverage (map_extensions_test.dart) with the bulletproofing edge cases from SPEC-map-count-items.md: all-empty values, single key/element, order-independence (empty value first vs last),Setpost-dedup count, lazy generated/mapped iterables, a1 << 20huge value and 1000-key sums (64-bit no-overflow), enum and custom-object keys (with equal-key collapse), Unicode/emoji and content-irrelevant elements, nullable elements counting toward length, fold-associativity (one-huge vs many-small), and an immutability snapshot assertion. - Full coverage for
DayInMonthCalculations(month_weekday_named_extensions_test.dart) implementing every case in SPEC-datetime-day-in-month.md: real US/EU/GB/Egypt DST anchor dates;daysInFebruaryacross standard/common/century-non-leap/century-leap/year-0/negative years;lastDayfor every 31-/30-day month, leap/common February, and the December month-13 roll-over; the 5th-occurrence present-vs-absent matrix for all seven weekdays; a non-null property test asserting 1st–4th exist for all weekdays across all 12 months of several years;StateErroron out-of-range months; local-midnight (isUtc == false, time-of-day zero) assertions across a DST fold; and far-future/far-past extremes (year 9999 and year 1). - Full coverage for
SimpleRelativeDay(simple_relative_day_utils_test.dart) implementing every case from SPEC-datetime-simple-relative-day.md plus its bulletproofing gaps: every exact-bucket boundary on both sides (±2/±3, ±6/±7, ±13/±14); the null-window vsmonthDiffinteraction (same-month +14..+20 → null, next-month +14 → nextMonth, large day-delta still nextMonth, ±2 months → null, Dec→Jan and Jan→Dec cross-year rollovers); leap Feb 29 in both directions, Jan 31→Mar 1 (monthDiff 2 → null), Mar 31→Feb 28; time-of-day dropped at midnight and one-microsecond boundaries; DST spring-forward and same-kind UTC inputs; Dart DateTime extremes (year 1 and 275760-09-13, no(year*12)overflow); default-nownon-throwing; a ±400-day sweep asserting only supported buckets are ever returned; and the weekday-formatter contract (verbatim forwarding, never invoked for exact/month buckets, null when absent, throwing-formatter propagation). - Full coverage for
NumIntlFormatExtensions.formatNumber(num_intl_format_extensions_test.dart) implementing every case in SPEC-num-locale-format.md plus its bulletproofing gaps: default/explicit en_US grouping; de_DE/es_ES dot grouping; the fr_FR U+202F narrow no-break group separator (built from the exact code point, never a literal space); de_DE decimal comma; en_IN 2-2-3 grouping; Arabic Western-digit grouping;ArgumentErrorfor unknown ('xx_YY') and empty ('') locales; pattern overrides (two-decimal, empty-string no-grouping,'00000'zero-pad, literal' kg'text,'#,##0%'×100 scaling); zero/small/grouping-boundary values (999/1000/99999); negatives (sign placement, parenthesized-negative, preserved-0.0); half-up rounding (1234.567/1234.565and2.5/3.5); int-vs-double receiver parity; extremes (9223372036854775807,double.maxFinitewith no exponent leak,0.0001at four decimals,±infinityandNaNlocale symbols viaString.fromCharCode(0x221E)); andIntl.defaultLocaledeterminism with per-test setUp/tearDown reset. - Full coverage for
ColorUtils(material_color_utils_test.dart) implementing the sample cases plus every bulletproofing gap from SPEC-color-material.md:materialColors19-in-order/no-duplicates/const-immutability (UnsupportedErroron.add);getColorexact swatch entry per shade, shade500 == base color, the full swatch×shade matrix assertingswatch[shade.value], and a partial customMaterialColorthrowingTypeErroron a missing level;getWhiteContrastColordeterminism, negative→non-negative-modulo equivalence (-1≡99), modulo-100 wrap (100≡0,142≡42), full opacity for all0..99,intmin/max no-throw + opacity, the exact red-on-red blend for0, boundary inputs9/10/90/99opacity and9≠10distinctness, and a WCAGcontrastRatio-against-white floor (≥1.15) over all0..99cross-checked via the package's ownniche/color_utils.dart. - Full coverage for the
List<String>/List<String?>string helpers (list_string_extensions_test.dart) implementing every sample case and every bulletproofing gap from SPEC-string-list-helpers.md:joinWithFinalempty/single/two/three-item connectors, no-Oxford-comma, custom/empty/multi-char separators, blank-entry-survives divergence, separator-bearing element not re-split, 10k-element no-stack join, and non-mutation;anyContainscase-sensitive/insensitive substring matching, null/emptycheck, empty list, whole-element and over-longcheck, accented-Unicode insensitive match, zero-width-space needle, and 10k-element short-circuit;removeTrimmedEmptyall-blank->null, trim-survivors,trim:falsekeeps whitespace-only/drops only literal empty, single empty/space, the non-breaking-space-dropped vs zero-width-space-survives boundary, and non-mutation;removeNullsAndTrimmedEmptythe ported all-null/null-removal/trim cases plus single-null, mixed-null,trim:falsesurvivor, and non-mutation;firstNotEqualTonull-value, empty list, differing element, all-equal, case-sensitivity, empty-string value, and single-equal->null; andtoLowerCase/toUpperCaseelement-wise mapping, nullable null-dropping, empty/all-null lists, German eszett length change, invariant-culture (not Turkish) casing, accented round-trip, emoji round-trip, and non-mutation. - Lint-cleanup refactors with no coverage change: the
unicodeClassRangesone-entry-per-enum assertion (unicode_class_utils_test.dart) useshasLength(1)instead of.lengthcompared to the literal1(clearer failure output, satisfiesavoid_misused_test_matchers); the lighten suite'sColorLightExtensions(color_light_test.dart) hoists the sharedoriginalbaseline into asetUpso each test recomputes it without leaking state.
Historical Archive #
Entries for older versions live in CHANGELOG_HISTORY.md.
....
-+shdmNMMMMNmdhs+-
-odMMMNyo/-..``.++:+o+/-
/dMMMMMM/ `````
dMMMMMMMMNdhhhdddmmmNmmddhs+-
/MMMMMMMMMMMMMMMMMMMMMMMMMMMMMNh/
. :sdmNNNNMMMMMNNNMMMMMMMMMMMMMMMMm+
o ..~~~::~+==+~:/+sdNMMMMMMMMMMMo
m .+NMMMMMMMMMN
m+ :MMMMMMMMMm
/N: :MMMMMMMMM/
oNs. +NMMMMMMMMo
:dNy/. ./smMMMMMMMMm:
/dMNmhyso+++oosydNNMMMMMMMMMd/
.odMMMMMMMMMMMMMMMMMMMMdo-
-+shdNNMMMMNNdhs+-
``
Made by Saropa. All rights reserved.
Learn more at https://saropa.com, or mailto://dev.tools@saropa.com