V- Modal AI: Visual Video / Image Search - Flutter Video SDK
Dart android-sdkflutterflutter-appflutter-packageflutter-sdkflutter-videoflutter-video-editingflutter-video-playerflutter-video-sdkflutter-videosflutter-videosdkmobile-videomobile-video-editor-sdkmobile-video-sdkvideo-editingvideo-sdkvideo-searchvideo-search-enginevideo-streaming
Release Flutter SDK from 7fb167d15e1fadc765c0d14d535a64d8f70a68c0
vmodal-release-appc27899a9b346
diff --git a/.flutter-version b/.flutter-versionnew file mode 100644index 0000000..c029e71--- /dev/null+++ b/.flutter-version@@ -0,0 +1,2 @@+3.44.6+diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.ymlnew file mode 100644index 0000000..5b24386--- /dev/null+++ b/.github/workflows/publish.yml@@ -0,0 +1,82 @@+name: publish_pub_dev++on:+ push:+ tags:+ - 'v[0-9]+.[0-9]+.[0-9]+'++permissions:+ contents: read++concurrency:+ group: pub_dev_${{ github.ref }}+ cancel-in-progress: false++jobs:+ verify_tagged_source:+ runs-on: ubuntu-latest+ timeout-minutes: 40+ steps:+ - name: Checkout exact tag+ uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5+ with:+ ref: ${{ github.ref }}+ persist-credentials: false+ - name: Verify tag and source provenance+ shell: bash+ run: |+ test "$(git rev-parse HEAD)" = "${{ github.sha }}"+ version=$(sed -n 's/^version:[[:space:]]*//p' pubspec.yaml)+ test "v$version" = "${GITHUB_REF_NAME}"+ sha256sum --check SOURCE_MANIFEST.sha256+ grep -Eq '^Source-vmx-api: [0-9a-f]{40}$' RELEASE_METADATA+ - name: Install pinned Flutter+ run: bash install.sh install+ - name: Verify tagged package+ run: |+ bash test.sh regression S17+ bash build.sh package+ - name: Record verification evidence+ run: |+ mkdir -p "$RUNNER_TEMP/pub-verification"+ sha256sum SOURCE_MANIFEST.sha256 > "$RUNNER_TEMP/pub-verification/SHA256SUMS"+ bash install.sh flutter_bin > "$RUNNER_TEMP/pub-verification/flutter-path.txt"+ - name: Upload verification evidence+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02+ with:+ name: pub-verification-${{ github.sha }}+ path: ${{ runner.temp }}/pub-verification+ if-no-files-found: error++ publish_pub_dev:+ needs: verify_tagged_source+ runs-on: ubuntu-latest+ timeout-minutes: 20+ environment: pub.dev+ permissions:+ contents: read+ id-token: write+ steps:+ - name: Checkout exact tag+ uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5+ with:+ ref: ${{ github.ref }}+ persist-credentials: false+ - name: Download verification evidence+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093+ with:+ name: pub-verification-${{ github.sha }}+ path: ${{ runner.temp }}/pub-verification+ - name: Recheck immutable tagged source+ run: |+ test "$(git rev-parse HEAD)" = "${{ github.sha }}"+ version=$(sed -n 's/^version:[[:space:]]*//p' pubspec.yaml)+ test "v$version" = "${GITHUB_REF_NAME}"+ sha256sum --check SOURCE_MANIFEST.sha256+ sha256sum --check "$RUNNER_TEMP/pub-verification/SHA256SUMS"+ - name: Install pinned Flutter+ run: bash install.sh install+ - name: Publish through pub.dev OIDC+ run: |+ bash build.sh package+ "$(bash install.sh dart_bin)" pub publish --forcediff --git a/.pubignore b/.pubignorenew file mode 100644index 0000000..576aa84--- /dev/null+++ b/.pubignore@@ -0,0 +1,13 @@+.dart_tool/+.git/+.github/+.idea/+build/+coverage/+docs/dev_plan.md+docs/dev_plan_step.md+release/+tool/live_test.dart+SOURCE_MANIFEST.sha256+*.iml+diff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 0000000..d9597ee--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,7 @@+## 1.0.0++- Initial Android/iOS Flutter SDK with typed API resources.+- Bearer-only gateway authentication and request-time API-key rotation.+- Bounded streamed responses and cancelable signed uploads.+- Explicit experimental multipart upload with checkpoint reconciliation.+diff --git a/LICENSE b/LICENSEindex 261eeb9..6ecda0b 100644--- a/LICENSE+++ b/LICENSE@@ -1,201 +1,22 @@- Apache License- Version 2.0, January 2004- http://www.apache.org/licenses/+MIT License- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION+Copyright (c) 2026 V-Modal- 1. Definitions.+Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:- "License" shall mean the terms and conditions for use, reproduction,- and distribution as defined by Sections 1 through 9 of this document.+The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.- "Licensor" shall mean the copyright owner or entity authorized by- the copyright owner that is granting the License.+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.- "Legal Entity" shall mean the union of the acting entity and all- other entities that control, are controlled by, or are under common- control with that entity. For the purposes of this definition,- "control" means (i) the power, direct or indirect, to cause the- direction or management of such entity, whether by contract or- otherwise, or (ii) ownership of fifty percent (50%) or more of the- outstanding shares, or (iii) beneficial ownership of such entity.-- "You" (or "Your") shall mean an individual or Legal Entity- exercising permissions granted by this License.-- "Source" form shall mean the preferred form for making modifications,- including but not limited to software source code, documentation- source, and configuration files.-- "Object" form shall mean any form resulting from mechanical- transformation or translation of a Source form, including but- not limited to compiled object code, generated documentation,- and conversions to other media types.-- "Work" shall mean the work of authorship, whether in Source or- Object form, made available under the License, as indicated by a- copyright notice that is included in or attached to the work- (an example is provided in the Appendix below).-- "Derivative Works" shall mean any work, whether in Source or Object- form, that is based on (or derived from) the Work and for which the- editorial revisions, annotations, elaborations, or other modifications- represent, as a whole, an original work of authorship. For the purposes- of this License, Derivative Works shall not include works that remain- separable from, or merely link (or bind by name) to the interfaces of,- the Work and Derivative Works thereof.-- "Contribution" shall mean any work of authorship, including- the original version of the Work and any modifications or additions- to that Work or Derivative Works thereof, that is intentionally- submitted to Licensor for inclusion in the Work by the copyright owner- or by an individual or Legal Entity authorized to submit on behalf of- the copyright owner. For the purposes of this definition, "submitted"- means any form of electronic, verbal, or written communication sent- to the Licensor or its representatives, including but not limited to- communication on electronic mailing lists, source code control systems,- and issue tracking systems that are managed by, or on behalf of, the- Licensor for the purpose of discussing and improving the Work, but- excluding communication that is conspicuously marked or otherwise- designated in writing by the copyright owner as "Not a Contribution."-- "Contributor" shall mean Licensor and any individual or Legal Entity- on behalf of whom a Contribution has been received by Licensor and- subsequently incorporated within the Work.-- 2. Grant of Copyright License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- copyright license to reproduce, prepare Derivative Works of,- publicly display, publicly perform, sublicense, and distribute the- Work and such Derivative Works in Source or Object form.-- 3. Grant of Patent License. Subject to the terms and conditions of- this License, each Contributor hereby grants to You a perpetual,- worldwide, non-exclusive, no-charge, royalty-free, irrevocable- (except as stated in this section) patent license to make, have made,- use, offer to sell, sell, import, and otherwise transfer the Work,- where such license applies only to those patent claims licensable- by such Contributor that are necessarily infringed by their- Contribution(s) alone or by combination of their Contribution(s)- with the Work to which such Contribution(s) was submitted. If You- institute patent litigation against any entity (including a- cross-claim or counterclaim in a lawsuit) alleging that the Work- or a Contribution incorporated within the Work constitutes direct- or contributory patent infringement, then any patent licenses- granted to You under this License for that Work shall terminate- as of the date such litigation is filed.-- 4. Redistribution. You may reproduce and distribute copies of the- Work or Derivative Works thereof in any medium, with or without- modifications, and in Source or Object form, provided that You- meet the following conditions:-- (a) You must give any other recipients of the Work or- Derivative Works a copy of this License; and-- (b) You must cause any modified files to carry prominent notices- stating that You changed the files; and-- (c) You must retain, in the Source form of any Derivative Works- that You distribute, all copyright, patent, trademark, and- attribution notices from the Source form of the Work,- excluding those notices that do not pertain to any part of- the Derivative Works; and-- (d) If the Work includes a "NOTICE" text file as part of its- distribution, then any Derivative Works that You distribute must- include a readable copy of the attribution notices contained- within such NOTICE file, excluding those notices that do not- pertain to any part of the Derivative Works, in at least one- of the following places: within a NOTICE text file distributed- as part of the Derivative Works; within the Source form or- documentation, if provided along with the Derivative Works; or,- within a display generated by the Derivative Works, if and- wherever such third-party notices normally appear. The contents- of the NOTICE file are for informational purposes only and- do not modify the License. You may add Your own attribution- notices within Derivative Works that You distribute, alongside- or as an addendum to the NOTICE text from the Work, provided- that such additional attribution notices cannot be construed- as modifying the License.-- You may add Your own copyright statement to Your modifications and- may provide additional or different license terms and conditions- for use, reproduction, or distribution of Your modifications, or- for any such Derivative Works as a whole, provided Your use,- reproduction, and distribution of the Work otherwise complies with- the conditions stated in this License.-- 5. Submission of Contributions. Unless You explicitly state otherwise,- any Contribution intentionally submitted for inclusion in the Work- by You to the Licensor shall be under the terms and conditions of- this License, without any additional terms or conditions.- Notwithstanding the above, nothing herein shall supersede or modify- the terms of any separate license agreement you may have executed- with Licensor regarding such Contributions.-- 6. Trademarks. This License does not grant permission to use the trade- names, trademarks, service marks, or product names of the Licensor,- except as required for reasonable and customary use in describing the- origin of the Work and reproducing the content of the NOTICE file.-- 7. Disclaimer of Warranty. Unless required by applicable law or- agreed to in writing, Licensor provides the Work (and each- Contributor provides its Contributions) on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or- implied, including, without limitation, any warranties or conditions- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A- PARTICULAR PURPOSE. You are solely responsible for determining the- appropriateness of using or redistributing the Work and assume any- risks associated with Your exercise of permissions under this License.-- 8. Limitation of Liability. In no event and under no legal theory,- whether in tort (including negligence), contract, or otherwise,- unless required by applicable law (such as deliberate and grossly- negligent acts) or agreed to in writing, shall any Contributor be- liable to You for damages, including any direct, indirect, special,- incidental, or consequential damages of any character arising as a- result of this License or out of the use or inability to use the- Work (including but not limited to damages for loss of goodwill,- work stoppage, computer failure or malfunction, or any and all- other commercial damages or losses), even if such Contributor- has been advised of the possibility of such damages.-- 9. Accepting Warranty or Additional Liability. While redistributing- the Work or Derivative Works thereof, You may choose to offer,- and charge a fee for, acceptance of support, warranty, indemnity,- or other liability obligations and/or rights consistent with this- License. However, in accepting such obligations, You may act only- on Your own behalf and on Your sole responsibility, not on behalf- of any other Contributor, and only if You agree to indemnify,- defend, and hold each Contributor harmless for any liability- incurred by, or claims asserted against, such Contributor by reason- of your accepting any such warranty or additional liability.-- END OF TERMS AND CONDITIONS-- APPENDIX: How to apply the Apache License to your work.-- To apply the Apache License to your work, attach the following- boilerplate notice, with the fields enclosed by brackets "[]"- replaced with your own identifying information. (Don't include- the brackets!) The text should be enclosed in the appropriate- comment syntax for the file format. We also recommend that a- file or class name and description of purpose be included on the- same "printed page" as the copyright notice for easier- identification within third-party archives.-- Copyright [yyyy] [name of copyright owner]-- Licensed under the Apache License, Version 2.0 (the "License");- you may not use this file except in compliance with the License.- You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing, software- distributed under the License is distributed on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- See the License for the specific language governing permissions and- limitations under the License.diff --git a/README.md b/README.mdindex b7b4540..6ca4f93 100644--- a/README.md+++ b/README.md@@ -1,2 +1,29 @@-# vmodal_sdk_flutter-V- Modal AI: Search anything anywhere SDK Flutter+# VModal Flutter SDK++Typed VModal access for Flutter applications on Android and iOS. Flutter Web is+not supported in this release. The package owns neither login UI nor credential+storage; inject an already-loaded runtime API key from the parent application.++```dart+final keys = MutableApiKeyProvider(runtimeKey);+final client = VmodalClient(+ config: SdkConfig(apiKeyProvider: keys),+);++final me = await client.auth.me();+final result = await client.searches.searchVideo(+ const SearchRequest(queryText: 'red bicycle'),+);+```++Gateway mode sends caller identity only through the bearer credential. Use+`VmodalClient.unsafeDirect` only inside a trusted private network. Rotate a key+with `keys.rotate(newKey)`; account switching requires canceling work, clearing+the provider and upload persistence, then creating a new client.++Signed single upload is the production default for every file size. Multipart+is experimental and requires explicit `VideoUploadOptions(multipart: true)`;+it fails with `FeatureDisabled` when the complete backend route family is not+available. The parent app owns file picking, private storage directories,+background scheduling, and lifecycle UI.+diff --git a/RELEASE_METADATA b/RELEASE_METADATAnew file mode 100644index 0000000..5b2f8e6--- /dev/null+++ b/RELEASE_METADATA@@ -0,0 +1 @@+Source-vmx-api: 7fb167d15e1fadc765c0d14d535a64d8f70a68c0diff --git a/SOURCE_MANIFEST.sha256 b/SOURCE_MANIFEST.sha256new file mode 100644index 0000000..ee0372d--- /dev/null+++ b/SOURCE_MANIFEST.sha256@@ -0,0 +1,115 @@+002abcc5d95c0cf20375adefe4ee2472581a615e64f5726bf361dd5c679cdea7 test/auth_http_test.dart+008655dc4707449090b05556247f12e3f210bae227e1dc62b1e28c40a2c3c537 test/resources_models_test.dart+05a8215a0f8d4d5ca26d8dfdf93d8c41b5785d84855459f979b079527f6232b3 lib/src/api_key_provider.dart+0a1394c90829b91541aa01e9786e3195aae04fc49a7b92775dbf404bf2802107 test/fakes_test.dart+0e00d398815f8dd7cded7624b0758d16db3e0c40f9f4598ef154ede76240f6a9 test/workflow_layout_test.dart+0f82b18017fba6bb5ce3aa4b2d1a00c9382fc8aae7b1d9326e44b18abd66d80b example/android/gradle.properties+119668af3446819daa6f8aa55b6e9c2160dda70241628709f6f1f14836f4aff9 example/pubspec.lock+11b247bc6796892d67c9a821d18604db4dd6a880981b34f38460b9866e6b247f example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings+11b247bc6796892d67c9a821d18604db4dd6a880981b34f38460b9866e6b247f example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings+13bacc486006b6b6ae11ae37b2cda0dddf588b8aa8e72c1b13e570b95f36aa59 doc/sdk_contract.md+14368b598ece0ce9b2e249148a10a92f2c80e38427c077013a1515826f4365bd test/fixtures/routes_contract.json+18cba02cc4f3295820e22fbca5fcf563beb7eca3ed81f6049f89f1db392faf0a README.md+19be171481dc71a0b2803ebcd01dd8b0c5fd5778dee34c0a3cabc948c225f24e example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]+19be171481dc71a0b2803ebcd01dd8b0c5fd5778dee34c0a3cabc948c225f24e example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]+1a8d11d01d1cc92c650c9c9ed35299240052d4683a15a719a2315ef44185e074 example/ios/Runner/Runner-Bridging-Header.h+1f8d8c8067b690902c8c719cd8628ce80defdd0863bbb7574c87fe33b4191bc7 doc/release.md+2261aee252795421960040a611bdda5cc86fe649411b13391e62a86e9d73a4f3 example/ios/Runner.xcodeproj/project.pbxproj+23756b83470b1f25f6a7e6b5a6270f123a5224e49fd8e2eda36001358951b688 install.sh+25a63a36db611a75e8101306807d6726d054d7198233c37f0833a0299a142253 RELEASE_METADATA+28315361fb94de58b44de0e303fab5271aec59c752a8c36ec76fd66c806bfc59 CHANGELOG.md+28960838bdddfa72b39ce7e86a23d547d5e5ec755498249af966d3733605dacc build.sh+28c321f8798c0e803246c737e0b634c5f3ade930239bb6e5429098bb2b096d86 doc/manage_api_key.md+28f1ad1be044eb3fbee9a9435c4905a8296ba1ded9a9508fda5436f0de7b93bf lib/src/routes.dart+2ad9b4183bce96eacd91c5514de9231b1f0a4f269392726e174507cfa507981a lib/src/http.dart+2b969fbd1d82d89a5dc7822032ce9fe0df4bda625da969bc8e93c57e43fcf2c2 pubspec.yaml+30b0832ed8b92dfbd6ae2abfa939ccf26333d37600056b1572bd4a397a18a74b example/android/app/src/debug/AndroidManifest.xml+30b0832ed8b92dfbd6ae2abfa939ccf26333d37600056b1572bd4a397a18a74b example/android/app/src/profile/AndroidManifest.xml+3156038fbb15ba2048a87f190b14744c13e4b858f1247b373f419090432ac7a2 lib/src/utils.dart+318ca9f582d3a74cbee346857d2df1b50a2deeb7fb687ab64eeeddd037157b3e example/ios/Runner/Info.plist+3221993eac1057198d652b7437105e2953ca4850d415eb0eb2b9625874fd059e example/android/gradle/wrapper/gradle-wrapper.properties+37b7148216ac6090e36adfb699d642b8dd1e1b8ba99870e65e88733947a59fa6 LICENSE+3b1e214f466ffedff74baa5598ad5c4421130eea6bc8d57b8fe23435e8280ae4 example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json+3c34e1f298d0c9ea3455d46db6b7759c8211a49e9ec6e44b635fc5c87dfb4180 example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png+406de1350b79662fcaf007cb0cacd7a6b71b83815dc7cd3c7b561fcfba5600a3 tool/check_route_sync.dart+41c7d42f6e61f8fe7f30b1ffa2256aecbc9682be06d18c4a3062043e1a2e547c example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]+4209a49e44a92ec40a327d3455eb1b1c153ee83d75de1c2be0a12ab18b2ff9de example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]+451c6d9ba0a2b3ff43092ea349c60fa79a91f1158b915eb29dbdd357cb95d7b8 example/ios/Runner/AppDelegate.swift+4630bdec004652eae39bd30f1e864a5b6e5f27a7d98f866bdea192b4d65b4046 lib/src/adaptive_upload.dart+46c3c9702ff7c5584e11c954d943cfb6e07fb26e3fbd072ddbc0f388aa352de1 example/ios/Runner.xcworkspace/contents.xcworkspacedata+471beea99cb1189fe081eb0fbe0365025b15ab9b7d9909461ac2c6bcae195d25 example/lib/main.dart+47ce679eef585b28fe5e10a92a642eef4946c5d33d56411202734139b1db8e7b example/android/app/src/main/kotlin/com/vmodal/sdk/vmodal_example/MainActivity.kt+4d470bf22d5c17d84edc5f82516d1ba8a1c09559cd761cefb792f86d9f52b540 example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png+52c47ca2a079343aa0d142883b3d53c1e02dd86a50563e7ece0c550f7bdbfb1b security_check.sh+5b386cfbac75cc03ab5bac6f075fd33bbac03d880911cd43384ae0c12c8fc2df example/pubspec.yaml+5c90a4437c33000865ee889e1e2afb875d3e1abc83e5d3150e867efe1240232c doc/sdk_doc.md+5d7e5bdf01b93802bc973345b3a78c038907147625035952a08a115a563b7f81 example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]+5dee24dc104ac76dc162e42ae0beb163d426bf365562ee28ba7b3ad368559a60 example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]+5e8f4908dacea6f29b2a790e4d38bf5fded69096063f9a27a2f21584d62b30c0 example/ios/RunnerTests/RunnerTests.swift+6a26dba2cb8dfba1e74f540b0d17a89d96c1301d3c3bfda14348bed257fddcba example/android/build.gradle.kts+6a7c8f0d703e3682108f9662f813302236240d3f8f638bb391e32bfb96055fef example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png+72fff91181fd3e25fd9afd766930a67025205b61096fd35c55cbdd9a3178ecf0 pubspec.lock+744ea1477f794e3a2f8f4b8f7e63fe5a84da6f027f5bf83c9780f81bce0fb09d lib/src/config.dart+7770183009e914112de7d8ef1d235a6a30c5834424858e0d2f8253f6b8d31926 example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]+79e3de3c03451cd9d62327430106edf861da6aeb97b546bbac2d93a0bcbbe3d3 test/transport_test.dart+7c61c42fc7b657d9cf314d32a4ec458f0647c3aaf360be1b9377857266ec2499 example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]+7ca6d5cec2169c5a98661a119db23a6f3399c8fef2256ff04f3a642831282478 example/android/app/src/main/res/drawable-v21/launch_background.xml+7f152a10a7ccaf6f9eade2b34a8a2d32b87ce6421e99f51e3f2737de8ee46ebc test.sh+7f3b00b5c3fdb45242d7b87e1e5c4e25d1fa8129a16c94295ecc4e8ea2235c5f example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata+807e56bf3e3fb8a082d8b802658ce8735bef5b88998ccd6f46f010955aa0081a example/android/app/build.gradle.kts+836c918cb613249eba0483a6b02fa3df3c1c0a89a315ee4d3b88509b83c7ab73 example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]+857e61203b3deafb05766d8fcda898b86a7cb6f3d5e385ecc9926c4d698215e9 example/ios/Runner/Base.lproj/LaunchScreen.storyboard+8b6a10c89a44568aed939d712b05b120f513e04e909ba141a4d55998afa9aaa5 lib/src/resources.dart+8c5bad5152f217e837519f9c15211d19f39bd45f5f67faf6dd81cb4b299e518f example/android/app/src/main/res/values-night/styles.xml+937d7c82f539c72eb94fd3a3773f29b3d3fef1997213c92cb632298cedf4bda9 example/android/app/src/main/res/values/styles.xml+93ae7d494fad0fb30cbf3ae746a39c4bc7a0f8bbf87fbb587a3f3c01f3c5ce20 example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png+93ae7d494fad0fb30cbf3ae746a39c4bc7a0f8bbf87fbb587a3f3c01f3c5ce20 example/ios/Runner/Assets.xcassets/LaunchImage.imageset/[email protected]+93ae7d494fad0fb30cbf3ae746a39c4bc7a0f8bbf87fbb587a3f3c01f3c5ce20 example/ios/Runner/Assets.xcassets/LaunchImage.imageset/[email protected]+94433756fe10005ddd6fc55cc5c0b1e9f3c10b66a08ceac795ece6713d34e28a example/android/app/src/main/res/drawable/launch_background.xml+970aad998c7e3d34430ff59c72aa224e60155f85038efa7ffc6fdf73b531437a test/regression_manifest_test.dart+9fbce429f56243561dd437a527136c9f9ed77165e3b271b923faf236cfcd0484 example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme+a3134f6fc8387589e96a345ea35d4c68240c7c1893ef5cd5926707e4168e5309 lib/src/transport.dart+a82d7765b37116ee4821d2cd1d65942febf8032353757ffb0826eabde785b4a6 example/ios/Flutter/Debug.xcconfig+a82d7765b37116ee4821d2cd1d65942febf8032353757ffb0826eabde785b4a6 example/ios/Flutter/Release.xcconfig+a985b626c4f7546a8ba392d135e9226c3547c8e2b46895f5f2bdf40d7b14ef9f example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md+a9b21eb6f4271385655a8771f76e29eef8c1107d7879cbcfc567e6619d1f716a example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]+ac2de3201a4c310b8e56e07317b67f841f177cb31279a67e9af2508caab90676 test/shell_scripts_test.dart+adc9bfd3287fdde7af102586342b16bb0da7ca0548b976972af46d13bad19de7 example/test/widget_test.dart+add68b905971dedfcc0d0b5b7118030de5925ba8c081ad9815463699e3a444ad example/ios/Runner/SceneDelegate.swift+af86f6d0d7c5f10f0df759b04790d0b0f495446916ce121b3ef68e4d86d4fd8a lib/src/client.dart+b1d3b70a6c9ecde707a9f139a3e7c5a2b4db808e9746db6ac6195c2205c9522e test/fakes.dart+b2dc1cfc58dcd93d62c8f4a1c05210c9f4a3e5b93e69541a40fcf8176cb5f2aa .pubignore+b76d554153a63772dddbe2ee91abdf582f5f871af40698b80a2ef7b70903d96f example/android/settings.gradle.kts+b8013ee0b123493f6277937c99ea4432063162a4167d99d5356647738261b7c1 example/android/app/src/main/AndroidManifest.xml+b9ad02cf6576a04d1b6806ac02a2431481b448dd0c2e505ce25842d1f7c4730b example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]+b9ad02cf6576a04d1b6806ac02a2431481b448dd0c2e505ce25842d1f7c4730b example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]+ba941377f1ee717091dd30522609d028f32cd60df575564c75ab0228c2543d35 test/config_routes_test.dart+be59599b9ba77d031e9b4bad7f8d5c59efd2687888c5b73be4fbea115902106b test/adaptive_upload_test.dart+c13557f89597f0be73f48dc8463aa7513e9e814c0e6a0ab871e441834687abb1 test/upload_test.dart+c5ce516b547327aab5b6fa27a523d4c76e66294ada3248b293c54b9595cd3a87 example/.metadata+c6e6d3b215ae744a9c391f4c4d44157eff5e739d6ad6c39f9bfa5df66dddd267 example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]+c7c0c0189145e4e32a401c61c9bdc615754b0264e7afae24e834bb81049eaf81 example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png+cab10a0d391ec5bc09ef50ce49e8ad401cee7ef03707ec0923a222c5c2b3d212 example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]+cafa2529768e48a6b89f85a069e337eff7a5cf75103d6ac8623bdbb7a1088549 lib/src/collection_uploads.dart+ccc7950fd5f5b82067c85f667940a9d59189151460761ece8098ca78daa19469 example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json+d09f68c36895c2550a6b78d378b0ca1d533b16ae12ead55f3d6dbcfb9997996f lib/src/models.dart+d2411f67f427c095c7d82718c23ddd114fa39221e43333bfd55ac8ece9e4c877 lib/src/upload.dart+d31d6bb36542a9022c62d2d9940b0efd07f60b1cdfb30e35f8be8b15a226c843 run.sh+d5f5f9246656a5c275c5ab5863dbf3945d8ef6b1c9042c9d1912cfafce93646f tool/flutter_checksums.txt+da12038f9b2688a8a26160fea2609fa8fcb11421448c109f09c0f573efe7698d example/ios/Flutter/AppFrameworkInfo.plist+da330cad4fc27776d249a5db97c1e20bf2cac015d0bbab73b781c0a9ec15b00f doc/search_app.md+dc1fe4b5d4cd1cf3ba061ebbd2a7ca199bdff014242ccd3ce89fc6d6fb527289 tool/release_manifest.dart+dd2a40eaedcf0f194d5faf7abf398124506f9db206d418617a69b7361d6ec349 lib/vmodal_sdk_flutter.dart+def7e4f643adff5b01b877b6a7fa5b2381612b693c0bf06bd232ee0f7197d342 analysis_options.yaml+dfa0f9bb85b95ccba9c6811adadf8cb407fb5d52088e89db83ebc308ec448542 example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist+dfa0f9bb85b95ccba9c6811adadf8cb407fb5d52088e89db83ebc308ec448542 example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist+e0ea485cfdbc3e12b93efb8679a5ea73ebfe20ea4ca0c473dc594fc2fb274ed5 example/analysis_options.yaml+e14aa40904929bf313fded22cf7e7ffcbf1d1aac4263b5ef1be8bfce650397aa example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png+e246ed229511a24a1ee7e98529c203ef90d1d352290ce8486caebe05683db3a0 env.sh+e677d701ffe4af7bc2935098d6b3984cc9ab7ace573e6900955a5535b12410cf example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]+e789cd4d1bed8a78ec8014c5c5913e300f81b63ea56a56aacb0dfec3b5e7ce2b .flutter-version+f40c8521b0cc5668568ff5a960ec1deab573cb60a95d5450e205ce35d08777d5 example/README.md+fbbda2e7e29bbd860539a9ca18c478f3b02de140f25a872c19a6dbecd11bc94b .github/workflows/publish.yml+fcef63e72b69415a1090c376095f8f44977e26104ffaeccf3a82430f65dcd4ff lib/src/errors.dart+fd2bad0ad87fbf2f15f7e9845b830db58408bb4c502c6ff105f39e4e7cce1905 test/multipart_upload_test.dart+fd367b6c43006d61b730f674970dd48b9f662c8f2264e52ffc1558102a2c9f2d example/ios/Runner/Base.lproj/Main.storyboarddiff --git a/analysis_options.yaml b/analysis_options.yamlnew file mode 100644index 0000000..adeee2c--- /dev/null+++ b/analysis_options.yaml@@ -0,0 +1,22 @@+include: package:flutter_lints/flutter.yaml++analyzer:+ language:+ strict-casts: true+ strict-inference: true+ strict-raw-types: true+ errors:+ missing_required_param: error+ missing_return: error++linter:+ rules:+ always_declare_return_types: true+ avoid_dynamic_calls: true+ cancel_subscriptions: true+ close_sinks: true+ directives_ordering: true+ discarded_futures: true+ unawaited_futures: true+ prefer_initializing_formals: false+ use_null_aware_elements: falsediff --git a/build.sh b/build.shnew file mode 100755index 0000000..d3ed617--- /dev/null+++ b/build.sh@@ -0,0 +1,143 @@+#!/usr/bin/env bash+help='+ Build and validate the VModal Flutter package.++ Examples:+ bash build.sh build+ bash build.sh test+ bash build.sh example_android+ bash build.sh package+'+set -euo pipefail+cd "$(dirname "$0")"+sdk_dir="$PWD"++sdk_flutter() {+ local help='+ ## Usage:+ sdk_flutter analyze+ '+ local bin+ bin="$(bash "$sdk_dir/install.sh" flutter_bin)"+ "$bin" "$@"+}++sdk_dart() {+ local help='+ ## Usage:+ sdk_dart format lib test+ '+ local bin+ bin="$(bash "$sdk_dir/install.sh" dart_bin)"+ "$bin" "$@"+}++sdk_pub_get() {+ local help='+ ## Usage:+ bash build.sh pub_get+ '+ bash install.sh check+ sdk_flutter pub get+ (cd example && sdk_flutter pub get)+}++sdk_format() {+ local help='+ ## Usage:+ bash build.sh format+ '+ sdk_dart format --output=none --set-exit-if-changed lib test tool example/lib example/test+}++sdk_analyze() {+ local help='+ ## Usage:+ bash build.sh analyze+ '+ sdk_flutter analyze+ (cd example && sdk_flutter analyze)+}++sdk_test() {+ local help='+ ## Usage:+ bash build.sh test+ '+ sdk_flutter test+ (cd example && sdk_flutter test)+}++sdk_example_android() {+ local help='+ ## Usage:+ bash build.sh example_android+ '+ (cd example && sdk_flutter build apk --debug)+}++sdk_example_ios() {+ local help='+ ## Usage:+ bash build.sh example_ios+ '+ [[ "$(uname -s)" == 'Darwin' ]] || { echo 'iOS builds require a configured macOS runner.' >&2; return 2; }+ (cd example && sdk_flutter build ios --simulator --debug --no-codesign)+}++sdk_package() {+ local help='+ ## Usage:+ bash build.sh package+ '+ local temp+ temp="$(mktemp -d "${TMPDIR:-/tmp}/vmodal-flutter-package.XXXXXX")"+ trap 'rm -rf "${temp:-}"' RETURN+ sdk_dart run tool/release_manifest.dart export "$temp"+ (cd "$temp" && sdk_dart pub publish --dry-run)+}++sdk_build() {+ local help='+ ## Usage:+ bash build.sh build+ '+ sdk_pub_get+ sdk_format+ sdk_analyze+ sdk_test+ sdk_package+ sdk_example_android+}++sdk_clean() {+ local help='+ ## Usage:+ bash build.sh clean+ '+ [[ "$PWD" == */uinterface/sdk_flutter ]] || { echo 'Refusing to clean outside sdk_flutter.' >&2; return 2; }+ sdk_flutter clean+ (cd example && sdk_flutter clean)+}++sdk_help() {+ local help='+ ## Usage:+ bash build.sh help+ '+ echo "$help"+}++case "${1:-help}" in+ build) sdk_build ;;+ pub_get) sdk_pub_get ;;+ format) sdk_format ;;+ analyze) sdk_analyze ;;+ test) sdk_test ;;+ example_android) sdk_example_android ;;+ example_ios) sdk_example_ios ;;+ package) sdk_package ;;+ clean) sdk_clean ;;+ help|-h|--help) sdk_help ;;+ *) echo "Unknown command: ${1:-}" >&2; echo "$help" >&2; exit 2 ;;+esacdiff --git a/doc/manage_api_key.md b/doc/manage_api_key.mdnew file mode 100644index 0000000..bada872--- /dev/null+++ b/doc/manage_api_key.md@@ -0,0 +1,21 @@+# Manage API keys++Retrieve credentials in the parent application's authenticated service, load+them into memory, then inject `MutableApiKeyProvider`. The SDK never stores a key.++```dart+final provider = MutableApiKeyProvider(await authService.currentApiKey());+final client = VmodalClient(+ config: SdkConfig(apiKeyProvider: provider),+);+```++`rotate` validates the complete new key before replacing the old one. A request+reads one snapshot; rotation affects the next request. `clear` and `close` fail+closed. Logout/account switch order is: cancel active work, clear upload state,+clear the provider, close the client, authenticate the next account, then create+a new provider and client. Key rotation is not an identity switch.++Do not commit keys, put them in assets, log them, add them to presigned requests,+or use compile-time `--dart-define` values as production mobile credential storage.+diff --git a/doc/release.md b/doc/release.mdnew file mode 100644index 0000000..0f5d4b1--- /dev/null+++ b/doc/release.md@@ -0,0 +1,18 @@+# Release process++The package is pinned to Flutter 3.44.6. `install.sh` verifies the official+archive checksum and installs only into a user-owned cache. Run `bash test.sh all`+for the offline gate and `bash test.sh live` only after explicitly loading the+existing repository test credential variables.++The internal workflow checks out one immutable candidate SHA, runs secret+detection only on the current `uinterface/sdk_flutter` tree and that path's Git+history, then runs offline tests, Android/iOS example builds, the live+signed-upload lifecycle, and package dry-run. It exports one checksummed source+artifact to the public repository. Optional pub.dev publication is triggered+only by the exported version tag and uses OIDC trusted publishing; no long-lived+pub token is stored.++Multipart is excluded from production live claims until all five backend routes+are verified. A failed publication is fixed forward with a new version after the+entire candidate pipeline passes again.diff --git a/doc/sdk_contract.md b/doc/sdk_contract.mdnew file mode 100644index 0000000..992a0a9--- /dev/null+++ b/doc/sdk_contract.md@@ -0,0 +1,32 @@+# Flutter SDK contract inventory++The route authority is `vmx_avideo/infra/search_api_ui/routers/apionly_routes.py`+plus `apionly_serve_img.py`. The Python SDK defines the cross-SDK wire contract;+the Android SDK defines mobile cancellation, streaming, upload, and key-rotation+behavior. `test/fixtures/routes_contract.json` is the reviewed normalized mirror.++| Resource | Public Flutter operations | Contract status |+|---|---|---|+| Client/auth | `health`, `authCheck`, `auth.me` | Active; gateway bearer only |+| Searches | `searchVideo(SearchRequest)` | Active; exact Python/Android defaults |+| Collections | `listGroups`, `uploadFile`, `uploadMetadataJsonl`, `addAssets`, `updateDescription`, `delete` | Active |+| Signed upload | `videoUpload`, `videoUploadBulk` | Active; signed single is default |+| Indexes | `jobsList`, `createIndex`, `indexStatus`, `deleteIndex` | Active |+| Admin | `userStats`, `usage`, `cacheStats` | Active; split external/users API bases |+| R2 | `presignUploadFile`, `presignUploadFolderVideo` | Active users API routes |+| Images | `getUrl`, `getUrlBulk`, `getImageFromUrl`, `getImageBulkFromUrls` | Active image routes |+| Multipart | explicit `VideoUploadOptions(multipart: true)` | Experimental; never selected by size |+| GDrive/SQL/auto-index/folder scan | compatibility methods | Disabled before transport |+| Google Drive collection upload | no public method | Mounted upstream but deprecated by SDK contract |++Every operation uses the centralized `Routes`, `VmodalHttp`, bounded response+reader, retry classifier, and cancellation token. Gateway payload serializers+remove caller identity; only unsafe direct mode may emit trusted identity fields.++Android regression groups map to Flutter suites as follows: configuration/routes+and credentials (`config_routes_test`, `auth_http_test`), transport/bounds and+cancellation (`transport_test`), resources/models (`resources_models_test`),+signed/bulk upload (`upload_test`), multipart/checkpoint (`multipart_upload_test`),+adaptive vectors (`adaptive_upload_test`), and release/tooling+(`shell_scripts_test`, `workflow_layout_test`).+diff --git a/doc/sdk_doc.md b/doc/sdk_doc.mdnew file mode 100644index 0000000..d805d2f--- /dev/null+++ b/doc/sdk_doc.md@@ -0,0 +1,23 @@+# SDK guide++Construct `VmodalClient` with an explicit `SdkConfig` and an app-owned+`ApiKeyProvider`. All ordinary operations are asynchronous. Gateway mode is the+default and sends only `Authorization: Bearer <key>` as caller identity.++Resources are grouped under `auth`, `searches`, `collections`, `indexes`,+`admin`, `r2`, and `images`. Request models preserve server snake_case during+serialization and response classes retain the raw JSON map for extension fields.++Responses are consumed through one bounded stream reader: JSON/text is limited+to 8 MiB, errors to 1 MiB, and binary results to 64 MiB. Only GET and HEAD retry+recognized transport failures or 500/502/503/504. Mutating requests are sent+once; reconcile server state before explicitly retrying an ambiguous mutation.++Uploads use reopenable `UploadSource` streams. Signed single upload is always+the default. `UploadTask` exposes a result future, broadcast progress stream,+and per-task cancellation. Multipart requires explicit opt-in and is experimental.++Flutter Web, login UI, key persistence, file picking, widget state management,+and background scheduling are outside the package. The first release supports+Flutter applications on Android and iOS.+diff --git a/doc/search_app.md b/doc/search_app.mdnew file mode 100644index 0000000..826d2a5--- /dev/null+++ b/doc/search_app.md@@ -0,0 +1,20 @@+# Search application integration++Keep the client above individual pages so navigation does not close shared+network state. Pages await typed futures and check `mounted` before changing UI.++```dart+final result = await client.searches.searchVideo(+ const SearchRequest(+ queryText: 'red bicycle',+ mode: 'vid_file',+ groupName: 'agroup',+ ),+);+```++Render only safe `SdkException.toString()` output. It contains classification+and status metadata, never response bodies, URLs, keys, or identities. Cancel an+upload task when the user explicitly cancels it; do not close the application+client merely because a page was disposed.+diff --git a/env.sh b/env.shnew file mode 100755index 0000000..978146b--- /dev/null+++ b/env.sh@@ -0,0 +1,47 @@+#!/usr/bin/env bash+help='+ Derive Flutter SDK live/release variable aliases without storing values.++ Examples:+ source env.sh && sdk_env_live+ bash env.sh live+ bash env.sh release+'++sdk_env_live() {+ local help='+ ## Usage:+ source env.sh && sdk_env_live+ '+ export VMODAL_API_KEY="${VMODAL_API_KEY:-${TEST_CLIENT_CLERK_USER_API_TOKEN:-}}"+ export VMODAL_BASE_URL="${VMODAL_BASE_URL:-${TEST_CLIENT_SERVER_API_URL:-}}"+ export VMODAL_USER_ID="${VMODAL_USER_ID:-${TEST_CLIENT_USER_ID:-}}"+ export VMODAL_ENV="${VMODAL_ENV:-prd}"+}++sdk_env_release() {+ local help='+ ## Usage:+ source env.sh && sdk_env_release+ '+ export GH_TOKEN="${GH_TOKEN:-}"+}++sdk_env_help() {+ local help='+ ## Usage:+ bash env.sh help+ '+ echo "$help"+}++if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then+ set -euo pipefail+ cd "$(dirname "$0")"+ case "${1:-help}" in+ live) sdk_env_live ;;+ release) sdk_env_release ;;+ help|-h|--help) sdk_env_help ;;+ *) echo "Unknown command: ${1:-}" >&2; echo "$help" >&2; exit 2 ;;+ esac+fidiff --git a/example/.gitignore b/example/.gitignorenew file mode 100644index 0000000..3820a95--- /dev/null+++ b/example/.gitignore@@ -0,0 +1,45 @@+# Miscellaneous+*.class+*.log+*.pyc+*.swp+.DS_Store+.atom/+.build/+.buildlog/+.history+.svn/+.swiftpm/+migrate_working_dir/++# IntelliJ related+*.iml+*.ipr+*.iws+.idea/++# The .vscode folder contains launch configuration and tasks you configure in+# VS Code which you may wish to be included in version control, so this line+# is commented out by default.+#.vscode/++# Flutter/Dart/Pub related+**/doc/api/+**/ios/Flutter/.last_build_id+.dart_tool/+.flutter-plugins-dependencies+.pub-cache/+.pub/+/build/+/coverage/++# Symbolication related+app.*.symbols++# Obfuscation related+app.*.map.json++# Android Studio will place build artifacts here+/android/app/debug+/android/app/profile+/android/app/releasediff --git a/example/.metadata b/example/.metadatanew file mode 100644index 0000000..92bca7e--- /dev/null+++ b/example/.metadata@@ -0,0 +1,33 @@+# This file tracks properties of this Flutter project.+# Used by Flutter tool to assess capabilities and perform upgrades etc.+#+# This file should be version controlled and should not be manually edited.++version:+ revision: "ee80f08bbf97172ec030b8751ceab557177a34a6"+ channel: "stable"++project_type: app++# Tracks metadata for the flutter migrate command+migration:+ platforms:+ - platform: root+ create_revision: ee80f08bbf97172ec030b8751ceab557177a34a6+ base_revision: ee80f08bbf97172ec030b8751ceab557177a34a6+ - platform: android+ create_revision: ee80f08bbf97172ec030b8751ceab557177a34a6+ base_revision: ee80f08bbf97172ec030b8751ceab557177a34a6+ - platform: ios+ create_revision: ee80f08bbf97172ec030b8751ceab557177a34a6+ base_revision: ee80f08bbf97172ec030b8751ceab557177a34a6++ # User provided section++ # List of Local paths (relative to this file) that should be+ # ignored by the migrate tool.+ #+ # Files that are not part of the templates will be ignored by default.+ unmanaged_files:+ - 'lib/main.dart'+ - 'ios/Runner.xcodeproj/project.pbxproj'diff --git a/example/README.md b/example/README.mdnew file mode 100644index 0000000..303df18--- /dev/null+++ b/example/README.md@@ -0,0 +1,17 @@+# vmodal_example++A new Flutter project.++## Getting Started++This project is a starting point for a Flutter application.++A few resources to get you started if this is your first Flutter project:++- [Learn Flutter](https://docs.flutter.dev/get-started/learn-flutter)+- [Write your first Flutter app](https://docs.flutter.dev/get-started/codelab)+- [Flutter learning resources](https://docs.flutter.dev/reference/learning-resources)++For help getting started with Flutter development, view the+[online documentation](https://docs.flutter.dev/), which offers tutorials,+samples, guidance on mobile development, and a full API reference.diff --git a/example/analysis_options.yaml b/example/analysis_options.yamlnew file mode 100644index 0000000..0d29021--- /dev/null+++ b/example/analysis_options.yaml@@ -0,0 +1,28 @@+# This file configures the analyzer, which statically analyzes Dart code to+# check for errors, warnings, and lints.+#+# The issues identified by the analyzer are surfaced in the UI of Dart-enabled+# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be+# invoked from the command line by running `flutter analyze`.++# The following line activates a set of recommended lints for Flutter apps,+# packages, and plugins designed to encourage good coding practices.+include: package:flutter_lints/flutter.yaml++linter:+ # The lint rules applied to this project can be customized in the+ # section below to disable rules from the `package:flutter_lints/flutter.yaml`+ # included above or to enable additional rules. A list of all available lints+ # and their documentation is published at https://dart.dev/lints.+ #+ # Instead of disabling a lint rule for the entire project in the+ # section below, it can also be suppressed for a single line of code+ # or a specific dart file by using the `// ignore: name_of_lint` and+ # `// ignore_for_file: name_of_lint` syntax on the line or in the file+ # producing the lint.+ rules:+ # avoid_print: false # Uncomment to disable the `avoid_print` rule+ # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule++# Additional information about this file can be found at+# https://dart.dev/guides/language/analysis-optionsdiff --git a/example/android/.gitignore b/example/android/.gitignorenew file mode 100644index 0000000..be3943c--- /dev/null+++ b/example/android/.gitignore@@ -0,0 +1,14 @@+gradle-wrapper.jar+/.gradle+/captures/+/gradlew+/gradlew.bat+/local.properties+GeneratedPluginRegistrant.java+.cxx/++# Remember to never publicly share your keystore.+# See https://flutter.dev/to/reference-keystore+key.properties+**/*.keystore+**/*.jksdiff --git a/example/android/app/build.gradle.kts b/example/android/app/build.gradle.ktsnew file mode 100644index 0000000..2a6ed07--- /dev/null+++ b/example/android/app/build.gradle.kts@@ -0,0 +1,45 @@+plugins {+ id("com.android.application")+ // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.+ id("dev.flutter.flutter-gradle-plugin")+}++android {+ namespace = "com.vmodal.sdk.vmodal_example"+ compileSdk = flutter.compileSdkVersion+ ndkVersion = flutter.ndkVersion++ compileOptions {+ sourceCompatibility = JavaVersion.VERSION_17+ targetCompatibility = JavaVersion.VERSION_17+ }++ defaultConfig {+ // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).+ applicationId = "com.vmodal.sdk.vmodal_example"+ // You can update the following values to match your application needs.+ // For more information, see: https://flutter.dev/to/review-gradle-config.+ minSdk = flutter.minSdkVersion+ targetSdk = flutter.targetSdkVersion+ versionCode = flutter.versionCode+ versionName = flutter.versionName+ }++ buildTypes {+ release {+ // TODO: Add your own signing config for the release build.+ // Signing with the debug keys for now, so `flutter run --release` works.+ signingConfig = signingConfigs.getByName("debug")+ }+ }+}++kotlin {+ compilerOptions {+ jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17+ }+}++flutter {+ source = "../.."+}diff --git a/example/android/app/src/debug/AndroidManifest.xml b/example/android/app/src/debug/AndroidManifest.xmlnew file mode 100644index 0000000..399f698--- /dev/null+++ b/example/android/app/src/debug/AndroidManifest.xml@@ -0,0 +1,7 @@+<manifest xmlns:android="http://schemas.android.com/apk/res/android">+ <!-- The INTERNET permission is required for development. Specifically,+ the Flutter tool needs it to communicate with the running application+ to allow setting breakpoints, to provide hot reload, etc.+ -->+ <uses-permission android:name="android.permission.INTERNET"/>+</manifest>diff --git a/example/android/app/src/main/AndroidManifest.xml b/example/android/app/src/main/AndroidManifest.xmlnew file mode 100644index 0000000..11aed79--- /dev/null+++ b/example/android/app/src/main/AndroidManifest.xml@@ -0,0 +1,45 @@+<manifest xmlns:android="http://schemas.android.com/apk/res/android">+ <application+ android:label="vmodal_example"+ android:name="${applicationName}"+ android:icon="@mipmap/ic_launcher">+ <activity+ android:name=".MainActivity"+ android:exported="true"+ android:launchMode="singleTop"+ android:taskAffinity=""+ android:theme="@style/LaunchTheme"+ android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"+ android:hardwareAccelerated="true"+ android:windowSoftInputMode="adjustResize">+ <!-- Specifies an Android theme to apply to this Activity as soon as+ the Android process has started. This theme is visible to the user+ while the Flutter UI initializes. After that, this theme continues+ to determine the Window background behind the Flutter UI. -->+ <meta-data+ android:name="io.flutter.embedding.android.NormalTheme"+ android:resource="@style/NormalTheme"+ />+ <intent-filter>+ <action android:name="android.intent.action.MAIN"/>+ <category android:name="android.intent.category.LAUNCHER"/>+ </intent-filter>+ </activity>+ <!-- Don't delete the meta-data below.+ This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->+ <meta-data+ android:name="flutterEmbedding"+ android:value="2" />+ </application>+ <!-- Required to query activities that can process text, see:+ https://developer.android.com/training/package-visibility and+ https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.++ In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->+ <queries>+ <intent>+ <action android:name="android.intent.action.PROCESS_TEXT"/>+ <data android:mimeType="text/plain"/>+ </intent>+ </queries>+</manifest>diff --git a/example/android/app/src/main/kotlin/com/vmodal/sdk/vmodal_example/MainActivity.kt b/example/android/app/src/main/kotlin/com/vmodal/sdk/vmodal_example/MainActivity.ktnew file mode 100644index 0000000..10d5d2a--- /dev/null+++ b/example/android/app/src/main/kotlin/com/vmodal/sdk/vmodal_example/MainActivity.kt@@ -0,0 +1,5 @@+package com.vmodal.sdk.vmodal_example++import io.flutter.embedding.android.FlutterActivity++class MainActivity : FlutterActivity()diff --git a/example/android/app/src/main/res/drawable-v21/launch_background.xml b/example/android/app/src/main/res/drawable-v21/launch_background.xmlnew file mode 100644index 0000000..f74085f--- /dev/null+++ b/example/android/app/src/main/res/drawable-v21/launch_background.xml@@ -0,0 +1,12 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Modify this file to customize your launch splash screen -->+<layer-list xmlns:android="http://schemas.android.com/apk/res/android">+ <item android:drawable="?android:colorBackground" />++ <!-- You can insert your own image assets here -->+ <!-- <item>+ <bitmap+ android:gravity="center"+ android:src="@mipmap/launch_image" />+ </item> -->+</layer-list>diff --git a/example/android/app/src/main/res/drawable/launch_background.xml b/example/android/app/src/main/res/drawable/launch_background.xmlnew file mode 100644index 0000000..304732f--- /dev/null+++ b/example/android/app/src/main/res/drawable/launch_background.xml@@ -0,0 +1,12 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Modify this file to customize your launch splash screen -->+<layer-list xmlns:android="http://schemas.android.com/apk/res/android">+ <item android:drawable="@android:color/white" />++ <!-- You can insert your own image assets here -->+ <!-- <item>+ <bitmap+ android:gravity="center"+ android:src="@mipmap/launch_image" />+ </item> -->+</layer-list>diff --git a/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.pngnew file mode 100644index 0000000..db77bb4Binary files /dev/null and b/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differdiff --git a/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.pngnew file mode 100644index 0000000..17987b7Binary files /dev/null and b/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differdiff --git a/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.pngnew file mode 100644index 0000000..09d4391Binary files /dev/null and b/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differdiff --git a/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.pngnew file mode 100644index 0000000..d5f1c8dBinary files /dev/null and b/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differdiff --git a/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.pngnew file mode 100644index 0000000..4d6372eBinary files /dev/null and b/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differdiff --git a/example/android/app/src/main/res/values-night/styles.xml b/example/android/app/src/main/res/values-night/styles.xmlnew file mode 100644index 0000000..06952be--- /dev/null+++ b/example/android/app/src/main/res/values-night/styles.xml@@ -0,0 +1,18 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->+ <style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">+ <!-- Show a splash screen on the activity. Automatically removed when+ the Flutter engine draws its first frame -->+ <item name="android:windowBackground">@drawable/launch_background</item>+ </style>+ <!-- Theme applied to the Android Window as soon as the process has started.+ This theme determines the color of the Android Window while your+ Flutter UI initializes, as well as behind your Flutter UI while its+ running.++ This Theme is only used starting with V2 of Flutter's Android embedding. -->+ <style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">+ <item name="android:windowBackground">?android:colorBackground</item>+ </style>+</resources>diff --git a/example/android/app/src/main/res/values/styles.xml b/example/android/app/src/main/res/values/styles.xmlnew file mode 100644index 0000000..cb1ef88--- /dev/null+++ b/example/android/app/src/main/res/values/styles.xml@@ -0,0 +1,18 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->+ <style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">+ <!-- Show a splash screen on the activity. Automatically removed when+ the Flutter engine draws its first frame -->+ <item name="android:windowBackground">@drawable/launch_background</item>+ </style>+ <!-- Theme applied to the Android Window as soon as the process has started.+ This theme determines the color of the Android Window while your+ Flutter UI initializes, as well as behind your Flutter UI while its+ running.++ This Theme is only used starting with V2 of Flutter's Android embedding. -->+ <style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">+ <item name="android:windowBackground">?android:colorBackground</item>+ </style>+</resources>diff --git a/example/android/app/src/profile/AndroidManifest.xml b/example/android/app/src/profile/AndroidManifest.xmlnew file mode 100644index 0000000..399f698--- /dev/null+++ b/example/android/app/src/profile/AndroidManifest.xml@@ -0,0 +1,7 @@+<manifest xmlns:android="http://schemas.android.com/apk/res/android">+ <!-- The INTERNET permission is required for development. Specifically,+ the Flutter tool needs it to communicate with the running application+ to allow setting breakpoints, to provide hot reload, etc.+ -->+ <uses-permission android:name="android.permission.INTERNET"/>+</manifest>diff --git a/example/android/build.gradle.kts b/example/android/build.gradle.ktsnew file mode 100644index 0000000..dbee657--- /dev/null+++ b/example/android/build.gradle.kts@@ -0,0 +1,24 @@+allprojects {+ repositories {+ google()+ mavenCentral()+ }+}++val newBuildDir: Directory =+ rootProject.layout.buildDirectory+ .dir("../../build")+ .get()+rootProject.layout.buildDirectory.value(newBuildDir)++subprojects {+ val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name)+ project.layout.buildDirectory.value(newSubprojectBuildDir)+}+subprojects {+ project.evaluationDependsOn(":app")+}++tasks.register<Delete>("clean") {+ delete(rootProject.layout.buildDirectory)+}diff --git a/example/android/gradle.properties b/example/android/gradle.propertiesnew file mode 100644index 0000000..e96108c--- /dev/null+++ b/example/android/gradle.properties@@ -0,0 +1,6 @@+org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError+android.useAndroidX=true+# This newDsl flag was added by the Flutter template+android.newDsl=false+# This builtInKotlin flag was added by the Flutter template+android.builtInKotlin=falsediff --git a/example/android/gradle/wrapper/gradle-wrapper.properties b/example/android/gradle/wrapper/gradle-wrapper.propertiesnew file mode 100644index 0000000..2d428bf--- /dev/null+++ b/example/android/gradle/wrapper/gradle-wrapper.properties@@ -0,0 +1,5 @@+distributionBase=GRADLE_USER_HOME+distributionPath=wrapper/dists+zipStoreBase=GRADLE_USER_HOME+zipStorePath=wrapper/dists+distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-all.zipdiff --git a/example/android/settings.gradle.kts b/example/android/settings.gradle.ktsnew file mode 100644index 0000000..c21f0c5--- /dev/null+++ b/example/android/settings.gradle.kts@@ -0,0 +1,26 @@+pluginManagement {+ val flutterSdkPath =+ run {+ val properties = java.util.Properties()+ file("local.properties").inputStream().use { properties.load(it) }+ val flutterSdkPath = properties.getProperty("flutter.sdk")+ require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" }+ flutterSdkPath+ }++ includeBuild("$flutterSdkPath/packages/flutter_tools/gradle")++ repositories {+ google()+ mavenCentral()+ gradlePluginPortal()+ }+}++plugins {+ id("dev.flutter.flutter-plugin-loader") version "1.0.0"+ id("com.android.application") version "9.0.1" apply false+ id("org.jetbrains.kotlin.android") version "2.3.20" apply false+}++include(":app")diff --git a/example/ios/.gitignore b/example/ios/.gitignorenew file mode 100644index 0000000..7a7f987--- /dev/null+++ b/example/ios/.gitignore@@ -0,0 +1,34 @@+**/dgph+*.mode1v3+*.mode2v3+*.moved-aside+*.pbxuser+*.perspectivev3+**/*sync/+.sconsign.dblite+.tags*+**/.vagrant/+**/DerivedData/+Icon?+**/Pods/+**/.symlinks/+profile+xcuserdata+**/.generated/+Flutter/App.framework+Flutter/Flutter.framework+Flutter/Flutter.podspec+Flutter/Generated.xcconfig+Flutter/ephemeral/+Flutter/app.flx+Flutter/app.zip+Flutter/flutter_assets/+Flutter/flutter_export_environment.sh+ServiceDefinitions.json+Runner/GeneratedPluginRegistrant.*++# Exceptions to above rules.+!default.mode1v3+!default.mode2v3+!default.pbxuser+!default.perspectivev3diff --git a/example/ios/Flutter/AppFrameworkInfo.plist b/example/ios/Flutter/AppFrameworkInfo.plistnew file mode 100644index 0000000..391a902--- /dev/null+++ b/example/ios/Flutter/AppFrameworkInfo.plist@@ -0,0 +1,24 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleDevelopmentRegion</key>+ <string>en</string>+ <key>CFBundleExecutable</key>+ <string>App</string>+ <key>CFBundleIdentifier</key>+ <string>io.flutter.flutter.app</string>+ <key>CFBundleInfoDictionaryVersion</key>+ <string>6.0</string>+ <key>CFBundleName</key>+ <string>App</string>+ <key>CFBundlePackageType</key>+ <string>FMWK</string>+ <key>CFBundleShortVersionString</key>+ <string>1.0</string>+ <key>CFBundleSignature</key>+ <string>????</string>+ <key>CFBundleVersion</key>+ <string>1.0</string>+</dict>+</plist>diff --git a/example/ios/Flutter/Debug.xcconfig b/example/ios/Flutter/Debug.xcconfignew file mode 100644index 0000000..592ceee--- /dev/null+++ b/example/ios/Flutter/Debug.xcconfig@@ -0,0 +1 @@+#include "Generated.xcconfig"diff --git a/example/ios/Flutter/Release.xcconfig b/example/ios/Flutter/Release.xcconfignew file mode 100644index 0000000..592ceee--- /dev/null+++ b/example/ios/Flutter/Release.xcconfig@@ -0,0 +1 @@+#include "Generated.xcconfig"diff --git a/example/ios/Runner.xcodeproj/project.pbxproj b/example/ios/Runner.xcodeproj/project.pbxprojnew file mode 100644index 0000000..89f0feb--- /dev/null+++ b/example/ios/Runner.xcodeproj/project.pbxproj@@ -0,0 +1,644 @@+// !$*UTF8*$!+{+ archiveVersion = 1;+ classes = {+ };+ objectVersion = 54;+ objects = {++/* Begin PBXBuildFile section */+ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; };+ 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; };+ 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };+ 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };+ 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; };+ 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; };+ 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };+ 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; };+ 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };+/* End PBXBuildFile section */++/* Begin PBXContainerItemProxy section */+ 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = {+ isa = PBXContainerItemProxy;+ containerPortal = 97C146E61CF9000F007C117D /* Project object */;+ proxyType = 1;+ remoteGlobalIDString = 97C146ED1CF9000F007C117D;+ remoteInfo = Runner;+ };+/* End PBXContainerItemProxy section */++/* Begin PBXCopyFilesBuildPhase section */+ 9705A1C41CF9048500538489 /* Embed Frameworks */ = {+ isa = PBXCopyFilesBuildPhase;+ buildActionMask = 2147483647;+ dstPath = "";+ dstSubfolderSpec = 10;+ files = (+ );+ name = "Embed Frameworks";+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXCopyFilesBuildPhase section */++/* Begin PBXFileReference section */+ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = "<group>"; };+ 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = "<group>"; };+ 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = "<group>"; };+ 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };+ 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = "<group>"; };+ 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = "<group>"; };+ 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };+ 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };+ 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = "<group>"; };+ 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };+ 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = "<group>"; };+ 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = "<group>"; };+ 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; };+ 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };+ 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };+ 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };+ 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };+/* End PBXFileReference section */++/* Begin PBXFrameworksBuildPhase section */+ 97C146EB1CF9000F007C117D /* Frameworks */ = {+ isa = PBXFrameworksBuildPhase;+ buildActionMask = 2147483647;+ files = (+ 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXFrameworksBuildPhase section */++/* Begin PBXGroup section */+ 331C8082294A63A400263BE5 /* RunnerTests */ = {+ isa = PBXGroup;+ children = (+ 331C807B294A618700263BE5 /* RunnerTests.swift */,+ );+ path = RunnerTests;+ sourceTree = "<group>";+ };+ 9740EEB11CF90186004384FC /* Flutter */ = {+ isa = PBXGroup;+ children = (+ 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */,+ 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */,+ 9740EEB21CF90195004384FC /* Debug.xcconfig */,+ 7AFA3C8E1D35360C0083082E /* Release.xcconfig */,+ 9740EEB31CF90195004384FC /* Generated.xcconfig */,+ );+ name = Flutter;+ sourceTree = "<group>";+ };+ 97C146E51CF9000F007C117D = {+ isa = PBXGroup;+ children = (+ 9740EEB11CF90186004384FC /* Flutter */,+ 97C146F01CF9000F007C117D /* Runner */,+ 97C146EF1CF9000F007C117D /* Products */,+ 331C8082294A63A400263BE5 /* RunnerTests */,+ );+ sourceTree = "<group>";+ };+ 97C146EF1CF9000F007C117D /* Products */ = {+ isa = PBXGroup;+ children = (+ 97C146EE1CF9000F007C117D /* Runner.app */,+ 331C8081294A63A400263BE5 /* RunnerTests.xctest */,+ );+ name = Products;+ sourceTree = "<group>";+ };+ 97C146F01CF9000F007C117D /* Runner */ = {+ isa = PBXGroup;+ children = (+ 97C146FA1CF9000F007C117D /* Main.storyboard */,+ 97C146FD1CF9000F007C117D /* Assets.xcassets */,+ 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */,+ 97C147021CF9000F007C117D /* Info.plist */,+ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */,+ 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */,+ 74858FAE1ED2DC5600515810 /* AppDelegate.swift */,+ 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */,+ 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */,+ );+ path = Runner;+ sourceTree = "<group>";+ };+/* End PBXGroup section */++/* Begin PBXNativeTarget section */+ 331C8080294A63A400263BE5 /* RunnerTests */ = {+ isa = PBXNativeTarget;+ buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */;+ buildPhases = (+ 331C807D294A63A400263BE5 /* Sources */,+ 331C807F294A63A400263BE5 /* Resources */,+ );+ buildRules = (+ );+ dependencies = (+ 331C8086294A63A400263BE5 /* PBXTargetDependency */,+ );+ name = RunnerTests;+ productName = RunnerTests;+ productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */;+ productType = "com.apple.product-type.bundle.unit-test";+ };+ 97C146ED1CF9000F007C117D /* Runner */ = {+ isa = PBXNativeTarget;+ buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */;+ buildPhases = (+ 9740EEB61CF901F6004384FC /* Run Script */,+ 97C146EA1CF9000F007C117D /* Sources */,+ 97C146EB1CF9000F007C117D /* Frameworks */,+ 97C146EC1CF9000F007C117D /* Resources */,+ 9705A1C41CF9048500538489 /* Embed Frameworks */,+ 3B06AD1E1E4923F5004D2608 /* Thin Binary */,+ );+ buildRules = (+ );+ dependencies = (+ );+ name = Runner;+ packageProductDependencies = (+ 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */,+ );+ productName = Runner;+ productReference = 97C146EE1CF9000F007C117D /* Runner.app */;+ productType = "com.apple.product-type.application";+ };+/* End PBXNativeTarget section */++/* Begin PBXProject section */+ 97C146E61CF9000F007C117D /* Project object */ = {+ isa = PBXProject;+ attributes = {+ BuildIndependentTargetsInParallel = YES;+ LastUpgradeCheck = 1510;+ ORGANIZATIONNAME = "";+ TargetAttributes = {+ 331C8080294A63A400263BE5 = {+ CreatedOnToolsVersion = 14.0;+ TestTargetID = 97C146ED1CF9000F007C117D;+ };+ 97C146ED1CF9000F007C117D = {+ CreatedOnToolsVersion = 7.3.1;+ LastSwiftMigration = 1100;+ };+ };+ };+ buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */;+ compatibilityVersion = "Xcode 9.3";+ developmentRegion = en;+ hasScannedForEncodings = 0;+ knownRegions = (+ en,+ Base,+ );+ mainGroup = 97C146E51CF9000F007C117D;+ packageReferences = (+ 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */,+ );+ productRefGroup = 97C146EF1CF9000F007C117D /* Products */;+ projectDirPath = "";+ projectRoot = "";+ targets = (+ 97C146ED1CF9000F007C117D /* Runner */,+ 331C8080294A63A400263BE5 /* RunnerTests */,+ );+ };+/* End PBXProject section */++/* Begin PBXResourcesBuildPhase section */+ 331C807F294A63A400263BE5 /* Resources */ = {+ isa = PBXResourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ 97C146EC1CF9000F007C117D /* Resources */ = {+ isa = PBXResourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */,+ 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */,+ 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */,+ 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXResourcesBuildPhase section */++/* Begin PBXShellScriptBuildPhase section */+ 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = {+ isa = PBXShellScriptBuildPhase;+ alwaysOutOfDate = 1;+ buildActionMask = 2147483647;+ files = (+ );+ inputPaths = (+ "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}",+ );+ name = "Thin Binary";+ outputPaths = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ shellPath = /bin/sh;+ shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin";+ };+ 9740EEB61CF901F6004384FC /* Run Script */ = {+ isa = PBXShellScriptBuildPhase;+ alwaysOutOfDate = 1;+ buildActionMask = 2147483647;+ files = (+ );+ inputPaths = (+ );+ name = "Run Script";+ outputPaths = (+ );+ runOnlyForDeploymentPostprocessing = 0;+ shellPath = /bin/sh;+ shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build";+ };+/* End PBXShellScriptBuildPhase section */++/* Begin PBXSourcesBuildPhase section */+ 331C807D294A63A400263BE5 /* Sources */ = {+ isa = PBXSourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ 97C146EA1CF9000F007C117D /* Sources */ = {+ isa = PBXSourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */,+ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,+ 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXSourcesBuildPhase section */++/* Begin PBXTargetDependency section */+ 331C8086294A63A400263BE5 /* PBXTargetDependency */ = {+ isa = PBXTargetDependency;+ target = 97C146ED1CF9000F007C117D /* Runner */;+ targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */;+ };+/* End PBXTargetDependency section */++/* Begin PBXVariantGroup section */+ 97C146FA1CF9000F007C117D /* Main.storyboard */ = {+ isa = PBXVariantGroup;+ children = (+ 97C146FB1CF9000F007C117D /* Base */,+ );+ name = Main.storyboard;+ sourceTree = "<group>";+ };+ 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = {+ isa = PBXVariantGroup;+ children = (+ 97C147001CF9000F007C117D /* Base */,+ );+ name = LaunchScreen.storyboard;+ sourceTree = "<group>";+ };+/* End PBXVariantGroup section */++/* Begin XCBuildConfiguration section */+ 249021D3217E4FDB00AE95B9 /* Profile */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ALWAYS_SEARCH_USER_PATHS = NO;+ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;+ CLANG_ANALYZER_NONNULL = YES;+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";+ CLANG_CXX_LIBRARY = "libc++";+ CLANG_ENABLE_MODULES = YES;+ CLANG_ENABLE_OBJC_ARC = YES;+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;+ CLANG_WARN_BOOL_CONVERSION = YES;+ CLANG_WARN_COMMA = YES;+ CLANG_WARN_CONSTANT_CONVERSION = YES;+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;+ CLANG_WARN_EMPTY_BODY = YES;+ CLANG_WARN_ENUM_CONVERSION = YES;+ CLANG_WARN_INFINITE_RECURSION = YES;+ CLANG_WARN_INT_CONVERSION = YES;+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;+ CLANG_WARN_STRICT_PROTOTYPES = YES;+ CLANG_WARN_SUSPICIOUS_MOVE = YES;+ CLANG_WARN_UNREACHABLE_CODE = YES;+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;+ "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";+ COPY_PHASE_STRIP = NO;+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";+ ENABLE_NS_ASSERTIONS = NO;+ ENABLE_STRICT_OBJC_MSGSEND = YES;+ ENABLE_USER_SCRIPT_SANDBOXING = NO;+ GCC_C_LANGUAGE_STANDARD = gnu99;+ GCC_NO_COMMON_BLOCKS = YES;+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;+ GCC_WARN_UNDECLARED_SELECTOR = YES;+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;+ GCC_WARN_UNUSED_FUNCTION = YES;+ GCC_WARN_UNUSED_VARIABLE = YES;+ IPHONEOS_DEPLOYMENT_TARGET = 13.0;+ MTL_ENABLE_DEBUG_INFO = NO;+ SDKROOT = iphoneos;+ SUPPORTED_PLATFORMS = iphoneos;+ TARGETED_DEVICE_FAMILY = "1,2";+ VALIDATE_PRODUCT = YES;+ };+ name = Profile;+ };+ 249021D4217E4FDB00AE95B9 /* Profile */ = {+ isa = XCBuildConfiguration;+ baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;+ buildSettings = {+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;+ CLANG_ENABLE_MODULES = YES;+ CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";+ ENABLE_BITCODE = NO;+ INFOPLIST_FILE = Runner/Info.plist;+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/Frameworks",+ );+ PRODUCT_BUNDLE_IDENTIFIER = com.vmodal.sdk.vmodalExample;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";+ SWIFT_VERSION = 5.0;+ VERSIONING_SYSTEM = "apple-generic";+ };+ name = Profile;+ };+ 331C8088294A63A400263BE5 /* Debug */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ BUNDLE_LOADER = "$(TEST_HOST)";+ CODE_SIGN_STYLE = Automatic;+ CURRENT_PROJECT_VERSION = 1;+ GENERATE_INFOPLIST_FILE = YES;+ MARKETING_VERSION = 1.0;+ PRODUCT_BUNDLE_IDENTIFIER = com.vmodal.sdk.vmodalExample.RunnerTests;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;+ SWIFT_OPTIMIZATION_LEVEL = "-Onone";+ SWIFT_VERSION = 5.0;+ TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner";+ };+ name = Debug;+ };+ 331C8089294A63A400263BE5 /* Release */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ BUNDLE_LOADER = "$(TEST_HOST)";+ CODE_SIGN_STYLE = Automatic;+ CURRENT_PROJECT_VERSION = 1;+ GENERATE_INFOPLIST_FILE = YES;+ MARKETING_VERSION = 1.0;+ PRODUCT_BUNDLE_IDENTIFIER = com.vmodal.sdk.vmodalExample.RunnerTests;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SWIFT_VERSION = 5.0;+ TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner";+ };+ name = Release;+ };+ 331C808A294A63A400263BE5 /* Profile */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ BUNDLE_LOADER = "$(TEST_HOST)";+ CODE_SIGN_STYLE = Automatic;+ CURRENT_PROJECT_VERSION = 1;+ GENERATE_INFOPLIST_FILE = YES;+ MARKETING_VERSION = 1.0;+ PRODUCT_BUNDLE_IDENTIFIER = com.vmodal.sdk.vmodalExample.RunnerTests;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SWIFT_VERSION = 5.0;+ TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner";+ };+ name = Profile;+ };+ 97C147031CF9000F007C117D /* Debug */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ALWAYS_SEARCH_USER_PATHS = NO;+ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;+ CLANG_ANALYZER_NONNULL = YES;+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";+ CLANG_CXX_LIBRARY = "libc++";+ CLANG_ENABLE_MODULES = YES;+ CLANG_ENABLE_OBJC_ARC = YES;+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;+ CLANG_WARN_BOOL_CONVERSION = YES;+ CLANG_WARN_COMMA = YES;+ CLANG_WARN_CONSTANT_CONVERSION = YES;+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;+ CLANG_WARN_EMPTY_BODY = YES;+ CLANG_WARN_ENUM_CONVERSION = YES;+ CLANG_WARN_INFINITE_RECURSION = YES;+ CLANG_WARN_INT_CONVERSION = YES;+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;+ CLANG_WARN_STRICT_PROTOTYPES = YES;+ CLANG_WARN_SUSPICIOUS_MOVE = YES;+ CLANG_WARN_UNREACHABLE_CODE = YES;+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;+ "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";+ COPY_PHASE_STRIP = NO;+ DEBUG_INFORMATION_FORMAT = dwarf;+ ENABLE_STRICT_OBJC_MSGSEND = YES;+ ENABLE_TESTABILITY = YES;+ ENABLE_USER_SCRIPT_SANDBOXING = NO;+ GCC_C_LANGUAGE_STANDARD = gnu99;+ GCC_DYNAMIC_NO_PIC = NO;+ GCC_NO_COMMON_BLOCKS = YES;+ GCC_OPTIMIZATION_LEVEL = 0;+ GCC_PREPROCESSOR_DEFINITIONS = (+ "DEBUG=1",+ "$(inherited)",+ );+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;+ GCC_WARN_UNDECLARED_SELECTOR = YES;+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;+ GCC_WARN_UNUSED_FUNCTION = YES;+ GCC_WARN_UNUSED_VARIABLE = YES;+ IPHONEOS_DEPLOYMENT_TARGET = 13.0;+ MTL_ENABLE_DEBUG_INFO = YES;+ ONLY_ACTIVE_ARCH = YES;+ SDKROOT = iphoneos;+ TARGETED_DEVICE_FAMILY = "1,2";+ };+ name = Debug;+ };+ 97C147041CF9000F007C117D /* Release */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ALWAYS_SEARCH_USER_PATHS = NO;+ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;+ CLANG_ANALYZER_NONNULL = YES;+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";+ CLANG_CXX_LIBRARY = "libc++";+ CLANG_ENABLE_MODULES = YES;+ CLANG_ENABLE_OBJC_ARC = YES;+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;+ CLANG_WARN_BOOL_CONVERSION = YES;+ CLANG_WARN_COMMA = YES;+ CLANG_WARN_CONSTANT_CONVERSION = YES;+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;+ CLANG_WARN_EMPTY_BODY = YES;+ CLANG_WARN_ENUM_CONVERSION = YES;+ CLANG_WARN_INFINITE_RECURSION = YES;+ CLANG_WARN_INT_CONVERSION = YES;+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;+ CLANG_WARN_STRICT_PROTOTYPES = YES;+ CLANG_WARN_SUSPICIOUS_MOVE = YES;+ CLANG_WARN_UNREACHABLE_CODE = YES;+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;+ "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";+ COPY_PHASE_STRIP = NO;+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";+ ENABLE_NS_ASSERTIONS = NO;+ ENABLE_STRICT_OBJC_MSGSEND = YES;+ ENABLE_USER_SCRIPT_SANDBOXING = NO;+ GCC_C_LANGUAGE_STANDARD = gnu99;+ GCC_NO_COMMON_BLOCKS = YES;+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;+ GCC_WARN_UNDECLARED_SELECTOR = YES;+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;+ GCC_WARN_UNUSED_FUNCTION = YES;+ GCC_WARN_UNUSED_VARIABLE = YES;+ IPHONEOS_DEPLOYMENT_TARGET = 13.0;+ MTL_ENABLE_DEBUG_INFO = NO;+ SDKROOT = iphoneos;+ SUPPORTED_PLATFORMS = iphoneos;+ SWIFT_COMPILATION_MODE = wholemodule;+ SWIFT_OPTIMIZATION_LEVEL = "-O";+ TARGETED_DEVICE_FAMILY = "1,2";+ VALIDATE_PRODUCT = YES;+ };+ name = Release;+ };+ 97C147061CF9000F007C117D /* Debug */ = {+ isa = XCBuildConfiguration;+ baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */;+ buildSettings = {+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;+ CLANG_ENABLE_MODULES = YES;+ CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";+ ENABLE_BITCODE = NO;+ INFOPLIST_FILE = Runner/Info.plist;+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/Frameworks",+ );+ PRODUCT_BUNDLE_IDENTIFIER = com.vmodal.sdk.vmodalExample;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";+ SWIFT_OPTIMIZATION_LEVEL = "-Onone";+ SWIFT_VERSION = 5.0;+ VERSIONING_SYSTEM = "apple-generic";+ };+ name = Debug;+ };+ 97C147071CF9000F007C117D /* Release */ = {+ isa = XCBuildConfiguration;+ baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;+ buildSettings = {+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;+ CLANG_ENABLE_MODULES = YES;+ CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";+ ENABLE_BITCODE = NO;+ INFOPLIST_FILE = Runner/Info.plist;+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/Frameworks",+ );+ PRODUCT_BUNDLE_IDENTIFIER = com.vmodal.sdk.vmodalExample;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";+ SWIFT_VERSION = 5.0;+ VERSIONING_SYSTEM = "apple-generic";+ };+ name = Release;+ };+/* End XCBuildConfiguration section */++/* Begin XCConfigurationList section */+ 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ 331C8088294A63A400263BE5 /* Debug */,+ 331C8089294A63A400263BE5 /* Release */,+ 331C808A294A63A400263BE5 /* Profile */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Release;+ };+ 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ 97C147031CF9000F007C117D /* Debug */,+ 97C147041CF9000F007C117D /* Release */,+ 249021D3217E4FDB00AE95B9 /* Profile */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Release;+ };+ 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ 97C147061CF9000F007C117D /* Debug */,+ 97C147071CF9000F007C117D /* Release */,+ 249021D4217E4FDB00AE95B9 /* Profile */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Release;+ };+/* End XCConfigurationList section */++/* Begin XCLocalSwiftPackageReference section */+ 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = {+ isa = XCLocalSwiftPackageReference;+ relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage;+ };+/* End XCLocalSwiftPackageReference section */++/* Begin XCSwiftPackageProductDependency section */+ 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = {+ isa = XCSwiftPackageProductDependency;+ productName = FlutterGeneratedPluginSwiftPackage;+ };+/* End XCSwiftPackageProductDependency section */+ };+ rootObject = 97C146E61CF9000F007C117D /* Project object */;+}diff --git a/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedatanew file mode 100644index 0000000..919434a--- /dev/null+++ b/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata@@ -0,0 +1,7 @@+<?xml version="1.0" encoding="UTF-8"?>+<Workspace+ version = "1.0">+ <FileRef+ location = "self:">+ </FileRef>+</Workspace>diff --git a/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plistnew file mode 100644index 0000000..18d9810--- /dev/null+++ b/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>IDEDidComputeMac32BitWarning</key>+ <true/>+</dict>+</plist>diff --git a/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettingsnew file mode 100644index 0000000..f9b0d7c--- /dev/null+++ b/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>PreviewsEnabled</key>+ <false/>+</dict>+</plist>diff --git a/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcschemenew file mode 100644index 0000000..c3fedb2--- /dev/null+++ b/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme@@ -0,0 +1,119 @@+<?xml version="1.0" encoding="UTF-8"?>+<Scheme+ LastUpgradeVersion = "1510"+ version = "1.3">+ <BuildAction+ parallelizeBuildables = "YES"+ buildImplicitDependencies = "YES">+ <PreActions>+ <ExecutionAction+ ActionType = "Xcode.IDEStandardExecutionActionsCore.ExecutionActionType.ShellScriptAction">+ <ActionContent+ title = "Run Prepare Flutter Framework Script"+ scriptText = "/bin/sh "$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" prepare ">+ <EnvironmentBuildable>+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "97C146ED1CF9000F007C117D"+ BuildableName = "Runner.app"+ BlueprintName = "Runner"+ ReferencedContainer = "container:Runner.xcodeproj">+ </BuildableReference>+ </EnvironmentBuildable>+ </ActionContent>+ </ExecutionAction>+ </PreActions>+ <BuildActionEntries>+ <BuildActionEntry+ buildForTesting = "YES"+ buildForRunning = "YES"+ buildForProfiling = "YES"+ buildForArchiving = "YES"+ buildForAnalyzing = "YES">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "97C146ED1CF9000F007C117D"+ BuildableName = "Runner.app"+ BlueprintName = "Runner"+ ReferencedContainer = "container:Runner.xcodeproj">+ </BuildableReference>+ </BuildActionEntry>+ </BuildActionEntries>+ </BuildAction>+ <TestAction+ buildConfiguration = "Debug"+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"+ customLLDBInitFile = "$(SRCROOT)/Flutter/ephemeral/flutter_lldbinit"+ shouldUseLaunchSchemeArgsEnv = "YES">+ <MacroExpansion>+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "97C146ED1CF9000F007C117D"+ BuildableName = "Runner.app"+ BlueprintName = "Runner"+ ReferencedContainer = "container:Runner.xcodeproj">+ </BuildableReference>+ </MacroExpansion>+ <Testables>+ <TestableReference+ skipped = "NO"+ parallelizable = "YES">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "331C8080294A63A400263BE5"+ BuildableName = "RunnerTests.xctest"+ BlueprintName = "RunnerTests"+ ReferencedContainer = "container:Runner.xcodeproj">+ </BuildableReference>+ </TestableReference>+ </Testables>+ </TestAction>+ <LaunchAction+ buildConfiguration = "Debug"+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"+ customLLDBInitFile = "$(SRCROOT)/Flutter/ephemeral/flutter_lldbinit"+ launchStyle = "0"+ useCustomWorkingDirectory = "NO"+ ignoresPersistentStateOnLaunch = "NO"+ debugDocumentVersioning = "YES"+ debugServiceExtension = "internal"+ enableGPUValidationMode = "1"+ allowLocationSimulation = "YES">+ <BuildableProductRunnable+ runnableDebuggingMode = "0">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "97C146ED1CF9000F007C117D"+ BuildableName = "Runner.app"+ BlueprintName = "Runner"+ ReferencedContainer = "container:Runner.xcodeproj">+ </BuildableReference>+ </BuildableProductRunnable>+ </LaunchAction>+ <ProfileAction+ buildConfiguration = "Profile"+ shouldUseLaunchSchemeArgsEnv = "YES"+ savedToolIdentifier = ""+ useCustomWorkingDirectory = "NO"+ debugDocumentVersioning = "YES">+ <BuildableProductRunnable+ runnableDebuggingMode = "0">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "97C146ED1CF9000F007C117D"+ BuildableName = "Runner.app"+ BlueprintName = "Runner"+ ReferencedContainer = "container:Runner.xcodeproj">+ </BuildableReference>+ </BuildableProductRunnable>+ </ProfileAction>+ <AnalyzeAction+ buildConfiguration = "Debug">+ </AnalyzeAction>+ <ArchiveAction+ buildConfiguration = "Release"+ revealArchiveInOrganizer = "YES">+ </ArchiveAction>+</Scheme>diff --git a/example/ios/Runner.xcworkspace/contents.xcworkspacedata b/example/ios/Runner.xcworkspace/contents.xcworkspacedatanew file mode 100644index 0000000..1d526a1--- /dev/null+++ b/example/ios/Runner.xcworkspace/contents.xcworkspacedata@@ -0,0 +1,7 @@+<?xml version="1.0" encoding="UTF-8"?>+<Workspace+ version = "1.0">+ <FileRef+ location = "group:Runner.xcodeproj">+ </FileRef>+</Workspace>diff --git a/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plistnew file mode 100644index 0000000..18d9810--- /dev/null+++ b/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>IDEDidComputeMac32BitWarning</key>+ <true/>+</dict>+</plist>diff --git a/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettingsnew file mode 100644index 0000000..f9b0d7c--- /dev/null+++ b/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>PreviewsEnabled</key>+ <false/>+</dict>+</plist>diff --git a/example/ios/Runner/AppDelegate.swift b/example/ios/Runner/AppDelegate.swiftnew file mode 100644index 0000000..c30b367--- /dev/null+++ b/example/ios/Runner/AppDelegate.swift@@ -0,0 +1,16 @@+import Flutter+import UIKit++@main+@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {+ override func application(+ _ application: UIApplication,+ didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?+ ) -> Bool {+ return super.application(application, didFinishLaunchingWithOptions: launchOptions)+ }++ func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {+ GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)+ }+}diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.jsonnew file mode 100644index 0000000..d36b1fa--- /dev/null+++ b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json@@ -0,0 +1,122 @@+{+ "images" : [+ {+ "size" : "20x20",+ "idiom" : "iphone",+ "filename" : "[email protected]",+ "scale" : "2x"+ },+ {+ "size" : "20x20",+ "idiom" : "iphone",+ "filename" : "[email protected]",+ "scale" : "3x"+ },+ {+ "size" : "29x29",+ "idiom" : "iphone",+ "filename" : "[email protected]",+ "scale" : "1x"+ },+ {+ "size" : "29x29",+ "idiom" : "iphone",+ "filename" : "[email protected]",+ "scale" : "2x"+ },+ {+ "size" : "29x29",+ "idiom" : "iphone",+ "filename" : "[email protected]",+ "scale" : "3x"+ },+ {+ "size" : "40x40",+ "idiom" : "iphone",+ "filename" : "[email protected]",+ "scale" : "2x"+ },+ {+ "size" : "40x40",+ "idiom" : "iphone",+ "filename" : "[email protected]",+ "scale" : "3x"+ },+ {+ "size" : "60x60",+ "idiom" : "iphone",+ "filename" : "[email protected]",+ "scale" : "2x"+ },+ {+ "size" : "60x60",+ "idiom" : "iphone",+ "filename" : "[email protected]",+ "scale" : "3x"+ },+ {+ "size" : "20x20",+ "idiom" : "ipad",+ "filename" : "[email protected]",+ "scale" : "1x"+ },+ {+ "size" : "20x20",+ "idiom" : "ipad",+ "filename" : "[email protected]",+ "scale" : "2x"+ },+ {+ "size" : "29x29",+ "idiom" : "ipad",+ "filename" : "[email protected]",+ "scale" : "1x"+ },+ {+ "size" : "29x29",+ "idiom" : "ipad",+ "filename" : "[email protected]",+ "scale" : "2x"+ },+ {+ "size" : "40x40",+ "idiom" : "ipad",+ "filename" : "[email protected]",+ "scale" : "1x"+ },+ {+ "size" : "40x40",+ "idiom" : "ipad",+ "filename" : "[email protected]",+ "scale" : "2x"+ },+ {+ "size" : "76x76",+ "idiom" : "ipad",+ "filename" : "[email protected]",+ "scale" : "1x"+ },+ {+ "size" : "76x76",+ "idiom" : "ipad",+ "filename" : "[email protected]",+ "scale" : "2x"+ },+ {+ "size" : "83.5x83.5",+ "idiom" : "ipad",+ "filename" : "[email protected]",+ "scale" : "2x"+ },+ {+ "size" : "1024x1024",+ "idiom" : "ios-marketing",+ "filename" : "[email protected]",+ "scale" : "1x"+ }+ ],+ "info" : {+ "version" : 1,+ "author" : "xcode"+ }+}diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 0000000..dc9ada4Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 0000000..7353c41Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 0000000..797d452Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 0000000..6ed2d93Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 0000000..4cd7b00Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 0000000..fe73094Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 0000000..321773cBinary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 0000000..797d452Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 0000000..502f463Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 0000000..0ec3034Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 0000000..0ec3034Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 0000000..e9f5feaBinary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 0000000..84ac32aBinary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 0000000..8953cbaBinary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 0000000..0467bf1Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.jsonnew file mode 100644index 0000000..0bedcf2--- /dev/null+++ b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json@@ -0,0 +1,23 @@+{+ "images" : [+ {+ "idiom" : "universal",+ "filename" : "LaunchImage.png",+ "scale" : "1x"+ },+ {+ "idiom" : "universal",+ "filename" : "[email protected]",+ "scale" : "2x"+ },+ {+ "idiom" : "universal",+ "filename" : "[email protected]",+ "scale" : "3x"+ }+ ],+ "info" : {+ "version" : 1,+ "author" : "xcode"+ }+}diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.pngnew file mode 100644index 0000000..9da19eaBinary files /dev/null and b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differdiff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/[email protected] b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/[email protected]new file mode 100644index 0000000..9da19eaBinary files /dev/null and b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/[email protected] differdiff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/[email protected] b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/[email protected]new file mode 100644index 0000000..9da19eaBinary files /dev/null and b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/[email protected] differdiff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.mdnew file mode 100644index 0000000..89c2725--- /dev/null+++ b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md@@ -0,0 +1,5 @@+# Launch Screen Assets++You can customize the launch screen with your own desired assets by replacing the image files in this directory.++You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images.\ No newline at end of filediff --git a/example/ios/Runner/Base.lproj/LaunchScreen.storyboard b/example/ios/Runner/Base.lproj/LaunchScreen.storyboardnew file mode 100644index 0000000..f2e259c--- /dev/null+++ b/example/ios/Runner/Base.lproj/LaunchScreen.storyboard@@ -0,0 +1,37 @@+<?xml version="1.0" encoding="UTF-8" standalone="no"?>+<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12121" systemVersion="16G29" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" colorMatched="YES" initialViewController="01J-lp-oVM">+ <dependencies>+ <deployment identifier="iOS"/>+ <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/>+ </dependencies>+ <scenes>+ <!--View Controller-->+ <scene sceneID="EHf-IW-A2E">+ <objects>+ <viewController id="01J-lp-oVM" sceneMemberID="viewController">+ <layoutGuides>+ <viewControllerLayoutGuide type="top" id="Ydg-fD-yQy"/>+ <viewControllerLayoutGuide type="bottom" id="xbc-2k-c8Z"/>+ </layoutGuides>+ <view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">+ <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>+ <subviews>+ <imageView opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" image="LaunchImage" translatesAutoresizingMaskIntoConstraints="NO" id="YRO-k0-Ey4">+ </imageView>+ </subviews>+ <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>+ <constraints>+ <constraint firstItem="YRO-k0-Ey4" firstAttribute="centerX" secondItem="Ze5-6b-2t3" secondAttribute="centerX" id="1a2-6s-vTC"/>+ <constraint firstItem="YRO-k0-Ey4" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="centerY" id="4X2-HB-R7a"/>+ </constraints>+ </view>+ </viewController>+ <placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>+ </objects>+ <point key="canvasLocation" x="53" y="375"/>+ </scene>+ </scenes>+ <resources>+ <image name="LaunchImage" width="168" height="185"/>+ </resources>+</document>diff --git a/example/ios/Runner/Base.lproj/Main.storyboard b/example/ios/Runner/Base.lproj/Main.storyboardnew file mode 100644index 0000000..f3c2851--- /dev/null+++ b/example/ios/Runner/Base.lproj/Main.storyboard@@ -0,0 +1,26 @@+<?xml version="1.0" encoding="UTF-8" standalone="no"?>+<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10117" systemVersion="15F34" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="BYZ-38-t0r">+ <dependencies>+ <deployment identifier="iOS"/>+ <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>+ </dependencies>+ <scenes>+ <!--Flutter View Controller-->+ <scene sceneID="tne-QT-ifu">+ <objects>+ <viewController id="BYZ-38-t0r" customClass="FlutterViewController" sceneMemberID="viewController">+ <layoutGuides>+ <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>+ <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>+ </layoutGuides>+ <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">+ <rect key="frame" x="0.0" y="0.0" width="600" height="600"/>+ <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>+ <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>+ </view>+ </viewController>+ <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>+ </objects>+ </scene>+ </scenes>+</document>diff --git a/example/ios/Runner/Info.plist b/example/ios/Runner/Info.plistnew file mode 100644index 0000000..e836e36--- /dev/null+++ b/example/ios/Runner/Info.plist@@ -0,0 +1,70 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CADisableMinimumFrameDurationOnPhone</key>+ <true/>+ <key>CFBundleDevelopmentRegion</key>+ <string>$(DEVELOPMENT_LANGUAGE)</string>+ <key>CFBundleDisplayName</key>+ <string>Vmodal Example</string>+ <key>CFBundleExecutable</key>+ <string>$(EXECUTABLE_NAME)</string>+ <key>CFBundleIdentifier</key>+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>+ <key>CFBundleInfoDictionaryVersion</key>+ <string>6.0</string>+ <key>CFBundleName</key>+ <string>vmodal_example</string>+ <key>CFBundlePackageType</key>+ <string>APPL</string>+ <key>CFBundleShortVersionString</key>+ <string>$(FLUTTER_BUILD_NAME)</string>+ <key>CFBundleSignature</key>+ <string>????</string>+ <key>CFBundleVersion</key>+ <string>$(FLUTTER_BUILD_NUMBER)</string>+ <key>LSRequiresIPhoneOS</key>+ <true/>+ <key>UIApplicationSceneManifest</key>+ <dict>+ <key>UIApplicationSupportsMultipleScenes</key>+ <false/>+ <key>UISceneConfigurations</key>+ <dict>+ <key>UIWindowSceneSessionRoleApplication</key>+ <array>+ <dict>+ <key>UISceneClassName</key>+ <string>UIWindowScene</string>+ <key>UISceneConfigurationName</key>+ <string>flutter</string>+ <key>UISceneDelegateClassName</key>+ <string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>+ <key>UISceneStoryboardFile</key>+ <string>Main</string>+ </dict>+ </array>+ </dict>+ </dict>+ <key>UIApplicationSupportsIndirectInputEvents</key>+ <true/>+ <key>UILaunchStoryboardName</key>+ <string>LaunchScreen</string>+ <key>UIMainStoryboardFile</key>+ <string>Main</string>+ <key>UISupportedInterfaceOrientations</key>+ <array>+ <string>UIInterfaceOrientationPortrait</string>+ <string>UIInterfaceOrientationLandscapeLeft</string>+ <string>UIInterfaceOrientationLandscapeRight</string>+ </array>+ <key>UISupportedInterfaceOrientations~ipad</key>+ <array>+ <string>UIInterfaceOrientationPortrait</string>+ <string>UIInterfaceOrientationPortraitUpsideDown</string>+ <string>UIInterfaceOrientationLandscapeLeft</string>+ <string>UIInterfaceOrientationLandscapeRight</string>+ </array>+</dict>+</plist>diff --git a/example/ios/Runner/Runner-Bridging-Header.h b/example/ios/Runner/Runner-Bridging-Header.hnew file mode 100644index 0000000..308a2a5--- /dev/null+++ b/example/ios/Runner/Runner-Bridging-Header.h@@ -0,0 +1 @@+#import "GeneratedPluginRegistrant.h"diff --git a/example/ios/Runner/SceneDelegate.swift b/example/ios/Runner/SceneDelegate.swiftnew file mode 100644index 0000000..b9ce8ea--- /dev/null+++ b/example/ios/Runner/SceneDelegate.swift@@ -0,0 +1,6 @@+import Flutter+import UIKit++class SceneDelegate: FlutterSceneDelegate {++}diff --git a/example/ios/RunnerTests/RunnerTests.swift b/example/ios/RunnerTests/RunnerTests.swiftnew file mode 100644index 0000000..86a7c3b--- /dev/null+++ b/example/ios/RunnerTests/RunnerTests.swift@@ -0,0 +1,12 @@+import Flutter+import UIKit+import XCTest++class RunnerTests: XCTestCase {++ func testExample() {+ // If you add code to the Runner application, consider adding tests here.+ // See https://developer.apple.com/documentation/xctest for more information about using XCTest.+ }++}diff --git a/example/lib/main.dart b/example/lib/main.dartnew file mode 100644index 0000000..e1c1615--- /dev/null+++ b/example/lib/main.dart@@ -0,0 +1,202 @@+import 'dart:async';+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';++void main() => runApp(const VmodalExampleApp());++class VmodalExampleApp extends StatefulWidget {+ const VmodalExampleApp({super.key});++ @override+ State<VmodalExampleApp> createState() => _VmodalExampleAppState();+}++class _VmodalExampleAppState extends State<VmodalExampleApp> {+ final _key = TextEditingController();+ final _query = TextEditingController(text: 'red bicycle');+ final _path = TextEditingController();+ MutableApiKeyProvider? _keys;+ VmodalClient? _client;+ UploadTask<VideoUploadResponse>? _upload;+ StreamSubscription<UploadProgress>? _progressSub;+ String _status =+ 'Enter a runtime API key supplied by your authenticated app.';+ int _progress = 0;+ bool _busy = false;++ Future<void> _connect() async {+ final value = _key.text.trim();+ if (value.isEmpty) {+ _safeState(() => _status = 'A runtime API key is required.');+ return;+ }+ _keys?.clear();+ await _client?.close();+ final keys = MutableApiKeyProvider(value);+ final client = VmodalClient(config: SdkConfig(apiKeyProvider: keys));+ _keys = keys;+ _client = client;+ _safeState(() {+ _key.clear();+ _status = 'Client configured. Resolve identity or search next.';+ });+ }++ Future<void> _identity() async {+ final client = _client;+ if (client == null) return _needClient();+ await _run(() async {+ final me = await client.auth.me();+ _safeState(() => _status = 'Authenticated user type: ${me.type}');+ });+ }++ Future<void> _search() async {+ final client = _client;+ if (client == null) return _needClient();+ await _run(() async {+ final result = await client.searches.searchVideo(+ SearchRequest(queryText: _query.text.trim()),+ );+ _safeState(() => _status = 'Search returned ${result.cntActual} items.');+ });+ }++ Future<void> _startUpload() async {+ final client = _client;+ if (client == null) return _needClient();+ final file = File(_path.text.trim());+ if (!file.existsSync()) {+ _safeState(() => _status = 'Select an app-accessible file first.');+ return;+ }+ final task = client.collections.videoUpload(+ UploadSource.fromFile(file),+ collectionName: 'flutter_example',+ subCollectionName: 'astream',+ );+ _upload = task;+ await _progressSub?.cancel();+ _progressSub = task.progress.listen((UploadProgress value) {+ _safeState(() => _progress = value.percent);+ });+ _safeState(() {+ _busy = true;+ _progress = 0;+ _status = 'Uploading with signed single upload...';+ });+ try {+ final result = await task.result;+ _safeState(() {+ _progress = 100;+ _status = 'Upload complete: ${result.fileName}';+ });+ } on OperationCanceled {+ _safeState(() => _status = 'Upload canceled.');+ } on SdkException catch (error) {+ _safeState(() => _status = error.toString());+ } finally {+ _safeState(() => _busy = false);+ }+ }++ void _cancelUpload() => _upload?.cancel();++ Future<void> _run(Future<void> Function() action) async {+ _safeState(() => _busy = true);+ try {+ await action();+ } on SdkException catch (error) {+ _safeState(() => _status = error.toString());+ } finally {+ _safeState(() => _busy = false);+ }+ }++ void _needClient() {+ _safeState(() => _status = 'Configure the client first.');+ }++ void _safeState(VoidCallback change) {+ if (mounted) setState(change);+ }++ @override+ void dispose() {+ _upload?.cancel();+ unawaited(_progressSub?.cancel());+ _keys?.clear();+ unawaited(_client?.close());+ _key.dispose();+ _query.dispose();+ _path.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) => MaterialApp(+ title: 'VModal SDK Example',+ theme: ThemeData(colorSchemeSeed: Colors.indigo),+ home: Scaffold(+ appBar: AppBar(title: const Text('VModal Flutter SDK')),+ body: ListView(+ padding: const EdgeInsets.all(16),+ children: <Widget>[+ TextField(+ controller: _key,+ obscureText: true,+ decoration: const InputDecoration(+ labelText: 'Runtime API key',+ helperText: 'Injected by the parent app; never committed.',+ ),+ ),+ FilledButton(+ onPressed: _busy ? null : _connect,+ child: const Text('Configure client'),+ ),+ const Divider(),+ FilledButton(+ onPressed: _busy ? null : _identity,+ child: const Text('Resolve auth.me'),+ ),+ TextField(+ controller: _query,+ decoration: const InputDecoration(labelText: 'Search query'),+ ),+ FilledButton(+ onPressed: _busy ? null : _search,+ child: const Text('Search'),+ ),+ const Divider(),+ TextField(+ controller: _path,+ decoration: const InputDecoration(+ labelText: 'App-accessible file path',+ helperText: 'A picker adapter belongs to the parent app.',+ ),+ ),+ LinearProgressIndicator(value: _progress / 100),+ Row(+ children: <Widget>[+ Expanded(+ child: FilledButton(+ onPressed: _busy ? null : _startUpload,+ child: const Text('Upload'),+ ),+ ),+ const SizedBox(width: 8),+ OutlinedButton(+ onPressed: _cancelUpload,+ child: const Text('Cancel'),+ ),+ ],+ ),+ const SizedBox(height: 16),+ Text(_status, key: const Key('status')),+ ],+ ),+ ),+ );+}diff --git a/example/pubspec.yaml b/example/pubspec.yamlnew file mode 100644index 0000000..6b821ca--- /dev/null+++ b/example/pubspec.yaml@@ -0,0 +1,91 @@+name: vmodal_example+description: "A new Flutter project."+# The following line prevents the package from being accidentally published to+# pub.dev using `flutter pub publish`. This is preferred for private packages.+publish_to: 'none' # Remove this line if you wish to publish to pub.dev++# The following defines the version and build number for your application.+# A version number is three numbers separated by dots, like 1.2.43+# followed by an optional build number separated by a +.+# Both the version and the builder number may be overridden in flutter+# build by specifying --build-name and --build-number, respectively.+# In Android, build-name is used as versionName while build-number used as versionCode.+# Read more about Android versioning at https://developer.android.com/studio/publish/versioning+# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.+# Read more about iOS versioning at+# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html+# In Windows, build-name is used as the major, minor, and patch parts+# of the product and file versions while build-number is used as the build suffix.+version: 1.0.0+1++environment:+ sdk: ^3.12.2++# Dependencies specify other packages that your package needs in order to work.+# To automatically upgrade your package dependencies to the latest versions+# consider running `flutter pub upgrade --major-versions`. Alternatively,+# dependencies can be manually updated by changing the version numbers below to+# the latest version available on pub.dev. To see which dependencies have newer+# versions available, run `flutter pub outdated`.+dependencies:+ flutter:+ sdk: flutter+ vmodal_sdk_flutter:+ path: ..++ # The following adds the Cupertino Icons font to your application.+ # Use with the CupertinoIcons class for iOS style icons.+ cupertino_icons: ^1.0.8++dev_dependencies:+ flutter_test:+ sdk: flutter++ # The "flutter_lints" package below contains a set of recommended lints to+ # encourage good coding practices. The lint set provided by the package is+ # activated in the `analysis_options.yaml` file located at the root of your+ # package. See that file for information about deactivating specific lint+ # rules and activating additional ones.+ flutter_lints: ^6.0.0++# For information on the generic Dart part of this file, see the+# following page: https://dart.dev/tools/pub/pubspec++# The following section is specific to Flutter packages.+flutter:++ # The following line ensures that the Material Icons font is+ # included with your application, so that you can use the icons in+ # the material Icons class.+ uses-material-design: true++ # To add assets to your application, add an assets section, like this:+ # assets:+ # - images/a_dot_burr.jpeg+ # - images/a_dot_ham.jpeg++ # An image asset can refer to one or more resolution-specific "variants", see+ # https://flutter.dev/to/resolution-aware-images++ # For details regarding adding assets from package dependencies, see+ # https://flutter.dev/to/asset-from-package++ # To add custom fonts to your application, add a fonts section here,+ # in this "flutter" section. Each entry in this list should have a+ # "family" key with the font family name, and a "fonts" key with a+ # list giving the asset and other descriptors for the font. For+ # example:+ # fonts:+ # - family: Schyler+ # fonts:+ # - asset: fonts/Schyler-Regular.ttf+ # - asset: fonts/Schyler-Italic.ttf+ # style: italic+ # - family: Trajan Pro+ # fonts:+ # - asset: fonts/TrajanPro.ttf+ # - asset: fonts/TrajanPro_Bold.ttf+ # weight: 700+ #+ # For details regarding fonts from package dependencies,+ # see https://flutter.dev/to/font-from-packagediff --git a/example/test/widget_test.dart b/example/test/widget_test.dartnew file mode 100644index 0000000..0b1b143--- /dev/null+++ b/example/test/widget_test.dart@@ -0,0 +1,14 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:vmodal_example/main.dart';++void main() {+ testWidgets('example requires runtime injection', (+ WidgetTester tester,+ ) async {+ await tester.pumpWidget(const VmodalExampleApp());+ expect(find.textContaining('runtime API key'), findsWidgets);+ expect(find.text('Configure client'), findsOneWidget);+ expect(find.text('Search'), findsOneWidget);+ expect(find.text('Upload'), findsOneWidget);+ });+}diff --git a/install.sh b/install.shnew file mode 100755index 0000000..baa9834--- /dev/null+++ b/install.sh@@ -0,0 +1,196 @@+#!/usr/bin/env bash+help='+ Install or locate the pinned Flutter SDK in a user-owned cache.++ Examples:+ bash install.sh install+ bash install.sh check+ bash install.sh flutter_bin+ bash install.sh dart_bin+'+set -euo pipefail+cd "$(dirname "$0")"++sdk_os_arch() {+ local help='+ ## Usage:+ bash install.sh os_arch+ '+ local os arch+ os="$(uname -s)"+ arch="$(uname -m)"+ case "$os:$arch" in+ Darwin:x86_64) echo 'macos-x64' ;;+ Darwin:arm64) echo 'macos-arm64' ;;+ Linux:x86_64) echo 'linux-x64' ;;+ *) echo "Unsupported Flutter host: $os $arch" >&2; return 2 ;;+ esac+}++sdk_check_sha256() {+ local help='+ ## Usage:+ sdk_check_sha256 FILE EXPECTED_SHA256+ '+ local file="${1:?file required}" expected="${2:?checksum required}" got+ if command -v shasum >/dev/null 2>&1; then+ got="$(shasum -a 256 "$file" | awk '{print $1}')"+ elif command -v sha256sum >/dev/null 2>&1; then+ got="$(sha256sum "$file" | awk '{print $1}')"+ else+ echo 'A SHA-256 utility is required (shasum or sha256sum).' >&2+ return 2+ fi+ [[ "$got" == "$expected" ]] || { echo 'Flutter archive checksum mismatch.' >&2; return 3; }+}++sdk_flutter_version() {+ local help='+ ## Usage:+ sdk_flutter_version+ '+ tr -d '[:space:]' < .flutter-version+}++sdk_cache_root() {+ local help='+ ## Usage:+ sdk_cache_root+ '+ echo "${VMODAL_FLUTTER_CACHE:-${XDG_CACHE_HOME:-$HOME/.cache}/vmodal/flutter}"+}++sdk_binary_version() {+ local help='+ ## Usage:+ sdk_binary_version /path/to/flutter+ '+ "${1:?flutter executable required}" --version --machine 2>/dev/null |+ sed -n 's/.*"frameworkVersion"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' |+ head -n 1+}++sdk_flutter_home() {+ local help='+ ## Usage:+ bash install.sh flutter_home+ '+ local version system cached+ version="$(sdk_flutter_version)"+ if command -v flutter >/dev/null 2>&1; then+ system="$(command -v flutter)"+ if [[ "$(sdk_binary_version "$system")" == "$version" ]]; then+ cd "$(dirname "$system")/.." && pwd+ return+ fi+ fi+ cached="$(sdk_cache_root)/$version/flutter"+ if [[ -x "$cached/bin/flutter" ]] && [[ "$(sdk_binary_version "$cached/bin/flutter")" == "$version" ]]; then+ echo "$cached"+ return+ fi+ echo "Pinned Flutter $version is not installed. Run: bash install.sh install" >&2+ return 1+}++sdk_flutter_bin() {+ local help='+ ## Usage:+ bash install.sh flutter_bin+ '+ echo "$(sdk_flutter_home)/bin/flutter"+}++sdk_dart_bin() {+ local help='+ ## Usage:+ bash install.sh dart_bin+ '+ echo "$(sdk_flutter_home)/bin/dart"+}++sdk_install_flutter() {+ local help='+ ## Usage:+ bash install.sh install_flutter+ '+ local version platform row archive checksum cache final temp bundle url+ version="$(sdk_flutter_version)"+ platform="$(sdk_os_arch)"+ row="$(awk -v v="$version" -v p="$platform" '$1 == v && $2 == p {print $0}' tool/flutter_checksums.txt)"+ [[ -n "$row" ]] || { echo "No reviewed Flutter artifact for $version $platform" >&2; return 2; }+ archive="$(awk '{print $3}' <<<"$row")"+ checksum="$(awk '{print $4}' <<<"$row")"+ cache="$(sdk_cache_root)"+ final="$cache/$version"+ if [[ -x "$final/flutter/bin/flutter" ]] && [[ "$(sdk_binary_version "$final/flutter/bin/flutter")" == "$version" ]]; then+ return+ fi+ command -v curl >/dev/null 2>&1 || { echo 'curl is required.' >&2; return 2; }+ mkdir -p "$cache"+ temp="$(mktemp -d "$cache/.flutter-${version}.XXXXXX")"+ bundle="$temp/$(basename "$archive")"+ trap 'rm -rf "${temp:-}"' RETURN+ url="https://storage.googleapis.com/flutter_infra_release/releases/$archive"+ curl --fail --location --retry 3 --retry-delay 2 --output "$bundle" "$url"+ sdk_check_sha256 "$bundle" "$checksum"+ case "$archive" in+ *.zip) command -v unzip >/dev/null 2>&1; unzip -q "$bundle" -d "$temp/extract" ;;+ *.tar.xz) command -v tar >/dev/null 2>&1; mkdir -p "$temp/extract"; tar -xJf "$bundle" -C "$temp/extract" ;;+ *) echo 'Unsupported Flutter archive format.' >&2; return 2 ;;+ esac+ [[ "$(sdk_binary_version "$temp/extract/flutter/bin/flutter")" == "$version" ]] || {+ echo 'Extracted Flutter version does not match the pin.' >&2+ return 3+ }+ rm -rf "$temp/stage"+ mv "$temp/extract" "$temp/stage"+ rm -rf "$final.partial"+ mv "$temp/stage" "$final.partial"+ rm -rf "$final"+ mv "$final.partial" "$final"+ "$final/flutter/bin/flutter" config --no-analytics >/dev/null+}++sdk_check_tools() {+ local help='+ ## Usage:+ bash install.sh check+ '+ local flutter_bin dart_bin version+ flutter_bin="$(sdk_flutter_bin)"+ dart_bin="$(sdk_dart_bin)"+ version="$(sdk_flutter_version)"+ [[ "$(sdk_binary_version "$flutter_bin")" == "$version" ]] || { echo 'Flutter version mismatch.' >&2; return 3; }+ "$dart_bin" --version+ "$flutter_bin" pub get+}++sdk_install() {+ local help='+ ## Usage:+ bash install.sh install+ '+ sdk_install_flutter+ sdk_check_tools+}++sdk_help() {+ local help='+ ## Usage:+ bash install.sh help+ '+ echo "$help"+}++case "${1:-help}" in+ install) sdk_install ;;+ install_flutter) sdk_install_flutter ;;+ check) sdk_check_tools ;;+ flutter_home) sdk_flutter_home ;;+ flutter_bin) sdk_flutter_bin ;;+ dart_bin) sdk_dart_bin ;;+ os_arch) sdk_os_arch ;;+ help|-h|--help) sdk_help ;;+ *) echo "Unknown command: ${1:-}" >&2; echo "$help" >&2; exit 2 ;;+esacdiff --git a/lib/src/adaptive_upload.dart b/lib/src/adaptive_upload.dartnew file mode 100644index 0000000..e5ffeba--- /dev/null+++ b/lib/src/adaptive_upload.dart@@ -0,0 +1,122 @@+import 'dart:math';++import 'errors.dart';++enum UploadNetworkType { wifi, cellular, unknown }++enum UploadNetworkSpeed { slow, standard, fast, unknown }++enum UploadDeviceMemory { low, standard, high }++class UploadConditions {+ const UploadConditions({+ this.networkType = UploadNetworkType.unknown,+ this.networkSpeed = UploadNetworkSpeed.unknown,+ this.deviceMemory = UploadDeviceMemory.standard,+ });++ final UploadNetworkType networkType;+ final UploadNetworkSpeed networkSpeed;+ final UploadDeviceMemory deviceMemory;+}++class AdaptiveUploadPreset {+ const AdaptiveUploadPreset({+ required this.name,+ required this.partSizeBytes,+ required this.maxConcurrency,+ required this.maxPartAttempts,+ required this.partTimeout,+ });++ final String name;+ final int partSizeBytes;+ final int maxConcurrency;+ final int maxPartAttempts;+ final Duration partTimeout;+}++abstract final class AdaptiveUploadPolicy {+ static AdaptiveUploadPreset select(+ int sizeBytes,+ UploadConditions conditions,+ ) {+ if (sizeBytes < 0) {+ throw const ValidationException('size_bytes must not be negative');+ }+ final tier = switch (sizeBytes) {+ < 100 * _mib => 'small',+ < _gib => 'medium',+ < 8 * _gib => 'large',+ _ => 'huge',+ };+ final profile = switch (conditions) {+ UploadConditions(deviceMemory: UploadDeviceMemory.low) => 'conservative',+ UploadConditions(+ networkType: UploadNetworkType.cellular,+ networkSpeed: UploadNetworkSpeed.slow,+ ) =>+ 'conservative',+ UploadConditions(networkType: UploadNetworkType.cellular) => 'cellular',+ UploadConditions(+ networkType: UploadNetworkType.wifi,+ networkSpeed: UploadNetworkSpeed.slow,+ ) =>+ 'conservative',+ UploadConditions(+ networkType: UploadNetworkType.wifi,+ networkSpeed: UploadNetworkSpeed.fast,+ deviceMemory: UploadDeviceMemory.high,+ ) =>+ 'fast',+ UploadConditions(networkType: UploadNetworkType.wifi) => 'balanced',+ _ => 'conservative',+ };+ final values = _presets[tier]![profile]!;+ final partSize = max(values[0] * _mib, _minPartSize(sizeBytes));+ return AdaptiveUploadPreset(+ name: '${tier}_$profile',+ partSizeBytes: partSize,+ maxConcurrency: values[1],+ maxPartAttempts: values[2],+ partTimeout: Duration(seconds: values[3]),+ );+ }++ static int _minPartSize(int sizeBytes) {+ if (sizeBytes <= 0) return 5 * _mib;+ final bytes = 1 + (sizeBytes - 1) ~/ 10000;+ return max(5 * _mib, (bytes + _mib - 1) ~/ _mib * _mib);+ }++ static const int _mib = 1024 * 1024;+ static const int _gib = 1024 * _mib;++ static const Map<String, Map<String, List<int>>> _presets =+ <String, Map<String, List<int>>>{+ 'small': <String, List<int>>{+ 'conservative': <int>[5, 1, 6, 360],+ 'cellular': <int>[8, 2, 5, 300],+ 'balanced': <int>[16, 3, 4, 240],+ 'fast': <int>[32, 4, 3, 180],+ },+ 'medium': <String, List<int>>{+ 'conservative': <int>[8, 1, 6, 480],+ 'cellular': <int>[16, 2, 5, 360],+ 'balanced': <int>[32, 3, 4, 300],+ 'fast': <int>[64, 4, 3, 240],+ },+ 'large': <String, List<int>>{+ 'conservative': <int>[16, 1, 7, 720],+ 'cellular': <int>[32, 2, 6, 600],+ 'balanced': <int>[64, 3, 5, 480],+ 'fast': <int>[128, 4, 4, 360],+ },+ 'huge': <String, List<int>>{+ 'conservative': <int>[32, 1, 8, 900],+ 'cellular': <int>[64, 2, 7, 720],+ 'balanced': <int>[128, 3, 6, 600],+ 'fast': <int>[256, 4, 5, 480],+ },+ };+}diff --git a/lib/src/api_key_provider.dart b/lib/src/api_key_provider.dartnew file mode 100644index 0000000..1db8b4d--- /dev/null+++ b/lib/src/api_key_provider.dart@@ -0,0 +1,51 @@+import 'errors.dart';++abstract interface class ApiKeyProvider {+ String current();+}++class MutableApiKeyProvider implements ApiKeyProvider {+ MutableApiKeyProvider(String initialKey) : _key = strApiKey(initialKey);++ String? _key;+ bool _closed = false;++ void rotate(String newKey) {+ final valid = strApiKey(newKey);+ if (_closed) throw const AuthException('API key is unavailable');+ _key = valid;+ }++ void clear() {+ _key = null;+ }++ void close() {+ _closed = true;+ clear();+ }++ @override+ String current() {+ final value = _key;+ if (_closed || value == null) {+ throw const AuthException('API key is unavailable');+ }+ return value;+ }++ @override+ String toString() => 'MutableApiKeyProvider([REDACTED])';+}++String strApiKey(String value) {+ final key = value.trim();+ if (key.isEmpty) throw const ValidationException('API key must not be blank');+ if (key.length > 8192) {+ throw const ValidationException('API key is too long');+ }+ if (key.runes.any((int value) => value < 32 || value == 127)) {+ throw const ValidationException('API key contains invalid characters');+ }+ return key;+}diff --git a/lib/src/client.dart b/lib/src/client.dartnew file mode 100644index 0000000..8221baa--- /dev/null+++ b/lib/src/client.dart@@ -0,0 +1,120 @@+import 'config.dart';+import 'errors.dart';+import 'http.dart';+import 'models.dart';+import 'resources.dart';+import 'transport.dart';+import 'upload.dart';++const String vmodalSdkVersion = '1.0.0';++class VmodalClient {+ VmodalClient({+ required this.config,+ VmodalTransport? transport,+ SignedUploadTransport? signedUploadTransport,+ DelayStrategy? delay,+ }) : transport = transport ?? HttpVmodalTransport(config),+ signedUploadTransport =+ signedUploadTransport ?? IoSignedUploadTransport(config.timeout) {+ http = VmodalHttp(config, this.transport, delay: delay);+ auth = AuthResource(http);+ searches = SearchesResource(http);+ collections = CollectionsResource(http, this.signedUploadTransport);+ indexes = IndexesResource(http);+ admin = AdminResource(http);+ r2 = R2Resource(http);+ images = ImagesResource(http);+ }++ final SdkConfig config;+ final VmodalTransport transport;+ final SignedUploadTransport signedUploadTransport;+ late final VmodalHttp http;+ late final AuthResource auth;+ late final SearchesResource searches;+ late final CollectionsResource collections;+ late final IndexesResource indexes;+ late final AdminResource admin;+ late final R2Resource r2;+ late final ImagesResource images;+ final GDriveResource gdrive = GDriveResource();+ final SqlResource sql = SqlResource();+ bool _closed = false;++ Future<HealthResponse> health({CancellationToken? cancellation}) =>+ auth.health(cancellation: cancellation);++ Future<bool> authCheck({CancellationToken? cancellation}) =>+ auth.authCheck(cancellation: cancellation);++ static Future<VmodalClient> fromEnvironment(+ Map<String, String> env, {+ VmodalTransport? transport,+ SignedUploadTransport? signedUploadTransport,+ bool resolveIdentity = true,+ DelayStrategy? delay,+ }) async {+ final config = SdkConfig.fromEnvironment(env);+ var client = VmodalClient(+ config: config,+ transport: transport,+ signedUploadTransport: signedUploadTransport,+ delay: delay,+ );+ if (!resolveIdentity || config.normalizedUserId.isNotEmpty) return client;+ final profile = await client.auth.me();+ final userId = profile.userId?.trim() ?? '';+ if (userId.isEmpty) {+ await client.close();+ throw const AuthException('auth/me returned no user_id');+ }+ final resolved = config.copyWith(+ userId: userId,+ tenantId: profile.tenantId ?? '',+ email: profile.email ?? '',+ );+ client = VmodalClient(+ config: resolved,+ transport: transport,+ signedUploadTransport: signedUploadTransport,+ delay: delay,+ );+ return client;+ }++ factory VmodalClient.unsafeDirect({+ required String baseUrl,+ required String userId,+ String tenantId = '',+ String email = '',+ Duration timeout = const Duration(seconds: 30),+ int maxRetries = 1,+ VmodalTransport? transport,+ SignedUploadTransport? signedUploadTransport,+ DelayStrategy? delay,+ }) {+ final config = SdkConfig(+ baseUrl: baseUrl,+ userId: userId,+ tenantId: tenantId,+ email: email,+ timeout: timeout,+ mode: 'direct',+ maxRetries: maxRetries,+ );+ return VmodalClient(+ config: config,+ transport: transport,+ signedUploadTransport: signedUploadTransport,+ delay: delay,+ );+ }++ Future<void> close() async {+ if (_closed) return;+ _closed = true;+ await transport.close();+ await signedUploadTransport.close();+ }+}diff --git a/lib/src/collection_uploads.dart b/lib/src/collection_uploads.dartnew file mode 100644index 0000000..b6f4255--- /dev/null+++ b/lib/src/collection_uploads.dart@@ -0,0 +1,980 @@+import 'dart:async';+import 'dart:convert';+import 'dart:math';++import 'package:crypto/crypto.dart';++import 'adaptive_upload.dart';+import 'errors.dart';+import 'models.dart';+import 'resources.dart';+import 'routes.dart';+import 'transport.dart';+import 'upload.dart';+import 'utils.dart';++class VideoUploadOptions {+ const VideoUploadOptions({+ this.multipart = false,+ this.multipartThresholdBytes = 100 * 1024 * 1024,+ this.partSizeBytes = 64 * 1024 * 1024,+ this.maxConcurrency = 4,+ this.maxPartAttempts = 5,+ this.partTimeout = const Duration(seconds: 300),+ this.resume = true,+ this.sessionStore,+ this.adaptiveConditions,+ });++ final bool multipart;+ final int multipartThresholdBytes;+ final int partSizeBytes;+ final int maxConcurrency;+ final int maxPartAttempts;+ final Duration partTimeout;+ final bool resume;+ final UploadSessionStore? sessionStore;+ final UploadConditions? adaptiveConditions;++ UploadSessionStore get store => sessionStore ?? UploadSessionStores.memory;++ VideoUploadOptions resolvedFor(int size) {+ if (!multipart || adaptiveConditions == null) return this;+ final preset = AdaptiveUploadPolicy.select(size, adaptiveConditions!);+ return copyWith(+ partSizeBytes: preset.partSizeBytes,+ maxConcurrency: preset.maxConcurrency,+ maxPartAttempts: preset.maxPartAttempts,+ partTimeout: preset.partTimeout,+ );+ }++ VideoUploadOptions copyWith({+ bool? multipart,+ int? multipartThresholdBytes,+ int? partSizeBytes,+ int? maxConcurrency,+ int? maxPartAttempts,+ Duration? partTimeout,+ bool? resume,+ UploadSessionStore? sessionStore,+ UploadConditions? adaptiveConditions,+ }) => VideoUploadOptions(+ multipart: multipart ?? this.multipart,+ multipartThresholdBytes:+ multipartThresholdBytes ?? this.multipartThresholdBytes,+ partSizeBytes: partSizeBytes ?? this.partSizeBytes,+ maxConcurrency: maxConcurrency ?? this.maxConcurrency,+ maxPartAttempts: maxPartAttempts ?? this.maxPartAttempts,+ partTimeout: partTimeout ?? this.partTimeout,+ resume: resume ?? this.resume,+ sessionStore: sessionStore ?? this.sessionStore,+ adaptiveConditions: adaptiveConditions ?? this.adaptiveConditions,+ );++ void validate(int size) {+ if (!multipart) return;+ if (partSizeBytes < 5 * 1024 * 1024) {+ throw const ValidationException('part_size_bytes must be at least 5 MiB');+ }+ if (maxConcurrency < 1 || maxConcurrency > 16) {+ throw const ValidationException('max_concurrency must be in 1..16');+ }+ if (maxPartAttempts < 1 || maxPartAttempts > 10) {+ throw const ValidationException('max_part_attempts must be in 1..10');+ }+ if (partTimeout <= Duration.zero) {+ throw const ValidationException('part_timeout must be positive');+ }+ if (size <= 0) {+ throw const ValidationException('multipart size must be positive');+ }+ if (_partCount(size, partSizeBytes) > 10000) {+ throw const ValidationException(+ 'part_size_bytes would create more than 10,000 parts',+ );+ }+ }+}++extension CollectionUploads on CollectionsResource {+ UploadTask<VideoUploadResponse> videoUpload(+ UploadSource source, {+ required String collectionName,+ required String subCollectionName,+ String mode = 'vid_file',+ String modality = 'vid_raw',+ int ttl = 12600,+ VideoUploadOptions options = const VideoUploadOptions(),+ }) {+ final resolved = options.resolvedFor(source.contentLength);+ resolved.validate(source.contentLength);+ return UploadTask<VideoUploadResponse>.start(+ (CancellationToken cancellation, void Function(UploadProgress) emit) =>+ _videoUploadRun(+ source,+ collectionName,+ subCollectionName,+ mode,+ modality,+ ttl,+ resolved,+ cancellation,+ emit,+ ),+ );+ }++ UploadTask<VideoUploadBulkResponse> videoUploadBulk(+ List<UploadSource> sources, {+ required String collectionName,+ required String subCollectionName,+ String mode = 'vid_file',+ String modality = 'vid_raw',+ int ttl = 12600,+ VideoUploadOptions options = const VideoUploadOptions(),+ }) {+ final resolved = sources+ .map((UploadSource source) => options.resolvedFor(source.contentLength))+ .toList();+ for (var i = 0; i < sources.length; i++) {+ resolved[i].validate(sources[i].contentLength);+ }+ return UploadTask<VideoUploadBulkResponse>.start((+ CancellationToken cancellation,+ void Function(UploadProgress) emit,+ ) async {+ if (sources.isEmpty) {+ return VideoUploadBulkResponse(const <String, Object?>{+ 'data': <Object?>[],+ 'total': 0,+ });+ }+ final total = sources.fold<int>(+ 0,+ (int value, UploadSource source) => value + source.contentLength,+ );+ final sent = List<int>.filled(sources.length, 0);+ final results = List<VideoUploadResponse?>.filled(sources.length, null);+ var cursor = 0;+ Object? firstError;+ StackTrace? firstStack;+ Future<void> worker() async {+ while (!cancellation.isCanceled && firstError == null) {+ final index = cursor++;+ if (index >= sources.length) return;+ try {+ results[index] = await _videoUploadRun(+ sources[index],+ collectionName,+ subCollectionName,+ mode,+ modality,+ ttl,+ resolved[index],+ cancellation,+ (UploadProgress progress) {+ sent[index] = max(sent[index], progress.uploadedBytes);+ emit(+ UploadProgress(+ sent.fold<int>(0, (int a, int b) => a + b),+ total,+ ),+ );+ },+ );+ sent[index] = sources[index].contentLength;+ } on Object catch (error, stack) {+ firstError ??= error;+ firstStack ??= stack;+ cancellation.cancel();+ }+ }+ }++ final concurrency = options.maxConcurrency.clamp(1, sources.length);+ await Future.wait(+ List<Future<void>>.generate(concurrency, (_) => worker()),+ );+ if (firstError != null) {+ Error.throwWithStackTrace(firstError!, firstStack!);+ }+ cancellation.throwIfCanceled();+ final data = results.cast<VideoUploadResponse>();+ return VideoUploadBulkResponse(<String, Object?>{+ 'data': data.map((VideoUploadResponse item) => item.raw).toList(),+ 'total': data.length,+ });+ });+ }++ Future<VideoUploadResponse> _videoUploadRun(+ UploadSource source,+ String collection,+ String stream,+ String mode,+ String modality,+ int ttl,+ VideoUploadOptions options,+ CancellationToken cancellation,+ void Function(UploadProgress) emit,+ ) async {+ if (!options.multipart) {+ return _singleUpload(+ source,+ collection,+ stream,+ mode,+ modality,+ ttl,+ cancellation,+ emit,+ );+ }+ try {+ return await _multipartUpload(+ source,+ collection,+ stream,+ mode,+ modality,+ ttl,+ options,+ cancellation,+ emit,+ );+ } on ApiException catch (error) {+ if (error.statusCode != 404) rethrow;+ throw const FeatureDisabled(+ 'experimental multipart upload is unavailable on this gateway; '+ 'retry with VideoUploadOptions(multipart: false)',+ );+ }+ }++ Future<VideoUploadResponse> _singleUpload(+ UploadSource source,+ String collection,+ String stream,+ String mode,+ String modality,+ int ttl,+ CancellationToken cancellation,+ void Function(UploadProgress) emit,+ ) async {+ cancellation.throwIfCanceled();+ final signed = await http.request(+ 'POST',+ Routes.full(Routes.externalUploadGetSignedUrl),+ params: _uploadParams(source, collection, stream, mode, modality, ttl),+ cancellation: cancellation,+ );+ cancellation.throwIfCanceled();+ final url = _signedUri('${signed['url'] ?? ''}');+ final result = await signedUploads.upload(+ source: source,+ url: url,+ method: '${signed['method'] ?? 'PUT'}',+ cancellation: cancellation,+ onProgress: emit,+ );+ cancellation.throwIfCanceled();+ final done = await _uploadDone(+ '${signed['key'] ?? ''}',+ source,+ collection,+ stream,+ mode,+ modality,+ cancellation,+ );+ return VideoUploadResponse(<String, Object?>{+ ...signed,+ 'filename': source.fileName,+ 'size_bytes': source.contentLength,+ 'status_code': result.statusCode,+ 'uploaded': true,+ 'upload_strategy': 'single',+ 'etag': result.etag,+ 'part_count': 1,+ 'parts_uploaded': 1,+ 'attempt_count': 1,+ 'upload_done': done,+ 'dest_path': '${done['dest_path'] ?? ''}',+ });+ }++ Future<VideoUploadResponse> _multipartUpload(+ UploadSource source,+ String collection,+ String stream,+ String mode,+ String modality,+ int ttl,+ VideoUploadOptions options,+ CancellationToken cancellation,+ void Function(UploadProgress) emit,+ ) async {+ final contract = _UploadContract(+ source: source,+ baseUrl: http.config.normalizedBaseUrl,+ userId: http.config.normalizedUserId,+ collection: collection,+ stream: stream,+ mode: mode,+ modality: modality,+ partSize: options.partSizeBytes,+ );+ final sessionKey = contract.key;+ final storedRaw = await options.store.load(sessionKey);+ var session = storedRaw == null+ ? null+ : _MultipartSession.fromJson(storedRaw, contract);+ if (!options.resume && session != null) {+ await _multipartAbort(session, cancellation);+ await options.store.remove(sessionKey);+ session = null;+ }+ var resumed = session != null;+ session ??= await _multipartCreate(contract, cancellation);+ await options.store.save(sessionKey, session.toJson(contract));++ Map<String, Object?> status;+ try {+ status = await _multipartStatus(session, cancellation);+ } on ApiException catch (error) {+ if (error.statusCode != 404) rethrow;+ await options.store.remove(sessionKey);+ session = await _multipartCreate(contract, cancellation);+ await options.store.save(sessionKey, session.toJson(contract));+ resumed = false;+ status = await _multipartStatus(session, cancellation);+ }+ if ('${status['status']}' == 'completed') {+ final etag = '${status['etag'] ?? ''}';+ if (intValue(status['size_bytes']) != source.contentLength ||+ etag.isEmpty) {+ throw const ApiException(+ 'completed multipart status does not match local upload contract',+ );+ }+ final done = await _uploadDone(+ session.key,+ source,+ collection,+ stream,+ mode,+ modality,+ cancellation,+ );+ await options.store.remove(sessionKey);+ return _multipartResponse(source, session, etag, resumed, 0, done);+ }++ final remote = objectList(status['parts']);+ final numbers = remote+ .map((Map<String, Object?> row) => intValue(row['part_number']))+ .toList();+ if (numbers.toSet().length != numbers.length ||+ numbers.any((int value) => value < 1 || value > session!.partCount)) {+ throw const ApiException(+ 'multipart status returned duplicate or out-of-range parts',+ );+ }+ final valid = <int, Map<String, Object?>>{};+ for (final part in remote) {+ final number = intValue(part['part_number']);+ final length = _partLength(+ source.contentLength,+ session.partSize,+ number,+ );+ if (intValue(part['size_bytes']) != length) continue;+ final expected =+ session.partMd5[number] ??+ await md5Hex(+ source,+ offset: (number - 1) * session.partSize,+ length: length,+ );+ if ('${part['etag'] ?? ''}'.toLowerCase() == expected.toLowerCase()) {+ valid[number] = part;+ session.partMd5[number] = expected;+ }+ }+ await options.store.save(sessionKey, session.toJson(contract));+ final sentByPart = <int, int>{+ for (final entry in valid.entries)+ entry.key: intValue(entry.value['size_bytes']),+ };+ var lastProgress = 0;+ void report() {+ final total = sentByPart.values+ .fold<int>(0, (int a, int b) => a + b)+ .clamp(0, source.contentLength);+ lastProgress = max(lastProgress, total);+ emit(UploadProgress(lastProgress, source.contentLength));+ }++ if (sentByPart.isNotEmpty) report();+ final missing = <int>[+ for (var number = 1; number <= session.partCount; number++)+ if (!valid.containsKey(number)) number,+ ];+ var attempts = 0;+ for (+ var start = 0;+ start < missing.length;+ start += max(1, options.maxConcurrency * 2)+ ) {+ cancellation.throwIfCanceled();+ final batch = missing.sublist(+ start,+ min(missing.length, start + max(1, options.maxConcurrency * 2)),+ );+ final signedRaw = await _multipartSign(session, batch, ttl, cancellation);+ final signed = <int, Map<String, Object?>>{+ for (final row in objectList(signedRaw['parts']))+ intValue(row['part_number']): row,+ };+ if (signed.length != batch.length ||+ !signed.keys.toSet().containsAll(batch)) {+ throw const ApiException(+ 'multipart sign response did not match requested parts',+ );+ }+ var cursor = 0;+ final uploaded = <_UploadedPart>[];+ Object? firstError;+ StackTrace? firstStack;+ Future<void> worker() async {+ while (firstError == null && !cancellation.isCanceled) {+ final index = cursor++;+ if (index >= batch.length) return;+ final number = batch[index];+ try {+ final part = await _multipartPutOne(+ source,+ session!,+ number,+ signed[number]!,+ ttl,+ options,+ cancellation,+ (UploadProgress progress) {+ sentByPart[number] = max(+ sentByPart[number] ?? 0,+ progress.uploadedBytes,+ );+ report();+ },+ );+ uploaded.add(part);+ } on Object catch (error, stack) {+ firstError ??= error;+ firstStack ??= stack;+ }+ }+ }++ await Future.wait(+ List<Future<void>>.generate(+ min(options.maxConcurrency, batch.length),+ (_) => worker(),+ ),+ );+ if (firstError != null) {+ Error.throwWithStackTrace(firstError!, firstStack!);+ }+ for (final part in uploaded) {+ attempts += part.attempts;+ session.partMd5[part.number] = part.md5;+ sentByPart[part.number] = part.size;+ }+ await options.store.save(sessionKey, session.toJson(contract));+ report();+ }++ cancellation.throwIfCanceled();+ status = await _multipartStatus(session, cancellation);+ final parts = _multipartFinalParts(session, source.contentLength, status);+ final complete = await http.request(+ 'POST',+ Routes.full(Routes.externalUploadMultipartComplete),+ json: <String, Object?>{+ 'request_id': session.requestId,+ 'upload_id': session.uploadId,+ 'key': session.key,+ 'size_bytes': source.contentLength,+ 'parts': parts,+ },+ cancellation: cancellation,+ );+ final etag = '${complete['etag'] ?? ''}';+ if (etag.isEmpty) {+ throw const ApiException('multipart complete response returned no ETag');+ }+ cancellation.throwIfCanceled();+ final done = await _uploadDone(+ session.key,+ source,+ collection,+ stream,+ mode,+ modality,+ cancellation,+ );+ await options.store.remove(sessionKey);+ emit(UploadProgress(source.contentLength, source.contentLength));+ return _multipartResponse(source, session, etag, resumed, attempts, done);+ }++ Future<_MultipartSession> _multipartCreate(+ _UploadContract contract,+ CancellationToken cancellation,+ ) async {+ final requestId =+ '${DateTime.now().microsecondsSinceEpoch}-${Random.secure().nextInt(1 << 32)}';+ final raw = await http.request(+ 'POST',+ Routes.full(Routes.externalUploadMultipartCreate),+ json: <String, Object?>{+ 'request_id': requestId,+ 'mode': contract.mode,+ 'group_name': contract.collection,+ 'stream_name': contract.stream,+ 'modality': contract.modality,+ 'filename': contract.source.fileName,+ 'content_type': contract.source.contentType,+ 'size_bytes': contract.source.contentLength,+ 'part_size_bytes': contract.partSize,+ },+ cancellation: cancellation,+ );+ final session = _MultipartSession(+ requestId: '${raw['request_id'] ?? requestId}',+ uploadId: '${raw['upload_id'] ?? ''}',+ key: '${raw['key'] ?? ''}',+ partCount: intValue(raw['part_count']),+ partSize: intValue(raw['part_size_bytes']),+ );+ final expected = _partCount(+ contract.source.contentLength,+ contract.partSize,+ );+ if (session.uploadId.isEmpty ||+ session.key.isEmpty ||+ session.partCount != expected ||+ session.partSize != contract.partSize) {+ throw const ApiException(+ 'multipart create response does not match local upload contract',+ );+ }+ return session;+ }++ Future<_UploadedPart> _multipartPutOne(+ UploadSource source,+ _MultipartSession session,+ int number,+ Map<String, Object?> signed,+ int ttl,+ VideoUploadOptions options,+ CancellationToken cancellation,+ void Function(UploadProgress) emit,+ ) async {+ final offset = (number - 1) * session.partSize;+ final length = _partLength(source.contentLength, session.partSize, number);+ var item = signed;+ for (var attempt = 1; attempt <= options.maxPartAttempts; attempt++) {+ cancellation.throwIfCanceled();+ try {+ final headers = objectMap(+ item['headers'],+ ).map((String key, Object? value) => MapEntry(key, '$value'));+ final result = await signedUploads.upload(+ source: source,+ url: _signedUri('${item['url'] ?? ''}'),+ method: '${item['method'] ?? 'PUT'}',+ offset: offset,+ length: length,+ headers: headers,+ timeout: options.partTimeout,+ cancellation: cancellation,+ onProgress: emit,+ );+ final expected = result.localMd5.isEmpty+ ? await md5Hex(source, offset: offset, length: length)+ : result.localMd5;+ if (result.etag.isEmpty ||+ result.etag.toLowerCase() != expected.toLowerCase()) {+ throw ApiException(+ 'multipart part ETag mismatch',+ body: <String, Object?>{'part_number': number},+ );+ }+ return _UploadedPart(number, result.etag, length, expected, attempt);+ } on Object catch (error) {+ cancellation.throwIfCanceled();+ final localMd5 =+ error is SignedUploadFailure && error.localMd5.isNotEmpty+ ? error.localMd5+ : await md5Hex(source, offset: offset, length: length);+ final found = await _multipartReconcilePart(+ session,+ number,+ length,+ localMd5,+ cancellation,+ );+ if (found != null) {+ return _UploadedPart(number, found, length, localMd5, attempt);+ }+ if (error is ApiException && error.statusCode == 403) {+ if (attempt == options.maxPartAttempts) rethrow;+ final refreshed = objectList(+ (await _multipartSign(+ session,+ <int>[number],+ ttl,+ cancellation,+ ))['parts'],+ );+ if (refreshed.length != 1 ||+ intValue(refreshed.single['part_number']) != number) {+ throw const ApiException(+ 'multipart URL refresh returned no matching part',+ );+ }+ item = refreshed.single;+ } else {+ final retryable =+ error is SignedUploadFailure ||+ error is TransportException ||+ (error is ApiException &&+ const <int>{+ 408,+ 429,+ 500,+ 502,+ 503,+ 504,+ }.contains(error.statusCode));+ if (!retryable || attempt == options.maxPartAttempts) rethrow;+ }+ await _cancelableDelay(+ Duration(milliseconds: min(30000, 250 << min(attempt - 1, 6))),+ cancellation,+ );+ }+ }+ throw const ApiException('multipart part attempts exhausted');+ }++ Future<String?> _multipartReconcilePart(+ _MultipartSession session,+ int number,+ int length,+ String localMd5,+ CancellationToken cancellation,+ ) async {+ final status = await _multipartStatus(session, cancellation);+ for (final row in objectList(status['parts'])) {+ if (intValue(row['part_number']) == number &&+ intValue(row['size_bytes']) == length &&+ '${row['etag'] ?? ''}'.toLowerCase() == localMd5.toLowerCase()) {+ return '${row['etag']}';+ }+ }+ return null;+ }++ List<Map<String, Object?>> _multipartFinalParts(+ _MultipartSession session,+ int size,+ Map<String, Object?> status,+ ) {+ final remote = objectList(status['parts'])+ ..sort(+ (Map<String, Object?> a, Map<String, Object?> b) =>+ intValue(a['part_number']).compareTo(intValue(b['part_number'])),+ );+ final numbers = remote+ .map((Map<String, Object?> row) => intValue(row['part_number']))+ .toList();+ if (numbers.length != session.partCount ||+ !List<int>.generate(+ session.partCount,+ (int index) => index + 1,+ ).asMap().entries.every(+ (MapEntry<int, int> entry) => numbers[entry.key] == entry.value,+ )) {+ throw const ApiException(+ 'multipart status is missing, duplicate, or unsorted parts',+ );+ }+ return remote.map((Map<String, Object?> row) {+ final number = intValue(row['part_number']);+ final expectedSize = _partLength(size, session.partSize, number);+ final etag = '${row['etag'] ?? ''}';+ final expectedMd5 = session.partMd5[number] ?? '';+ if (intValue(row['size_bytes']) != expectedSize ||+ etag.isEmpty ||+ expectedMd5.isEmpty ||+ etag.toLowerCase() != expectedMd5.toLowerCase()) {+ throw ApiException(+ 'multipart status returned an invalid part',+ body: <String, Object?>{'part_number': number},+ );+ }+ return <String, Object?>{'part_number': number, 'etag': etag};+ }).toList();+ }++ Future<Map<String, Object?>> _multipartStatus(+ _MultipartSession session,+ CancellationToken cancellation,+ ) => http.request(+ 'GET',+ Routes.full(Routes.externalUploadMultipartStatus),+ params: <String, Object?>{+ 'request_id': session.requestId,+ 'upload_id': session.uploadId,+ 'key': session.key,+ },+ cancellation: cancellation,+ );++ Future<Map<String, Object?>> _multipartSign(+ _MultipartSession session,+ List<int> numbers,+ int ttl,+ CancellationToken cancellation,+ ) => http.request(+ 'POST',+ Routes.full(Routes.externalUploadMultipartSignParts),+ json: <String, Object?>{+ 'request_id': session.requestId,+ 'upload_id': session.uploadId,+ 'key': session.key,+ 'part_numbers': numbers,+ 'ttl': ttl,+ },+ cancellation: cancellation,+ );++ Future<Map<String, Object?>> _multipartAbort(+ _MultipartSession session,+ CancellationToken cancellation,+ ) => http.request(+ 'POST',+ Routes.full(Routes.externalUploadMultipartAbort),+ json: <String, Object?>{+ 'request_id': session.requestId,+ 'upload_id': session.uploadId,+ 'key': session.key,+ },+ cancellation: cancellation,+ );++ Future<Map<String, Object?>> _uploadDone(+ String key,+ UploadSource source,+ String collection,+ String stream,+ String mode,+ String modality,+ CancellationToken cancellation,+ ) => http.request(+ 'POST',+ Routes.full(Routes.externalUploadDone),+ params: <String, Object?>{+ 'key': key,+ 'mode': mode,+ 'group_name': collection,+ 'stream_name': stream,+ 'modality': modality,+ 'filename': source.fileName,+ },+ cancellation: cancellation,+ );+}++class _UploadContract {+ const _UploadContract({+ required this.source,+ required this.baseUrl,+ required this.userId,+ required this.collection,+ required this.stream,+ required this.mode,+ required this.modality,+ required this.partSize,+ });++ final UploadSource source;+ final String baseUrl;+ final String userId;+ final String collection;+ final String stream;+ final String mode;+ final String modality;+ final int partSize;++ Map<String, Object?> get fields => <String, Object?>{+ 'protocol': 'vmodal_multipart_v2',+ 'base_url': baseUrl,+ 'user_id': userId,+ 'source_id': source.sourceId,+ 'source_version': source.versionTag,+ 'filename': source.fileName,+ 'content_type': source.contentType,+ 'size_bytes': source.contentLength,+ 'part_size_bytes': partSize,+ 'mode': mode,+ 'group_name': collection,+ 'stream_name': stream,+ 'modality': modality,+ };++ String get key => sha256.convert(utf8.encode(jsonEncode(fields))).toString();+}++class _MultipartSession {+ _MultipartSession({+ required this.requestId,+ required this.uploadId,+ required this.key,+ required this.partCount,+ required this.partSize,+ Map<int, String>? partMd5,+ }) : partMd5 = partMd5 ?? <int, String>{};++ final String requestId;+ final String uploadId;+ final String key;+ final int partCount;+ final int partSize;+ final Map<int, String> partMd5;++ Map<String, Object?> toJson(_UploadContract contract) => <String, Object?>{+ 'version': 2,+ 'contract': contract.fields,+ 'request_id': requestId,+ 'upload_id': uploadId,+ 'key': key,+ 'part_count': partCount,+ 'part_size_bytes': partSize,+ 'part_md5': partMd5.map((int key, String value) => MapEntry('$key', value)),+ };++ factory _MultipartSession.fromJson(+ Map<String, Object?> raw,+ _UploadContract contract,+ ) {+ if (intValue(raw['version']) != 2 ||+ jsonEncode(objectMap(raw['contract'])) != jsonEncode(contract.fields)) {+ throw const ApiException('multipart upload checkpoint is incompatible');+ }+ final session = _MultipartSession(+ requestId: '${raw['request_id'] ?? ''}',+ uploadId: '${raw['upload_id'] ?? ''}',+ key: '${raw['key'] ?? ''}',+ partCount: intValue(raw['part_count']),+ partSize: intValue(raw['part_size_bytes']),+ partMd5: objectMap(+ raw['part_md5'],+ ).map((String key, Object? value) => MapEntry(int.parse(key), '$value')),+ );+ if (session.requestId.isEmpty ||+ session.uploadId.isEmpty ||+ session.key.isEmpty ||+ session.partCount <= 0 ||+ session.partSize != contract.partSize) {+ throw const ApiException('multipart upload checkpoint is invalid');+ }+ return session;+ }+}++class _UploadedPart {+ const _UploadedPart(+ this.number,+ this.etag,+ this.size,+ this.md5,+ this.attempts,+ );++ final int number;+ final String etag;+ final int size;+ final String md5;+ final int attempts;+}++Map<String, Object?> _uploadParams(+ UploadSource source,+ String collection,+ String stream,+ String mode,+ String modality,+ int ttl,+) => <String, Object?>{+ 'mode': mode,+ 'group_name': collection,+ 'stream_name': stream,+ 'modality': modality,+ 'filename': source.fileName,+ 'ttl': ttl,+};++VideoUploadResponse _multipartResponse(+ UploadSource source,+ _MultipartSession session,+ String etag,+ bool resumed,+ int attempts,+ Map<String, Object?> done,+) => VideoUploadResponse(<String, Object?>{+ 'filename': source.fileName,+ 'size_bytes': source.contentLength,+ 'status_code': 200,+ 'uploaded': true,+ 'upload_strategy': 'multipart',+ 'upload_id': session.uploadId,+ 'key': session.key,+ 'etag': etag,+ 'part_size_bytes': session.partSize,+ 'part_count': session.partCount,+ 'parts_uploaded': session.partCount,+ 'resumed': resumed,+ 'attempt_count': attempts,+ 'upload_done': done,+ 'dest_path': '${done['dest_path'] ?? ''}',+});++Uri _signedUri(String value) {+ final uri = Uri.tryParse(value);+ if (uri == null || !uri.hasScheme || uri.host.isEmpty) {+ throw const ValidationException('signed upload URL is empty or invalid');+ }+ return uri;+}++int _partLength(int size, int partSize, int number) =>+ min(partSize, size - (number - 1) * partSize);++int _partCount(int size, int partSize) =>+ size <= 0 ? 1 : 1 + (size - 1) ~/ partSize;++Future<void> _cancelableDelay(+ Duration duration,+ CancellationToken cancellation,+) async {+ await Future.any(<Future<void>>[+ Future<void>.delayed(duration),+ cancellation.whenCanceled,+ ]);+ cancellation.throwIfCanceled();+}diff --git a/lib/src/config.dart b/lib/src/config.dartnew file mode 100644index 0000000..3a5c2f3--- /dev/null+++ b/lib/src/config.dart@@ -0,0 +1,194 @@+import 'dart:convert';++import 'api_key_provider.dart';+import 'errors.dart';++const String publicGatewayUrlHash =+ 'aHR0cHM6Ly9zZWFyY2hhcGktdGVzdC52LW1vZGFsLmNvbQ==';+final String publicGatewayUrl = utf8.decode(base64Decode(publicGatewayUrlHash));+const String devGatewayUrl = 'http://127.0.0.1:3099';++class SdkConfig {+ SdkConfig({+ String? baseUrl,+ this.userId = '',+ this.tenantId = '',+ this.email = '',+ this.token = '',+ this.timeout = const Duration(seconds: 30),+ this.mode = 'gateway',+ this.maxRetries = 1,+ this.apiKeyProvider,+ }) : baseUrl = baseUrl ?? publicGatewayUrl {+ if (timeout <= Duration.zero) {+ throw const ValidationException('timeout must be positive');+ }+ if (maxRetries < 0) {+ throw const ValidationException('max_retries must not be negative');+ }+ if (!const <String>{'gateway', 'direct'}.contains(normalizedMode)) {+ throw const ValidationException('mode must be gateway or direct');+ }+ _validateBase(normalizedBaseUrl);+ }++ final String baseUrl;+ final String userId;+ final String tenantId;+ final String email;+ final String token;+ final Duration timeout;+ final String mode;+ final int maxRetries;+ final ApiKeyProvider? apiKeyProvider;++ String get normalizedMode {+ final value = mode.trim().toLowerCase();+ return value.isEmpty ? 'gateway' : value;+ }++ String get normalizedBaseUrl => strGatewayBaseUrl(baseUrl, normalizedMode);+ String get normalizedUserId => userId.trim();+ String get normalizedTenantId => tenantId.trim();+ String get normalizedEmail => email.trim();+ int get normalizedMaxRetries => maxRetries;++ String currentApiKey() {+ final value = apiKeyProvider?.current() ?? token;+ return value.trim().isEmpty ? '' : strApiKey(value);+ }++ SdkConfig copyWith({+ String? baseUrl,+ String? userId,+ String? tenantId,+ String? email,+ String? token,+ Duration? timeout,+ String? mode,+ int? maxRetries,+ ApiKeyProvider? apiKeyProvider,+ }) => SdkConfig(+ baseUrl: baseUrl ?? this.baseUrl,+ userId: userId ?? this.userId,+ tenantId: tenantId ?? this.tenantId,+ email: email ?? this.email,+ token: token ?? this.token,+ timeout: timeout ?? this.timeout,+ mode: mode ?? this.mode,+ maxRetries: maxRetries ?? this.maxRetries,+ apiKeyProvider: apiKeyProvider ?? this.apiKeyProvider,+ );++ factory SdkConfig.fromEnvironment(+ Map<String, String> env, {+ String? baseUrl,+ String? userId,+ String? tenantId,+ String? email,+ String? token,+ Duration? timeout,+ String? mode,+ int? maxRetries,+ ApiKeyProvider? apiKeyProvider,+ }) {+ final envName = (env['VMODAL_ENV'] ?? 'prd').trim().toLowerCase();+ if (!const <String>{'dev', 'prd'}.contains(envName)) {+ throw const ValidationException('VMODAL_ENV must be dev or prd');+ }+ final fallback = envName == 'dev' ? devGatewayUrl : publicGatewayUrl;+ final rawBase =+ baseUrl ??+ _first(<String?>[+ env['VMODAL_BASE_URL'],+ env['TEST_CLIENT_SERVER_API_URL'],+ fallback,+ ]);+ final rawToken =+ token ??+ _first(<String?>[+ env['VMODAL_API_KEY'],+ env['VMODAL_API_TOKEN'],+ env['TEST_CLIENT_CLERK_USER_API_TOKEN'],+ env['TEST_CLIENT_USER_TOKEN'],+ ]);+ if (rawToken.isEmpty && apiKeyProvider == null) {+ throw const ValidationException('VMODAL_API_KEY is required');+ }+ final seconds = double.tryParse(env['VMODAL_TIMEOUT'] ?? '');+ return SdkConfig(+ baseUrl: rawBase,+ userId: userId ?? env['VMODAL_USER_ID'] ?? '',+ tenantId: tenantId ?? env['VMODAL_TENANT_ID'] ?? '',+ email: email ?? env['VMODAL_USER_EMAIL'] ?? '',+ token: rawToken,+ timeout:+ timeout ??+ (seconds == null+ ? const Duration(seconds: 30)+ : Duration(milliseconds: (seconds * 1000).round())),+ mode: mode ?? 'gateway',+ maxRetries:+ maxRetries ?? int.tryParse(env['VMODAL_MAX_RETRIES'] ?? '') ?? 1,+ apiKeyProvider: apiKeyProvider,+ );+ }++ @override+ String toString() =>+ 'SdkConfig('+ 'baseUrlConfigured=${baseUrl.isNotEmpty}, '+ 'userIdConfigured=${userId.isNotEmpty}, '+ 'tenantIdConfigured=${tenantId.isNotEmpty}, '+ 'emailConfigured=${email.isNotEmpty}, '+ 'tokenConfigured=${token.isNotEmpty}, '+ 'timeoutMs=${timeout.inMilliseconds}, '+ 'mode=$normalizedMode, '+ 'maxRetries=$maxRetries, '+ 'apiKeyProviderConfigured=${apiKeyProvider != null})';+}++String strGatewayBaseUrl(String baseUrl, [String mode = '']) {+ final base = baseUrl.trim().replaceFirst(RegExp(r'/+$'), '');+ if (base.isEmpty || mode.trim().toLowerCase() != 'gateway') return base;+ const suffix = '/api/v1/proxy/search_api';+ return base.endsWith(suffix) ? base : '$base$suffix';+}++String strUsersBaseUrl(String baseUrl) {+ final base = baseUrl.trim().replaceFirst(RegExp(r'/+$'), '');+ const suffix = '/api/v1/proxy/search_api';+ return base.endsWith(suffix)+ ? base.substring(0, base.length - suffix.length)+ : base;+}++String _first(List<String?> values) {+ for (final value in values) {+ if (value != null && value.trim().isNotEmpty) return value;+ }+ return '';+}++void _validateBase(String value) {+ final uri = Uri.tryParse(value);+ if (uri == null || !uri.hasScheme || uri.host.isEmpty) {+ throw const ValidationException('invalid HTTP URL');+ }+ if (uri.scheme != 'http' && uri.scheme != 'https') {+ throw const ValidationException('HTTP or HTTPS URL is required');+ }+ if (uri.userInfo.isNotEmpty) {+ throw const ValidationException('URL user information is not allowed');+ }+ if (uri.scheme == 'http' && !_loopback(uri.host)) {+ throw const ValidationException('HTTPS is required for non-local URLs');+ }+}++bool _loopback(String host) => const <String>{+ 'localhost',+ '127.0.0.1',+ '::1',+ '0:0:0:0:0:0:0:1',+}.contains(host.toLowerCase());diff --git a/lib/src/errors.dart b/lib/src/errors.dartnew file mode 100644index 0000000..997058c--- /dev/null+++ b/lib/src/errors.dart@@ -0,0 +1,71 @@+class SdkException implements Exception {+ const SdkException(+ this.message, {+ this.statusCode = 0,+ this.body,+ this.details,+ });++ final String message;+ final int statusCode;+ final Object? body;+ final Object? details;++ @override+ String toString() {+ final status = statusCode == 0 ? '' : ' | status=$statusCode';+ return '$runtimeType: $message$status';+ }+}++class AuthException extends SdkException {+ const AuthException(+ super.message, {+ super.statusCode = 401,+ super.body,+ super.details,+ });+}++class ApiException extends SdkException {+ const ApiException(+ super.message, {+ super.statusCode,+ super.body,+ super.details,+ });+}++class ValidationException extends SdkException {+ const ValidationException(+ super.message, {+ super.statusCode = 422,+ super.body,+ super.details,+ });+}++class FeatureDisabled extends SdkException {+ const FeatureDisabled(super.message);+}++class TransportException extends SdkException {+ const TransportException([Object? cause])+ : super('transport error', details: cause);+}++class ResponseTooLarge extends SdkException {+ const ResponseTooLarge(this.limitBytes, this.observedBytes)+ : super('response exceeds the configured limit');++ final int limitBytes;+ final int observedBytes;+}++class MalformedResponse extends SdkException {+ const MalformedResponse([super.message = 'malformed JSON response']);+}++class OperationCanceled extends SdkException {+ const OperationCanceled() : super('operation canceled');+}diff --git a/lib/src/http.dart b/lib/src/http.dartnew file mode 100644index 0000000..1f9c3ad--- /dev/null+++ b/lib/src/http.dart@@ -0,0 +1,318 @@+import 'dart:async';+import 'dart:convert';+import 'dart:typed_data';++import 'config.dart';+import 'errors.dart';+import 'transport.dart';+import 'utils.dart';++typedef DelayStrategy = Future<void> Function(Duration duration);++class VmodalHttp {+ VmodalHttp(this.config, this.transport, {DelayStrategy? delay})+ : _delay = delay ?? Future<void>.delayed;++ final SdkConfig config;+ final VmodalTransport transport;+ final DelayStrategy _delay;++ Map<String, String> headers({+ bool forceToken = false,+ bool requireUserId = true,+ }) {+ final out = <String, String>{};+ if (config.normalizedMode == 'direct') {+ final userId = config.normalizedUserId;+ if (requireUserId && userId.isEmpty) {+ throw const AuthException('user_id is required');+ }+ if (userId.isNotEmpty) {+ out['X-User-Id'] = strHeaderValue('user_id', userId);+ }+ if (config.normalizedTenantId.isNotEmpty) {+ out['X-Tenant-Id'] = strHeaderValue(+ 'tenant_id',+ config.normalizedTenantId,+ );+ }+ if (config.normalizedEmail.isNotEmpty) {+ out['X-User-Email'] = strHeaderValue('email', config.normalizedEmail);+ }+ }+ if (forceToken || config.normalizedMode != 'direct') {+ final key = config.currentApiKey();+ if (key.isEmpty) throw const AuthException('API key is required');+ out['Authorization'] = 'Bearer $key';+ }+ _assertGatewayHeaders(out);+ return Map<String, String>.unmodifiable(out);+ }++ Future<Map<String, Object?>> request(+ String method,+ String path, {+ Object? json,+ Map<String, Object?> data = const <String, Object?>{},+ List<VmodalFilePart> files = const <VmodalFilePart>[],+ Map<String, Object?> params = const <String, Object?>{},+ CancellationToken? cancellation,+ }) => _requestJson(+ method,+ path,+ headers: headers(),+ json: json,+ data: data,+ files: files,+ params: params,+ cancellation: cancellation,+ );++ Future<Map<String, Object?>> requestUsers(+ String method,+ String path, {+ Object? json,+ Map<String, Object?> params = const <String, Object?>{},+ CancellationToken? cancellation,+ }) => _requestJson(+ method,+ path,+ headers: headers(forceToken: true, requireUserId: false),+ json: json,+ params: params,+ usersApi: true,+ cancellation: cancellation,+ );++ Future<Uint8List> requestBytes(+ String method,+ String path, {+ Object? json,+ Map<String, Object?> params = const <String, Object?>{},+ CancellationToken? cancellation,+ }) async {+ final token = cancellation ?? CancellationToken();+ final response = await _execute(+ method,+ path,+ headers: headers(),+ json: json,+ params: params,+ responseMode: VmodalResponseMode.bytes,+ cancellation: token,+ );+ return readBounded(response, binaryResponseLimitBytes, cancellation: token);+ }++ Future<Map<String, Object?>> _requestJson(+ String method,+ String path, {+ required Map<String, String> headers,+ Object? json,+ Map<String, Object?> data = const <String, Object?>{},+ List<VmodalFilePart> files = const <VmodalFilePart>[],+ Map<String, Object?> params = const <String, Object?>{},+ bool usersApi = false,+ CancellationToken? cancellation,+ }) async {+ final token = cancellation ?? CancellationToken();+ final response = await _execute(+ method,+ path,+ headers: headers,+ json: json,+ data: data,+ files: files,+ params: params,+ usersApi: usersApi,+ cancellation: token,+ );+ final bytes = await readBounded(+ response,+ jsonResponseLimitBytes,+ cancellation: token,+ );+ if (bytes.isEmpty) return <String, Object?>{};+ final value = jsonDecodeStrict(bytes);+ if (value is! Map) {+ throw const MalformedResponse('JSON object response required');+ }+ return objectMap(value);+ }++ Future<VmodalResponse> _execute(+ String method,+ String path, {+ required Map<String, String> headers,+ Object? json,+ Map<String, Object?> data = const <String, Object?>{},+ List<VmodalFilePart> files = const <VmodalFilePart>[],+ Map<String, Object?> params = const <String, Object?>{},+ bool usersApi = false,+ VmodalResponseMode responseMode = VmodalResponseMode.json,+ required CancellationToken cancellation,+ }) async {+ final normalized = method.toUpperCase();+ final canRetry = normalized == 'GET' || normalized == 'HEAD';+ final uri = _uri(path, params, usersApi: usersApi);+ final request = VmodalRequest(+ method: normalized,+ uri: uri,+ headers: headers,+ jsonBody: json,+ formFields: data,+ files: files,+ responseMode: responseMode,+ cancellation: cancellation,+ );+ for (var attempt = 0; attempt <= config.normalizedMaxRetries; attempt++) {+ cancellation.throwIfCanceled();+ try {+ final response = await transport.send(request);+ if (canRetry &&+ const <int>{500, 502, 503, 504}.contains(response.statusCode) &&+ attempt < config.normalizedMaxRetries) {+ await _discard(response, cancellation);+ await _delay(Duration(milliseconds: 50 * (attempt + 1)));+ continue;+ }+ if (response.statusCode < 200 || response.statusCode > 299) {+ await _raiseForStatus(response, cancellation);+ }+ return response;+ } on TransportException {+ if (!canRetry || attempt >= config.normalizedMaxRetries) rethrow;+ await _delay(Duration(milliseconds: 50 * (attempt + 1)));+ }+ }+ throw const TransportException();+ }++ Future<void> _raiseForStatus(+ VmodalResponse response,+ CancellationToken token,+ ) async {+ final bytes = await readBounded(+ response,+ errorResponseLimitBytes,+ cancellation: token,+ );+ Object? body;+ if (bytes.isNotEmpty) {+ final contentType = response.headers.entries+ .where(+ (MapEntry<String, String> item) =>+ item.key.toLowerCase() == 'content-type',+ )+ .map((MapEntry<String, String> item) => item.value)+ .join(';')+ .toLowerCase();+ final text = utf8.decode(bytes);+ if (contentType.contains('json') ||+ text.trimLeft().startsWith('{') ||+ text.trimLeft().startsWith('[')) {+ try {+ body = jsonDecode(text);+ } on Object {+ body = null;+ }+ } else {+ body = text;+ }+ }+ if (response.statusCode == 401) {+ throw AuthException(+ 'authentication failed',+ statusCode: response.statusCode,+ body: body,+ );+ }+ if (response.statusCode == 422) {+ throw ValidationException(+ 'validation failed',+ statusCode: response.statusCode,+ body: body,+ details: body is Map ? body['detail'] : body,+ );+ }+ throw ApiException(+ 'api request failed',+ statusCode: response.statusCode,+ body: body,+ );+ }++ Future<void> _discard(+ VmodalResponse response,+ CancellationToken token,+ ) async {+ await readBounded(response, errorResponseLimitBytes, cancellation: token);+ }++ Uri _uri(String path, Map<String, Object?> params, {required bool usersApi}) {+ final base = usersApi+ ? strUsersBaseUrl(config.normalizedBaseUrl)+ : config.normalizedBaseUrl;+ final target = Uri.tryParse(path);+ final uri = target != null && target.hasScheme+ ? target+ : Uri.parse('$base${path.startsWith('/') ? path : '/$path'}');+ _requireSameOrigin(uri, Uri.parse(base));+ final query = <String, List<String>>{};+ uri.queryParametersAll.forEach((String key, List<String> values) {+ query[key] = List<String>.from(values);+ });+ params.forEach((String key, Object? value) {+ if (value == null) return;+ query[key] = value is Iterable+ ? value+ .where((Object? item) => item != null)+ .map((Object? item) => '$item')+ .toList()+ : <String>['$value'];+ });+ final pairs = <String>[];+ query.forEach((String key, List<String> values) {+ for (final value in values) {+ pairs.add(+ '${Uri.encodeQueryComponent(key)}=${Uri.encodeQueryComponent(value)}',+ );+ }+ });+ return uri.replace(query: pairs.isEmpty ? null : pairs.join('&'));+ }++ void _requireSameOrigin(Uri target, Uri base) {+ int port(Uri uri) => uri.hasPort+ ? uri.port+ : switch (uri.scheme) {+ 'https' => 443,+ 'http' => 80,+ _ => -1,+ };+ if (target.scheme != base.scheme ||+ target.host.toLowerCase() != base.host.toLowerCase() ||+ port(target) != port(base)) {+ throw const ValidationException(+ 'absolute API URL must match the configured origin',+ );+ }+ }++ void _assertGatewayHeaders(Map<String, String> values) {+ if (config.normalizedMode != 'gateway') return;+ const forbidden = <String>{+ 'x-user-id',+ 'x-tenant-id',+ 'x-user-email',+ 'x-userid',+ };+ if (values.keys.any(+ (String key) => forbidden.contains(key.toLowerCase()),+ )) {+ throw const ValidationException(+ 'gateway request contains forbidden identity headers',+ );+ }+ }+}diff --git a/lib/src/models.dart b/lib/src/models.dartnew file mode 100644index 0000000..57bed31--- /dev/null+++ b/lib/src/models.dart@@ -0,0 +1,701 @@+import 'errors.dart';+import 'utils.dart';++class JsonBackedResponse {+ const JsonBackedResponse([this.raw = const <String, Object?>{}]);++ final Map<String, Object?> raw;+}++class SearchResultItem extends JsonBackedResponse {+ const SearchResultItem(super.raw);+}++class GroupItem extends JsonBackedResponse {+ const GroupItem(super.raw);+}++class FolderUploadItem extends JsonBackedResponse {+ const FolderUploadItem(super.raw);+}++class CollectionAsset extends JsonBackedResponse {+ const CollectionAsset(super.raw);+}++class IndexationJobItem extends JsonBackedResponse {+ const IndexationJobItem(super.raw);+}++class AdminUserStatItem extends JsonBackedResponse {+ const AdminUserStatItem(super.raw);+}++class SearchRequest {+ const SearchRequest({+ this.queryText = '',+ this.queryMetadata,+ this.imageQuery,+ this.mode = 'vid_file',+ this.groupName = 'agroup',+ this.streamName = 'astream',+ this.searchSources = const <String>['ocr', 'asr', 'image'],+ this.searchCombineMode = 'union',+ this.startDate,+ this.endDate,+ this.offset = 0,+ this.limit = 50,+ this.textEmbScoreMin = 0.90,+ this.imageEmbScoreMin = 1.5,+ this.versionLancedb,+ });++ final String queryText;+ final Map<String, Object?>? queryMetadata;+ final String? imageQuery;+ final String mode;+ final String groupName;+ final String streamName;+ final List<String> searchSources;+ final String searchCombineMode;+ final String? startDate;+ final String? endDate;+ final int offset;+ final int limit;+ final double textEmbScoreMin;+ final double imageEmbScoreMin;+ final int? versionLancedb;++ void validate() {+ if (queryText.trim().isEmpty && (imageQuery?.trim().isEmpty ?? true)) {+ throw const ValidationException('query_text or image_query is required');+ }+ }++ Map<String, Object?> toJson() => _withoutNull(<String, Object?>{+ 'query_text': queryText,+ 'query_metadata': queryMetadata,+ 'image_query': imageQuery,+ 'mode': mode,+ 'group_name': groupName,+ 'stream_name': streamName,+ 'search_sources': searchSources,+ 'search_combine_mode': searchCombineMode,+ 'start_date': startDate,+ 'end_date': endDate,+ 'offset': offset,+ 'limit': limit,+ 'text_emb_score_min': textEmbScoreMin,+ 'image_emb_score_min': imageEmbScoreMin,+ 'version_lancedb': versionLancedb,+ });+}++class DeleteCollectionRequest {+ const DeleteCollectionRequest({+ required this.groupName,+ required this.mode,+ this.scope = 'all',+ this.dryRun = false,+ this.confirm = false,+ });++ final String groupName;+ final String mode;+ final String scope;+ final bool dryRun;+ final bool confirm;++ void validate() {+ strRequired(groupName, 'group_name');+ strRequired(mode, 'mode');+ }++ Map<String, Object?> toJson() => <String, Object?>{+ 'group_name': groupName,+ 'mode': mode,+ 'scope': scope,+ 'dry_run': dryRun,+ 'confirm': confirm,+ };+}++class CollectionAddAssetsRequest {+ const CollectionAddAssetsRequest({+ required this.collectionId,+ required this.assetIds,+ required this.mode,+ required this.groupName,+ this.streamName = 'astream',+ });++ final String collectionId;+ final List<String> assetIds;+ final String mode;+ final String groupName;+ final String streamName;++ void validate() {+ strRequired(collectionId, 'collection_id');+ if (assetIds.isEmpty) {+ throw const ValidationException('asset_ids is required');+ }+ strRequired(mode, 'mode');+ strRequired(groupName, 'group_name');+ }++ Map<String, Object?> toJson() => <String, Object?>{+ 'collection_id': collectionId,+ 'asset_ids': assetIds,+ 'mode': mode,+ 'group_name': groupName,+ 'stream_name': streamName,+ };+}++class IndexationSubmitRequest {+ const IndexationSubmitRequest({+ required this.mode,+ required this.groupName,+ this.streamName,+ this.indexType,+ this.modality,+ this.insertMode = 'append',+ this.createIndex = true,+ this.version = 'new_version',+ this.startDate,+ this.endDate,+ this.embeddingModel,+ this.reProcess = false,+ this.dryRun = false,+ });++ final String mode;+ final String groupName;+ final String? streamName;+ final String? indexType;+ final String? modality;+ final String insertMode;+ final bool createIndex;+ final String version;+ final String? startDate;+ final String? endDate;+ final String? embeddingModel;+ final bool reProcess;+ final bool dryRun;++ void validate() {+ strRequired(mode, 'mode');+ strRequired(groupName, 'group_name');+ }++ Map<String, Object?> toJson() => _withoutNull(<String, Object?>{+ 'mode': mode,+ 'group_name': groupName,+ 'stream_name': streamName,+ 'index_type': indexType,+ 'modality': modality,+ 'insert_mode': insertMode,+ 'create_index': createIndex,+ 'version': version,+ 'start_date': startDate,+ 'end_date': endDate,+ 'embedding_model': embeddingModel,+ 're_process': reProcess,+ 'dry_run': dryRun,+ });+}++class IndexationDeleteRequest {+ const IndexationDeleteRequest({+ required this.mode,+ required this.groupName,+ required this.version,+ this.modality,+ this.dryRun = false,+ this.confirm = false,+ });++ final String mode;+ final String groupName;+ final String version;+ final String? modality;+ final bool dryRun;+ final bool confirm;++ void validate() {+ strRequired(mode, 'mode');+ strRequired(groupName, 'group_name');+ strRequired(version, 'version');+ }++ Map<String, Object?> toJson() => _withoutNull(<String, Object?>{+ 'mode': mode,+ 'group_name': groupName,+ 'modality': modality,+ 'version': version,+ 'dry_run': dryRun,+ 'confirm': confirm,+ });+}++class ImageRecord {+ const ImageRecord({+ this.mode = '',+ this.groupName = '',+ this.streamName = 'astream',+ this.filename = '',+ this.frameId = '',+ this.userid,+ });++ final String mode;+ final String groupName;+ final String streamName;+ final String filename;+ final String frameId;+ final String? userid;++ Map<String, Object?> toJson({bool includeIdentity = true}) =>+ _withoutNull(<String, Object?>{+ 'mode': mode,+ 'group_name': groupName,+ 'stream_name': streamName,+ 'filename': filename,+ 'frame_id': frameId,+ if (includeIdentity) 'userid': userid,+ });+}++class ImageUrlRecord {+ const ImageUrlRecord({+ this.mode = '',+ this.groupName = '',+ this.modality = '',+ this.streamName = 'astream',+ this.filename = '',+ this.tsUnix13digits,+ });++ final String mode;+ final String groupName;+ final String modality;+ final String streamName;+ final String filename;+ final String? tsUnix13digits;++ Map<String, Object?> toJson() => _withoutNull(<String, Object?>{+ 'mode': mode,+ 'group_name': groupName,+ 'modality': modality,+ 'stream_name': streamName,+ 'filename': filename,+ 'ts_unix_13digits': tsUnix13digits,+ });+}++class HealthResponse extends JsonBackedResponse {+ HealthResponse(super.raw)+ : status = '${raw['status'] ?? ''}',+ timestamp = raw['timestamp']?.toString(),+ version = raw['version']?.toString(),+ pythonVersion = raw['python_version']?.toString(),+ dependencies = raw['dependencies'];++ final String status;+ final String? timestamp;+ final String? version;+ final String? pythonVersion;+ final Object? dependencies;+}++class SearchResponse extends JsonBackedResponse {+ SearchResponse(super.raw)+ : data = raw['data'] is List+ ? List<Object?>.from(raw['data']! as List)+ : <Object?>[],+ cntActual = intValue(raw['cnt_actual']),+ cntTotal = intValue(raw['cnt_total']),+ executionTimeMs = doubleValue(raw['execution_time_ms']);++ final List<Object?> data;+ final int cntActual;+ final int cntTotal;+ final double executionTimeMs;+}++class GroupsResponse extends JsonBackedResponse {+ GroupsResponse(super.raw)+ : data = raw['data'] is List+ ? List<Object?>.from(raw['data']! as List)+ : <Object?>[],+ total = intValue(raw['total']),+ executionTimeMs = doubleValue(raw['execution_time_ms']);++ final List<Object?> data;+ final int total;+ final double executionTimeMs;+}++class ExternalUploadSignedUrlResponse extends JsonBackedResponse {+ ExternalUploadSignedUrlResponse(super.raw)+ : userId = '${raw['user_id'] ?? ''}',+ expiresIn = intValue(raw['expires_in']),+ key = '${raw['key'] ?? ''}',+ url = '${raw['url'] ?? ''}',+ method = '${raw['method'] ?? 'PUT'}';++ final String userId;+ final int expiresIn;+ final String key;+ final String url;+ final String method;+}++class MultipartPart extends JsonBackedResponse {+ MultipartPart(super.raw)+ : partNumber = intValue(raw['part_number']),+ etag = '${raw['etag'] ?? ''}',+ sizeBytes = intValue(raw['size_bytes']);++ final int partNumber;+ final String etag;+ final int sizeBytes;+}++class MultipartSignedPart extends JsonBackedResponse {+ MultipartSignedPart(super.raw)+ : partNumber = intValue(raw['part_number']),+ url = '${raw['url'] ?? ''}',+ method = '${raw['method'] ?? 'PUT'}',+ headers = objectMap(+ raw['headers'],+ ).map((String key, Object? value) => MapEntry(key, '$value'));++ final int partNumber;+ final String url;+ final String method;+ final Map<String, String> headers;+}++class MultipartCreateResponse extends JsonBackedResponse {+ MultipartCreateResponse(super.raw)+ : requestId = '${raw['request_id'] ?? ''}',+ uploadId = '${raw['upload_id'] ?? ''}',+ key = '${raw['key'] ?? ''}',+ sizeBytes = intValue(raw['size_bytes']),+ partSizeBytes = intValue(raw['part_size_bytes']),+ partCount = intValue(raw['part_count']),+ status = '${raw['status'] ?? 'created'}';++ final String requestId;+ final String uploadId;+ final String key;+ final int sizeBytes;+ final int partSizeBytes;+ final int partCount;+ final String status;+}++class MultipartSignResponse extends JsonBackedResponse {+ MultipartSignResponse(super.raw)+ : parts = objectList(raw['parts']).map(MultipartSignedPart.new).toList(),+ expiresIn = intValue(raw['expires_in']);++ final List<MultipartSignedPart> parts;+ final int expiresIn;+}++class MultipartStatusResponse extends JsonBackedResponse {+ MultipartStatusResponse(super.raw)+ : status = '${raw['status'] ?? 'uploading'}',+ parts = objectList(raw['parts']).map(MultipartPart.new).toList(),+ etag = '${raw['etag'] ?? ''}',+ sizeBytes = intValue(raw['size_bytes']);++ final String status;+ final List<MultipartPart> parts;+ final String etag;+ final int sizeBytes;+}++class MultipartCompleteResponse extends JsonBackedResponse {+ MultipartCompleteResponse(super.raw)+ : status = '${raw['status'] ?? 'completed'}',+ key = '${raw['key'] ?? ''}',+ etag = '${raw['etag'] ?? ''}',+ sizeBytes = intValue(raw['size_bytes']),+ alreadyCompleted = raw['already_completed'] == true;++ final String status;+ final String key;+ final String etag;+ final int sizeBytes;+ final bool alreadyCompleted;+}++class UploadResponse extends JsonBackedResponse {+ const UploadResponse(super.raw);+}++class VideoUploadResponse extends JsonBackedResponse {+ VideoUploadResponse(super.raw)+ : userId = '${raw['user_id'] ?? ''}',+ key = '${raw['key'] ?? ''}',+ url = '${raw['url'] ?? ''}',+ method = '${raw['method'] ?? 'PUT'}',+ fileName = '${raw['filename'] ?? ''}',+ sizeBytes = intValue(raw['size_bytes']),+ statusCode = intValue(raw['status_code']),+ uploaded = raw['uploaded'] == true,+ uploadStrategy = '${raw['upload_strategy'] ?? 'single'}',+ uploadId = '${raw['upload_id'] ?? ''}',+ etag = '${raw['etag'] ?? ''}',+ partSizeBytes = intValue(raw['part_size_bytes']),+ partCount = intValue(raw['part_count']),+ partsUploaded = intValue(raw['parts_uploaded']),+ resumed = raw['resumed'] == true,+ attemptCount = intValue(raw['attempt_count']),+ destPath = '${raw['dest_path'] ?? ''}';++ final String userId;+ final String key;+ final String url;+ final String method;+ final String fileName;+ final int sizeBytes;+ final int statusCode;+ final bool uploaded;+ final String uploadStrategy;+ final String uploadId;+ final String etag;+ final int partSizeBytes;+ final int partCount;+ final int partsUploaded;+ final bool resumed;+ final int attemptCount;+ final String destPath;+}++class VideoUploadBulkResponse extends JsonBackedResponse {+ VideoUploadBulkResponse(super.raw)+ : data = objectList(raw['data']).map(VideoUploadResponse.new).toList(),+ total = intValue(raw['total']);++ final List<VideoUploadResponse> data;+ final int total;+}++class FolderUploadResponse extends JsonBackedResponse {+ const FolderUploadResponse(super.raw);+}++class MetadataParquetUploadResponse extends JsonBackedResponse {+ const MetadataParquetUploadResponse(super.raw);+}++class CollectionDescriptionUpdateResponse extends JsonBackedResponse {+ const CollectionDescriptionUpdateResponse(super.raw);+}++class DeleteCollectionResponse extends JsonBackedResponse {+ const DeleteCollectionResponse(super.raw);+}++class CollectionAddAssetsResponse extends JsonBackedResponse {+ const CollectionAddAssetsResponse(super.raw);+}++class IndexationJobsListResponse extends JsonBackedResponse {+ IndexationJobsListResponse(super.raw)+ : data = raw['data'] is List+ ? List<Object?>.from(raw['data']! as List)+ : <Object?>[],+ total = intValue(raw['total']);++ final List<Object?> data;+ final int total;+}++class IndexationSubmitResponse extends JsonBackedResponse {+ IndexationSubmitResponse(super.raw)+ : jobId = '${raw['job_id'] ?? ''}',+ status = '${raw['status'] ?? ''}';++ final String jobId;+ final String status;+}++class IndexationStatusResponse extends JsonBackedResponse {+ IndexationStatusResponse(super.raw)+ : jobId = '${raw['job_id'] ?? ''}',+ status = '${raw['status'] ?? ''}';++ final String jobId;+ final String status;+}++class IndexationDeleteResponse extends JsonBackedResponse {+ IndexationDeleteResponse(super.raw) : status = '${raw['status'] ?? ''}';++ final String status;+}++class AdminUserStatsResponse extends JsonBackedResponse {+ AdminUserStatsResponse(super.raw)+ : data = raw['data'] is List+ ? List<Object?>.from(raw['data']! as List)+ : <Object?>[],+ total = intValue(raw['total']);++ final List<Object?> data;+ final int total;+}++class UserProfile extends JsonBackedResponse {+ UserProfile(super.raw)+ : userId = raw['user_id']?.toString(),+ email = raw['email']?.toString(),+ name = raw['name']?.toString(),+ roles = raw['roles'] is List+ ? List<Object?>.from(raw['roles']! as List)+ : <Object?>[],+ tenantId = raw['tenant_id']?.toString(),+ permissions = raw['permissions'] is List+ ? (raw['permissions']! as List)+ .map((Object? value) => '$value')+ .toList()+ : <String>[],+ type = '${raw['type'] ?? 'user'}';++ final String? userId;+ final String? email;+ final String? name;+ final List<Object?> roles;+ final String? tenantId;+ final List<String> permissions;+ final String type;+}++class UsageUserDetail extends JsonBackedResponse {+ UsageUserDetail(super.raw)+ : date = '${raw['date'] ?? ''}',+ userId = '${raw['user_id'] ?? ''}',+ total = intValue(raw['total']),+ endpoints = objectMap(+ raw['endpoints'],+ ).map((String key, Object? value) => MapEntry(key, intValue(value)));++ final String date;+ final String userId;+ final int total;+ final Map<String, int> endpoints;+}++class CacheStats extends JsonBackedResponse {+ CacheStats(super.raw)+ : apikeyCacheSize = intValue(raw['apikey_cache_size']),+ rateLimiterBuckets = intValue(raw['rate_limiter_buckets']),+ config = objectMap(raw['config']);++ final int apikeyCacheSize;+ final int rateLimiterBuckets;+ final Map<String, Object?> config;+}++class PresignedUploadResponse extends JsonBackedResponse {+ PresignedUploadResponse(super.raw)+ : userId = '${raw['user_id'] ?? ''}',+ expiresIn = intValue(raw['expires_in']),+ key = '${raw['key'] ?? ''}',+ url = '${raw['url'] ?? ''}',+ method = '${raw['method'] ?? 'PUT'}';++ final String userId;+ final int expiresIn;+ final String key;+ final String url;+ final String method;+}++class PresignedFolderItem extends JsonBackedResponse {+ PresignedFolderItem(super.raw)+ : filename = '${raw['filename'] ?? ''}',+ key = '${raw['key'] ?? ''}',+ url = '${raw['url'] ?? ''}',+ method = '${raw['method'] ?? 'PUT'}';++ final String filename;+ final String key;+ final String url;+ final String method;+}++class PresignedFolderResponse extends JsonBackedResponse {+ PresignedFolderResponse(super.raw)+ : userId = '${raw['user_id'] ?? ''}',+ expiresIn = intValue(raw['expires_in']),+ files = objectList(raw['files']).map(PresignedFolderItem.new).toList();++ final String userId;+ final int expiresIn;+ final List<PresignedFolderItem> files;+}++class ImageUrlResponse extends JsonBackedResponse {+ ImageUrlResponse(super.raw)+ : found = raw['found'] == true,+ urlPreSigned = '${raw['url_pre_signed'] ?? ''}',+ fullPath = '${raw['full_path'] ?? ''}',+ expireSec = intValue(raw['expire_sec']),+ error = '${raw['error'] ?? ''}';++ final bool found;+ final String urlPreSigned;+ final String fullPath;+ final int expireSec;+ final String error;+}++class ImageUrlBulkResponse extends JsonBackedResponse {+ ImageUrlBulkResponse(super.raw) : records = objectList(raw['records']);++ final List<Map<String, Object?>> records;+}++class ImageGetBulkResponse extends JsonBackedResponse {+ ImageGetBulkResponse(super.raw) : records = objectList(raw['records']);++ final List<Map<String, Object?>> records;+}++class ImageResponse extends JsonBackedResponse {+ ImageResponse(super.raw)+ : found = raw['found'] == true,+ imgBase64 = '${raw['img_base64'] ?? ''}';++ final bool found;+ final String imgBase64;+}++class FullPathImageResponse extends JsonBackedResponse {+ FullPathImageResponse(super.raw)+ : found = raw['found'] == true,+ imgBase64 = '${raw['img_base64'] ?? ''}',+ fullpath = '${raw['fullpath'] ?? ''}';++ final bool found;+ final String imgBase64;+ final String fullpath;+}++class ImageBulkResponse extends JsonBackedResponse {+ ImageBulkResponse(super.raw) : records = objectList(raw['records']);++ final List<Map<String, Object?>> records;+}++Map<String, Object?> _withoutNull(Map<String, Object?> value) {+ value.removeWhere((String key, Object? item) => item == null);+ return value;+}diff --git a/lib/src/resources.dart b/lib/src/resources.dartnew file mode 100644index 0000000..494f6c7--- /dev/null+++ b/lib/src/resources.dart@@ -0,0 +1,534 @@+import 'dart:typed_data';++import 'errors.dart';+import 'http.dart';+import 'models.dart';+import 'routes.dart';+import 'transport.dart';+import 'upload.dart';+import 'utils.dart';++class AuthResource {+ AuthResource(this.http);++ final VmodalHttp http;++ Future<HealthResponse> health({CancellationToken? cancellation}) async =>+ HealthResponse(+ await http.request(+ 'GET',+ Routes.full(Routes.health),+ cancellation: cancellation,+ ),+ );++ Future<bool> authCheck({CancellationToken? cancellation}) async {+ await health(cancellation: cancellation);+ return true;+ }++ Future<UserProfile> me({CancellationToken? cancellation}) async =>+ UserProfile(+ await http.requestUsers(+ 'GET',+ Routes.usersFull(Routes.authMe),+ cancellation: cancellation,+ ),+ );+}++class SearchesResource {+ SearchesResource(this.http);++ final VmodalHttp http;++ Future<SearchResponse> searchVideo(+ SearchRequest request, {+ CancellationToken? cancellation,+ }) async {+ request.validate();+ return SearchResponse(+ await http.request(+ 'POST',+ Routes.full(Routes.searchClient),+ json: request.toJson(),+ cancellation: cancellation,+ ),+ );+ }+}++class CollectionsResource {+ CollectionsResource(this.http, this.signedUploads);++ final VmodalHttp http;+ final SignedUploadTransport signedUploads;++ Future<GroupsResponse> listGroups({+ String? mode,+ CancellationToken? cancellation,+ }) async => GroupsResponse(+ await http.request(+ 'GET',+ Routes.full(Routes.groups),+ params: <String, Object?>{if (mode != null) 'mode': mode},+ cancellation: cancellation,+ ),+ );++ Future<UploadResponse> uploadFile(+ VmodalFilePart part, {+ String groupName = '',+ String mode = 'vid_file',+ String streamName = 'astream',+ String description = '',+ List<String> tag = const <String>[],+ CancellationToken? cancellation,+ }) async => UploadResponse(+ await http.request(+ 'POST',+ Routes.full(Routes.upload),+ data: <String, Object?>{+ 'mode': mode,+ 'group_name': groupName,+ 'stream_name': streamName,+ 'description': description,+ if (tag.isNotEmpty) 'tag': tag,+ },+ files: <VmodalFilePart>[part],+ cancellation: cancellation,+ ),+ );++ Never uploadFolder() => throw const FeatureDisabled(+ 'folder upload is disabled on server (cannot scan remote PC/laptop)',+ );++ Future<MetadataParquetUploadResponse> uploadMetadataJsonl(+ VmodalFilePart part, {+ String mode = 'img_file',+ String groupName = '',+ String streamName = '',+ String writeMode = 'append',+ bool allowOverlap = false,+ CancellationToken? cancellation,+ }) async {+ final form = <String, Object?>{+ 'mode': mode,+ 'group_name': groupName,+ 'stream_name': streamName,+ 'write_mode': writeMode,+ 'allow_overlap': '$allowOverlap',+ if (http.config.normalizedMode == 'direct')+ 'user_id': http.config.normalizedUserId,+ };+ Map<String, Object?> raw;+ try {+ raw = await http.request(+ 'POST',+ Routes.full(Routes.uploadMetadataJsonl),+ data: form,+ files: <VmodalFilePart>[part],+ cancellation: cancellation,+ );+ } on ApiException catch (error) {+ if (error.statusCode != 404) rethrow;+ raw = await http.request(+ 'POST',+ Routes.uploadMetadataItemParquetInternal,+ data: form,+ files: <VmodalFilePart>[part],+ cancellation: cancellation,+ );+ }+ return MetadataParquetUploadResponse(raw);+ }++ Future<CollectionAddAssetsResponse> addAssets({+ required String collectionId,+ required List<String> assetIds,+ required String mode,+ required String groupName,+ String streamName = 'astream',+ CancellationToken? cancellation,+ }) async {+ final request = CollectionAddAssetsRequest(+ collectionId: collectionId,+ assetIds: assetIds,+ mode: mode,+ groupName: groupName,+ streamName: streamName,+ );+ request.validate();+ final path = Routes.collectionAddAssets.replaceAll(+ '{collection_id}',+ Uri.encodeComponent(collectionId),+ );+ return CollectionAddAssetsResponse(+ await http.request(+ 'POST',+ Routes.full(path),+ json: request.toJson(),+ cancellation: cancellation,+ ),+ );+ }++ Future<CollectionDescriptionUpdateResponse> updateDescription({+ required String groupName,+ required String mode,+ required String streamName,+ required String filenameSanitized,+ String? description,+ List<String>? tag,+ CancellationToken? cancellation,+ }) async => CollectionDescriptionUpdateResponse(+ await http.request(+ 'POST',+ Routes.full(Routes.collectionDescriptionUpdate),+ data: <String, Object?>{+ 'group_name': groupName,+ 'mode': mode,+ 'stream_name': streamName,+ 'filename_sanitized': filenameSanitized,+ if (description != null) 'description': description,+ if (tag != null) 'tag': tag,+ },+ cancellation: cancellation,+ ),+ );++ Future<DeleteCollectionResponse> delete({+ required String groupName,+ required String mode,+ String scope = 'all',+ bool dryRun = false,+ bool confirm = false,+ CancellationToken? cancellation,+ }) async {+ final request = DeleteCollectionRequest(+ groupName: groupName,+ mode: mode,+ scope: scope,+ dryRun: dryRun,+ confirm: confirm,+ );+ request.validate();+ return DeleteCollectionResponse(+ await http.request(+ 'DELETE',+ Routes.full(Routes.collectionDelete),+ json: request.toJson(),+ cancellation: cancellation,+ ),+ );+ }++ Never create() => throw const FeatureDisabled(+ 'no server endpoint; upload creates collection implicitly',+ );+ Never edit() => throw const FeatureDisabled(+ 'no server endpoint; upload creates collection implicitly',+ );+ Never autoIndexGet() => throw const FeatureDisabled(+ 'collection auto_index is disabled on server',+ );+ Never autoIndexSet() => throw const FeatureDisabled(+ 'collection auto_index is disabled on server',+ );+}++class IndexesResource {+ IndexesResource(this.http);++ final VmodalHttp http;++ Future<IndexationJobsListResponse> jobsList({+ String? status,+ String? mode,+ String? groupName,+ int limit = 200,+ CancellationToken? cancellation,+ }) async {+ if (limit < 1 || limit > 1000) {+ throw const ValidationException('limit must be between 1 and 1000');+ }+ return IndexationJobsListResponse(+ await http.request(+ 'GET',+ Routes.full(Routes.indexationJobs),+ params: <String, Object?>{+ 'limit': limit,+ if (status != null) 'status': status,+ if (mode != null) 'mode': mode,+ if (groupName != null) 'group_name': groupName,+ },+ cancellation: cancellation,+ ),+ );+ }++ Future<IndexationSubmitResponse> createIndex(+ IndexationSubmitRequest request, {+ CancellationToken? cancellation,+ }) async {+ request.validate();+ return IndexationSubmitResponse(+ await http.request(+ 'POST',+ Routes.full(Routes.indexationSubmit),+ json: request.toJson(),+ cancellation: cancellation,+ ),+ );+ }++ Future<IndexationStatusResponse> indexStatus(+ String jobId, {+ CancellationToken? cancellation,+ }) async {+ final clean = strRequired(jobId, 'job_id');+ final path = Routes.indexationStatus.replaceAll(+ '{job_id}',+ Uri.encodeComponent(clean),+ );+ try {+ return IndexationStatusResponse(+ await http.request(+ 'GET',+ Routes.full(path),+ cancellation: cancellation,+ ),+ );+ } on ApiException catch (error) {+ if (error.statusCode != 404) rethrow;+ final jobs = await jobsList(limit: 1000, cancellation: cancellation);+ final row = objectList(jobs.raw['data'])+ .where((Map<String, Object?> value) => '${value['job_id']}' == clean)+ .firstOrNull;+ if (row == null) rethrow;+ return IndexationStatusResponse(row);+ }+ }++ Future<IndexationDeleteResponse> deleteIndex(+ IndexationDeleteRequest request, {+ CancellationToken? cancellation,+ }) async {+ request.validate();+ return IndexationDeleteResponse(+ await http.request(+ 'DELETE',+ Routes.full(Routes.indexationDelete),+ json: request.toJson(),+ cancellation: cancellation,+ ),+ );+ }++ Never embeddingModels() => throw const FeatureDisabled(+ 'embedding models endpoint is disabled on server',+ );+}++class AdminResource {+ AdminResource(this.http);++ final VmodalHttp http;++ Future<AdminUserStatsResponse> userStats({+ CancellationToken? cancellation,+ }) async => AdminUserStatsResponse(+ await http.request(+ 'GET',+ Routes.full(Routes.adminUserStats),+ cancellation: cancellation,+ ),+ );++ Future<UsageUserDetail> usage({+ String date = '',+ CancellationToken? cancellation,+ }) async => UsageUserDetail(+ await http.requestUsers(+ 'GET',+ Routes.usersFull(Routes.adminUsage),+ params: <String, Object?>{+ if (date.trim().isNotEmpty) 'date': date.trim(),+ },+ cancellation: cancellation,+ ),+ );++ Future<CacheStats> cacheStats({CancellationToken? cancellation}) async =>+ CacheStats(+ await http.requestUsers(+ 'GET',+ Routes.usersFull(Routes.adminCacheStats),+ cancellation: cancellation,+ ),+ );+}++class R2Resource {+ R2Resource(this.http);++ final VmodalHttp http;++ Future<PresignedUploadResponse> presignUploadFile({+ required String mode,+ required String groupName,+ required String streamName,+ required String modality,+ required String filename,+ int expiresIn = 900,+ CancellationToken? cancellation,+ }) async => PresignedUploadResponse(+ await http.requestUsers(+ 'GET',+ Routes.usersFull(Routes.r2UploadFile),+ params: <String, Object?>{+ 'mode': mode,+ 'group_name': groupName,+ 'stream_name': streamName,+ 'modality': modality,+ 'filename': filename,+ 'expires_in': expiresIn,+ },+ cancellation: cancellation,+ ),+ );++ Future<PresignedFolderResponse> presignUploadFolderVideo({+ required String mode,+ required String groupName,+ required String streamName,+ required List<String> filenames,+ int expiresIn = 900,+ CancellationToken? cancellation,+ }) async => PresignedFolderResponse(+ await http.requestUsers(+ 'POST',+ Routes.usersFull(Routes.r2UploadFolderVideo),+ json: <String, Object?>{+ 'mode': mode,+ 'group_name': groupName,+ 'stream_name': streamName,+ 'filenames': filenames,+ 'expires_in': expiresIn,+ },+ cancellation: cancellation,+ ),+ );+}++class ImagesResource {+ ImagesResource(this.http);++ final VmodalHttp http;++ Future<ImageUrlResponse> getUrl({+ required String mode,+ required String groupName,+ required String modality,+ required String filename,+ String streamName = 'astream',+ Object? tsUnix13digits,+ String? userid,+ CancellationToken? cancellation,+ }) async => ImageUrlResponse(+ await http.request(+ 'POST',+ Routes.full(Routes.imageGetUrl),+ json: <String, Object?>{+ 'mode': mode,+ 'group_name': groupName,+ 'modality': modality,+ 'stream_name': streamName,+ 'filename': filename,+ if (tsUnix13digits != null) 'ts_unix_13digits': '$tsUnix13digits',+ if (http.config.normalizedMode == 'direct' &&+ (userid?.trim().isNotEmpty ?? false))+ 'userid': userid,+ },+ cancellation: cancellation,+ ),+ );++ Future<ImageUrlBulkResponse> getUrlBulk(+ List<Map<String, Object?>> records, {+ String? userid,+ CancellationToken? cancellation,+ }) async {+ final safe = http.config.normalizedMode == 'direct'+ ? records+ : records+ .map(+ (Map<String, Object?> row) => Map<String, Object?>.from(row)+ ..remove('userid')+ ..remove('user_id'),+ )+ .toList();+ return ImageUrlBulkResponse(+ await http.request(+ 'POST',+ Routes.full(Routes.imageGetUrlBulk),+ json: <String, Object?>{+ 'records': safe,+ if (http.config.normalizedMode == 'direct' &&+ (userid?.trim().isNotEmpty ?? false))+ 'userid': userid,+ },+ cancellation: cancellation,+ ),+ );+ }++ Future<Uint8List> getImageFromUrl(+ String urlPreSigned, {+ String? userid,+ CancellationToken? cancellation,+ }) => http.requestBytes(+ 'POST',+ Routes.full(Routes.imageGetImage),+ json: <String, Object?>{+ 'url_pre_signed': urlPreSigned,+ if (http.config.normalizedMode == 'direct' &&+ (userid?.trim().isNotEmpty ?? false))+ 'userid': userid,+ },+ cancellation: cancellation,+ );++ Future<ImageGetBulkResponse> getImageBulkFromUrls(+ List<String> urls, {+ String? userid,+ CancellationToken? cancellation,+ }) async => ImageGetBulkResponse(+ await http.request(+ 'POST',+ Routes.full(Routes.imageGetImageBulk),+ json: <String, Object?>{+ 'urls': urls,+ if (http.config.normalizedMode == 'direct' &&+ (userid?.trim().isNotEmpty ?? false))+ 'userid': userid,+ },+ cancellation: cancellation,+ ),+ );+}++class GDriveResource {+ Never privateAuthUrl() => throw const FeatureDisabled(+ 'private google drive auth endpoint is disabled on server',+ );+ Never privateDownload() => throw const FeatureDisabled(+ 'private google drive download endpoint is disabled on server',+ );+}++class SqlResource {+ Never query() =>+ throw const FeatureDisabled('sql query endpoint is disabled on server');+}diff --git a/lib/src/routes.dart b/lib/src/routes.dartnew file mode 100644index 0000000..a33d7a9--- /dev/null+++ b/lib/src/routes.dart@@ -0,0 +1,377 @@+import 'errors.dart';++enum RouteCategory {+ active,+ usersApi,+ image,+ signedSingle,+ multipartExperimental,+ deprecated,+ disabled,+}++class RouteSpec {+ const RouteSpec(+ this.name,+ this.method,+ this.path,+ this.category,+ this.source,+ );++ final String name;+ final String method;+ final String path;+ final RouteCategory category;+ final String source;+}++abstract final class Routes {+ static const String prefix = '/api/external/v1';+ static const String usersApiPrefix = '/api/v1';++ static const String health = '/health';+ static const String searchClient = '/search';+ static const String groups = '/collection/groups';+ static const String indexationJobs = '/indexation/jobs';+ static const String indexationSubmit = '/indexation/job/create';+ static const String indexationStatus = '/indexation/job/{job_id}';+ static const String indexationDelete = '/indexation/index/delete';+ static const String upload = '/collection/upload';+ static const String uploadFolder = '/upload/folder';+ static const String uploadGoogleDriveFolder =+ '/collection/upload/google_drive';+ static const String uploadMetadataJsonl = '/collection/upload/metadata';+ static const String collectionDescriptionUpdate =+ '/collection/description/update';+ static const String collectionDelete = '/collection/delete';+ static const String collectionAddAssets =+ '/collection/{collection_id}/assets/create';+ static const String adminUserStats = '/admin/user-stats';+ static const String uploadMetadataItemParquetInternal =+ '/api/internal/v1/collection/upload/metadata';++ static const String imageGetUrl = '/image/get_url';+ static const String imageGetUrlBulk = '/image/get_url_bulk';+ static const String imageGetImage = '/image/get_image';+ static const String imageGetImageBulk = '/image/get_image_bulk';++ static const String authMe = '/auth/me';+ static const String adminUsage = '/admin/usage';+ static const String adminCacheStats = '/admin/cache/stats';+ static const String r2Credentials = '/get_r2_credentials/';+ static const String r2UploadFile = '/upload_file/';+ static const String r2UploadFolderVideo = '/upload_folder_video/';++ static const String externalUploadGetSignedUrl =+ '/collections/external_upload_get_signed_url';+ static const String externalUploadDone = '/collection/upload/done';+ static const String externalUploadMultipartCreate =+ '/collections/external_upload_multipart/create';+ static const String externalUploadMultipartSignParts =+ '/collections/external_upload_multipart/sign_parts';+ static const String externalUploadMultipartStatus =+ '/collections/external_upload_multipart/status';+ static const String externalUploadMultipartComplete =+ '/collections/external_upload_multipart/complete';+ static const String externalUploadMultipartAbort =+ '/collections/external_upload_multipart/abort';++ static const List<RouteSpec> specs = <RouteSpec>[+ RouteSpec('auth.health', 'GET', health, RouteCategory.active, 'upstream'),+ RouteSpec(+ 'auth.auth_check',+ 'GET',+ health,+ RouteCategory.active,+ 'upstream',+ ),+ RouteSpec(+ 'searches.search_video',+ 'POST',+ searchClient,+ RouteCategory.active,+ 'upstream',+ ),+ RouteSpec(+ 'collections.list_groups',+ 'GET',+ groups,+ RouteCategory.active,+ 'upstream',+ ),+ RouteSpec(+ 'collections.upload_file',+ 'POST',+ upload,+ RouteCategory.active,+ 'upstream',+ ),+ RouteSpec(+ 'collections.upload_metadata_jsonl',+ 'POST',+ uploadMetadataJsonl,+ RouteCategory.active,+ 'upstream',+ ),+ RouteSpec(+ 'collections.update_description',+ 'POST',+ collectionDescriptionUpdate,+ RouteCategory.active,+ 'upstream',+ ),+ RouteSpec(+ 'collections.delete',+ 'DELETE',+ collectionDelete,+ RouteCategory.active,+ 'upstream',+ ),+ RouteSpec(+ 'collections.add_assets',+ 'POST',+ collectionAddAssets,+ RouteCategory.active,+ 'upstream',+ ),+ RouteSpec(+ 'indexes.jobs_list',+ 'GET',+ indexationJobs,+ RouteCategory.active,+ 'upstream',+ ),+ RouteSpec(+ 'indexes.create_index',+ 'POST',+ indexationSubmit,+ RouteCategory.active,+ 'upstream',+ ),+ RouteSpec(+ 'indexes.index_status',+ 'GET',+ indexationStatus,+ RouteCategory.active,+ 'upstream',+ ),+ RouteSpec(+ 'indexes.delete_index',+ 'DELETE',+ indexationDelete,+ RouteCategory.active,+ 'upstream',+ ),+ RouteSpec(+ 'admin.user_stats',+ 'GET',+ adminUserStats,+ RouteCategory.active,+ 'upstream',+ ),+ RouteSpec(+ 'collections.upload_google_drive_folder',+ 'POST',+ uploadGoogleDriveFolder,+ RouteCategory.deprecated,+ 'upstream',+ ),+ RouteSpec(+ 'collections.upload_folder',+ 'POST',+ uploadFolder,+ RouteCategory.disabled,+ 'upstream',+ ),+ RouteSpec(+ 'indexes.embedding_models',+ 'GET',+ '/indexes/embedding_models',+ RouteCategory.disabled,+ 'upstream',+ ),+ RouteSpec(+ 'collections.auto_index_get',+ 'GET',+ '/collection/auto_index',+ RouteCategory.disabled,+ 'upstream',+ ),+ RouteSpec(+ 'collections.auto_index_set',+ 'POST',+ '/collection/auto_index',+ RouteCategory.disabled,+ 'upstream',+ ),+ RouteSpec(+ 'gdrive.private_auth_url',+ 'POST',+ '/gdrive/private/auth-url',+ RouteCategory.disabled,+ 'upstream',+ ),+ RouteSpec(+ 'gdrive.private_download',+ 'POST',+ '/gdrive/private/folder/download',+ RouteCategory.disabled,+ 'upstream',+ ),+ RouteSpec(+ 'sql.query',+ 'POST',+ '/sql/query',+ RouteCategory.disabled,+ 'upstream',+ ),+ RouteSpec(+ 'collections.create',+ 'NONE',+ '',+ RouteCategory.disabled,+ 'sdk_contract',+ ),+ RouteSpec(+ 'collections.edit',+ 'NONE',+ '',+ RouteCategory.disabled,+ 'sdk_contract',+ ),+ RouteSpec(+ 'images.get_url',+ 'POST',+ imageGetUrl,+ RouteCategory.image,+ 'apionly_serve_img.py',+ ),+ RouteSpec(+ 'images.get_url_bulk',+ 'POST',+ imageGetUrlBulk,+ RouteCategory.image,+ 'apionly_serve_img.py',+ ),+ RouteSpec(+ 'images.get_image_from_url',+ 'POST',+ imageGetImage,+ RouteCategory.image,+ 'apionly_serve_img.py',+ ),+ RouteSpec(+ 'images.get_image_bulk_from_urls',+ 'POST',+ imageGetImageBulk,+ RouteCategory.image,+ 'apionly_serve_img.py',+ ),+ RouteSpec('auth.me', 'GET', authMe, RouteCategory.usersApi, 'users_api'),+ RouteSpec(+ 'admin.usage',+ 'GET',+ adminUsage,+ RouteCategory.usersApi,+ 'users_api',+ ),+ RouteSpec(+ 'admin.cache_stats',+ 'GET',+ adminCacheStats,+ RouteCategory.usersApi,+ 'users_api',+ ),+ RouteSpec(+ 'r2.credentials',+ 'GET',+ r2Credentials,+ RouteCategory.usersApi,+ 'users_api',+ ),+ RouteSpec(+ 'r2.presign_upload_file',+ 'GET',+ r2UploadFile,+ RouteCategory.usersApi,+ 'users_api',+ ),+ RouteSpec(+ 'r2.presign_upload_folder_video',+ 'POST',+ r2UploadFolderVideo,+ RouteCategory.usersApi,+ 'users_api',+ ),+ RouteSpec(+ 'collections.video_upload.presign',+ 'POST',+ externalUploadGetSignedUrl,+ RouteCategory.signedSingle,+ 'sdk_python',+ ),+ RouteSpec(+ 'collections.video_upload.done',+ 'POST',+ externalUploadDone,+ RouteCategory.signedSingle,+ 'sdk_python',+ ),+ RouteSpec(+ 'multipart.create',+ 'POST',+ externalUploadMultipartCreate,+ RouteCategory.multipartExperimental,+ 'sdk_python',+ ),+ RouteSpec(+ 'multipart.sign_parts',+ 'POST',+ externalUploadMultipartSignParts,+ RouteCategory.multipartExperimental,+ 'sdk_python',+ ),+ RouteSpec(+ 'multipart.status',+ 'GET',+ externalUploadMultipartStatus,+ RouteCategory.multipartExperimental,+ 'sdk_python',+ ),+ RouteSpec(+ 'multipart.complete',+ 'POST',+ externalUploadMultipartComplete,+ RouteCategory.multipartExperimental,+ 'sdk_python',+ ),+ RouteSpec(+ 'multipart.abort',+ 'POST',+ externalUploadMultipartAbort,+ RouteCategory.multipartExperimental,+ 'sdk_python',+ ),+ RouteSpec(+ 'metadata.internal_fallback',+ 'POST',+ uploadMetadataItemParquetInternal,+ RouteCategory.active,+ 'sdk_python',+ ),+ ];++ static String full(String path) => _addPrefix(path, prefix);+ static String usersFull(String path) => _addPrefix(path, usersApiPrefix);++ static String _addPrefix(String path, String valuePrefix) {+ if (Uri.tryParse(path)?.hasScheme ?? false) {+ throw const ValidationException(+ 'absolute URLs are not allowed in the API route table',+ );+ }+ final clean = path.startsWith('/') ? path : '/$path';+ return '$valuePrefix$clean';+ }+}diff --git a/lib/src/transport.dart b/lib/src/transport.dartnew file mode 100644index 0000000..b073061--- /dev/null+++ b/lib/src/transport.dart@@ -0,0 +1,301 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';+import 'dart:typed_data';++import 'package:http/http.dart' as http;+import 'package:http_parser/http_parser.dart';++import 'config.dart';+import 'errors.dart';+import 'utils.dart';++enum VmodalResponseMode { json, bytes }++class CancellationToken {+ final Completer<void> _abort = Completer<void>();++ bool get isCanceled => _abort.isCompleted;+ Future<void> get whenCanceled => _abort.future;++ void cancel() {+ if (!_abort.isCompleted) _abort.complete();+ }++ void throwIfCanceled() {+ if (isCanceled) throw const OperationCanceled();+ }+}++class VmodalFilePart {+ VmodalFilePart({+ required this.fieldName,+ required this.fileName,+ required this.contentLength,+ required Stream<List<int>> Function() opener,+ this.contentType = 'application/octet-stream',+ }) : _opener = opener {+ strMultipartValue('field name', fieldName, 128);+ strMultipartValue('file name', fileName, 1024);+ strMultipartValue('content type', contentType, 255);+ if (contentLength < 0) {+ throw const ValidationException('content_length must not be negative');+ }+ }++ factory VmodalFilePart.bytes({+ required String fieldName,+ required String fileName,+ required List<int> bytes,+ String contentType = 'application/octet-stream',+ }) {+ final stable = Uint8List.fromList(bytes);+ return VmodalFilePart(+ fieldName: fieldName,+ fileName: fileName,+ contentLength: stable.length,+ contentType: contentType,+ opener: () => Stream<List<int>>.value(stable),+ );+ }++ final String fieldName;+ final String fileName;+ final int contentLength;+ final String contentType;+ final Stream<List<int>> Function() _opener;++ Stream<List<int>> open() => _opener();+}++VmodalFilePart filePart(String fieldName, File file, {String? contentType}) {+ if (!file.existsSync()) {+ throw const ValidationException('file must exist');+ }+ return VmodalFilePart(+ fieldName: fieldName,+ fileName: file.uri.pathSegments.last,+ contentLength: file.lengthSync(),+ contentType: contentType ?? guessContentType(file.path),+ opener: file.openRead,+ );+}++VmodalFilePart streamPart({+ required String fieldName,+ required String fileName,+ required int contentLength,+ required Stream<List<int>> Function() opener,+ String? contentType,+}) => VmodalFilePart(+ fieldName: fieldName,+ fileName: fileName,+ contentLength: contentLength,+ contentType: contentType ?? guessContentType(fileName),+ opener: opener,+);++String guessContentType(String name) {+ final ext = name.contains('.') ? name.split('.').last.toLowerCase() : '';+ return switch (ext) {+ 'json' || 'jsonl' => 'application/json',+ 'txt' => 'text/plain',+ 'jpg' || 'jpeg' => 'image/jpeg',+ 'png' => 'image/png',+ 'mp4' => 'video/mp4',+ _ => 'application/octet-stream',+ };+}++class VmodalRequest {+ VmodalRequest({+ required this.method,+ required this.uri,+ this.headers = const <String, String>{},+ this.jsonBody,+ this.formFields = const <String, Object?>{},+ this.files = const <VmodalFilePart>[],+ this.responseMode = VmodalResponseMode.json,+ CancellationToken? cancellation,+ }) : cancellation = cancellation ?? CancellationToken();++ final String method;+ final Uri uri;+ final Map<String, String> headers;+ final Object? jsonBody;+ final Map<String, Object?> formFields;+ final List<VmodalFilePart> files;+ final VmodalResponseMode responseMode;+ final CancellationToken cancellation;++ @override+ String toString() =>+ 'VmodalRequest('+ 'method=$method, '+ 'pathType=${uri.hasScheme ? 'absolute' : 'relative'}, '+ 'queryParameterKeys=${uri.queryParametersAll.keys}, '+ 'headerNames=${headers.keys}, '+ 'hasJsonBody=${jsonBody != null}, '+ 'formFieldNames=${formFields.keys}, '+ 'fileCount=${files.length})';+}++class VmodalResponse {+ const VmodalResponse({+ required this.statusCode,+ required this.body,+ this.headers = const <String, String>{},+ this.contentLength = -1,+ });++ final int statusCode;+ final Stream<List<int>> body;+ final Map<String, String> headers;+ final int contentLength;++ @override+ String toString() =>+ 'VmodalResponse('+ 'statusCode=$statusCode, headerNames=${headers.keys}, '+ 'contentLength=$contentLength)';+}++abstract interface class VmodalTransport {+ Future<VmodalResponse> send(VmodalRequest request);++ Future<void> close();+}++class HttpVmodalTransport implements VmodalTransport {+ HttpVmodalTransport(SdkConfig config, {http.Client? client})+ : _config = config,+ _client = client ?? http.Client();++ final SdkConfig _config;+ final http.Client _client;+ bool _closed = false;++ @override+ Future<VmodalResponse> send(VmodalRequest request) async {+ if (_closed) throw const TransportException();+ request.cancellation.throwIfCanceled();+ final http.BaseRequest wire = request.files.isNotEmpty+ ? _multipart(request)+ : _ordinary(request);+ wire.followRedirects = false;+ wire.headers.addAll(request.headers);+ wire.headers.putIfAbsent('Accept', () => 'application/json');+ try {+ final response = await _client.send(wire).timeout(_config.timeout);+ final headers = <String, String>{};+ response.headers.forEach((String key, String value) {+ headers[key] = value;+ });+ return VmodalResponse(+ statusCode: response.statusCode,+ body: response.stream,+ headers: headers,+ contentLength: response.contentLength ?? -1,+ );+ } on http.RequestAbortedException {+ throw const OperationCanceled();+ } on TimeoutException catch (error) {+ request.cancellation.cancel();+ throw TransportException(error);+ } on SocketException catch (error) {+ throw TransportException(error);+ } on http.ClientException catch (error) {+ throw TransportException(error);+ }+ }++ http.BaseRequest _ordinary(VmodalRequest request) {+ final wire = http.AbortableRequest(+ request.method,+ request.uri,+ abortTrigger: request.cancellation.whenCanceled,+ );+ if (request.jsonBody != null) {+ wire.headers['Content-Type'] = 'application/json';+ wire.bodyBytes = utf8.encode(jsonEncode(request.jsonBody));+ } else if (request.formFields.isNotEmpty) {+ wire.headers['Content-Type'] = 'application/x-www-form-urlencoded';+ wire.bodyFields = _formStrings(request.formFields);+ }+ return wire;+ }++ http.BaseRequest _multipart(VmodalRequest request) {+ final wire = http.AbortableMultipartRequest(+ request.method,+ request.uri,+ abortTrigger: request.cancellation.whenCanceled,+ );+ request.formFields.forEach((String key, Object? value) {+ strMultipartValue('field name', key, 128);+ if (value == null) return;+ if (value is Iterable) {+ for (final item in value) {+ if (item != null) wire.fields[key] = '$item';+ }+ } else {+ wire.fields[key] = '$value';+ }+ });+ for (final part in request.files) {+ wire.files.add(+ http.MultipartFile(+ part.fieldName,+ http.ByteStream(part.open()),+ part.contentLength,+ filename: part.fileName,+ contentType: MediaType.parse(part.contentType),+ ),+ );+ }+ return wire;+ }++ Map<String, String> _formStrings(Map<String, Object?> values) {+ final out = <String, String>{};+ values.forEach((String key, Object? value) {+ if (value != null) out[key] = '$value';+ });+ return out;+ }++ @override+ Future<void> close() async {+ _closed = true;+ _client.close();+ }+}++Future<Uint8List> readBounded(+ VmodalResponse response,+ int limitBytes, {+ CancellationToken? cancellation,+}) async {+ if (limitBytes <= 0) {+ throw const ValidationException('response limit is invalid');+ }+ if (response.contentLength < -1) {+ throw const MalformedResponse('invalid Content-Length');+ }+ if (response.contentLength > limitBytes) {+ cancellation?.cancel();+ throw ResponseTooLarge(limitBytes, response.contentLength);+ }+ final builder = BytesBuilder(copy: false);+ var total = 0;+ await for (final chunk in response.body) {+ cancellation?.throwIfCanceled();+ if (chunk.length > limitBytes - total) {+ cancellation?.cancel();+ throw ResponseTooLarge(limitBytes, total + chunk.length);+ }+ builder.add(chunk);+ total += chunk.length;+ }+ return builder.takeBytes();+}diff --git a/lib/src/upload.dart b/lib/src/upload.dartnew file mode 100644index 0000000..3ecf7d7--- /dev/null+++ b/lib/src/upload.dart@@ -0,0 +1,471 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';+import 'dart:typed_data';++import 'package:crypto/crypto.dart';++import 'errors.dart';+import 'transport.dart';+import 'utils.dart';++class UploadSource {+ UploadSource({+ required this.fileName,+ required this.contentLength,+ required Stream<List<int>> Function() opener,+ this.contentType = 'application/octet-stream',+ String? sourceId,+ this.versionTag = '',+ Stream<List<int>> Function(int offset)? rangeOpener,+ }) : sourceId = sourceId ?? fileName,+ _opener = opener,+ _rangeOpener = rangeOpener {+ strMultipartValue('file name', fileName, 1024);+ strMultipartValue('content type', contentType, 255);+ strMultipartValue('source id', this.sourceId, 4096);+ if (contentLength < 0) {+ throw const ValidationException(+ 'content_length must be known for a signed upload',+ );+ }+ }++ factory UploadSource.fromFile(File file, {String? contentType}) {+ if (!file.existsSync()) {+ throw const ValidationException('file must exist');+ }+ final stat = file.statSync();+ final name = file.uri.pathSegments.last;+ return UploadSource(+ fileName: name,+ contentLength: stat.size,+ contentType: contentType ?? guessContentType(name),+ sourceId: file.absolute.path,+ versionTag: '${stat.size}:${stat.modified.millisecondsSinceEpoch}',+ opener: file.openRead,+ rangeOpener: (int offset) => file.openRead(offset),+ );+ }++ final String fileName;+ final int contentLength;+ final String contentType;+ final String sourceId;+ final String versionTag;+ final Stream<List<int>> Function() _opener;+ final Stream<List<int>> Function(int offset)? _rangeOpener;++ Stream<List<int>> open({int offset = 0, int? length}) async* {+ final wanted = length ?? contentLength - offset;+ if (offset < 0 || wanted < 0 || offset + wanted > contentLength) {+ throw const ValidationException('upload source range is invalid');+ }+ final direct = _rangeOpener;+ var skip = direct == null ? offset : 0;+ var left = wanted;+ final stream = direct?.call(offset) ?? _opener();+ await for (final chunk in stream) {+ var start = 0;+ if (skip > 0) {+ if (skip >= chunk.length) {+ skip -= chunk.length;+ continue;+ }+ start = skip;+ skip = 0;+ }+ if (left == 0) break;+ final count = left < chunk.length - start ? left : chunk.length - start;+ if (count > 0) {+ yield Uint8List.fromList(chunk.sublist(start, start + count));+ left -= count;+ }+ if (left == 0) break;+ }+ if (skip != 0 || left != 0) {+ throw const TransportException('upload source ended early');+ }+ }+}++class UploadProgress {+ const UploadProgress(this.uploadedBytes, this.totalBytes);++ final int uploadedBytes;+ final int totalBytes;++ int get percent =>+ totalBytes <= 0 ? 0 : ((uploadedBytes * 100) ~/ totalBytes).clamp(0, 100);+}++enum UploadTaskState { running, succeeded, failed, canceled }++typedef UploadRunner<T> =+ Future<T> Function(+ CancellationToken cancellation,+ void Function(UploadProgress progress) emit,+ );++class UploadTask<T> {+ UploadTask.start(UploadRunner<T> runner) {+ unawaited(_start(runner));+ }++ final Completer<T> _result = Completer<T>();+ final StreamController<UploadProgress> _progress =+ StreamController<UploadProgress>.broadcast(sync: true);+ final CancellationToken cancellation = CancellationToken();+ UploadTaskState _state = UploadTaskState.running;+ int _lastBytes = 0;++ Future<T> get result => _result.future;+ Stream<UploadProgress> get progress => _progress.stream;+ UploadTaskState get state => _state;+ bool get isCanceled => _state == UploadTaskState.canceled;++ void cancel() {+ if (_state != UploadTaskState.running) return;+ _state = UploadTaskState.canceled;+ cancellation.cancel();+ if (!_result.isCompleted) _result.completeError(const OperationCanceled());+ unawaited(_progress.close());+ }++ Future<void> _start(UploadRunner<T> runner) async {+ try {+ final value = await runner(cancellation, _emit);+ if (_state != UploadTaskState.running) return;+ _state = UploadTaskState.succeeded;+ _result.complete(value);+ } on Object catch (error, stack) {+ if (_state != UploadTaskState.running) return;+ _state = error is OperationCanceled+ ? UploadTaskState.canceled+ : UploadTaskState.failed;+ _result.completeError(error, stack);+ } finally {+ if (!_progress.isClosed) await _progress.close();+ }+ }++ void _emit(UploadProgress value) {+ if (_state != UploadTaskState.running) return;+ final safe = value.uploadedBytes.clamp(_lastBytes, value.totalBytes);+ _lastBytes = safe;+ _progress.add(UploadProgress(safe, value.totalBytes));+ }+}++class SignedUploadResult {+ const SignedUploadResult({+ required this.statusCode,+ this.etag = '',+ this.localMd5 = '',+ });++ final int statusCode;+ final String etag;+ final String localMd5;+}++class SignedUploadFailure extends TransportException {+ const SignedUploadFailure({+ required this.sentBytes,+ required this.localMd5,+ Object? cause,+ }) : super(cause);++ final int sentBytes;+ final String localMd5;+}++abstract interface class SignedUploadTransport {+ Future<SignedUploadResult> upload({+ required UploadSource source,+ required Uri url,+ String method = 'PUT',+ int offset = 0,+ int? length,+ Map<String, String> headers = const <String, String>{},+ Duration? timeout,+ required CancellationToken cancellation,+ void Function(UploadProgress progress)? onProgress,+ });++ Future<void> close();+}++class IoSignedUploadTransport implements SignedUploadTransport {+ IoSignedUploadTransport(this.defaultTimeout, {HttpClient? client})+ : _client = client ?? HttpClient();++ final Duration defaultTimeout;+ final HttpClient _client;+ bool _closed = false;++ @override+ Future<SignedUploadResult> upload({+ required UploadSource source,+ required Uri url,+ String method = 'PUT',+ int offset = 0,+ int? length,+ Map<String, String> headers = const <String, String>{},+ Duration? timeout,+ required CancellationToken cancellation,+ void Function(UploadProgress progress)? onProgress,+ }) async {+ if (_closed) throw const TransportException();+ cancellation.throwIfCanceled();+ if (url.scheme != 'https' &&+ !(url.scheme == 'http' && _isLoopback(url.host))) {+ throw const ValidationException('invalid signed upload URL');+ }+ final safeHeaders = _signedHeaders(headers);+ final wanted = length ?? source.contentLength - offset;+ HttpClientRequest? request;+ var sent = 0;+ final digestSink = _DigestSink();+ final digest = md5.startChunkedConversion(digestSink);+ try {+ request = await _client+ .openUrl(method.toUpperCase(), url)+ .timeout(timeout ?? defaultTimeout);+ request.followRedirects = false;+ request.contentLength = wanted;+ request.headers.contentType = ContentType.parse(source.contentType);+ safeHeaders.forEach(request.headers.set);+ unawaited(+ cancellation.whenCanceled.then((_) {+ request?.abort(const OperationCanceled());+ }),+ );+ await for (final chunk in source.open(offset: offset, length: wanted)) {+ cancellation.throwIfCanceled();+ request.add(chunk);+ digest.add(chunk);+ sent += chunk.length;+ onProgress?.call(UploadProgress(sent, wanted));+ }+ digest.close();+ final response = await request.close().timeout(timeout ?? defaultTimeout);+ if (response.statusCode < 200 || response.statusCode > 299) {+ final bytes = await _readIoBounded(response, errorResponseLimitBytes);+ throw ApiException(+ 'signed upload failed',+ statusCode: response.statusCode,+ body: utf8.decode(bytes, allowMalformed: true),+ );+ }+ await response.drain<void>();+ return SignedUploadResult(+ statusCode: response.statusCode,+ etag: (response.headers.value('etag') ?? '').replaceAll('"', '').trim(),+ localMd5: digestSink.value?.toString() ?? '',+ );+ } on OperationCanceled {+ rethrow;+ } on ApiException {+ rethrow;+ } on Object catch (error) {+ request?.abort(error);+ try {+ digest.close();+ } on Object {+ // Digest may already be closed after all bytes were sent.+ }+ throw SignedUploadFailure(+ sentBytes: sent,+ localMd5: digestSink.value?.toString() ?? '',+ cause: error,+ );+ }+ }++ Map<String, String> _signedHeaders(Map<String, String> values) {+ const forbidden = <String>{+ 'authorization',+ 'cookie',+ 'origin',+ 'referer',+ 'x-user-id',+ 'x-tenant-id',+ 'x-user-email',+ };+ final out = <String, String>{};+ values.forEach((String key, String value) {+ final lower = key.toLowerCase();+ if (forbidden.contains(lower)) {+ throw const ValidationException(+ 'signed upload contains forbidden authentication headers',+ );+ }+ final allowed =+ lower == 'content-md5' ||+ lower == 'content-type' ||+ lower == 'content-length' ||+ lower.startsWith('x-amz-') ||+ lower.startsWith('x-goog-');+ if (!allowed) {+ throw const ValidationException('signed upload header is not allowed');+ }+ out[key] = strHeaderValue('signed header', value);+ });+ return out;+ }++ @override+ Future<void> close() async {+ if (_closed) return;+ _closed = true;+ _client.close(force: true);+ }+}++abstract interface class UploadSessionStore {+ Future<Map<String, Object?>?> load(String key);+ Future<void> save(String key, Map<String, Object?> value);+ Future<void> remove(String key);+}++class MemoryUploadSessionStore implements UploadSessionStore {+ final Map<String, Map<String, Object?>> _values =+ <String, Map<String, Object?>>{};++ @override+ Future<Map<String, Object?>?> load(String key) async {+ final value = _values[key];+ return value == null ? null : Map<String, Object?>.from(value);+ }++ @override+ Future<void> save(String key, Map<String, Object?> value) async {+ _values[key] = Map<String, Object?>.from(value);+ }++ @override+ Future<void> remove(String key) async {+ _values.remove(key);+ }+}++class FileUploadSessionStore implements UploadSessionStore {+ FileUploadSessionStore(this.directory) {+ if (!directory.existsSync()) directory.createSync(recursive: true);+ if (!directory.statSync().type.toString().contains('directory')) {+ throw const TransportException('upload checkpoint path is invalid');+ }+ }++ final Directory directory;++ @override+ Future<Map<String, Object?>?> load(String key) async {+ final primary = _file(key);+ final backup = File('${primary.path}.bak');+ final source = await primary.exists()+ ? primary+ : await backup.exists()+ ? backup+ : null;+ if (source == null) return null;+ final size = await source.length();+ if (size > checkpointJsonLimitBytes) {+ throw ResponseTooLarge(checkpointJsonLimitBytes, size);+ }+ final bytes = await source.readAsBytes();+ final value = jsonDecodeStrict(bytes);+ if (value is! Map) {+ throw const MalformedResponse('upload checkpoint is invalid');+ }+ return objectMap(value);+ }++ @override+ Future<void> save(String key, Map<String, Object?> value) async {+ final bytes = utf8.encode(jsonEncode(value));+ if (bytes.length > checkpointJsonLimitBytes) {+ throw ResponseTooLarge(checkpointJsonLimitBytes, bytes.length);+ }+ final primary = _file(key);+ final temp = File(+ '${primary.path}.${DateTime.now().microsecondsSinceEpoch}.tmp',+ );+ final backup = File('${primary.path}.bak');+ await temp.writeAsBytes(bytes, flush: true);+ if (await backup.exists()) await backup.delete();+ if (await primary.exists()) await primary.rename(backup.path);+ try {+ await temp.rename(primary.path);+ if (await backup.exists()) await backup.delete();+ } on Object {+ if (await backup.exists()) await backup.rename(primary.path);+ if (await temp.exists()) await temp.delete();+ rethrow;+ }+ }++ @override+ Future<void> remove(String key) async {+ final primary = _file(key);+ final backup = File('${primary.path}.bak');+ if (await primary.exists()) await primary.delete();+ if (await backup.exists()) await backup.delete();+ }++ File _file(String key) =>+ File('${directory.path}/${sha256.convert(utf8.encode(key))}.json');+}++abstract final class UploadSessionStores {+ static final UploadSessionStore memory = MemoryUploadSessionStore();+}++Future<String> md5Hex(+ UploadSource source, {+ required int offset,+ required int length,+}) async {+ final sink = _DigestSink();+ final input = md5.startChunkedConversion(sink);+ await for (final chunk in source.open(offset: offset, length: length)) {+ input.add(chunk);+ }+ input.close();+ return sink.value?.toString() ?? '';+}++class _DigestSink implements Sink<Digest> {+ Digest? value;++ @override+ void add(Digest data) {+ value = data;+ }++ @override+ void close() {}+}++Future<Uint8List> _readIoBounded(HttpClientResponse response, int limit) async {+ final declared = response.contentLength;+ if (declared > limit) throw ResponseTooLarge(limit, declared);+ final out = BytesBuilder(copy: false);+ var count = 0;+ await for (final chunk in response) {+ if (chunk.length > limit - count) {+ throw ResponseTooLarge(limit, count + chunk.length);+ }+ out.add(chunk);+ count += chunk.length;+ }+ return out.takeBytes();+}++bool _isLoopback(String host) => const <String>{+ 'localhost',+ '127.0.0.1',+ '::1',+ '0:0:0:0:0:0:0:1',+}.contains(host.toLowerCase());diff --git a/lib/src/utils.dart b/lib/src/utils.dartnew file mode 100644index 0000000..5d32c1f--- /dev/null+++ b/lib/src/utils.dart@@ -0,0 +1,78 @@+import 'dart:convert';++import 'errors.dart';++const int jsonResponseLimitBytes = 8 * 1024 * 1024;+const int errorResponseLimitBytes = 1024 * 1024;+const int binaryResponseLimitBytes = 64 * 1024 * 1024;+const int checkpointJsonLimitBytes = 1024 * 1024;++String strRequired(String value, String fieldName) {+ final clean = value.trim();+ if (clean.isEmpty) {+ throw ValidationException('$fieldName is required');+ }+ return clean;+}++String strHeaderValue(String name, String value) {+ if (value.length > 4096 || value.runes.any(_isControl)) {+ throw ValidationException('$name contains invalid header characters');+ }+ return value;+}++String strMultipartValue(String name, String value, int maxLength) {+ if (value.isEmpty) {+ throw ValidationException('$name must not be blank');+ }+ if (value.length > maxLength) {+ throw ValidationException('$name is too long');+ }+ if (value.runes.any(_isControl)) {+ throw ValidationException('$name contains control characters');+ }+ return value;+}++bool _isControl(int value) => value < 32 || value == 127;++int intValue(Object? value) {+ if (value is int) return value;+ if (value is num && value.isFinite && value == value.roundToDouble()) {+ return value.toInt();+ }+ if (value is String) return int.tryParse(value) ?? 0;+ return 0;+}++double doubleValue(Object? value) {+ if (value is num && value.isFinite) return value.toDouble();+ if (value is String) {+ final parsed = double.tryParse(value);+ return parsed != null && parsed.isFinite ? parsed : 0;+ }+ return 0;+}++Map<String, Object?> objectMap(Object? value) {+ if (value is! Map<Object?, Object?>) return <String, Object?>{};+ return value.map((Object? key, Object? item) => MapEntry('$key', item));+}++List<Map<String, Object?>> objectList(Object? value) {+ if (value is! List) return <Map<String, Object?>>[];+ return value+ .whereType<Map<Object?, Object?>>()+ .map(objectMap)+ .toList(growable: false);+}++Object? jsonDecodeStrict(List<int> bytes) {+ try {+ final text = utf8.decode(bytes);+ return jsonDecode(text);+ } on Object {+ throw const MalformedResponse();+ }+}diff --git a/lib/vmodal_sdk_flutter.dart b/lib/vmodal_sdk_flutter.dartnew file mode 100644index 0000000..c9e15af--- /dev/null+++ b/lib/vmodal_sdk_flutter.dart@@ -0,0 +1,23 @@+library;++export 'src/adaptive_upload.dart';+export 'src/api_key_provider.dart';+export 'src/client.dart';+export 'src/collection_uploads.dart';+export 'src/config.dart';+export 'src/errors.dart';+export 'src/models.dart';+export 'src/resources.dart';+export 'src/routes.dart' show RouteCategory, RouteSpec, Routes;+export 'src/transport.dart'+ show+ CancellationToken,+ VmodalFilePart,+ VmodalRequest,+ VmodalResponse,+ VmodalResponseMode,+ VmodalTransport,+ filePart,+ guessContentType,+ streamPart;+export 'src/upload.dart';diff --git a/pubspec.yaml b/pubspec.yamlnew file mode 100644index 0000000..8882d39--- /dev/null+++ b/pubspec.yaml@@ -0,0 +1,25 @@+name: vmodal_sdk_flutter+description: Typed VModal API client for Flutter applications on Android and iOS.+version: 1.0.0+license: MIT+repository: https://github.com/v-modal/vmodal_sdk_flutter+issue_tracker: https://github.com/v-modal/vmodal_sdk_flutter/issues++environment:+ sdk: '>=3.12.0 <4.0.0'+ flutter: '>=3.44.0'++dependencies:+ crypto: ^3.0.7+ flutter:+ sdk: flutter+ http: ^1.6.0+ http_parser: ^4.1.2++dev_dependencies:+ flutter_lints: ^6.0.0+ flutter_test:+ sdk: flutter++flutter:+ uses-material-design: truediff --git a/run.sh b/run.shnew file mode 100755index 0000000..260d19f--- /dev/null+++ b/run.sh@@ -0,0 +1,71 @@+#!/usr/bin/env bash+help='+ Run the deterministic SDK simulation or the example on one chosen device.++ Examples:+ bash run.sh sim+ bash run.sh example --device emulator-5554+'+set -euo pipefail+cd "$(dirname "$0")"+sdk_dir="$PWD"++sdk_dart() {+ local help='+ ## Usage:+ sdk_dart run tool/sim.dart+ '+ local bin+ bin="$(bash "$sdk_dir/install.sh" dart_bin)"+ "$bin" "$@"+}++sdk_flutter() {+ local help='+ ## Usage:+ sdk_flutter devices+ '+ local bin+ bin="$(bash "$sdk_dir/install.sh" flutter_bin)"+ "$bin" "$@"+}++sdk_run_sim() {+ local help='+ ## Usage:+ bash run.sh sim+ '+ sdk_dart run tool/sim.dart+}++sdk_run_example() {+ local help='+ ## Usage:+ bash run.sh example --device DEVICE_ID+ '+ shift || true+ local device=''+ while [[ $# -gt 0 ]]; do+ case "$1" in+ --device) device="${2:-}"; shift 2 ;;+ *) echo "Unknown example argument: $1" >&2; return 2 ;;+ esac+ done+ [[ -n "$device" ]] || { echo '--device DEVICE_ID is required.' >&2; return 2; }+ (cd example && sdk_flutter run --device-id "$device")+}++sdk_help() {+ local help='+ ## Usage:+ bash run.sh help+ '+ echo "$help"+}++case "${1:-sim}" in+ sim) sdk_run_sim ;;+ example) sdk_run_example "$@" ;;+ help|-h|--help) sdk_help ;;+ *) echo "Unknown command: ${1:-}" >&2; echo "$help" >&2; exit 2 ;;+esacdiff --git a/security_check.sh b/security_check.shnew file mode 100755index 0000000..4a2770d--- /dev/null+++ b/security_check.sh@@ -0,0 +1,154 @@+#!/usr/bin/env bash+help='+ Validate Flutter SDK release workflow, toolchain, metadata, package, and secret policy.++ Examples:+ bash security_check.sh workflow+ bash security_check.sh all+'+set -euo pipefail+cd "$(dirname "$0")"++sdk_security_workflow() {+ local help='+ ## Usage:+ bash security_check.sh workflow+ '+ local internal='../../.github/workflows/sdk_flutter_test_release.yml'+ local public='release/public_publish.yml'+ [[ -f "$internal" && -f "$public" ]] || { echo 'Flutter release workflow is missing.' >&2; return 2; }+ ! grep -Eiq 'maven|gradle publication|github packages|\bosv\b|\bsbom\b|security_policy' "$internal" "$public"+ ! grep -Eq 'uses:[[:space:]]+[^[:space:]]+@(v[0-9]|main|master|latest)' "$internal" "$public"+ grep -Eq 'permissions:[[:space:]]*$' "$internal"+ grep -Eq 'id-token:[[:space:]]+write' "$public"+ grep -Eq 'needs:[[:space:]]+verify_tagged_source' "$public"+ grep -Eq 'environment:[[:space:]]+pub\.dev' "$public"+ grep -Eq 'environment:[[:space:]]+sdk-flutter-production' "$internal"+ grep -Eq 'fetch-depth:[[:space:]]+0' "$internal"+ grep -Eq 'persist-credentials:[[:space:]]+false' "$internal" "$public"+ grep -Fq -- '--source "$WORKDIR"' "$internal"+ grep -Fq -- '--log-opts="--all -- $WORKDIR"' "$internal"+ grep -Fq 'RELEASE_TOKEN: ${{ secrets.GH_TOKEN }}' "$internal"+ ! grep -Fq 'FLUTTER_SDK_APP_' "$internal"+ ! grep -Eq 'git merge|git push[^\n]*--force|--skip-validation' "$internal" "$public"+ if grep -E 'uses:[[:space:]]+' "$internal" "$public" |+ grep -Ev 'uses:[[:space:]]+[^[:space:]]+@[0-9a-f]{40}([[:space:]]|$)' >/dev/null; then+ echo 'Every action must use a full commit SHA.' >&2+ return 3+ fi+}++sdk_security_toolchain() {+ local help='+ ## Usage:+ bash security_check.sh toolchain+ '+ local version rows+ version="$(tr -d '[:space:]' < .flutter-version)"+ [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo 'Invalid Flutter version pin.' >&2; return 3; }+ rows="$(awk -v v="$version" '$1 == v {count++} END {print count + 0}' tool/flutter_checksums.txt)"+ [[ "$rows" == 3 ]] || { echo 'All three reviewed Flutter artifacts must be pinned.' >&2; return 3; }+ awk -v v="$version" '$1 == v && $4 !~ /^[0-9a-f]{64}$/ {exit 1}' tool/flutter_checksums.txt+}++sdk_security_version() {+ local help='+ ## Usage:+ bash security_check.sh version+ '+ "$(bash install.sh dart_bin)" run tool/release_manifest.dart check+}++sdk_security_license() {+ local help='+ ## Usage:+ bash security_check.sh license+ '+ [[ -s LICENSE ]] || { echo 'LICENSE is missing or empty.' >&2; return 3; }+ grep -q 'MIT License' LICENSE+ grep -q '^license: MIT$' pubspec.yaml+}++sdk_security_package() {+ local help='+ ## Usage:+ bash security_check.sh package+ '+ local listing+ listing="$(bash build.sh package 2>&1)"+ printf '%s\n' "$listing"+ ! grep -Eiq '(^|/)(\.env|ztmp|\.dart_tool|build|checkpoints?)(/|$)|private[_-]?key|presigned' <<<"$listing"+}++sdk_security_secrets() {+ local help='+ ## Usage:+ bash security_check.sh secrets+ '+ local detector_version='8.30.1'+ local platform detector_sha+ local cache="${XDG_CACHE_HOME:-$HOME/.cache}/vmodal/gitleaks/$detector_version"+ local archive="$cache/gitleaks.tar.gz" bin="$cache/gitleaks"+ case "$(uname -s):$(uname -m)" in+ Darwin:arm64) platform='darwin_arm64'; detector_sha='b40ab0ae55c505963e365f271a8d3846efbc170aa17f2607f13df610a9aeb6a5' ;;+ Darwin:x86_64) platform='darwin_x64'; detector_sha='dfe101a4db2255fc85120ac7f3d25e4342c3c20cf749f2c20a18081af1952709' ;;+ Linux:x86_64) platform='linux_x64'; detector_sha='551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb' ;;+ *) echo 'No reviewed gitleaks artifact for this host.' >&2; return 2 ;;+ esac+ mkdir -p "$cache"+ if [[ ! -x "$bin" ]]; then+ curl --fail --location --retry 3 --output "$archive" \+ "https://github.com/gitleaks/gitleaks/releases/download/v${detector_version}/gitleaks_${detector_version}_${platform}.tar.gz"+ sdk_security_sha256 "$archive" "$detector_sha"+ tar -xzf "$archive" -C "$cache" gitleaks+ chmod 755 "$bin"+ fi+ "$bin" detect --source . --config .gitleaks.toml --no-banner --redact --no-git+}++sdk_security_sha256() {+ local help='+ ## Usage:+ sdk_security_sha256 FILE EXPECTED+ '+ local file="${1:?file required}" expected="${2:?checksum required}" got+ if command -v shasum >/dev/null 2>&1; then+ got="$(shasum -a 256 "$file" | awk '{print $1}')"+ else+ got="$(sha256sum "$file" | awk '{print $1}')"+ fi+ [[ "$got" == "$expected" ]] || { echo 'Security tool checksum mismatch.' >&2; return 3; }+}++sdk_security_all() {+ local help='+ ## Usage:+ bash security_check.sh all+ '+ sdk_security_workflow+ sdk_security_toolchain+ sdk_security_version+ sdk_security_license+ sdk_security_package+ sdk_security_secrets+}++sdk_security_help() {+ local help='+ ## Usage:+ bash security_check.sh help+ '+ echo "$help"+}++case "${1:-help}" in+ workflow) sdk_security_workflow ;;+ toolchain) sdk_security_toolchain ;;+ version) sdk_security_version ;;+ license) sdk_security_license ;;+ package) sdk_security_package ;;+ secrets) sdk_security_secrets ;;+ all) sdk_security_all ;;+ help|-h|--help) sdk_security_help ;;+ *) echo "Unknown command: ${1:-}" >&2; echo "$help" >&2; exit 2 ;;+esacdiff --git a/test.sh b/test.shnew file mode 100755index 0000000..54dd82d--- /dev/null+++ b/test.sh@@ -0,0 +1,142 @@+#!/usr/bin/env bash+help='+ Run VModal Flutter offline, regression, package, security, or explicit live gates.++ Examples:+ bash test.sh test+ bash test.sh regression S16+ bash test.sh all+ bash test.sh live+'+set -euo pipefail+cd "$(dirname "$0")"++sdk_test() {+ local help='+ ## Usage:+ bash test.sh test+ '+ bash install.sh check+ bash build.sh test+}++sdk_regression() {+ local help='+ ## Usage:+ bash test.sh regression S16+ '+ local step="${1:-}" flutter+ case "$step" in+ S04|S05|S06|S07|S08|S09|S10|S11_1|S11_2|S11_3|S11_4|S11_5|S11_6|S11|S12|S13|S14|S15|S16|S17|S18|S19) ;;+ *) echo "Unknown regression step: $step" >&2; return 2 ;;+ esac+ bash build.sh format+ bash build.sh analyze+ flutter="$(bash install.sh flutter_bin)"+ "$flutter" test test/config_routes_test.dart+ [[ "$step" == 'S04' ]] || "$flutter" test test/fakes_test.dart test/auth_http_test.dart+ case "$step" in+ S04|S05|S06|S07|S08) ;;+ *) "$flutter" test test/transport_test.dart ;;+ esac+ case "$step" in+ S04|S05|S06|S07|S08|S09|S10) ;;+ *) "$flutter" test test/resources_models_test.dart ;;+ esac+ case "$step" in+ S12|S13|S14|S15|S16|S17|S18|S19) "$flutter" test test/upload_test.dart ;;+ esac+ case "$step" in+ S15|S16|S17|S18|S19) "$flutter" test test/multipart_upload_test.dart ;;+ esac+ case "$step" in+ S16|S17|S18|S19) "$flutter" test test/adaptive_upload_test.dart ;;+ esac+ case "$step" in+ S11|S12|S13|S14|S15|S16|S17|S18|S19) "$flutter" test ;;+ esac+ "$(bash install.sh dart_bin)" run tool/check_route_sync.dart+ case "$step" in+ S17|S18|S19) bash build.sh package; bash build.sh example_android ;;+ esac+ case "$step" in+ S18|S19) bash security_check.sh all; sdk_live ;;+ esac+}++sdk_sim() {+ local help='+ ## Usage:+ bash test.sh sim+ '+ bash run.sh sim+}++sdk_security() {+ local help='+ ## Usage:+ bash test.sh security+ '+ bash security_check.sh all+}++sdk_package() {+ local help='+ ## Usage:+ bash test.sh package+ '+ bash build.sh package+}++sdk_live() {+ local help='+ ## Usage:+ source ../../ztmp/env_gitignore.sh+ bash test.sh live+ '+ source env.sh+ sdk_env_live+ [[ -n "${VMODAL_API_KEY:-}" ]] || { echo 'Live API credential is required.' >&2; return 2; }+ "$(bash install.sh dart_bin)" run tool/live_test.dart+}++sdk_all() {+ local help='+ ## Usage:+ bash test.sh all+ '+ sdk_test+ sdk_security+ sdk_package+ sdk_sim+}++sdk_clean() {+ local help='+ ## Usage:+ bash test.sh clean+ '+ bash build.sh clean+}++sdk_help() {+ local help='+ ## Usage:+ bash test.sh help+ '+ echo "$help"+}++case "${1:-test}" in+ test) sdk_test ;;+ regression) shift; sdk_regression "${1:-}" ;;+ sim) sdk_sim ;;+ security) sdk_security ;;+ package) sdk_package ;;+ live) sdk_live ;;+ all) sdk_all ;;+ clean) sdk_clean ;;+ help|-h|--help) sdk_help ;;+ *) echo "Unknown command: ${1:-}" >&2; echo "$help" >&2; exit 2 ;;+esac+diff --git a/test/adaptive_upload_test.dart b/test/adaptive_upload_test.dartnew file mode 100644index 0000000..02fe31e--- /dev/null+++ b/test/adaptive_upload_test.dart@@ -0,0 +1,88 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';++void main() {+ test('Android adaptive preset vectors match exactly', () {+ const mib = 1024 * 1024;+ const gib = 1024 * mib;+ final vectors = <(int, UploadConditions, String, int, int, int, int)>[+ (+ 10 * mib,+ const UploadConditions(deviceMemory: UploadDeviceMemory.low),+ 'small_conservative',+ 5 * mib,+ 1,+ 6,+ 360,+ ),+ (+ 100 * mib,+ const UploadConditions(+ networkType: UploadNetworkType.cellular,+ networkSpeed: UploadNetworkSpeed.standard,+ ),+ 'medium_cellular',+ 16 * mib,+ 2,+ 5,+ 360,+ ),+ (+ gib,+ const UploadConditions(+ networkType: UploadNetworkType.wifi,+ networkSpeed: UploadNetworkSpeed.standard,+ ),+ 'large_balanced',+ 64 * mib,+ 3,+ 5,+ 480,+ ),+ (+ 8 * gib,+ const UploadConditions(+ networkType: UploadNetworkType.wifi,+ networkSpeed: UploadNetworkSpeed.fast,+ deviceMemory: UploadDeviceMemory.high,+ ),+ 'huge_fast',+ 256 * mib,+ 4,+ 5,+ 480,+ ),+ ];+ for (final vector in vectors) {+ final preset = AdaptiveUploadPolicy.select(vector.$1, vector.$2);+ expect(preset.name, vector.$3);+ expect(preset.partSizeBytes, vector.$4);+ expect(preset.maxConcurrency, vector.$5);+ expect(preset.maxPartAttempts, vector.$6);+ expect(preset.partTimeout.inSeconds, vector.$7);+ }+ });++ test('10,000 part ceiling raises minimum part size', () {+ const mib = 1024 * 1024;+ final preset = AdaptiveUploadPolicy.select(+ 10001 * 5 * mib,+ const UploadConditions(),+ );+ expect(+ (10001 * 5 * mib + preset.partSizeBytes - 1) ~/ preset.partSizeBytes,+ lessThanOrEqualTo(10000),+ );+ });++ test('adaptive settings do nothing when multipart is false', () {+ const options = VideoUploadOptions(+ adaptiveConditions: UploadConditions(+ networkType: UploadNetworkType.wifi,+ networkSpeed: UploadNetworkSpeed.fast,+ deviceMemory: UploadDeviceMemory.high,+ ),+ );+ expect(identical(options.resolvedFor(10 * 1024 * 1024), options), isTrue);+ });+}diff --git a/test/auth_http_test.dart b/test/auth_http_test.dartnew file mode 100644index 0000000..b0c2554--- /dev/null+++ b/test/auth_http_test.dart@@ -0,0 +1,128 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';++import 'fakes.dart';++void main() {+ test(+ 'gateway request reads provider once and sends no identity headers',+ () async {+ final keys = CountingKeyProvider('old-key');+ final fake = FakeTransport()+ ..addResponse(jsonResponse('{"status":"ok"}'));+ final client = VmodalClient(+ config: SdkConfig(+ baseUrl: 'https://gateway.test',+ userId: 'spoof-user',+ tenantId: 'spoof-tenant',+ email: '[email protected]',+ apiKeyProvider: keys,+ ),+ transport: fake,+ signedUploadTransport: FakeSignedUploadTransport(),+ );+ await client.health();+ expect(keys.reads, 1);+ final headers = fake.requests.single.headers;+ expect(headers['Authorization'], 'Bearer old-key');+ expect(+ headers.keys.map((String value) => value.toLowerCase()),+ isNot(contains('x-user-id')),+ );+ expect(+ headers.keys.map((String value) => value.toLowerCase()),+ isNot(contains('x-tenant-id')),+ );+ },+ );++ test('rotation validates before swap and clear fails closed', () {+ final keys = MutableApiKeyProvider('good-key');+ expect(() => keys.rotate('bad\nkey'), throwsA(isA<ValidationException>()));+ expect(keys.current(), 'good-key');+ keys.rotate('new-key');+ expect(keys.current(), 'new-key');+ keys.clear();+ expect(() => keys.current(), throwsA(isA<AuthException>()));+ keys.close();+ expect(() => keys.current(), throwsA(isA<AuthException>()));+ });++ test('GET retries retryable statuses but POST is sent once', () async {+ final getFake = FakeTransport()+ ..addResponse(jsonResponse('{"error":true}', status: 503))+ ..addResponse(jsonResponse('{"status":"ok"}'));+ final client = VmodalClient(+ config: SdkConfig(+ baseUrl: 'https://gateway.test',+ token: 'key',+ maxRetries: 1,+ ),+ transport: getFake,+ signedUploadTransport: FakeSignedUploadTransport(),+ delay: (_) async {},+ );+ await client.health();+ expect(getFake.requests, hasLength(2));++ final postFake = FakeTransport()+ ..addResponse(jsonResponse('{"error":true}', status: 503));+ final postClient = VmodalClient(+ config: SdkConfig(+ baseUrl: 'https://gateway.test',+ token: 'key',+ maxRetries: 5,+ ),+ transport: postFake,+ signedUploadTransport: FakeSignedUploadTransport(),+ delay: (_) async {},+ );+ await expectLater(+ postClient.searches.searchVideo(const SearchRequest(queryText: 'one')),+ throwsA(isA<ApiException>()),+ );+ expect(postFake.requests, hasLength(1));+ });++ test('401 and 422 map to typed redacted errors', () async {+ final fake = FakeTransport()+ ..addResponse(jsonResponse('{"secret":"body-sentinel"}', status: 401))+ ..addResponse(jsonResponse('{"detail":"bad"}', status: 422));+ final client = VmodalClient(+ config: SdkConfig(baseUrl: 'https://gateway.test', token: 'key'),+ transport: fake,+ signedUploadTransport: FakeSignedUploadTransport(),+ );+ Object? auth;+ try {+ await client.health();+ } on Object catch (error) {+ auth = error;+ }+ expect(auth, isA<AuthException>());+ expect('$auth', isNot(contains('body-sentinel')));+ await expectLater(+ client.searches.searchVideo(const SearchRequest(queryText: 'one')),+ throwsA(isA<ValidationException>()),+ );+ });++ test('unsafe direct requires identity and keeps branches separate', () {+ final fake = FakeTransport();+ final client = VmodalClient.unsafeDirect(+ baseUrl: 'http://localhost:4099',+ userId: 'trusted-user',+ transport: fake,+ signedUploadTransport: FakeSignedUploadTransport(),+ );+ expect(client.http.headers()['X-User-Id'], 'trusted-user');+ expect(client.http.headers(), isNot(contains('Authorization')));+ final missing = VmodalClient.unsafeDirect(+ baseUrl: 'http://localhost:4099',+ userId: '',+ transport: fake,+ signedUploadTransport: FakeSignedUploadTransport(),+ );+ expect(() => missing.http.headers(), throwsA(isA<AuthException>()));+ });+}diff --git a/test/config_routes_test.dart b/test/config_routes_test.dartnew file mode 100644index 0000000..98481d8--- /dev/null+++ b/test/config_routes_test.dart@@ -0,0 +1,80 @@+import 'dart:convert';+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';++void main() {+ test('route fixture exactly matches categorized SDK routes', () {+ final rows =+ (jsonDecode(+ File('test/fixtures/routes_contract.json').readAsStringSync(),+ )+ as List)+ .cast<Map<String, Object?>>();+ expect(rows, hasLength(Routes.specs.length));+ expect(+ rows.map((Map<String, Object?> row) => row['name']).toSet(),+ hasLength(rows.length),+ );+ expect(+ Routes.specs+ .where(+ (RouteSpec row) =>+ row.category == RouteCategory.multipartExperimental,+ )+ .length,+ 5,+ );+ expect(+ Routes.specs+ .singleWhere(+ (RouteSpec row) =>+ row.name == 'collections.upload_google_drive_folder',+ )+ .category,+ RouteCategory.deprecated,+ );+ });++ test('prefix resolver rejects absolute API URLs', () {+ expect(Routes.full('/health'), '/api/external/v1/health');+ expect(Routes.usersFull('/auth/me'), '/api/v1/auth/me');+ expect(+ () => Routes.full('https://evil.test/path'),+ throwsA(isA<ValidationException>()),+ );+ });++ test('configuration normalizes gateway once and redacts values', () {+ const key = 'sentinel-key-do-not-print';+ const user = 'sentinel-user-do-not-print';+ final config = SdkConfig(+ baseUrl: 'https://gateway.test/',+ userId: user,+ token: key,+ );+ expect(+ config.normalizedBaseUrl,+ 'https://gateway.test/api/v1/proxy/search_api',+ );+ expect(config.toString(), isNot(contains(key)));+ expect(config.toString(), isNot(contains(user)));+ expect(strUsersBaseUrl(config.normalizedBaseUrl), 'https://gateway.test');+ });++ test('invalid configuration fails before transport', () {+ expect(+ () => SdkConfig(baseUrl: 'http://remote.test'),+ throwsA(isA<ValidationException>()),+ );+ expect(+ () => SdkConfig(maxRetries: -1),+ throwsA(isA<ValidationException>()),+ );+ expect(+ () => SdkConfig(timeout: Duration.zero),+ throwsA(isA<ValidationException>()),+ );+ });+}diff --git a/test/fakes.dart b/test/fakes.dartnew file mode 100644index 0000000..e714ac5--- /dev/null+++ b/test/fakes.dart@@ -0,0 +1,195 @@+import 'dart:async';+import 'dart:typed_data';++import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';++class FakeTransport implements VmodalTransport {+ final List<VmodalRequest> requests = <VmodalRequest>[];+ final List<Object> queued = <Object>[];+ bool closed = false;++ void addJson(+ Map<String, Object?> value, {+ int status = 200,+ Map<String, String> headers = const <String, String>{+ 'content-type': 'application/json',+ },+ }) {+ final bytes = Uint8List.fromList(+ value.isEmpty+ ? <int>[123, 125]+ : Uint8List.fromList(+ // Keep fake serialization independent from SDK internals.+ _jsonBytes(value),+ ),+ );+ queued.add(+ VmodalResponse(+ statusCode: status,+ headers: headers,+ contentLength: bytes.length,+ body: Stream<List<int>>.value(bytes),+ ),+ );+ }++ void addResponse(VmodalResponse response) => queued.add(response);+ void addError(Object error) => queued.add(error);++ @override+ Future<VmodalResponse> send(VmodalRequest request) async {+ requests.add(request);+ if (queued.isEmpty) throw StateError('fake response queue is empty');+ final value = queued.removeAt(0);+ if (value is VmodalResponse) return value;+ throw value;+ }++ @override+ Future<void> close() async {+ closed = true;+ }+}++class HandlerTransport implements VmodalTransport {+ HandlerTransport(this.handler);++ final Future<VmodalResponse> Function(VmodalRequest request) handler;+ final List<VmodalRequest> requests = <VmodalRequest>[];++ @override+ Future<VmodalResponse> send(VmodalRequest request) {+ requests.add(request);+ return handler(request);+ }++ @override+ Future<void> close() async {}+}++class CountingKeyProvider implements ApiKeyProvider {+ CountingKeyProvider(this.value);++ String value;+ int reads = 0;++ @override+ String current() {+ reads++;+ return value;+ }+}++class SignedCall {+ SignedCall({+ required this.url,+ required this.method,+ required this.headers,+ required this.offset,+ required this.length,+ });++ final Uri url;+ final String method;+ final Map<String, String> headers;+ final int offset;+ final int length;+}++class FakeSignedUploadTransport implements SignedUploadTransport {+ final List<SignedCall> calls = <SignedCall>[];+ final List<Object> queued = <Object>[];+ int active = 0;+ int maxActive = 0;+ bool closed = false;++ @override+ Future<SignedUploadResult> upload({+ required UploadSource source,+ required Uri url,+ String method = 'PUT',+ int offset = 0,+ int? length,+ Map<String, String> headers = const <String, String>{},+ Duration? timeout,+ required CancellationToken cancellation,+ void Function(UploadProgress progress)? onProgress,+ }) async {+ final wanted = length ?? source.contentLength - offset;+ calls.add(+ SignedCall(+ url: url,+ method: method,+ headers: Map<String, String>.from(headers),+ offset: offset,+ length: wanted,+ ),+ );+ active++;+ if (active > maxActive) maxActive = active;+ final value = queued.isEmpty+ ? const SignedUploadResult(statusCode: 200, etag: 'etag')+ : queued.removeAt(0);+ try {+ var sent = 0;+ await for (final chunk in source.open(offset: offset, length: wanted)) {+ cancellation.throwIfCanceled();+ sent += chunk.length;+ onProgress?.call(UploadProgress(sent, wanted));+ }+ if (value is SignedUploadResult) return value;+ throw value;+ } finally {+ active--;+ }+ }++ @override+ Future<void> close() async {+ closed = true;+ }+}++VmodalResponse jsonResponse(+ String json, {+ int status = 200,+ int? declaredLength,+ List<int>? chunks,+}) {+ final bytes = Uint8List.fromList(json.codeUnits);+ final sizes = chunks ?? <int>[bytes.length];+ Stream<List<int>> body() async* {+ var offset = 0;+ for (final size in sizes) {+ if (offset >= bytes.length) break;+ final end = (offset + size).clamp(0, bytes.length);+ yield bytes.sublist(offset, end);+ offset = end;+ }+ if (offset < bytes.length) yield bytes.sublist(offset);+ }++ return VmodalResponse(+ statusCode: status,+ headers: const <String, String>{'content-type': 'application/json'},+ contentLength: declaredLength ?? bytes.length,+ body: body(),+ );+}++List<int> _jsonBytes(Map<String, Object?> value) {+ String string(Object? item) {+ if (item == null) return 'null';+ if (item is bool || item is num) return '$item';+ if (item is String) {+ return '"${item.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"';+ }+ if (item is List) return '[${item.map(string).join(',')}]';+ if (item is Map) {+ return '{${item.entries.map((MapEntry<Object?, Object?> row) => '${string('${row.key}')}:${string(row.value)}').join(',')}}';+ }+ return string('$item');+ }++ return string(value).codeUnits;+}diff --git a/test/fakes_test.dart b/test/fakes_test.dartnew file mode 100644index 0000000..e3405b1--- /dev/null+++ b/test/fakes_test.dart@@ -0,0 +1,48 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:vmodal_sdk_flutter/src/transport.dart' show readBounded;+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';++import 'fakes.dart';++void main() {+ test('queued fake records requests and preserves order', () async {+ final fake = FakeTransport()+ ..addResponse(jsonResponse('{"value":1}'))+ ..addError(const TransportException());+ final request = VmodalRequest(+ method: 'GET',+ uri: Uri.parse('https://example.test/a'),+ );+ expect((await fake.send(request)).statusCode, 200);+ await expectLater(fake.send(request), throwsA(isA<TransportException>()));+ expect(fake.requests, hasLength(2));+ });++ test('chunk fake preserves all bytes', () async {+ final response = jsonResponse('{"ok":true}', chunks: <int>[1, 2, 3]);+ final bytes = await readBounded(response, 100);+ expect(String.fromCharCodes(bytes), '{"ok":true}');+ });++ test('fake signed transport streams and records progress', () async {+ final fake = FakeSignedUploadTransport();+ final source = UploadSource(+ fileName: 'a.mp4',+ contentLength: 4,+ sourceId: 'source-a',+ opener: () => Stream<List<int>>.fromIterable(<List<int>>[+ <int>[1, 2],+ <int>[3, 4],+ ]),+ );+ final values = <int>[];+ await fake.upload(+ source: source,+ url: Uri.parse('https://objects.test/a'),+ cancellation: CancellationToken(),+ onProgress: (UploadProgress value) => values.add(value.uploadedBytes),+ );+ expect(values, <int>[2, 4]);+ expect(fake.calls, hasLength(1));+ });+}diff --git a/test/fixtures/routes_contract.json b/test/fixtures/routes_contract.jsonnew file mode 100644index 0000000..3fb5a41--- /dev/null+++ b/test/fixtures/routes_contract.json@@ -0,0 +1 @@+[{"category":"usersApi","method":"GET","name":"admin.cache_stats","path":"/admin/cache/stats","source":"users_api"},{"category":"usersApi","method":"GET","name":"admin.usage","path":"/admin/usage","source":"users_api"},{"category":"active","method":"GET","name":"admin.user_stats","path":"/admin/user-stats","source":"upstream"},{"category":"active","method":"GET","name":"auth.auth_check","path":"/health","source":"upstream"},{"category":"active","method":"GET","name":"auth.health","path":"/health","source":"upstream"},{"category":"usersApi","method":"GET","name":"auth.me","path":"/auth/me","source":"users_api"},{"category":"active","method":"POST","name":"collections.add_assets","path":"/collection/{collection_id}/assets/create","source":"upstream"},{"category":"disabled","method":"GET","name":"collections.auto_index_get","path":"/collection/auto_index","source":"upstream"},{"category":"disabled","method":"POST","name":"collections.auto_index_set","path":"/collection/auto_index","source":"upstream"},{"category":"disabled","method":"NONE","name":"collections.create","path":"","source":"sdk_contract"},{"category":"active","method":"DELETE","name":"collections.delete","path":"/collection/delete","source":"upstream"},{"category":"disabled","method":"NONE","name":"collections.edit","path":"","source":"sdk_contract"},{"category":"active","method":"GET","name":"collections.list_groups","path":"/collection/groups","source":"upstream"},{"category":"active","method":"POST","name":"collections.update_description","path":"/collection/description/update","source":"upstream"},{"category":"active","method":"POST","name":"collections.upload_file","path":"/collection/upload","source":"upstream"},{"category":"disabled","method":"POST","name":"collections.upload_folder","path":"/upload/folder","source":"upstream"},{"category":"deprecated","method":"POST","name":"collections.upload_google_drive_folder","path":"/collection/upload/google_drive","source":"upstream"},{"category":"active","method":"POST","name":"collections.upload_metadata_jsonl","path":"/collection/upload/metadata","source":"upstream"},{"category":"signedSingle","method":"POST","name":"collections.video_upload.done","path":"/collection/upload/done","source":"sdk_python"},{"category":"signedSingle","method":"POST","name":"collections.video_upload.presign","path":"/collections/external_upload_get_signed_url","source":"sdk_python"},{"category":"disabled","method":"POST","name":"gdrive.private_auth_url","path":"/gdrive/private/auth-url","source":"upstream"},{"category":"disabled","method":"POST","name":"gdrive.private_download","path":"/gdrive/private/folder/download","source":"upstream"},{"category":"image","method":"POST","name":"images.get_image_bulk_from_urls","path":"/image/get_image_bulk","source":"apionly_serve_img.py"},{"category":"image","method":"POST","name":"images.get_image_from_url","path":"/image/get_image","source":"apionly_serve_img.py"},{"category":"image","method":"POST","name":"images.get_url","path":"/image/get_url","source":"apionly_serve_img.py"},{"category":"image","method":"POST","name":"images.get_url_bulk","path":"/image/get_url_bulk","source":"apionly_serve_img.py"},{"category":"active","method":"POST","name":"indexes.create_index","path":"/indexation/job/create","source":"upstream"},{"category":"active","method":"DELETE","name":"indexes.delete_index","path":"/indexation/index/delete","source":"upstream"},{"category":"disabled","method":"GET","name":"indexes.embedding_models","path":"/indexes/embedding_models","source":"upstream"},{"category":"active","method":"GET","name":"indexes.index_status","path":"/indexation/job/{job_id}","source":"upstream"},{"category":"active","method":"GET","name":"indexes.jobs_list","path":"/indexation/jobs","source":"upstream"},{"category":"active","method":"POST","name":"metadata.internal_fallback","path":"/api/internal/v1/collection/upload/metadata","source":"sdk_python"},{"category":"multipartExperimental","method":"POST","name":"multipart.abort","path":"/collections/external_upload_multipart/abort","source":"sdk_python"},{"category":"multipartExperimental","method":"POST","name":"multipart.complete","path":"/collections/external_upload_multipart/complete","source":"sdk_python"},{"category":"multipartExperimental","method":"POST","name":"multipart.create","path":"/collections/external_upload_multipart/create","source":"sdk_python"},{"category":"multipartExperimental","method":"POST","name":"multipart.sign_parts","path":"/collections/external_upload_multipart/sign_parts","source":"sdk_python"},{"category":"multipartExperimental","method":"GET","name":"multipart.status","path":"/collections/external_upload_multipart/status","source":"sdk_python"},{"category":"usersApi","method":"GET","name":"r2.credentials","path":"/get_r2_credentials/","source":"users_api"},{"category":"usersApi","method":"GET","name":"r2.presign_upload_file","path":"/upload_file/","source":"users_api"},{"category":"usersApi","method":"POST","name":"r2.presign_upload_folder_video","path":"/upload_folder_video/","source":"users_api"},{"category":"active","method":"POST","name":"searches.search_video","path":"/search","source":"upstream"},{"category":"disabled","method":"POST","name":"sql.query","path":"/sql/query","source":"upstream"}]diff --git a/test/multipart_upload_test.dart b/test/multipart_upload_test.dartnew file mode 100644index 0000000..7004a09--- /dev/null+++ b/test/multipart_upload_test.dart@@ -0,0 +1,167 @@+import 'dart:io';+import 'dart:typed_data';++import 'package:crypto/crypto.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';++import 'fakes.dart';++void main() {+ test('multipart validates explicit options and size never enables it', () {+ expect(+ () => const VideoUploadOptions(+ multipart: true,+ partSizeBytes: 1024,+ ).validate(10 * 1024 * 1024),+ throwsA(isA<ValidationException>()),+ );+ expect(+ const VideoUploadOptions(+ multipartThresholdBytes: 1,+ ).resolvedFor(1024 * 1024 * 1024).multipart,+ isFalse,+ );+ });++ test(+ 'missing multipart route maps to FeatureDisabled without single fallback',+ () async {+ final api = FakeTransport()+ ..addResponse(jsonResponse('{"detail":"missing"}', status: 404));+ final client = VmodalClient(+ config: SdkConfig(baseUrl: 'https://gateway.test', token: 'key'),+ transport: api,+ signedUploadTransport: FakeSignedUploadTransport(),+ );+ final task = client.collections.videoUpload(+ UploadSource(+ fileName: 'a.mp4',+ contentLength: 6 * 1024 * 1024,+ sourceId: 'source-a',+ opener: () => _bytes(6 * 1024 * 1024, 1),+ ),+ collectionName: 'g',+ subCollectionName: 's',+ options: const VideoUploadOptions(+ multipart: true,+ partSizeBytes: 5 * 1024 * 1024,+ ),+ );+ await expectLater(task.result, throwsA(isA<FeatureDisabled>()));+ expect(api.requests, hasLength(1));+ expect(+ api.requests.single.uri.path,+ endsWith(Routes.externalUploadMultipartCreate),+ );+ },+ );++ test('multipart completes only ordered server-verified parts', () async {+ const mib = 1024 * 1024;+ final source = UploadSource(+ fileName: 'a.mp4',+ contentLength: 6 * mib,+ sourceId: 'source-a',+ versionTag: 'v1',+ opener: () => _bytes(6 * mib, 7),+ );+ final md5a = await md5Hex(source, offset: 0, length: 5 * mib);+ final md5b = await md5Hex(source, offset: 5 * mib, length: mib);+ var statusCalls = 0;+ final api = HandlerTransport((VmodalRequest request) async {+ final path = request.uri.path;+ if (path.endsWith(Routes.externalUploadMultipartCreate)) {+ return jsonResponse(+ '{"request_id":"r","upload_id":"u","key":"k",'+ '"part_count":2,"part_size_bytes":${5 * mib}}',+ );+ }+ if (path.endsWith(Routes.externalUploadMultipartStatus)) {+ statusCalls++;+ if (statusCalls == 1) {+ return jsonResponse('{"status":"uploading","parts":[]}');+ }+ return jsonResponse(+ '{"status":"uploading","parts":['+ '{"part_number":2,"etag":"$md5b","size_bytes":$mib},'+ '{"part_number":1,"etag":"$md5a","size_bytes":${5 * mib}}]}',+ );+ }+ if (path.endsWith(Routes.externalUploadMultipartSignParts)) {+ return jsonResponse(+ '{"parts":['+ '{"part_number":1,"url":"https://objects.test/1","method":"PUT"},'+ '{"part_number":2,"url":"https://objects.test/2","method":"PUT"}]}',+ );+ }+ if (path.endsWith(Routes.externalUploadMultipartComplete)) {+ final body = request.jsonBody! as Map<String, Object?>;+ final parts = body['parts']! as List;+ expect(+ parts.map(+ (Object? item) => (item! as Map<String, Object?>)['part_number'],+ ),+ <int>[1, 2],+ );+ return jsonResponse('{"etag":"complete-etag"}');+ }+ if (path.endsWith(Routes.externalUploadDone)) {+ return jsonResponse('{"dest_path":"done/a.mp4"}');+ }+ throw StateError('unexpected route: $path');+ });+ final signed = FakeSignedUploadTransport()+ ..queued.add(const SignedUploadResult(statusCode: 200))+ ..queued.add(const SignedUploadResult(statusCode: 200));+ // Fake result MD5/ETag must match the bytes. Set them after construction.+ signed.queued+ ..clear()+ ..add(SignedUploadResult(statusCode: 200, etag: md5a, localMd5: md5a))+ ..add(SignedUploadResult(statusCode: 200, etag: md5b, localMd5: md5b));+ final client = VmodalClient(+ config: SdkConfig(baseUrl: 'https://gateway.test', token: 'key'),+ transport: api,+ signedUploadTransport: signed,+ );+ final result = await client.collections+ .videoUpload(+ source,+ collectionName: 'g',+ subCollectionName: 's',+ options: VideoUploadOptions(+ multipart: true,+ partSizeBytes: 5 * mib,+ maxConcurrency: 2,+ sessionStore: MemoryUploadSessionStore(),+ ),+ )+ .result;+ expect(result.uploadStrategy, 'multipart');+ expect(result.partCount, 2);+ expect(result.destPath, 'done/a.mp4');+ expect(statusCalls, 2);+ });++ test('file checkpoint rejects oversized and malformed state', () async {+ final dir = await Directory.systemTemp.createTemp('vmodal-checkpoint-');+ addTearDown(() => dir.delete(recursive: true));+ final store = FileUploadSessionStore(dir);+ await store.save('a', <String, Object?>{'valid': true});+ expect(await store.load('a'), <String, Object?>{'valid': true});+ await File(+ '${dir.path}/${sha256.convert('b'.codeUnits)}.json',+ ).writeAsString('{bad');+ await expectLater(store.load('b'), throwsA(isA<MalformedResponse>()));+ });+}++Stream<List<int>> _bytes(int length, int value) async* {+ const chunkSize = 256 * 1024;+ var left = length;+ while (left > 0) {+ final size = left < chunkSize ? left : chunkSize;+ yield Uint8List(size)..fillRange(0, size, value);+ left -= size;+ }+}diff --git a/test/regression_manifest_test.dart b/test/regression_manifest_test.dartnew file mode 100644index 0000000..d5a5061--- /dev/null+++ b/test/regression_manifest_test.dart@@ -0,0 +1,122 @@+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';++void main() {+ test('regression manifest covers every implemented step in order', () {+ final text = File('test.sh').readAsStringSync();+ const steps = <String>[+ 'S04',+ 'S05',+ 'S06',+ 'S07',+ 'S08',+ 'S09',+ 'S10',+ 'S11_1',+ 'S11_2',+ 'S11_3',+ 'S11_4',+ 'S11_5',+ 'S11_6',+ 'S11',+ 'S12',+ 'S13',+ 'S14',+ 'S15',+ 'S16',+ 'S17',+ 'S18',+ 'S19',+ ];+ for (final step in steps) {+ expect(text, contains(step));+ }+ expect(+ text.indexOf('config_routes_test.dart'),+ lessThan(text.indexOf('adaptive_upload_test.dart')),+ );+ expect(+ text.indexOf('adaptive_upload_test.dart'),+ lessThan(text.indexOf('security_check.sh all')),+ );+ });++ test('required implementation and release artifacts exist', () {+ const files = <String>[+ 'lib/vmodal_sdk_flutter.dart',+ 'lib/src/client.dart',+ 'lib/src/transport.dart',+ 'lib/src/upload.dart',+ 'lib/src/adaptive_upload.dart',+ 'tool/check_route_sync.dart',+ 'tool/release_manifest.dart',+ 'example/lib/main.dart',+ ];+ for (final path in files) {+ expect(File(path).existsSync(), isTrue, reason: path);+ }+ expect(+ File('release/public_publish.yml').existsSync() ||+ File('.github/workflows/publish.yml').existsSync(),+ isTrue,+ reason: 'public publish workflow',+ );+ if (Directory('docs').existsSync()) {+ expect(File('tool/live_test.dart').existsSync(), isTrue);+ }+ expect(+ File('docs/sdk_contract.md').existsSync() ||+ File('doc/sdk_contract.md').existsSync(),+ isTrue,+ reason: 'SDK contract documentation',+ );+ });++ test('default all suite remains offline', () {+ final text = File('test.sh').readAsStringSync();+ final body = RegExp(+ r'sdk_all\(\) \{([\s\S]*?)\n\}',+ ).firstMatch(text)!.group(1)!;+ expect(body, isNot(contains('sdk_live')));+ expect(body, contains('sdk_test'));+ expect(body, contains('sdk_package'));+ expect(body, contains('sdk_sim'));+ });++ test(+ 'source export keeps lockfile and excludes generated platform files',+ () async {+ final dir = Directory.systemTemp.createTempSync('vmodal-export-test.');+ addTearDown(() => dir.deleteSync(recursive: true));+ final bin = await Process.run('bash', <String>['install.sh', 'dart_bin']);+ expect(bin.exitCode, 0, reason: '${bin.stderr}');+ final result = await Process.run('${bin.stdout}'.trim(), <String>[+ 'run',+ 'tool/release_manifest.dart',+ 'export',+ dir.path,+ ]);+ expect(result.exitCode, 0, reason: '${result.stderr}');+ expect(File('${dir.path}/pubspec.lock').existsSync(), isTrue);+ for (final path in <String>[+ 'example/android/local.properties',+ 'example/android/gradle/wrapper/gradle-wrapper.jar',+ 'example/android/gradlew',+ 'example/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java',+ 'example/.idea',+ 'example/vmodal_example.iml',+ 'example/ios/Flutter/Generated.xcconfig',+ 'example/ios/Flutter/flutter_export_environment.sh',+ 'example/ios/Flutter/ephemeral',+ 'example/ios/Runner/GeneratedPluginRegistrant.h',+ 'example/ios/Runner/GeneratedPluginRegistrant.m',+ ]) {+ expect(+ FileSystemEntity.typeSync('${dir.path}/$path'),+ FileSystemEntityType.notFound,+ );+ }+ },+ );+}diff --git a/test/resources_models_test.dart b/test/resources_models_test.dartnew file mode 100644index 0000000..fc5058e--- /dev/null+++ b/test/resources_models_test.dart@@ -0,0 +1,134 @@+import 'dart:convert';++import 'package:flutter_test/flutter_test.dart';+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';++import 'fakes.dart';++void main() {+ test(+ 'search serialization preserves exact defaults and snake case',+ () async {+ final fake = FakeTransport()+ ..addResponse(jsonResponse('{"data":[],"cnt_actual":0,"cnt_total":0}'));+ final client = VmodalClient(+ config: SdkConfig(baseUrl: 'https://gateway.test', token: 'key'),+ transport: fake,+ signedUploadTransport: FakeSignedUploadTransport(),+ );+ await client.searches.searchVideo(const SearchRequest(queryText: 'bike'));+ final request = fake.requests.single;+ expect(request.method, 'POST');+ expect(request.uri.path, endsWith('/api/external/v1/search'));+ final body = request.jsonBody! as Map<String, Object?>;+ expect(body['query_text'], 'bike');+ expect(body['group_name'], 'agroup');+ expect(body['stream_name'], 'astream');+ expect(body['search_sources'], <String>['ocr', 'asr', 'image']);+ expect(body, isNot(contains('user_id')));+ },+ );++ test('model validation and numeric coercion match mobile contract', () {+ expect(+ () => const SearchRequest().validate(),+ throwsA(isA<ValidationException>()),+ );+ final response = SearchResponse(<String, Object?>{+ 'data': <Object?>[],+ 'cnt_actual': '2',+ 'cnt_total': 3.0,+ 'execution_time_ms': '1.5',+ });+ expect(response.cntActual, 2);+ expect(response.cntTotal, 3);+ expect(response.executionTimeMs, 1.5);+ });++ test('gateway bulk image payload removes nested identity fields', () async {+ final fake = FakeTransport()..addResponse(jsonResponse('{"records":[]}'));+ final client = VmodalClient(+ config: SdkConfig(baseUrl: 'https://gateway.test', token: 'key'),+ transport: fake,+ signedUploadTransport: FakeSignedUploadTransport(),+ );+ await client.images.getUrlBulk(<Map<String, Object?>>[+ <String, Object?>{+ 'mode': 'img_file',+ 'userid': 'malicious-a',+ 'user_id': 'malicious-b',+ },+ ], userid: 'malicious-outer');+ final body = fake.requests.single.jsonBody! as Map<String, Object?>;+ expect(body, isNot(contains('userid')));+ final row = (body['records']! as List).single as Map<String, Object?>;+ expect(row, isNot(contains('userid')));+ expect(row, isNot(contains('user_id')));+ });++ test('resource paths and users API base are exact', () async {+ final fake = FakeTransport()+ ..addResponse(jsonResponse('{"user_id":"u"}'))+ ..addResponse(jsonResponse('{"data":[],"total":0}'))+ ..addResponse(jsonResponse('{"job_id":"j","status":"queued"}'));+ final client = VmodalClient(+ config: SdkConfig(baseUrl: 'https://gateway.test', token: 'key'),+ transport: fake,+ signedUploadTransport: FakeSignedUploadTransport(),+ );+ expect((await client.auth.me()).userId, 'u');+ await client.indexes.jobsList(groupName: 'g');+ await client.indexes.createIndex(+ const IndexationSubmitRequest(mode: 'vid_file', groupName: 'g'),+ );+ expect(+ fake.requests[0].uri.toString(),+ 'https://gateway.test/api/v1/auth/me',+ );+ expect(+ fake.requests[1].uri.path,+ endsWith('/api/external/v1/indexation/jobs'),+ );+ expect(fake.requests[1].uri.queryParameters['group_name'], 'g');+ expect(fake.requests[2].method, 'POST');+ });++ test('all disabled methods fail before transport', () {+ final fake = FakeTransport();+ final client = VmodalClient(+ config: SdkConfig(baseUrl: 'https://gateway.test', token: 'key'),+ transport: fake,+ signedUploadTransport: FakeSignedUploadTransport(),+ );+ expect(client.collections.create, throwsA(isA<FeatureDisabled>()));+ expect(client.collections.edit, throwsA(isA<FeatureDisabled>()));+ expect(client.collections.uploadFolder, throwsA(isA<FeatureDisabled>()));+ expect(client.indexes.embeddingModels, throwsA(isA<FeatureDisabled>()));+ expect(client.gdrive.privateAuthUrl, throwsA(isA<FeatureDisabled>()));+ expect(client.sql.query, throwsA(isA<FeatureDisabled>()));+ expect(fake.requests, isEmpty);+ });++ test('request JSON remains serializable for every primary model', () {+ final values = <Map<String, Object?>>[+ const SearchRequest(queryText: 'a').toJson(),+ const DeleteCollectionRequest(groupName: 'g', mode: 'vid_file').toJson(),+ const CollectionAddAssetsRequest(+ collectionId: 'c',+ assetIds: <String>['a'],+ mode: 'vid_file',+ groupName: 'g',+ ).toJson(),+ const IndexationSubmitRequest(mode: 'vid_file', groupName: 'g').toJson(),+ const IndexationDeleteRequest(+ mode: 'vid_file',+ groupName: 'g',+ version: 'v1',+ ).toJson(),+ const ImageUrlRecord(mode: 'img_file').toJson(),+ ];+ for (final value in values) {+ expect(() => jsonEncode(value), returnsNormally);+ }+ });+}diff --git a/test/shell_scripts_test.dart b/test/shell_scripts_test.dartnew file mode 100644index 0000000..63b79ca--- /dev/null+++ b/test/shell_scripts_test.dart@@ -0,0 +1,86 @@+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';++const scripts = <String>[+ 'install.sh',+ 'build.sh',+ 'run.sh',+ 'test.sh',+ 'env.sh',+ 'security_check.sh',+];++void main() {+ test(+ 'all shell scripts have valid syntax and executable dispatchers',+ () async {+ for (final path in scripts) {+ expect(File(path).existsSync(), isTrue, reason: path);+ final syntax = await Process.run('bash', <String>['-n', path]);+ expect(syntax.exitCode, 0, reason: '$path: ${syntax.stderr}');+ final help = await Process.run('bash', <String>[path, 'help']);+ expect(help.exitCode, 0, reason: '$path: ${help.stderr}');+ expect(help.stdout, contains('Usage'));+ final bad = await Process.run('bash', <String>[path, 'not-a-command']);+ expect(bad.exitCode, isNot(0));+ }+ },+ );++ test(+ 'env.sh is source-only, idempotent, and preserves explicit values',+ () async {+ const sentinel = 'sdk-secret-sentinel';+ final result = await Process.run('bash', <String>[+ '-c',+ 'VMODAL_API_KEY=$sentinel; source env.sh; sdk_env_live; '+ 'test "\$VMODAL_API_KEY" = "$sentinel"; sdk_env_live',+ ]);+ expect(result.exitCode, 0, reason: '${result.stderr}');+ expect('${result.stdout}${result.stderr}', isNot(contains(sentinel)));+ },+ );++ test('local helpers cannot publish', () {+ for (final path in scripts.where(+ (String path) => path != 'security_check.sh',+ )) {+ final text = File(path).readAsStringSync();+ expect(text, isNot(contains('pub publish --force')), reason: path);+ expect(text, isNot(contains('--skip-validation')), reason: path);+ expect(text, isNot(contains('git merge')), reason: path);+ }+ });++ test('security commands and fixed all ordering are registered', () {+ final text = File('security_check.sh').readAsStringSync();+ for (final command in <String>[+ 'workflow',+ 'toolchain',+ 'version',+ 'license',+ 'package',+ 'secrets',+ 'all',+ ]) {+ expect(text, contains('$command)'));+ }+ final body = RegExp(+ r'sdk_security_all\(\) \{([\s\S]*?)\n\}',+ ).firstMatch(text)!.group(1)!;+ var offset = -1;+ for (final call in <String>[+ 'sdk_security_workflow',+ 'sdk_security_toolchain',+ 'sdk_security_version',+ 'sdk_security_license',+ 'sdk_security_package',+ 'sdk_security_secrets',+ ]) {+ final next = body.indexOf(call);+ expect(next, greaterThan(offset), reason: call);+ offset = next;+ }+ });+}diff --git a/test/transport_test.dart b/test/transport_test.dartnew file mode 100644index 0000000..a31c9c9--- /dev/null+++ b/test/transport_test.dart@@ -0,0 +1,118 @@+import 'dart:async';+import 'dart:typed_data';++import 'package:flutter_test/flutter_test.dart';+import 'package:vmodal_sdk_flutter/src/http.dart';+import 'package:vmodal_sdk_flutter/src/transport.dart' show readBounded;+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';++import 'fakes.dart';++void main() {+ test(+ 'bounded reader accepts exact limit and rejects limit plus one',+ () async {+ final exact = VmodalResponse(+ statusCode: 200,+ contentLength: 4,+ body: Stream<List<int>>.value(<int>[1, 2, 3, 4]),+ );+ expect(+ await readBounded(exact, 4),+ Uint8List.fromList(<int>[1, 2, 3, 4]),+ );+ final token = CancellationToken();+ final overflow = VmodalResponse(+ statusCode: 200,+ contentLength: -1,+ body: Stream<List<int>>.fromIterable(<List<int>>[+ <int>[1, 2],+ <int>[3, 4, 5],+ <int>[6, 7],+ ]),+ );+ await expectLater(+ readBounded(overflow, 4, cancellation: token),+ throwsA(isA<ResponseTooLarge>()),+ );+ expect(token.isCanceled, isTrue);+ },+ );++ test('declared overflow fails before stream consumption', () async {+ var listened = false;+ final response = VmodalResponse(+ statusCode: 200,+ contentLength: 10,+ body: Stream<List<int>>.multi((MultiStreamController<List<int>> out) {+ listened = true;+ out.add(<int>[1]);+ unawaited(out.close());+ }),+ );+ await expectLater(+ readBounded(response, 4),+ throwsA(isA<ResponseTooLarge>()),+ );+ expect(listened, isFalse);+ });++ test('strict JSON rejects malformed and wrong top-level shapes', () async {+ final malformed = FakeTransport()..addResponse(jsonResponse('{"broken":'));+ final http = VmodalHttp(+ SdkConfig(baseUrl: 'https://gateway.test', token: 'key'),+ malformed,+ );+ await expectLater(+ http.request('GET', '/api/external/v1/health'),+ throwsA(isA<MalformedResponse>()),+ );+ final list = FakeTransport()..addResponse(jsonResponse('[]'));+ final listHttp = VmodalHttp(+ SdkConfig(baseUrl: 'https://gateway.test', token: 'key'),+ list,+ );+ await expectLater(+ listHttp.request('GET', '/api/external/v1/health'),+ throwsA(isA<MalformedResponse>()),+ );+ });++ test('canceling one response does not affect a concurrent request', () async {+ final firstReady = Completer<void>();+ final releaseSecond = Completer<void>();+ var calls = 0;+ final fake = HandlerTransport((VmodalRequest request) async {+ calls++;+ if (calls == 1) {+ firstReady.complete();+ return VmodalResponse(+ statusCode: 200,+ contentLength: -1,+ body: Stream<List<int>>.periodic(+ const Duration(milliseconds: 1),+ (_) => <int>[123],+ ),+ );+ }+ await releaseSecond.future;+ return jsonResponse('{"status":"ok"}');+ });+ final http = VmodalHttp(+ SdkConfig(baseUrl: 'https://gateway.test', token: 'key'),+ fake,+ );+ final token = CancellationToken();+ final one = http.request(+ 'GET',+ '/api/external/v1/one',+ cancellation: token,+ );+ await firstReady.future;+ final two = http.request('GET', '/api/external/v1/two');+ token.cancel();+ releaseSecond.complete();+ await expectLater(one, throwsA(isA<OperationCanceled>()));+ expect((await two)['status'], 'ok');+ });+}diff --git a/test/upload_test.dart b/test/upload_test.dartnew file mode 100644index 0000000..9e9b740--- /dev/null+++ b/test/upload_test.dart@@ -0,0 +1,165 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';++import 'fakes.dart';++void main() {+ test('upload source is reopenable and range exact', () async {+ var opens = 0;+ final source = UploadSource(+ fileName: 'a.mp4',+ contentLength: 6,+ sourceId: 'stable-a',+ opener: () {+ opens++;+ return Stream<List<int>>.fromIterable(<List<int>>[+ <int>[0, 1, 2],+ <int>[3, 4, 5],+ ]);+ },+ );+ Future<List<int>> read(int offset, int length) => source+ .open(offset: offset, length: length)+ .expand((List<int> x) => x)+ .toList();+ expect(await read(2, 3), <int>[2, 3, 4]);+ expect(await read(0, 6), <int>[0, 1, 2, 3, 4, 5]);+ expect(opens, 2);+ });++ test('premature source EOF is an error', () async {+ final source = UploadSource(+ fileName: 'a.mp4',+ contentLength: 4,+ sourceId: 'short-a',+ opener: () => Stream<List<int>>.value(<int>[1, 2]),+ );+ await expectLater(+ source.open().drain<void>(),+ throwsA(isA<TransportException>()),+ );+ });++ test(+ 'signed single upload streams, isolates headers, then finalizes',+ () async {+ final api = FakeTransport()+ ..addResponse(+ jsonResponse(+ '{"url":"https://objects.test/u","method":"PUT","key":"k"}',+ ),+ )+ ..addResponse(jsonResponse('{"dest_path":"done/a.mp4"}'));+ final signed = FakeSignedUploadTransport()+ ..queued.add(const SignedUploadResult(statusCode: 200, etag: 'etag-a'));+ final client = VmodalClient(+ config: SdkConfig(baseUrl: 'https://gateway.test', token: 'secret-key'),+ transport: api,+ signedUploadTransport: signed,+ );+ final source = UploadSource(+ fileName: 'a.mp4',+ contentLength: 4,+ sourceId: 'source-a',+ opener: () => Stream<List<int>>.fromIterable(<List<int>>[+ <int>[1, 2],+ <int>[3, 4],+ ]),+ );+ final task = client.collections.videoUpload(+ source,+ collectionName: 'g',+ subCollectionName: 's',+ );+ final progress = <int>[];+ final sub = task.progress.listen(+ (UploadProgress value) => progress.add(value.uploadedBytes),+ );+ final result = await task.result;+ await sub.cancel();+ expect(result.uploaded, isTrue);+ expect(result.uploadStrategy, 'single');+ expect(result.destPath, 'done/a.mp4');+ expect(progress, <int>[2, 4]);+ expect(signed.calls.single.headers, isEmpty);+ expect(signed.calls.single.url.host, 'objects.test');+ expect(api.requests, hasLength(2));+ expect(api.requests.last.method, 'POST');+ },+ );++ test(+ 'cancel before upload produces exactly one canceled terminal state',+ () async {+ final wait = Completer<void>();+ final api = HandlerTransport((VmodalRequest request) async {+ await wait.future;+ request.cancellation.throwIfCanceled();+ return jsonResponse('{}');+ });+ final client = VmodalClient(+ config: SdkConfig(baseUrl: 'https://gateway.test', token: 'key'),+ transport: api,+ signedUploadTransport: FakeSignedUploadTransport(),+ );+ final task = client.collections.videoUpload(+ UploadSource(+ fileName: 'a.mp4',+ contentLength: 1,+ sourceId: 'source-a',+ opener: () => Stream<List<int>>.value(<int>[1]),+ ),+ collectionName: 'g',+ subCollectionName: 's',+ );+ task.cancel();+ wait.complete();+ await expectLater(task.result, throwsA(isA<OperationCanceled>()));+ expect(task.state, UploadTaskState.canceled);+ },+ );++ test('bulk results retain input order under bounded work', () async {+ final api = FakeTransport();+ for (var i = 0; i < 3; i++) {+ api+ ..addResponse(+ jsonResponse(+ '{"url":"https://objects.test/$i","method":"PUT","key":"k$i"}',+ ),+ )+ ..addResponse(jsonResponse('{"dest_path":"done/$i"}'));+ }+ final signed = FakeSignedUploadTransport();+ final client = VmodalClient(+ config: SdkConfig(baseUrl: 'https://gateway.test', token: 'key'),+ transport: api,+ signedUploadTransport: signed,+ );+ final sources = List<UploadSource>.generate(+ 3,+ (int index) => UploadSource(+ fileName: '$index.mp4',+ contentLength: 1,+ sourceId: 'source-$index',+ opener: () => Stream<List<int>>.value(<int>[index]),+ ),+ );+ final result = await client.collections+ .videoUploadBulk(+ sources,+ collectionName: 'g',+ subCollectionName: 's',+ options: const VideoUploadOptions(maxConcurrency: 1),+ )+ .result;+ expect(result.data.map((VideoUploadResponse row) => row.fileName), <String>[+ '0.mp4',+ '1.mp4',+ '2.mp4',+ ]);+ expect(signed.maxActive, 1);+ });+}diff --git a/test/workflow_layout_test.dart b/test/workflow_layout_test.dartnew file mode 100644index 0000000..794302b--- /dev/null+++ b/test/workflow_layout_test.dart@@ -0,0 +1,111 @@+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';++final internalFile = File(+ '../../.github/workflows/sdk_flutter_test_release.yml',+);+final internal = internalFile.existsSync()+ ? internalFile.readAsStringSync()+ : '';+final publicFile = File('release/public_publish.yml').existsSync()+ ? File('release/public_publish.yml')+ : File('.github/workflows/publish.yml');+final public = publicFile.readAsStringSync();++void checkWorkflow(String main, String tagged) {+ expect(main, contains('name: sdk_flutter_test_release'));+ expect(main, contains('publish_sdk_flutter:'));+ expect(main, contains('publish_pub_dev:'));+ expect(main, contains('default: true'));+ expect(main, contains('group: sdk_flutter_release_\${{ github.ref }}'));+ expect(main, contains('WORKDIR: uinterface/sdk_flutter'));+ expect(main, contains('RELEASE_SHA: \${{ github.sha }}'));+ expect(main, contains('secret_detection:'));+ expect(main, contains('needs: secret_detection'));+ expect(main, contains('needs: [offline_test, example_android]'));+ expect(+ main,+ contains(+ 'needs: [secret_detection, offline_test, example_android, example_ios, live_test, pub_package]',+ ),+ );+ expect(main, contains('needs: release_gate'));+ expect(main, contains('pub.dev publication requires source export.'));+ expect(main, contains('if: \${{ inputs.publish_pub_dev }}'));+ expect(main, contains('environment: sdk-flutter-production'));+ expect(main, contains('fetch-depth: 0'));+ expect(main, contains('gitleaks_'));+ expect(main, contains('--source "\$WORKDIR"'));+ expect(main, contains('--log-opts="--all -- \$WORKDIR"'));+ expect(main, contains('SHA256SUMS'));+ expect(main, contains('SOURCE_MANIFEST.sha256'));+ expect(main, contains('RELEASE_TOKEN: \${{ secrets.GH_TOKEN }}'));+ expect(main, isNot(contains('FLUTTER_SDK_APP_')));+ expect(main, contains('git push --atomic'));+ expect(main, contains('for attempt in {1..30}'));+ expect(main, contains('https://pub.dev/api/packages/vmodal_sdk_flutter'));++ final actions = RegExp(+ r'uses:\s+[^\s]+@([^\s]+)',+ ).allMatches('$main\n$tagged');+ expect(actions, isNotEmpty);+ for (final action in actions) {+ expect(action.group(1), matches(RegExp(r'^[0-9a-f]{40}$')));+ }+ for (final checkout in RegExp(+ r'uses:\s+actions/checkout@[\s\S]*?(?=\n\s*- name:|\n\s*- uses:|\n\s*$)',+ ).allMatches('$main\n$tagged')) {+ expect(checkout.group(0), contains('persist-credentials: false'));+ }++ expect(main, isNot(contains('id-token: write')));+ expect(+ main.toLowerCase(),+ isNot(matches(RegExp(r'maven|\bosv\b|\bsbom\b|security_policy'))),+ );+ expect(main, isNot(contains('git merge')));+ expect(main, isNot(contains('git push --force')));+ expect(main, isNot(contains('--skip-validation')));++ expect(tagged, contains('name: publish_pub_dev'));+ expect(tagged, contains("- 'v[0-9]+.[0-9]+.[0-9]+'"));+ expect(tagged, isNot(contains('workflow_dispatch')));+ expect(tagged, contains('needs: verify_tagged_source'));+ expect(tagged, contains('environment: pub.dev'));+ expect(tagged, contains('id-token: write'));+ expect(tagged, contains('pub publish --force'));+ expect(tagged, isNot(contains('--skip-validation')));+ expect(tagged.toLowerCase(), isNot(contains('pub_token')));+}++void main() {+ test('release workflows enforce tested-source causality', () {+ if (internal.isEmpty) return;+ checkWorkflow(internal, public);+ });++ test('floating action pin mutation fails', () {+ if (internal.isEmpty) return;+ final bad = internal.replaceFirst(+ RegExp(r'actions/checkout@[0-9a-f]{40}'),+ 'actions/checkout@v4',+ );+ expect(() => checkWorkflow(bad, public), throwsA(isA<TestFailure>()));+ });++ test('publication shortcut mutation fails', () {+ if (internal.isEmpty) return;+ final bad = internal.replaceFirst(+ 'needs: release_gate',+ 'needs: offline_test',+ );+ expect(() => checkWorkflow(bad, public), throwsA(isA<TestFailure>()));+ });++ test('stored publication token mutation fails', () {+ if (internal.isEmpty) return;+ final bad = '$public\n PUB_TOKEN: \${{ secrets.PUB_TOKEN }}\n';+ expect(() => checkWorkflow(internal, bad), throwsA(isA<TestFailure>()));+ });+}diff --git a/tool/check_route_sync.dart b/tool/check_route_sync.dartnew file mode 100644index 0000000..4845077--- /dev/null+++ b/tool/check_route_sync.dart@@ -0,0 +1,128 @@+import 'dart:convert';+import 'dart:io';++import 'package:vmodal_sdk_flutter/src/routes.dart';++void main() {+ final root = _packageRoot();+ final fixtureFile = File('${root.path}/test/fixtures/routes_contract.json');+ final upstream = File(+ '${root.path}/../../../vmx_avideo/infra/search_api_ui/routers/apionly_routes.py',+ );+ final images = File(+ '${root.path}/../../../vmx_avideo/infra/search_api_ui/routers/apionly_serve_img.py',+ );+ if (!fixtureFile.existsSync()) _fail('route fixture is unavailable');+ final fixture = (jsonDecode(fixtureFile.readAsStringSync()) as List)+ .map((Object? item) => Map<String, Object?>.from(item! as Map))+ .toList();+ final normalized =+ Routes.specs+ .map(+ (RouteSpec spec) => <String, Object?>{+ 'category': spec.category.name,+ 'method': spec.method,+ 'name': spec.name,+ 'path': spec.path,+ 'source': spec.source,+ },+ )+ .toList()+ ..sort(+ (Map<String, Object?> a, Map<String, Object?> b) =>+ '${a['name']}'.compareTo('${b['name']}'),+ );+ _same(fixture, normalized, 'fixture differs from Routes.specs');+ if (!upstream.existsSync() || !images.existsSync()) {+ stdout.writeln(+ 'local route contract OK: ${fixture.length} classified operations; '+ 'upstream source unavailable',+ );+ return;+ }++ final source = upstream.readAsStringSync();+ final block = RegExp(+ r'class apiEndpoints:[\s\S]*?(?=\n\n# [─#]|\n@dataclass\nclass UserCtx)',+ ).firstMatch(source)?.group(0);+ final endpointBlock = block ?? _fail('apiEndpoints block was not found');+ final declared = RegExp(r'^\s+([a-z_]+): str = "([^"]+)"', multiLine: true)+ .allMatches(endpointBlock)+ .map((RegExpMatch match) => match.group(2)!)+ .toSet();+ final upstreamRows = fixture+ .where((Map<String, Object?> row) => row['source'] == 'upstream')+ .map((Map<String, Object?> row) => '${row['path']}')+ .toSet();+ final missingDeclared = declared.difference(upstreamRows);+ if (missingDeclared.isNotEmpty) {+ _fail('missing upstream declarations: $missingDeclared');+ }++ final active = _decorators(source, commented: false);+ final representedActive = fixture+ .where(+ (Map<String, Object?> row) =>+ row['source'] == 'upstream' &&+ (row['category'] == 'active' || row['category'] == 'deprecated'),+ )+ .map(_wireKey)+ .toSet();+ final missingActive = active.difference(representedActive);+ if (missingActive.isNotEmpty) {+ _fail('missing active upstream routes: $missingActive');+ }++ final imageActive = _decorators(images.readAsStringSync(), commented: false);+ final imageRows = fixture+ .where((Map<String, Object?> row) => row['category'] == 'image')+ .map(_wireKey)+ .toSet();+ _same(+ imageActive.toList()..sort(),+ imageRows.toList()..sort(),+ 'image routes differ from upstream',+ );++ final names = fixture.map((Map<String, Object?> row) => row['name']).toList();+ if (names.toSet().length != names.length) _fail('duplicate route name');+ final sorted = List<Object?>.from(names)+ ..sort((Object? a, Object? b) => '$a'.compareTo('$b'));+ _same(names, sorted, 'fixture is not sorted by name');+ stdout.writeln('route contract OK: ${fixture.length} classified operations');+}++Directory _packageRoot() {+ var dir = Directory.current.absolute;+ while (!File('${dir.path}/pubspec.yaml').existsSync()) {+ final parent = dir.parent;+ if (parent.path == dir.path) _fail('package root was not found');+ dir = parent;+ }+ return dir;+}++Set<String> _decorators(String source, {required bool commented}) {+ final prefix = commented ? r'#\s*' : '';+ final pattern = RegExp(+ '^$prefix@router\\.(get|post|delete)\\("([^"]+)"',+ multiLine: true,+ );+ return pattern+ .allMatches(source)+ .map(+ (RegExpMatch match) =>+ '${match.group(1)!.toUpperCase()} ${match.group(2)}',+ )+ .toSet();+}++String _wireKey(Map<String, Object?> row) => '${row['method']} ${row['path']}';++Never _fail(String message) {+ throw StateError(message);+}++void _same(Object? actual, Object? expected, String message) {+ if (jsonEncode(actual) != jsonEncode(expected)) _fail(message);+}diff --git a/tool/flutter_checksums.txt b/tool/flutter_checksums.txtnew file mode 100644index 0000000..aeeb38e--- /dev/null+++ b/tool/flutter_checksums.txt@@ -0,0 +1,5 @@+# version platform archive sha256+3.44.6 macos-x64 stable/macos/flutter_macos_3.44.6-stable.zip d698aeb050198878ec6d5cdc1e6ccf1ef6850ec336985b03812b2525df2289ce+3.44.6 macos-arm64 stable/macos/flutter_macos_arm64_3.44.6-stable.zip e4824875f22cc7e0f4878bfc8b9382e98ff0137074c5d3ab4686f7a4b5ac775c+3.44.6 linux-x64 stable/linux/flutter_linux_3.44.6-stable.tar.xz a6320fd72e9a2690c08e2a6a70874a30cb120dee7c78f49d2c628bd7c9e20525+diff --git a/tool/release_manifest.dart b/tool/release_manifest.dartnew file mode 100644index 0000000..31875b2--- /dev/null+++ b/tool/release_manifest.dart@@ -0,0 +1,168 @@+import 'dart:io';++import 'package:crypto/crypto.dart';++const generatedNames = <String>{+ '.dart_tool',+ '.flutter-plugins',+ '.flutter-plugins-dependencies',+ '.gradle',+ '.idea',+ '.last_build_id',+ '.packages',+ '.symlinks',+ 'Generated.xcconfig',+ 'GeneratedPluginRegistrant.h',+ 'GeneratedPluginRegistrant.java',+ 'GeneratedPluginRegistrant.m',+ 'Pods',+ 'build',+ 'coverage',+ 'ephemeral',+ 'flutter_export_environment.sh',+ 'gradle-wrapper.jar',+ 'gradlew',+ 'gradlew.bat',+ 'local.properties',+};++bool isGeneratedName(String name) =>+ generatedNames.contains(name) || name.endsWith('.iml');++Future<void> main(List<String> args) async {+ final command = args.isEmpty ? 'check' : args.first;+ final root = Directory.current.absolute;+ final version = _version(root);+ _checkVersion(root, version);+ switch (command) {+ case 'check':+ stdout.writeln('release metadata OK: v$version');+ return;+ case 'export':+ if (args.length != 2) throw ArgumentError('export destination required');+ await _export(root, Directory(args[1]));+ stdout.writeln('source export OK: v$version');+ return;+ case 'manifest':+ await _manifest(args.length == 2 ? Directory(args[1]).absolute : root);+ stdout.writeln('source manifest OK: v$version');+ return;+ default:+ throw ArgumentError('unknown command');+ }+}++String _version(Directory root) {+ final text = File('${root.path}/pubspec.yaml').readAsStringSync();+ return RegExp(+ r'^version:\s*([^\s]+)',+ multiLine: true,+ ).firstMatch(text)?.group(1) ??+ (throw StateError('pubspec version missing'));+}++void _checkVersion(Directory root, String version) {+ final client = File('${root.path}/lib/src/client.dart').readAsStringSync();+ final changelog = File('${root.path}/CHANGELOG.md').readAsStringSync();+ if (!client.contains("vmodalSdkVersion = '$version'") ||+ !changelog.contains('## $version')) {+ throw StateError('version metadata mismatch');+ }+ if (!File('${root.path}/LICENSE').existsSync()) {+ throw StateError('license missing');+ }+}++Future<void> _export(Directory root, Directory destination) async {+ if (await destination.exists()) {+ await destination.delete(recursive: true);+ }+ await destination.create(recursive: true);+ const roots = <String>[+ 'pubspec.yaml',+ 'pubspec.lock',+ 'analysis_options.yaml',+ 'LICENSE',+ 'README.md',+ 'CHANGELOG.md',+ '.flutter-version',+ '.pubignore',+ 'lib',+ 'test',+ 'example',+ 'install.sh',+ 'build.sh',+ 'run.sh',+ 'test.sh',+ 'env.sh',+ 'security_check.sh',+ 'tool/flutter_checksums.txt',+ 'tool/check_route_sync.dart',+ 'tool/release_manifest.dart',+ ];+ for (final name in roots) {+ final source = FileSystemEntity.typeSync('${root.path}/$name');+ if (source == FileSystemEntityType.file) {+ final target = File('${destination.path}/$name');+ await target.parent.create(recursive: true);+ await File('${root.path}/$name').copy(target.path);+ } else if (source == FileSystemEntityType.directory) {+ await _copyDirectory(+ Directory('${root.path}/$name'),+ Directory('${destination.path}/$name'),+ );+ }+ }+ final docs = Directory('${root.path}/docs').existsSync() ? 'docs' : 'doc';+ await _copyDirectory(+ Directory('${root.path}/$docs'),+ Directory('${destination.path}/doc'),+ );+ final publish = File('${root.path}/release/public_publish.yml').existsSync()+ ? File('${root.path}/release/public_publish.yml')+ : File('${root.path}/.github/workflows/publish.yml');+ final target = File('${destination.path}/.github/workflows/publish.yml');+ await target.parent.create(recursive: true);+ await publish.copy(target.path);+ await _manifest(destination);+}++Future<void> _copyDirectory(Directory source, Directory destination) async {+ await destination.create(recursive: true);+ await for (final entity in source.list(recursive: false)) {+ final name = entity.uri.pathSegments+ .where((String value) => value.isNotEmpty)+ .last;+ if (isGeneratedName(name) ||+ const <String>{'dev_plan.md', 'dev_plan_step.md'}.contains(name)) {+ continue;+ }+ if (entity is File) {+ await entity.copy('${destination.path}/$name');+ } else if (entity is Directory) {+ await _copyDirectory(entity, Directory('${destination.path}/$name'));+ }+ }+}++Future<void> _manifest(Directory root) async {+ final rows = <String>[];+ await for (final entity in root.list(recursive: true, followLinks: false)) {+ final rel = entity.path.substring(root.path.length + 1);+ if (entity is! File ||+ entity.path.endsWith('/SOURCE_MANIFEST.sha256') ||+ entity.path.endsWith('/.gitignore')) {+ continue;+ }+ final names = rel.split(Platform.pathSeparator);+ if (entity.path.contains('/.git/') || names.any(isGeneratedName)) {+ continue;+ }+ final digest = sha256.convert(await entity.readAsBytes());+ rows.add('$digest $rel');+ }+ rows.sort();+ await File(+ '${root.path}/SOURCE_MANIFEST.sha256',+ ).writeAsString('${rows.join('\n')}\n');+}