cutils 0.6.3
cutils: ^0.6.3 copied to clipboard
Flutter utility kit: money math, bytes, datetime, debounce, regex, crypto, storage, network and a log collector with optional viewer UI.
CHANGELOG #
Release notes for cutils. A short Chinese summary (中文) closes each version section; the English text is the record of note.
0.6.3 Static analysis fix: putObjectList awaits in try #
-
fix:
SpUtils.putObjectListnow awaitsSharedPreferences.setStringListinside itstryblock, matchingSpUtils._put's existing pattern. Resolves theunawaited_future_in_tryWARNING pub.dev's analyzer reported on 0.6.2 (the only WARNING in that release's static-analysis section). Failure semantics are unchanged: errors are still caught, logged (key only - values are never logged) and mapped tofalse.中文:
putObjectList在 try 内真正 await setStringList(与 _put 同口径),消 pub.dev 分析器 unawaited-in-try WARNING;失败语义不变(捕获、仅记 key、返回 false)。
0.6.2 Packaging fix: exclude build cache and internal dist-face #
-
chore:
.pubignorenow excludesbuild/(flutter test cache dill, 55 MB uncompressed - the bulk of the 17 MB packages 0.6.0/0.6.1 shipped),checklist.md(with its.crules-basetwin) and进阶/- internal engineering docs were previously published into the public package (publish honours.pubignoreonly, not.gitignore). No code changes.中文:
.pubignore新增排除 build/ 测试缓存与内部分发面文档,包体 17MB→246KB;无代码变化。
0.6.1 pana fix batch (satellite branch / await semantics / dependency lower bounds) #
-
fix:
NetUtilsexhaustive switch now handlesConnectivityResult.satellite("卫星网络" / satellite network). The enum member was added in connectivity_plus_platform_interface 2.1.0; missing it failed pana and downstream analyze with non_exhaustive_switch_statement (observed on the pub.dev 0.6.0 score). pubspec now declaresconnectivity_plus_platform_interface: ^2.1.0explicitly to pin the transitive lower bound - a downgrade resolution to 2.0.1 was reproduced to break compilation without the declaration. -
fix:
SpUtils._putawaits the write inside try. Behavior change: write failures are caught and returnfalse; previously the un-awaited future propagated the error to the caller. -
fix:
FileUtils.zipFilesawaitsZipFileEncoder.close(). Behavior change: since archive 3.6 close() is async finalization (the zip is complete only after the central directory is written); previously it returned without waiting. Requires the archive lower bound bump below. -
chore: archive constraint
^3.3.7->^3.6.1(close() returnsFuture<void>from the 3.6 line; no in-constraint compatible call pattern exists - assigning a void result to dynamic / FutureOr both fail use_of_void, verified by downgrade analysis).中文:补 satellite 穷尽分支并显式锁 platform_interface ^2.1.0 下限;
_put/zipFiles 改为真正 await(行为变化:失败返回 false 而非抛出,zip 收尾完才返回);archive 下限收紧 ^3.6.1。
0.6.0 TimeUtils absorbs (timespan / format parsing / AM-PM / zodiac) + DebounceUtils + review batch 1 #
-
feat:
DebounceUtilsthrottle & debounce utility (top-level singletondebounceUtil; instances may create scoped instances).canRunis a front-edge throttle gate: first call passes and locks a cooldown window, same key rejected inside the window, default 1000ms (aligned with Blankj DebouncingUtils).debounceis a trailing-edge debounce (default 500ms).cancelclears one key,clearclears all (test isolation). Timer-map implementation, zero third-party deps (dart:async only). Empty key (after trim) or negative duration throws ArgumentError; keys share one global namespace - prefix keys with a scenario name. Design & review:docs/superpowers/specs/2026-11-25-debounce-utils-design.md. -
feat:
DateTimeUtils.formatFitTimeSpan- duration breakdown into day/hour/minute/second/millisecond with precision truncation and clamping, zero-unit skipping, negative prefix, custom units; throws ArgumentError when units length is not 5. -
feat:
DateTimeUtils.getDateTime/getDateMsByTimeStraccept an optionalformat- hand-written parsing with the same token set asformatDate(exact literal matching, explicit range validation preventing silent DateTime normalization,yyanchored to 2000+, missing fields default to 1970). No-argument behavior unchanged. -
feat:
DateTimeUtils.isAm/isPm. -
feat:
DateTimeUtils.getChineseZodiac(ByYear)/getZodiac(ByMonthDay)- approximated by Gregorian year/month-day (no solar-term boundary). -
feat:
RegexUtils.isMobileExactoptionalnewSegments- dynamic validation against caller-provided new carrier segments when the static pattern misses (11-digit numeric precondition kept). -
feat:
RegexUtils.getMatches- all matches of a pattern in the input. -
fix:
LogStoragefailure-path hardening - storage and rotation failures log viadart:developerinstead ofdebugPrint(cuts the loop where a failed store is recycled by the interceptor and fails again); a broken sink is nulled before flush/close during rotation; a single old-file delete failure does not block rotation; new-file bookkeeping is guaranteed. -
fix:
getAllLogs/exportLogsduplicated results between memory and file -LogEntrygains aseqcounter (assigned at enqueue on a microsecond base to avoid cross-session collisions); merged results dedupe by seq; legacy on-disk entries without seq are kept as-is. -
fix:
ExceptionInterceptor'sPlatformDispatcher.onErrorhandler forwards to a host-registered handler first and returns its verdict (previously always returned true, swallowing the host decision); behavior unchanged when no handler is registered. -
fix:
LogCollector.initializefailure rollback - if storage or interceptor startup throws, it stops started interceptors, removes outputs and interceptors added this round, restores config/storage and rethrows; no half-initialized state (retries no longer double-register). -
fix:
DateTimeUtils.getBusinessDateconverts UTC inputs to the local timezone before comparing against the day-cut line (the cut line is local wall-clock semantics; unchanged when cutoffTime is absent). -
fix:
UuidUtils.generateV5cache key is nownamespace|name(previously cached by name only - same name under different namespaces returned the wrong UUID); cache caps at 1024 and evicts the oldest. -
fix:
KeyboardUtils.analysisKeyEventnumpad handling - numpad0-9 and operator keys carry keyIds in the high region (>255) and were filtered to an empty string; the high-region branch now attempts numpad resolution (character -> physical key map) before giving up.中文:DebounceUtils 防抖节流;DateTimeUtils 四件(时长拆解/format 解析/上下午/生肖星座);RegexUtils 新号段与 getMatches;log_collector 六项失败路径加固;getBusinessDate UTC 折算、generateV5 缓存串台修复、小键盘识别修复。
0.5.0 Log viewer (floating ball + panel) #
-
feat: log viewer (floating ball + panel) - new
view/family andRouteLogObserver, exported vialog_collector_export.dartinto the top-level barrel (new public symbols: attachViewer / LogViewerController / loadViewerLogs / ViewerBridgeOutput / LogViewerPanel / LogViewerPanelState / LogViewerEntryTile / LogViewerTheme / RouteLogObserver). -
feat:
LogCollectorHelper.network()unified network logging (level derived from statusCode;extraalways carries the same six keys). -
feat:
LogSourceenum gainsroute(downstream code not calling the new API is unaffected). -
feat:
FileLogOutputfully implemented (the constructor used to throwUnimplementedError; now a working file output, signature unchanged:filePath/maxFileSize/maxFileCount) - line-by-line append writing (entry.toString()text lines, not a parsed format), lazyIOSinkopen (parent directories auto-created), in-memory byte tracking, rotation on exceedingmaxFileSize(_yyyy-MM-dd_HHMMsstimestamp suffix, no dangling dot for extension-less paths), oldest-file deletion beyondmaxFileCountby exact base-name prefix match, dispose safeguards, and errors reported viadeveloper.log(not debugPrint, avoiding a loop with the default DebugPrintInterceptor). Two caveats: on web the wholelog_output.dart(incl. ConsoleLogOutput / BatchLogOutput) does not compile due todart:io; no periodic flush (flush happens on rotation and dispose only - abnormal process death may lose the tail buffer).中文:日志查看器(悬浮球+面板)及新公开符号面;网络打点 helper;LogSource 增 route;FileLogOutput 占位实装(逐行追加/惰性 sink/轮转归档);注意 web 端 log_output.dart 不可编译、无周期 flush。
0.4.0 saas_pos absorbs (version compare / LAN IPv4 / masking family / business day / SP self-heal / SHA & HMAC) #
Six capabilities absorbed from saas_pos_smart_edition (POS client) by "absorb and rewrite" - no file copies: everything re-written on this repo's baseline, silent error swallowing replaced with explicit throws, private benefits generalized into utilities.
-
New
lib/system/version_utils.dart:VersionUtils.compare/isNewer- three-way dotted version comparison (strips v/V prefix, per-segment
numeric order, trailing zeros equal so
1.0 == 1, missing segments sort lower). Empty input throws ArgumentError (previously silently returned false). Pre-release labels are not parsed (1.0.0-betaequals1.0.0).
- three-way dotted version comparison (strips v/V prefix, per-segment
numeric order, trailing zeros equal so
-
New
lib/net/lan_utils.dart:LanUtils.getPreferredLanIpv4- preferred LAN IPv4 (192.168 > 10 > 172.16-31 > others; loopback/APIPA excluded, virtual adapters de-prioritized but not excluded); returns null without network, never throws. Unavailable on web (dart:io). -
StringExtmasking family upgraded (lib/ext/string_ext.dart):maskMobiletiered masking (>=10 digits: first 3 last 4 / 7-9: first 2 last 2 / 4-6: first 1 last 1 / <4: unchanged; country-code prefix kept and re-joined with a space; tier decided by digit count). Behavior change: the old implementation only worked for exactly 11 digits and returned anything else untouched (a privacy leak). Non-11-digit inputs are now tier-masked, and the mask body is rebuilt from digits only - non-digit characters (e.g.-separators) are no longer preserved, so 11-digit inputs containing noise change output too.- New
maskMobileOr/maskMiddle/maskMiddleOr(generic head/tail masking; negative arguments throw ArgumentError).
-
DateTimeUtils.getBusinessDate(lib/datetime/date_utils.dart): business-day attribution - attributes a checkout moment to its business-day anchor via an"HH:mm:ss"day-cut line (the returned anchor is the cut moment, not midnight of the date); returns the input unchanged without a cut line; an invalid cut line throws ArgumentError (previously swallowed). -
Windows SP file self-heal (
lib/storage/sp_util.dart+sp_backup_io.dart/sp_backup_none.dart): after a successfulSpUtils.init()theshared_preferences.jsonis backed up; on init failure the backup is validated (a legal JSON object) before being restored (validate-then-replace, keep the scene on failure); rethrow semantics unchanged; backup/restore IO failures only log. Platform surface change: sp_util now conditionally importsdart:io(web uses a no-op stub - backup/restore entries are no-ops on web); no-op on non-Windows platforms. The file layout is coupled to shared_preferences_windows 2.4.1 defaults. -
CryptoUtilsnew digests / signatures (lib/crypto/crypto_utils.dart):encodeSha256(lowercase hex),encodeHmacSha1/encodeHmacSha256(utf8 input, lowercase hex by default,base64: truefor standard base64).中文:六件自 saas_pos 吸收重写:版本比较、首选局域网 IPv4、脱敏族升级(maskMobile 分级脱敏,行为变化)、营业日归属、Windows SP 自愈(条件 import 引入 dart:io)、SHA256/HMAC。
0.3.0 YCFlutterUtils absorbs (byte utils / yuan-to-cents / validators) #
Three capabilities absorbed from YCFlutterUtils by "absorb and rewrite" - the source is pre-null-safety code with defects; everything was rewritten on this repo's baseline with fixes:
-
New
lib/byte/byte utilities module (zero third-party deps, onlydart:typed_data/dart:convert):ByteUtils- readable string <->Uint8List(hex/dec with value validation rejecting tokens above 0xFF, no silent truncation), base64 conversion, clone/equality and window ops (slice/concat/insert/delete with bounds clamping, inputs unmodified);ByteWord/ByteDoubleWord- 16/32-bit integers split and packed per explicitEndian. -
MoneyUtils.changeY2F(String) -> intyuan-to-cents: symmetric withchangeF2Y; Decimal end-to-end without going throughdouble(no precision loss beyond the 2^53 boundary); unparseable input, non-integral cents, or results beyond the platform int range throw ArgumentError. -
RegexUtils15 new validators with matchingREGEX_*constants: file-type family of 11 (isImage / isAudio / isVideo / isTxt / isDoc / isExcel / isPpt / isApk / isPdf / isHtml / isVector - extension heuristics, double-anchored with escaped separator dots, case insensitive), hash format family of 3 (isMD5 / isSHA1 / isSHA256 - format-only checks, no checksum verification; colon-separated forms supported), andisHexadecimal(bare hex string - different semantics fromisHexColor).中文:字节工具模块(可读串互转/端序拆装/窗口操作)、元转分(全程 Decimal 不经 double)、正则 15 个校验方法与配套常量(文件类型族/哈希族/十六进制)。
0.2.1 Per-entry console suppression for log_collector #
LogEntry gains a suppressConsole flag (default false, existing
behavior unchanged): flagged entries still enter the pipeline (memory +
file, visible via getLogs / export) but console-type outputs skip them on
dispatch - for low-value, high-frequency logs in release builds (keep the
archive, skip the noise).
-
The six level helpers on
LogCollectorHelper(log/debug/info/warning/error/fatal) pass the flag through an optional parameter. -
The
LogOutputbase class gains anisConsolecontract getter (defaultfalse): custom outputs writing to the console must override it to true; wrapper/delegating outputs must forwarddelegate.isConsole(ConsoleLogOutput/BatchLogOutputalready implement it correctly). -
Semantics: does not retroactively suppress original output already sent to the console by interceptors (e.g. raw debugPrint); the flag is an in-process routing hint only and is not persisted in
toJson. -
Reviewed via an independent review loop (
docs/评审-plan-log-suppress-console.md); 15 new test cases (test/log_collector/log_collector_suppress_console_test.dart).中文:LogEntry 增 suppressConsole 条目级压制(仅跳过控制台分发,档案照写);六个级别方法透传;LogOutput 增 isConsole 契约;新增 15 个测试。
0.2.0 Naming unification (breaking) #
All utility classes unified to the *Utils suffix (21/21), removing the
Util/Utils double track and two misspellings. File names and import paths
are unchanged; top-level lowercase instances (spUtil / netUtil /
eventBus / deviceInfo / packageInfoUtil / logger) unchanged; no
old-name aliases kept (pre-1.0 with no existing downstream - aliases
would only prolong the double track). Rename call sites per the table.
| Old | New |
|---|---|
UUIDUtils |
UuidUtils |
KeyBoardUtils |
KeyboardUtils |
NetUtil |
NetUtils |
TimerUtil |
TimerUtils |
SpUtil |
SpUtils |
TimelineUtil |
TimelineUtils |
DeviceInfoUtil |
DeviceInfoUtils |
EventBusUtil |
EventBusUtils |
PackageInfoUtil |
PackageInfoUtils |
Docs
-
Module headers now declare dependencies (the platform plugin surface is explicit, flagging downstream integration/stub cost) plus a
log/<->log_collector/dual-track positioning note;log_collector's dependency onpath_providervialog_storageis stated explicitly.中文:21 个工具类统一 *Utils 后缀(破坏性改名,不保留别名,按表改调用点);文件名与 import 路径不变;模块头补依赖标注。
0.1.0 Restructure and quality pass (breaking) #
Restructured from a plugin package into a pure Dart/Flutter utility library; directory structure and public API overhauled; a batch of high-severity bugs fixed. Pre-1.0 - APIs may evolve.
Restructure
- Downgraded from plugin to a plain Dart/Flutter package (removed
method_channel / platform_interface / android / ios / scaffold tests,
neutralized
example). - New top-level barrel
lib/cutils.dart- one import for all core tools:import 'package:cutils/cutils.dart';. - Directory moves:
date/+time/->datetime/;encrypt/->crypto/;sp/->storage/; dissolved theutils/grab-bag ->event/+ui/+identifier/;text/split intoui/+ext/. - Removed hardware dead code:
scanner/,system/serial_util(deferred to a separate sub-packagecutils_pos). - Cleaned dead dependencies and the pubspec plugin section; removed
dartx(one.filterusage migrated todart:corewhere; theStringExt.isNullOrEmptyconflict with its own extension is resolved).
API style (stateless tools become static classes)
The stateless utilities below moved from "instance + singleton" to static
classes; call sites change from xUtils.foo() to XUtils.foo():
NumUtils, DateTimeUtils, CryptoUtils, JsonUtils, RandomUtils,
UUIDUtils, KeyBoardUtils, RegexUtils, MoneyUtils.
Stateful singletons kept: spUtil, logCollector, eventBus, netUtil,
deviceInfo, packageInfoUtil, logger.
Renames
NumUtilsexact-arithmetic family (addDec/subtractDec/multiplyDec/divideDec/remainderand the matching*DecStringvariants) now returnsString?(a decimal string) instead ofDecimal?-Decimalis internal again and no longer appears in public signatures (downstream no longer needs thedecimalpackage directly). Failure semantics unchanged (parse failure / division by zero still return null).SpUtil.init()returnsFuture<bool>(wasFuture<SharedPreferences?>; true on success, throws on failure) - theSharedPreferencesobject is no longer exposed; usegetSp()when the raw instance is needed.moneyFormatWithUnit(StringExt/DoubleFormating) now computes viaDecimal(same strategy asformatMoney) - no precision loss near the 2^53 boundary; exotic inputs that Decimal cannot parse fall back to the old double path (behavior compatible).DateUtils->DateTimeUtils(avoiding the Flutter SDKDateUtilsname clash);EncryptUtils->CryptoUtils;printJson->logJson(with a@Deprecatedalias);putObject->putJsonable(with a@Deprecatedalias);TimerUtil.updateTotalTimebecomes a pure setter (no implicit restart), newrestart()carries the old behavior.
Semantic / behavior changes
- Regex:
REGEX_INTEGER/REGEX_FLOATand friends fully anchored ("123abc"no longer false-positives);REGEX_EMAILnon-backtracking with a 254 cap (looser and ReDoS-resistant);isURL/isIPfully anchored;isNumeric("123.")-> false;isJSONtightened to object / array only. - Numbers:
NumUtils.*Num()throws ArgumentError on non-finite input (was a silent0.0);divideDec(1, 3)no longer throws. - Money:
MoneyUtils.changeF2Y*throws ArgumentError on invalid input or overflow (was a raw FormatException); large amounts are formatted via Decimal. - Crypto:
CryptoUtils.xorBase64*encodes the raw UTF-8 bytes as base64 (the code-unit path threw on surrogate pairs);encodeMd5Fileis streaming (reading as a string corrupted binary hashes). - File:
createFileFromBase64throws a typedInvalidBase64Exception. - System:
KeyBoardUtils.closeKeyBoardno longer hides system UI (the immersive side effect is removed);NetUtil: Windows no longer hardcoded online, Bluetooth counts as online, multi-result aggregation (any non-none result = online). - Extensions:
double_ext.percentFormatmultiplies by 100;object_ext.isNullOrBlankno longer treats0as empty;int_ext.currencyFormatWithSymboldrops the space after the symbol;string_ext.formatMoneyno longer appends.0for whole yuan. - Datetime:
DateTimeUtils.nextMonthreturnsDateTime(wasint);getYesterdayis calendar-day (DST-correct);isToday/isWeekno longer treatms == 0as "no value". - JSON:
JsonUtils.encodeObjectList([])returns"[]"(was null).
Deletions (unused, zero callers)
- 14 lowercase regex constants (email / url / hexadecimal / vector / image / audio / video / txt / doc / excel / ppt / apk / pdf / html).
net/url_utils.dart(emptyUrlUtils);ext/bool_ext.then;TimelineInfo.weeks.
High-severity fixes (abridged)
-
log_collector: FlutterError recursion / no-op rotation / Timer leaks / dispose not releasing outputs / unbounded queue / init race / ConsoleLogOutput using print.
-
file_utils:
readBySinkempty returns /cleanExpiredLogusing.millisecondcausing random deletions / several un-awaited futures /deleteLogignoringsaveDays/ path traversal /getFileListanddeleteLogenumeration switched to suffix matching plus directory-link exclusion (substring matching collected*.log.bakand directories named*.log, and zipping those threw) /cleanLogexcludes directory links (an empty*.logdirectory was silently deleted) / expiry check switched from ctime to mtime. -
datetime: SSS millisecond formatting /
isTodayisUtc / countdown drift / uncanceledFuture.delayed. -
system:
winUniqueIdentifiermixing inDateTime.now/navigationBarHeightformula. -
ext: thousands-separator negatives / undisposed
TextPainter/ sp logging values into logs (PII).中文:自 plugin 重组为纯工具库(顶层 barrel、目录重组、移除硬件死代码与死依赖);无状态工具转静态类;签名变更(*Dec 族改返回 String?、init 返回 bool、若干改名);正则/数值/金额/加解密/文件/系统/扩展/日期/JSON 全面语义修复;删除零调用死代码;高危 bug 修复清单见英文段。
0.0.1 #
Initial placeholder release (plugin scaffold).
中文:初始占位版本(plugin 脚手架)。