release(desktop): Release v1.6.0 (#4970)
* docs(mobile): prepare release changelog * release(mobile): release v0.4.1 * fix(ssr): route dist-external assets (#4956) * fix(cli): close login callback sockets (#4957) * fix(ci): sync release branches to dev via pull request * fix(mobile): increase ai summary font size * fix(desktop): improve pdf export layout and branding * fix(mobile): refresh social login state * fix: correct French translation language detection * build(deps): bump android-actions/setup-android from 3 to 4 (#4929) Bumps [android-actions/setup-android](https://github.com/android-actions/setup-android) from 3 to 4. - [Release notes](https://github.com/android-actions/setup-android/releases) - [Commits](https://github.com/android-actions/setup-android/compare/v3...v4) --- updated-dependencies: - dependency-name: android-actions/setup-android dependency-version: '4' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * fix(ai-chat): show reset date for future credits * feat: refine spotlight settings and highlighting * feat: add spotlight settings across desktop and mobile * build(deps): bump actions/github-script from 8 to 9 (#4961) Bumps [actions/github-script](https://github.com/actions/github-script) from 8 to 9. - [Release notes](https://github.com/actions/github-script/releases) - [Commits](https://github.com/actions/github-script/compare/v8...v9) --- updated-dependencies: - dependency-name: actions/github-script dependency-version: '9' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * build(deps): bump signpath/github-action-submit-signing-request (#4960) Bumps [signpath/github-action-submit-signing-request](https://github.com/signpath/github-action-submit-signing-request) from 2.0 to 2.1. - [Release notes](https://github.com/signpath/github-action-submit-signing-request/releases) - [Commits](https://github.com/signpath/github-action-submit-signing-request/compare/v2.0...v2.1) --- updated-dependencies: - dependency-name: signpath/github-action-submit-signing-request dependency-version: '2.1' dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * fix(mobile): avoid YouTube embed error on iOS close #4958 * fix(mobile): patch fmt for Xcode 26.4 builds * build(deps): bump pnpm/action-setup from 4 to 5 (#4922) Bumps [pnpm/action-setup](https://github.com/pnpm/action-setup) from 4 to 5. - [Release notes](https://github.com/pnpm/action-setup/releases) - [Commits](https://github.com/pnpm/action-setup/compare/v4...v5) --- updated-dependencies: - dependency-name: pnpm/action-setup dependency-version: '5' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * feat(desktop): migrate tts to folo service * docs(ota): add OTA service design spec * feat(ota): scaffold Cloudflare worker app * fix(ota): align scaffold with task spec * fix(ota): use standard worker types * fix(ota): tighten scaffold schema and dev config * fix(ota): require at least one platform * fix(ota): use dev env for local wrangler * docs(ota): add implementation plan and release scoping * chore(ota): update lockfile for worker deps * feat(ota): add release selection primitives * test(ota): cover incompatible newer release selection * fix(ota): tighten release compatibility checks * fix(ota): reject empty platform payloads * feat(ota): add kv helpers and policy logic * fix(ota): enforce min binary store policy * feat(ota): fetch OTA releases from GitHub * fix(ota): return GitHub release etags * feat(ota): mirror release payloads into R2 * fix(ota): stream mirrored archive extraction * fix(ota): verify mirrored asset hashes * feat(ota): serve manifests assets and policy * fix(ota): harden manifest and policy routes * fix(ota): validate route semver inputs * fix(ota): verify manifest pointer version * feat(ota): add sync orchestration routes * fix(ota): dedupe concurrent sync passes * feat(mobile): enable OTA background updates * fix(mobile): restore OTA provider typecheck * feat(mobile): add streaming tts playback * fix(mobile): align OTA provider state * feat(mobile): add ota policy client and debug controls * fix(mobile): harden ota policy and debug controls * test(mobile): cover ota provider helpers * ci(desktop): automate Mac App Store pkg upload * feat(ota): generate release assets from mobile export * test(mobile): fix ota provider test typing * test(mobile): discover ota script test via explicit config * fix: tighten OTA release asset metadata handling * fix: require OTA platform asset arrays * ci(ota): publish releases and trigger sync * fix(ci): harden ota publish workflow * ci(ota): tighten trailer validation * docs(ota): add rollout and rollback runbook * feat(mobile): upgrade expo sdk 55 and rnfirebase * fix(ota): emit expo-compatible update identifiers * fix(ota): support private GitHub release assets * fix(mobile): unblock ios archive on expo sdk 55 * build(deps): bump pnpm/action-setup from 5 to 6 (#4962) Bumps [pnpm/action-setup](https://github.com/pnpm/action-setup) from 5 to 6. - [Release notes](https://github.com/pnpm/action-setup/releases) - [Commits](https://github.com/pnpm/action-setup/compare/v5...v6) --- updated-dependencies: - dependency-name: pnpm/action-setup dependency-version: '6' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * fix(ci): restore ota typing and tailwind config compatibility * test(mobile): fix ota provider test typing * chore(ota): persist production cloudflare bindings * fix(ci): restore semver types and ota test mocks * feat(release): drive mobile release mode from config files * fix(ota): sign manifests and pin runtime version * fix(ci): disable frozen lockfile for local eas builds * docs(spec): add desktop ota unification design * feat(ota): unify desktop updates with ota service * fix(ota): harden desktop sync and updater flow * docs(skill): update desktop release workflow * fix(release): repair ota and desktop update flows * feat: cache storefront versions for ota policy * feat: expose ota version badges * feat: expose ota version badges * fix: backfill github version badges * fix: backfill github version badges * docs(skills): align release modes with implementation * fix: update Discord invite link in README.md * fix: update macOS and Windows app store links in README.md * fix: update GitHub badge labels in README.md * build(deps): bump actions/download-artifact from 5 to 8 (#4969) Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 5 to 8. - [Release notes](https://github.com/actions/download-artifact/releases) - [Commits](https://github.com/actions/download-artifact/compare/v5...v8) --- updated-dependencies: - dependency-name: actions/download-artifact dependency-version: '8' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * build(deps): bump softprops/action-gh-release from 2 to 3 (#4968) Bumps [softprops/action-gh-release](https://github.com/softprops/action-gh-release) from 2 to 3. - [Release notes](https://github.com/softprops/action-gh-release/releases) - [Changelog](https://github.com/softprops/action-gh-release/blob/master/CHANGELOG.md) - [Commits](https://github.com/softprops/action-gh-release/compare/v2...v3) --- updated-dependencies: - dependency-name: softprops/action-gh-release dependency-version: '3' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * docs(release): prepare desktop and mobile release metadata * release(desktop): release v1.6.0 * fix(desktop): restore spotlight settings sync * fix(desktop): apply spotlight highlights in entry rendering * fix(desktop): extend spotlight highlight coverage --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
dependabot[bot]
parent
b469f07029
commit
bfbce383a2
@@ -1,23 +1,45 @@
|
||||
---
|
||||
name: desktop-release
|
||||
description: Perform a regular desktop release from the dev branch. Gathers commits since last release, updates changelog, evaluates mainHash changes, bumps version, and creates release PR.
|
||||
description: Perform a regular desktop release from the dev branch. Gather changes since the last desktop tag, update the changelog, choose the desktop release mode in release-plan.json, bump the version, and prepare the release PR.
|
||||
disable-model-invocation: true
|
||||
allowed-tools: Bash, Read, Write, Edit, Glob, Grep
|
||||
---
|
||||
|
||||
# Desktop Regular Release
|
||||
|
||||
Perform a regular desktop release. This skill handles the full release workflow from the `dev` branch.
|
||||
Perform a regular desktop release from the `dev` branch.
|
||||
|
||||
This workflow is now file-driven:
|
||||
|
||||
- `apps/desktop/changelog/next.md` is the human-edited changelog draft.
|
||||
- `apps/desktop/release-plan.json` is the human-edited release intent.
|
||||
- `pnpm --dir apps/desktop bump` applies both inputs, writes `apps/desktop/release.json`, resets `apps/desktop/release-plan.json`, bumps the version, creates `release/desktop/{NEW_VERSION}`, pushes it, and opens the PR.
|
||||
|
||||
Important notes:
|
||||
|
||||
- `mainHash` is still regenerated automatically, but it is **not** the OTA compatibility switch anymore. Do not use it as the release decision point.
|
||||
- `runtimeVersion` in `apps/desktop/package.json` is the desktop OTA compatibility key. `apps/desktop/scripts/apply-release-config.impl.ts` writes it during bump.
|
||||
- This skill covers the normal `build` and `ota` desktop release flow.
|
||||
- Do not recommend or write any other mode. The current implementation only supports `build` and `ota`.
|
||||
|
||||
## Pre-flight checks
|
||||
|
||||
1. Confirm the current branch is `dev`. If not, abort with a warning.
|
||||
2. Run `git pull --rebase` in the repo root to ensure the local branch is up to date.
|
||||
3. Read `apps/desktop/package.json` to get the current `version` and `mainHash`.
|
||||
3. Read:
|
||||
- `apps/desktop/package.json`
|
||||
- `apps/desktop/release-plan.json`
|
||||
- `apps/desktop/release.json`
|
||||
- `apps/desktop/bump.config.ts`
|
||||
4. Record the current:
|
||||
- `version`
|
||||
- `runtimeVersion`
|
||||
- `release-plan.json` contents
|
||||
5. Note that `pnpm --dir apps/desktop bump` will push a branch and open a PR. Do not run it without explicit user approval.
|
||||
|
||||
## Step 1: Gather changes since last release
|
||||
## Step 1: Gather changes since last desktop release
|
||||
|
||||
1. Find the last release tag:
|
||||
1. Find the last desktop release tag:
|
||||
```bash
|
||||
git tag --sort=-creatordate | grep '^desktop/v' | head -1
|
||||
```
|
||||
@@ -26,138 +48,170 @@ Perform a regular desktop release. This skill handles the full release workflow
|
||||
git log <last-tag>..HEAD --oneline --no-merges
|
||||
```
|
||||
3. Categorize commits into:
|
||||
- **Shiny new things** (feat: commits, new features)
|
||||
- **Improvements** (refactor:, perf:, chore: improvements, dependency updates)
|
||||
- **No longer broken** (fix: commits, bug fixes)
|
||||
- **Thanks** (identify external contributor GitHub usernames from commits)
|
||||
- **Shiny new things**
|
||||
- **Improvements**
|
||||
- **No longer broken**
|
||||
- **Thanks**
|
||||
|
||||
## Step 2: Update changelog
|
||||
## Step 2: Update changelog draft
|
||||
|
||||
1. Read `apps/desktop/changelog/next.md`.
|
||||
2. Present the categorized changes to the user and draft the changelog content.
|
||||
3. Wait for user confirmation or edits before writing.
|
||||
4. Write the final content to `apps/desktop/changelog/next.md`, following the template format:
|
||||
2. Draft the changelog content from the categorized commits.
|
||||
3. Present the draft to the user.
|
||||
4. Wait for user confirmation or edits before writing.
|
||||
5. Write the final content to `apps/desktop/changelog/next.md` using the existing template structure.
|
||||
6. Keep `NEXT_VERSION` as the placeholder. `apps/desktop/scripts/apply-changelog.ts` replaces it during bump.
|
||||
|
||||
```markdown
|
||||
# What's new in vNEXT_VERSION
|
||||
## Step 3: Choose the desktop release mode
|
||||
|
||||
## Shiny new things
|
||||
This replaces the old `mainHash` decision.
|
||||
|
||||
- description of new feature
|
||||
Inspect runtime-affecting changes since the last desktop tag:
|
||||
|
||||
## Improvements
|
||||
```bash
|
||||
git diff <last-tag>..HEAD --name-only -- \
|
||||
apps/desktop/layer/main/ \
|
||||
apps/desktop/layer/preload/ \
|
||||
apps/desktop/forge.config.cts \
|
||||
apps/desktop/resources/ \
|
||||
apps/desktop/scripts/ \
|
||||
apps/desktop/package.json
|
||||
```
|
||||
|
||||
- description of improvement
|
||||
Use this decision table:
|
||||
|
||||
## No longer broken
|
||||
- `build`
|
||||
Use this when the release requires a new binary.
|
||||
Typical triggers:
|
||||
- main process changes
|
||||
- preload or IPC changes
|
||||
- updater flow changes
|
||||
- Electron / Forge / packaging / signing changes
|
||||
- native resource changes
|
||||
- dependency or package changes that affect runtime behavior
|
||||
|
||||
- description of fix
|
||||
- `ota`
|
||||
Use this when the release is renderer-compatible with an already-installed binary.
|
||||
Typical triggers:
|
||||
- renderer UI changes
|
||||
- web behavior changes
|
||||
- shared frontend logic changes that do not require a new desktop binary
|
||||
|
||||
## Thanks
|
||||
For `ota`, you must choose:
|
||||
- `runtimeVersion`: the newest installed desktop binary version that this renderer update is compatible with
|
||||
- `channel`: usually `stable`
|
||||
|
||||
Special thanks to volunteer contributors @username for their valuable contributions
|
||||
```
|
||||
If you are unsure whether a change is binary-compatible, prefer `build`.
|
||||
|
||||
5. Keep `NEXT_VERSION` as the placeholder - it will be replaced by `apply-changelog.ts` during bump.
|
||||
Present the analysis to the user with:
|
||||
|
||||
## Step 3: Commit changelog updates before bump
|
||||
- changed runtime-affecting files
|
||||
- summary of what changed
|
||||
- recommended mode: `build` or `ota`
|
||||
- recommended `release-plan.json`
|
||||
- explicit request for confirmation
|
||||
|
||||
`nbump` requires a clean working tree. Commit changelog edits before running bump.
|
||||
## Step 4: Update release inputs
|
||||
|
||||
1. Stage the changelog update:
|
||||
```bash
|
||||
git add apps/desktop/changelog/next.md
|
||||
```
|
||||
2. Commit it on `dev`:
|
||||
```bash
|
||||
git commit -m "docs(desktop): prepare release changelog"
|
||||
```
|
||||
3. If there are no changes to commit, continue without creating an extra commit.
|
||||
1. Edit `apps/desktop/changelog/next.md`.
|
||||
2. Edit `apps/desktop/release-plan.json`.
|
||||
3. Do **not** edit `apps/desktop/release.json` directly. It is generated during bump.
|
||||
4. Because `nbump` requires a clean working tree, commit the release inputs before bump.
|
||||
|
||||
## Step 4: Evaluate mainHash
|
||||
Stage the inputs:
|
||||
|
||||
This is critical for determining whether users need a full app update or can use the lightweight renderer hot update.
|
||||
```bash
|
||||
git add apps/desktop/changelog/next.md apps/desktop/release-plan.json
|
||||
```
|
||||
|
||||
1. Check what files changed in `apps/desktop/layer/main/` since the last release tag:
|
||||
```bash
|
||||
git diff <last-tag>..HEAD --name-only -- apps/desktop/layer/main/
|
||||
```
|
||||
2. Also check changes to `apps/desktop/package.json` fields other than version/mainHash (since package.json is included in the hash calculation):
|
||||
```bash
|
||||
git diff <last-tag>..HEAD -- apps/desktop/package.json
|
||||
```
|
||||
Commit them on `dev`:
|
||||
|
||||
**Decision logic:**
|
||||
```bash
|
||||
git commit -m "docs(desktop): prepare release inputs"
|
||||
```
|
||||
|
||||
- If there are **NO changes** in `layer/main/` and no meaningful `package.json` changes (only version/mainHash/changelog-related), then mainHash should NOT be updated. Users will get a fast renderer-only hot update.
|
||||
- If there are **trivial changes** in `layer/main/` (typo fixes, comment changes, logging tweaks) that don't affect runtime behavior, recommend NOT updating mainHash. Present the changes to the user and ask for confirmation.
|
||||
- If there are **meaningful changes** in `layer/main/` (new features, bug fixes, dependency changes, API changes), mainHash MUST be updated. Users will need a full app update.
|
||||
If there are no changes to commit, continue.
|
||||
|
||||
Present your analysis to the user with:
|
||||
## Step 5: Run the bump
|
||||
|
||||
- List of changed files in `layer/main/`
|
||||
- A summary of what changed
|
||||
- Your recommendation (update or skip mainHash)
|
||||
- Ask for explicit confirmation
|
||||
Do not execute this step until the user explicitly approves pushing code.
|
||||
|
||||
## Step 5: Save old mainHash and execute bump
|
||||
Run:
|
||||
|
||||
1. Save the current mainHash from `apps/desktop/package.json` for later comparison.
|
||||
2. Verify working tree is clean before bump:
|
||||
```bash
|
||||
git status --short
|
||||
```
|
||||
3. Change directory to `apps/desktop/` and run the bump:
|
||||
```bash
|
||||
cd apps/desktop && pnpm bump
|
||||
```
|
||||
4. This command will:
|
||||
- Pull latest changes
|
||||
- Apply changelog (rename next.md to {version}.md, create new next.md)
|
||||
- Recalculate mainHash and write to package.json
|
||||
- Format package.json
|
||||
- Bump minor version
|
||||
- Commit with message `release(desktop): release v{NEW_VERSION}`
|
||||
- Create branch `release/desktop/{NEW_VERSION}`
|
||||
- Push branch and create PR to `main`
|
||||
```bash
|
||||
pnpm --dir apps/desktop bump
|
||||
```
|
||||
|
||||
## Step 6: Restore mainHash if skipping update
|
||||
This command currently does all of the following:
|
||||
|
||||
If Step 4 decided mainHash should NOT be updated, restore the old value now. The bump has already committed, pushed, and created the PR on a new release branch, so we amend the commit and force push. This is safe because the release branch was just created.
|
||||
- pulls latest changes
|
||||
- applies the changelog
|
||||
- regenerates `mainHash`
|
||||
- runs `apps/desktop/scripts/apply-release-config.ts ${NEW_VERSION}`
|
||||
- writes `apps/desktop/release.json`
|
||||
- updates `apps/desktop/package.json` `runtimeVersion`
|
||||
- resets `apps/desktop/release-plan.json` back to the default `build` template
|
||||
- commits `release(desktop): release v{NEW_VERSION}`
|
||||
- creates `release/desktop/{NEW_VERSION}`
|
||||
- pushes the branch
|
||||
- creates a PR to `main`
|
||||
|
||||
1. Change back to the repo root first (Step 5 left the working directory at `apps/desktop/`):
|
||||
```bash
|
||||
cd ../..
|
||||
```
|
||||
2. Ensure you are on the `release/desktop/{NEW_VERSION}` branch (bump should have switched to it).
|
||||
3. Replace the recalculated mainHash with the saved old value in `apps/desktop/package.json`.
|
||||
4. Stage and amend the release commit:
|
||||
```bash
|
||||
git add apps/desktop/package.json && git commit --amend --no-edit
|
||||
```
|
||||
5. Force push the release branch:
|
||||
```bash
|
||||
git push --force origin release/desktop/{NEW_VERSION}
|
||||
```
|
||||
## Step 6: Verify the generated release state
|
||||
|
||||
If Step 4 decided mainHash SHOULD be updated, skip this step entirely — the bump already wrote the correct new value.
|
||||
After bump completes, verify:
|
||||
|
||||
## Step 7: Verify
|
||||
1. Current branch is `release/desktop/{NEW_VERSION}`.
|
||||
2. `apps/desktop/package.json` has the expected:
|
||||
- `version`
|
||||
- `runtimeVersion`
|
||||
3. `apps/desktop/release.json` matches the intended mode and release settings.
|
||||
4. `apps/desktop/release-plan.json` was reset to the default template.
|
||||
5. The PR was created successfully.
|
||||
|
||||
1. Confirm the PR was created successfully by checking the output.
|
||||
2. Report the new version number and PR URL to the user.
|
||||
3. Summarize:
|
||||
- New version: v{NEW_VERSION}
|
||||
- mainHash updated: yes/no (and why)
|
||||
- Changelog highlights
|
||||
- PR URL
|
||||
Also note what will happen after merge:
|
||||
|
||||
- merging the PR to `main` triggers `.github/workflows/tag.yml`
|
||||
- `tag.yml` creates `desktop/v{NEW_VERSION}`
|
||||
- `tag.yml` dispatches `.github/workflows/build-desktop.yml`
|
||||
- `build-desktop.yml` publishes the desktop release draft
|
||||
|
||||
Expected release artifacts by mode:
|
||||
|
||||
- `build`
|
||||
publishes binary artifacts and desktop binary metadata (`ota-release.json`)
|
||||
|
||||
- `ota`
|
||||
publishes binary artifacts, desktop binary metadata, and renderer OTA assets such as:
|
||||
- `apps/desktop/dist/manifest.yml`
|
||||
- `apps/desktop/dist/*.tar.gz`
|
||||
- `apps/desktop/dist/ota-release.json`
|
||||
- `apps/desktop/dist.tar.zst`
|
||||
|
||||
## Step 7: Report back to the user
|
||||
|
||||
Summarize:
|
||||
|
||||
- new version: `v{NEW_VERSION}`
|
||||
- release mode: `build` or `ota`
|
||||
- `runtimeVersion`
|
||||
- renderer OTA included: yes or no
|
||||
- release branch
|
||||
- PR URL
|
||||
- short changelog highlights
|
||||
|
||||
When mentioning `mainHash`, only describe it as "regenerated automatically", never as the release decision mechanism.
|
||||
|
||||
## Reference
|
||||
|
||||
- Bump config: `apps/desktop/bump.config.ts`
|
||||
- Changelog dir: `apps/desktop/changelog/`
|
||||
- Changelog template: `apps/desktop/changelog/next.template.md`
|
||||
- mainHash generator: `apps/desktop/plugins/vite/generate-main-hash.ts`
|
||||
- Hot updater logic: `apps/desktop/layer/main/src/updater/hot-updater.ts`
|
||||
- CI build workflow: `.github/workflows/build-desktop.yml`
|
||||
- Tag workflow: `.github/workflows/tag.yml`
|
||||
- Changelog apply script: `apps/desktop/scripts/apply-changelog.ts`
|
||||
- Release plan input: `apps/desktop/release-plan.json`
|
||||
- Generated release config: `apps/desktop/release.json`
|
||||
- Release config apply script: `apps/desktop/scripts/apply-release-config.impl.ts`
|
||||
- Desktop release config resolver: `.github/scripts/resolve-desktop-release-config.mjs`
|
||||
- Desktop OTA metadata builder: `.github/scripts/build-ota-release.mjs`
|
||||
- Desktop build workflow: `.github/workflows/build-desktop.yml`
|
||||
- Tag orchestrator: `.github/workflows/tag.yml`
|
||||
- Desktop hot updater: `apps/desktop/layer/main/src/updater/hot-updater.ts`
|
||||
|
||||
@@ -1,132 +1,205 @@
|
||||
---
|
||||
name: mobile-release
|
||||
description: Perform a regular mobile release from the dev branch. Gathers commits since last release, updates changelog, bumps version, updates iOS Info.plist, and creates release PR to mobile-main.
|
||||
description: Use when preparing a mobile release from the dev branch and deciding whether changes should ship through the app stores or through the OTA pipeline before creating the release PR to mobile-main.
|
||||
disable-model-invocation: true
|
||||
allowed-tools: Bash, Read, Write, Edit, Glob, Grep
|
||||
---
|
||||
|
||||
# Mobile Regular Release
|
||||
# Mobile Release
|
||||
|
||||
Perform a regular mobile release. This skill handles the full release workflow from the `dev` branch.
|
||||
Perform a mobile release from `dev`, with an explicit release-mode decision before the bump.
|
||||
|
||||
The skill must recommend one of these modes, explain why, ask the user to confirm, and then write `apps/mobile/release-plan.json` before running the bump:
|
||||
|
||||
- `store`: normal App Store / Google Play release
|
||||
- `ota`: OTA-only publish, no store builds
|
||||
|
||||
Do not recommend or write any other mode. The current implementation only supports `store` and `ota`.
|
||||
|
||||
The CI release flow is file-driven:
|
||||
|
||||
- `apps/mobile/release-plan.json` is the editable plan on `dev`
|
||||
- `pnpm bump` runs `apps/mobile/scripts/apply-release-config.ts`
|
||||
- that script writes `apps/mobile/release.json` for the new version and resets the plan back to a safe default
|
||||
- GitHub Actions reads `apps/mobile/release.json` after merge to decide which pipelines to trigger
|
||||
|
||||
## Pre-flight checks
|
||||
|
||||
1. Confirm the current branch is `dev`. If not, abort with a warning.
|
||||
2. Run `git pull --rebase` in the repo root to ensure the local branch is up to date.
|
||||
3. Read `apps/mobile/package.json` to get the current `version`.
|
||||
2. Run `git pull --rebase` in the repo root.
|
||||
3. Read:
|
||||
- `apps/mobile/package.json`
|
||||
- `apps/mobile/release-plan.json`
|
||||
- `.github/workflows/tag.yml`
|
||||
- `.github/workflows/publish-ota.yml`
|
||||
|
||||
## Step 1: Gather changes since last release
|
||||
|
||||
1. Find the last release tag (both old `mobile@` and new `mobile/v` prefixes exist):
|
||||
1. Find the last mobile tag:
|
||||
```bash
|
||||
git tag --sort=-creatordate | grep -E '^mobile[@/]' | head -1
|
||||
```
|
||||
2. If no tag found, find the last release commit by matching only the subject line:
|
||||
2. If no tag exists, fall back to the last release commit subject:
|
||||
```bash
|
||||
git log --format="%H %s" | grep "^[a-f0-9]* release(mobile): release v" | head -1 | awk '{print $1}'
|
||||
git log --format="%H %s" | grep -Ei "^[a-f0-9]* release\\(mobile\\): release v" | head -1 | awk '{print $1}'
|
||||
```
|
||||
3. Get all commits since the last release on the current branch:
|
||||
3. Collect commits since that point:
|
||||
```bash
|
||||
git log <last-tag-or-commit>..HEAD --oneline --no-merges
|
||||
```
|
||||
4. Categorize commits into:
|
||||
- **Shiny new things** (feat: commits, new features)
|
||||
- **Improvements** (refactor:, perf:, chore: improvements, dependency updates)
|
||||
- **No longer broken** (fix: commits, bug fixes)
|
||||
- **Thanks** (identify external contributor GitHub usernames from commits)
|
||||
4. Collect changed files:
|
||||
```bash
|
||||
git diff --name-only <last-tag-or-commit>..HEAD
|
||||
```
|
||||
5. Categorize commits into:
|
||||
- `Shiny new things`
|
||||
- `Improvements`
|
||||
- `No longer broken`
|
||||
- `Thanks`
|
||||
|
||||
## Step 2: Update changelog
|
||||
## Step 2: Recommend a release mode
|
||||
|
||||
### Recommend `store` when:
|
||||
|
||||
- any native or binary-affecting paths changed, for example:
|
||||
- `apps/mobile/ios/**`
|
||||
- `apps/mobile/android/**`
|
||||
- `apps/mobile/native/**`
|
||||
- `apps/mobile/package.json`
|
||||
- `apps/mobile/app.config.ts`
|
||||
- `apps/mobile/app.config.base.ts`
|
||||
- `apps/mobile/eas.json`
|
||||
- `apps/mobile/ios/Folo/Info.plist`
|
||||
- `.github/workflows/build-ios.yml`
|
||||
- `.github/workflows/build-android.yml`
|
||||
- Expo / React Native / native dependency changes require a new binary
|
||||
- permissions, entitlements, icons, splash, Firebase config, or build configuration changed
|
||||
|
||||
### Recommend `ota` when:
|
||||
|
||||
- changes are limited to JS/TS/assets that the current binary can already run
|
||||
- no native or runtime-affecting paths changed
|
||||
- the goal is to ship without store review
|
||||
|
||||
### Determine the target runtime
|
||||
|
||||
If recommending `ota`, derive the target store binary version from recent `origin/mobile-main` releases and propose it as the `runtimeVersion`.
|
||||
|
||||
If you cannot determine the runtime confidently, stop and ask the user to confirm it.
|
||||
|
||||
### Confirmation gate
|
||||
|
||||
Present:
|
||||
|
||||
- the recommended mode
|
||||
- rationale based on changed files and commits
|
||||
- for `ota`, the proposed `runtimeVersion`
|
||||
- for `ota`, the proposed `channel`
|
||||
|
||||
Wait for explicit user confirmation before continuing.
|
||||
|
||||
## Step 3: Write the release plan file
|
||||
|
||||
Update `apps/mobile/release-plan.json` to match the confirmed mode.
|
||||
|
||||
Examples:
|
||||
|
||||
### Store release
|
||||
|
||||
```json
|
||||
{
|
||||
"mode": "store",
|
||||
"runtimeVersion": null,
|
||||
"channel": null
|
||||
}
|
||||
```
|
||||
|
||||
### OTA release
|
||||
|
||||
```json
|
||||
{
|
||||
"mode": "ota",
|
||||
"runtimeVersion": "0.4.1",
|
||||
"channel": "production"
|
||||
}
|
||||
```
|
||||
|
||||
## Step 4: Update changelog
|
||||
|
||||
1. Read `apps/mobile/changelog/next.md`.
|
||||
2. Present the categorized changes to the user and draft the changelog content.
|
||||
2. Present the categorized changes and draft changelog content.
|
||||
3. Wait for user confirmation or edits before writing.
|
||||
4. Write the final content to `apps/mobile/changelog/next.md`, following the template format:
|
||||
4. Write the final content to `apps/mobile/changelog/next.md`.
|
||||
|
||||
```markdown
|
||||
# What's New in vNEXT_VERSION
|
||||
## Step 5: Commit pre-bump files before bump
|
||||
|
||||
## Shiny new things
|
||||
`nbump` requires a clean working tree.
|
||||
|
||||
- description of new feature
|
||||
|
||||
## Improvements
|
||||
|
||||
- description of improvement
|
||||
|
||||
## No longer broken
|
||||
|
||||
- description of fix
|
||||
|
||||
## Thanks
|
||||
|
||||
Special thanks to volunteer contributors @username for their valuable contributions
|
||||
```
|
||||
|
||||
5. Keep `NEXT_VERSION` as the placeholder - it will be replaced by `apply-changelog.ts` during bump.
|
||||
|
||||
## Step 3: Commit changelog updates before bump
|
||||
|
||||
`nbump` requires a clean working tree. Commit changelog edits before running bump.
|
||||
|
||||
1. Stage the changelog update:
|
||||
1. Stage:
|
||||
```bash
|
||||
git add apps/mobile/changelog/next.md
|
||||
git add apps/mobile/changelog/next.md apps/mobile/release-plan.json
|
||||
```
|
||||
2. Commit it on `dev`:
|
||||
2. Commit:
|
||||
```bash
|
||||
git commit -m "docs(mobile): prepare release changelog"
|
||||
git commit -m "docs(mobile): prepare release metadata"
|
||||
```
|
||||
3. If there are no changes to commit, continue without creating an extra commit.
|
||||
3. If nothing changed, continue.
|
||||
|
||||
## Step 4: Execute bump
|
||||
## Step 6: Execute bump
|
||||
|
||||
1. Verify working tree is clean before bump:
|
||||
1. Verify the working tree is clean:
|
||||
```bash
|
||||
git status --short
|
||||
```
|
||||
2. Change directory to `apps/mobile/` and run the bump:
|
||||
2. Run:
|
||||
```bash
|
||||
cd apps/mobile && pnpm bump
|
||||
```
|
||||
3. This is an interactive `nbump` command that prompts for version selection. It will:
|
||||
- Pull latest changes
|
||||
- Apply changelog (rename next.md to {version}.md, create new next.md from template)
|
||||
- Format package.json with eslint + prettier
|
||||
- Bump version in `package.json`
|
||||
- Update `ios/Folo/Info.plist`:
|
||||
- Set `CFBundleShortVersionString` to the new version
|
||||
- Increment `CFBundleVersion` (build number) by 1
|
||||
- Commit with message `release(mobile): release v{NEW_VERSION}`
|
||||
- Create branch `release/mobile/{NEW_VERSION}`
|
||||
- Push branch and create PR to `mobile-main`
|
||||
3. `pnpm bump` will:
|
||||
- apply changelog
|
||||
- bump `package.json`
|
||||
- update `ios/Folo/Info.plist`
|
||||
- run `tsx scripts/apply-release-config.ts ${NEW_VERSION}`
|
||||
- write `apps/mobile/release.json`
|
||||
- reset `apps/mobile/release-plan.json` back to the safe default `store`
|
||||
- create the release branch
|
||||
- push the branch
|
||||
- open a PR to `mobile-main`
|
||||
|
||||
## Step 5: Verify
|
||||
## Step 7: Verify and report
|
||||
|
||||
1. Confirm the PR was created successfully by checking the output.
|
||||
2. Report the new version number and PR URL to the user.
|
||||
3. Summarize:
|
||||
- New version: v{NEW_VERSION}
|
||||
- Changelog highlights
|
||||
1. Confirm the PR was created successfully.
|
||||
2. Read `apps/mobile/release.json` on the release branch and report:
|
||||
- new version
|
||||
- final release mode
|
||||
- runtimeVersion and channel if present
|
||||
- PR URL
|
||||
3. Summarize expected post-merge automation:
|
||||
|
||||
## Post-release (manual steps, inform user)
|
||||
### `mode=store`
|
||||
|
||||
After the release PR is merged to `mobile-main`:
|
||||
- create mobile tag
|
||||
- trigger preview Android build
|
||||
- trigger production Android build
|
||||
- trigger production iOS build
|
||||
- no OTA publish
|
||||
|
||||
1. **Trigger production builds** via GitHub Actions `workflow_dispatch`:
|
||||
- Go to "Build iOS" workflow, select `mobile-main` branch, profile = `production`
|
||||
- Go to "Build Android" workflow, select `mobile-main` branch, profile = `production`
|
||||
2. Production builds auto-submit to App Store (via `eas submit`) and Google Play (as draft).
|
||||
3. After submission, go to App Store Connect and Google Play Console to complete the review/release process.
|
||||
### `mode=ota`
|
||||
|
||||
## Reference
|
||||
- create mobile tag
|
||||
- trigger OTA publish only
|
||||
- no store builds
|
||||
|
||||
## References
|
||||
|
||||
- Bump config: `apps/mobile/bump.config.ts`
|
||||
- Release plan: `apps/mobile/release-plan.json`
|
||||
- Release config: `apps/mobile/release.json`
|
||||
- Apply release config script: `apps/mobile/scripts/apply-release-config.ts`
|
||||
- Changelog dir: `apps/mobile/changelog/`
|
||||
- Changelog template: `apps/mobile/changelog/next.template.md`
|
||||
- Apply changelog script: `apps/mobile/scripts/apply-changelog.ts`
|
||||
- EAS config: `apps/mobile/eas.json`
|
||||
- Release config resolver: `.github/scripts/resolve-mobile-release-config.mjs`
|
||||
- Tag orchestration: `.github/workflows/tag.yml`
|
||||
- OTA publish workflow: `.github/workflows/publish-ota.yml`
|
||||
- App config: `apps/mobile/app.config.ts`
|
||||
- iOS Info.plist: `apps/mobile/ios/Folo/Info.plist`
|
||||
- CI build iOS: `.github/workflows/build-ios.yml`
|
||||
- CI build Android: `.github/workflows/build-android.yml`
|
||||
|
||||
@@ -0,0 +1,925 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { spawn, spawnSync } from "node:child_process"
|
||||
import { createHash } from "node:crypto"
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises"
|
||||
import { fileURLToPath } from "node:url"
|
||||
|
||||
import yaml from "js-yaml"
|
||||
import { dirname, extname, join, resolve } from "pathe"
|
||||
|
||||
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url))
|
||||
const REPO_ROOT = resolve(SCRIPT_DIR, "..", "..")
|
||||
const DEFAULT_MOBILE_PROJECT_DIR = join(REPO_ROOT, "apps", "mobile")
|
||||
const DEFAULT_DESKTOP_PROJECT_DIR = join(REPO_ROOT, "apps", "desktop")
|
||||
const OTA_PLATFORMS = ["ios", "android"]
|
||||
const DESKTOP_PLATFORMS = new Set(["macos", "windows", "linux"])
|
||||
const DESKTOP_DEFAULT_CHANNEL = "stable"
|
||||
const CONTENT_TYPES = new Map([
|
||||
[".aac", "audio/aac"],
|
||||
[".bmp", "image/bmp"],
|
||||
[".bundle", "application/javascript"],
|
||||
[".css", "text/css"],
|
||||
[".gif", "image/gif"],
|
||||
[".gz", "application/gzip"],
|
||||
[".hbc", "application/javascript"],
|
||||
[".html", "text/html"],
|
||||
[".jpeg", "image/jpeg"],
|
||||
[".jpg", "image/jpeg"],
|
||||
[".js", "application/javascript"],
|
||||
[".json", "application/json"],
|
||||
[".m4a", "audio/mp4"],
|
||||
[".mp3", "audio/mpeg"],
|
||||
[".mp4", "video/mp4"],
|
||||
[".otf", "font/otf"],
|
||||
[".pdf", "application/pdf"],
|
||||
[".png", "image/png"],
|
||||
[".svg", "image/svg+xml"],
|
||||
[".ttf", "font/ttf"],
|
||||
[".txt", "text/plain; charset=utf-8"],
|
||||
[".wav", "audio/wav"],
|
||||
[".webm", "video/webm"],
|
||||
[".webp", "image/webp"],
|
||||
[".woff", "font/woff"],
|
||||
[".woff2", "font/woff2"],
|
||||
[".xml", "application/xml"],
|
||||
])
|
||||
const DESKTOP_MANIFEST_FILE_NAMES = new Set(["latest.yml", "latest-mac.yml", "latest-linux.yml"])
|
||||
|
||||
/**
|
||||
* @typedef {{
|
||||
* path: string
|
||||
* ext?: string
|
||||
* }} ExportAssetMetadata
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {{
|
||||
* path: string
|
||||
* sha256: string
|
||||
* contentType: string
|
||||
* }} OtaAsset
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {{
|
||||
* bundle: string
|
||||
* assets?: unknown[]
|
||||
* }} ExportPlatformMetadata
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {{
|
||||
* fileMetadata?: Partial<Record<"ios" | "android", ExportPlatformMetadata>>
|
||||
* }} ExportMetadata
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {{
|
||||
* product: string
|
||||
* channel: string
|
||||
* releaseVersion: string
|
||||
* releaseKind: string
|
||||
* runtimeVersion: string
|
||||
* gitTag: string
|
||||
* gitCommit: string
|
||||
* publishedAt: string
|
||||
* policy: {
|
||||
* storeRequired: boolean
|
||||
* minSupportedBinaryVersion: string
|
||||
* message: string | null
|
||||
* }
|
||||
* metadata: ExportMetadata
|
||||
* resolveAsset: (asset: ExportAssetMetadata) => Promise<OtaAsset>
|
||||
* }} BuildOtaMetadataInput
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {BuildOtaMetadataInput} input
|
||||
*/
|
||||
export async function buildOtaMetadata(input) {
|
||||
/** @type {Record<string, { launchAsset: OtaAsset, assets: OtaAsset[] }>} */
|
||||
const platforms = {}
|
||||
|
||||
if (input.releaseKind === "ota") {
|
||||
const fileMetadata = resolveExportFileMetadata(input.metadata)
|
||||
|
||||
for (const platform of OTA_PLATFORMS) {
|
||||
const platformMetadata = resolvePlatformMetadata(fileMetadata, platform)
|
||||
const launchAsset = { path: normalizeAssetPath(platformMetadata.bundle) }
|
||||
const assets = collectAssets(platformMetadata.assets, platform)
|
||||
|
||||
platforms[platform] = {
|
||||
launchAsset: await input.resolveAsset(launchAsset),
|
||||
assets: await Promise.all(assets.map((asset) => input.resolveAsset(asset))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
updateId: createDeterministicUuid(
|
||||
`${input.product}:${input.channel}:${input.releaseVersion}:${input.runtimeVersion}:${input.gitTag}:${input.gitCommit}`,
|
||||
),
|
||||
product: input.product,
|
||||
channel: input.channel,
|
||||
releaseVersion: input.releaseVersion,
|
||||
releaseKind: input.releaseKind,
|
||||
runtimeVersion: input.runtimeVersion,
|
||||
publishedAt: input.publishedAt,
|
||||
git: {
|
||||
tag: input.gitTag,
|
||||
commit: input.gitCommit,
|
||||
},
|
||||
policy: input.policy,
|
||||
platforms,
|
||||
}
|
||||
}
|
||||
|
||||
function createDeterministicUuid(seed) {
|
||||
const digest = createHash("sha1").update(seed).digest()
|
||||
const bytes = Buffer.from(digest.subarray(0, 16))
|
||||
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x50
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80
|
||||
|
||||
const hex = bytes.toString("hex")
|
||||
return [
|
||||
hex.slice(0, 8),
|
||||
hex.slice(8, 12),
|
||||
hex.slice(12, 16),
|
||||
hex.slice(16, 20),
|
||||
hex.slice(20, 32),
|
||||
].join("-")
|
||||
}
|
||||
|
||||
export async function buildReleaseAssets(options = {}) {
|
||||
const projectDir = resolveMobileProjectDir(options.projectDir)
|
||||
const distDir = join(projectDir, "dist")
|
||||
const metadataPath = join(distDir, "metadata.json")
|
||||
const archivePath = join(projectDir, "dist.tar.zst")
|
||||
|
||||
const packageJson = await readJson(join(projectDir, "package.json"))
|
||||
const product = process.env.OTA_PRODUCT ?? "mobile"
|
||||
const channel = process.env.OTA_CHANNEL ?? "production"
|
||||
const releaseVersion = process.env.OTA_RELEASE_VERSION ?? packageJson.version
|
||||
const releaseKind = process.env.OTA_RELEASE_KIND ?? "ota"
|
||||
const runtimeVersion = process.env.OTA_RUNTIME_VERSION ?? packageJson.version
|
||||
const gitTag = process.env.OTA_GIT_TAG ?? `${product}/v${releaseVersion}`
|
||||
const gitCommit = process.env.OTA_GIT_COMMIT ?? execGit(["rev-parse", "HEAD"], REPO_ROOT)
|
||||
const publishedAt = process.env.OTA_PUBLISHED_AT ?? new Date().toISOString()
|
||||
|
||||
if (releaseKind === "ota" && !existsSync(metadataPath)) {
|
||||
throw new Error(
|
||||
`Missing Expo export metadata at ${metadataPath}. Run "pnpm --dir apps/mobile run update:export" first.`,
|
||||
)
|
||||
}
|
||||
|
||||
const metadata = releaseKind === "ota" ? await readJson(metadataPath) : { fileMetadata: {} }
|
||||
|
||||
const otaMetadata = await buildOtaMetadata({
|
||||
product,
|
||||
channel,
|
||||
releaseVersion,
|
||||
releaseKind,
|
||||
runtimeVersion,
|
||||
gitTag,
|
||||
gitCommit,
|
||||
publishedAt,
|
||||
policy: {
|
||||
storeRequired: parseBooleanEnv("OTA_STORE_REQUIRED", false),
|
||||
minSupportedBinaryVersion: process.env.OTA_MIN_SUPPORTED_BINARY_VERSION ?? runtimeVersion,
|
||||
message: parseNullableEnv("OTA_POLICY_MESSAGE"),
|
||||
},
|
||||
metadata,
|
||||
resolveAsset: async (asset) => {
|
||||
const assetFilePath = join(distDir, asset.path)
|
||||
let assetBuffer
|
||||
|
||||
try {
|
||||
assetBuffer = await readFile(assetFilePath)
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error)
|
||||
throw new Error(
|
||||
`Failed to read exported asset "${asset.path}" at ${assetFilePath}: ${reason}`,
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
path: asset.path,
|
||||
sha256: createHash("sha256").update(assetBuffer).digest("hex"),
|
||||
contentType: resolveContentType(asset),
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
const outputPath = join(distDir, "ota-release.json")
|
||||
|
||||
await mkdir(distDir, { recursive: true })
|
||||
await writeFile(outputPath, `${JSON.stringify(otaMetadata, null, 2)}\n`, "utf8")
|
||||
|
||||
if (releaseKind === "ota") {
|
||||
await createTarZstArchive({ distDir, archivePath })
|
||||
}
|
||||
|
||||
return {
|
||||
projectDir,
|
||||
distDir,
|
||||
metadataPath,
|
||||
outputPath,
|
||||
archivePath: releaseKind === "ota" ? archivePath : null,
|
||||
otaMetadata,
|
||||
}
|
||||
}
|
||||
|
||||
export async function buildDesktopReleaseAssets(options = {}) {
|
||||
const projectDir = resolveDesktopProjectDir(options.projectDir)
|
||||
const distDir = join(projectDir, "dist")
|
||||
const outputPath = join(distDir, "ota-release.json")
|
||||
const archivePath = join(projectDir, "dist.tar.zst")
|
||||
const releaseConfig = await readJson(join(projectDir, "release.json"))
|
||||
const packageJson = await readJson(join(projectDir, "package.json"))
|
||||
const releaseVersion = releaseConfig.version ?? packageJson.version
|
||||
const product = process.env.OTA_PRODUCT ?? "desktop"
|
||||
const gitTag = process.env.OTA_GIT_TAG ?? `${product}/v${releaseVersion}`
|
||||
const gitCommit = process.env.OTA_GIT_COMMIT ?? execGit(["rev-parse", "HEAD"], REPO_ROOT)
|
||||
const publishedAt = process.env.OTA_PUBLISHED_AT ?? new Date().toISOString()
|
||||
const [owner, repo] = resolveRepository(options)
|
||||
const releaseKind = releaseConfig.mode === "ota" ? "ota" : "binary"
|
||||
const runtimeVersion = releaseConfig.mode === "ota" ? releaseConfig.runtimeVersion : null
|
||||
const channel = releaseConfig.channel ?? DESKTOP_DEFAULT_CHANNEL
|
||||
const desktopApp = await collectDesktopAppPayload({
|
||||
projectDir,
|
||||
owner,
|
||||
repo,
|
||||
gitTag,
|
||||
})
|
||||
|
||||
if (!desktopApp) {
|
||||
throw new Error(
|
||||
`Desktop ${releaseConfig.mode} mode requires direct installer manifests in ${join(projectDir, "out", "make")}`,
|
||||
)
|
||||
}
|
||||
const desktopRenderer =
|
||||
releaseConfig.mode === "ota"
|
||||
? await collectDesktopRendererPayload({
|
||||
projectDir,
|
||||
owner,
|
||||
repo,
|
||||
gitTag,
|
||||
})
|
||||
: null
|
||||
|
||||
await mkdir(distDir, { recursive: true })
|
||||
|
||||
const otaMetadata = {
|
||||
schemaVersion: 2,
|
||||
product,
|
||||
channel,
|
||||
releaseVersion,
|
||||
releaseKind,
|
||||
runtimeVersion,
|
||||
publishedAt,
|
||||
git: {
|
||||
tag: gitTag,
|
||||
commit: gitCommit,
|
||||
},
|
||||
policy: {
|
||||
required: false,
|
||||
minSupportedBinaryVersion: process.env.OTA_MIN_SUPPORTED_BINARY_VERSION ?? releaseVersion,
|
||||
message: null,
|
||||
distributions: {},
|
||||
},
|
||||
desktop: {
|
||||
renderer: desktopRenderer,
|
||||
app: desktopApp,
|
||||
},
|
||||
}
|
||||
|
||||
await writeFile(outputPath, `${JSON.stringify(otaMetadata, null, 2)}\n`, "utf8")
|
||||
|
||||
if (releaseConfig.mode === "ota") {
|
||||
await createTarZstArchive({ distDir, archivePath })
|
||||
}
|
||||
|
||||
return {
|
||||
projectDir,
|
||||
distDir,
|
||||
outputPath,
|
||||
archivePath: releaseConfig.mode === "ota" ? archivePath : null,
|
||||
otaMetadata,
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
const result =
|
||||
(process.env.OTA_PRODUCT ?? "mobile") === "desktop"
|
||||
? await buildDesktopReleaseAssets()
|
||||
: await buildReleaseAssets()
|
||||
|
||||
console.info(`Wrote OTA metadata: ${result.outputPath}`)
|
||||
if (result.archivePath) {
|
||||
console.info(`Wrote OTA archive: ${result.archivePath}`)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error instanceof Error ? error.message : String(error))
|
||||
process.exitCode = 1
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {unknown} value
|
||||
*/
|
||||
function resolveExportFileMetadata(metadata) {
|
||||
if (!metadata || typeof metadata !== "object") {
|
||||
throw new Error("Expo export metadata is missing fileMetadata")
|
||||
}
|
||||
|
||||
if (!metadata.fileMetadata || typeof metadata.fileMetadata !== "object") {
|
||||
throw new Error("Expo export metadata is missing fileMetadata")
|
||||
}
|
||||
|
||||
return metadata.fileMetadata
|
||||
}
|
||||
|
||||
function resolvePlatformMetadata(fileMetadata, platform) {
|
||||
const platformMetadata = fileMetadata[platform]
|
||||
|
||||
if (!platformMetadata || typeof platformMetadata !== "object") {
|
||||
throw new Error(`Expo export metadata is missing ${platform} platform metadata`)
|
||||
}
|
||||
|
||||
if (typeof platformMetadata.bundle !== "string" || platformMetadata.bundle.length === 0) {
|
||||
throw new Error(`Expo export metadata is missing ${platform} bundle metadata`)
|
||||
}
|
||||
|
||||
return platformMetadata
|
||||
}
|
||||
|
||||
function collectAssets(value, platform) {
|
||||
if (value == null) {
|
||||
throw new TypeError(`Expo export metadata is missing ${platform} assets metadata`)
|
||||
}
|
||||
|
||||
if (!Array.isArray(value)) {
|
||||
throw new TypeError(`Expo export metadata has invalid ${platform} assets metadata`)
|
||||
}
|
||||
|
||||
/** @type {Map<string, ExportAssetMetadata>} */
|
||||
const dedupedAssets = new Map()
|
||||
|
||||
for (const asset of value) {
|
||||
const normalizedAsset = normalizeExportAsset(asset)
|
||||
const existingAsset = dedupedAssets.get(normalizedAsset.path)
|
||||
|
||||
if (!existingAsset || (!existingAsset.ext && normalizedAsset.ext)) {
|
||||
dedupedAssets.set(normalizedAsset.path, normalizedAsset)
|
||||
continue
|
||||
}
|
||||
|
||||
if (existingAsset.ext && normalizedAsset.ext && existingAsset.ext !== normalizedAsset.ext) {
|
||||
throw new Error(
|
||||
`Expo export metadata has conflicting ext values for asset "${normalizedAsset.path}"`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return [...dedupedAssets.values()]
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {unknown} asset
|
||||
*/
|
||||
function normalizeExportAsset(asset) {
|
||||
if (typeof asset === "string") {
|
||||
return { path: normalizeAssetPath(asset) }
|
||||
}
|
||||
|
||||
if (!asset || typeof asset !== "object") {
|
||||
throw new Error(`Unsupported Expo asset metadata entry: ${JSON.stringify(asset)}`)
|
||||
}
|
||||
|
||||
const assetPath =
|
||||
"path" in asset && typeof asset.path === "string"
|
||||
? asset.path
|
||||
: "file" in asset && typeof asset.file === "string"
|
||||
? asset.file
|
||||
: null
|
||||
|
||||
if (!assetPath) {
|
||||
throw new Error(`Unsupported Expo asset metadata entry: ${JSON.stringify(asset)}`)
|
||||
}
|
||||
|
||||
return {
|
||||
path: normalizeAssetPath(assetPath),
|
||||
...("ext" in asset && asset.ext != null ? { ext: normalizeAssetExtension(asset.ext) } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeAssetExtension(ext) {
|
||||
if (typeof ext !== "string") {
|
||||
throw new TypeError(`Unsupported Expo asset ext metadata: ${JSON.stringify(ext)}`)
|
||||
}
|
||||
|
||||
const normalizedExt = ext.trim().replace(/^\.+/, "").toLowerCase()
|
||||
|
||||
if (!normalizedExt) {
|
||||
throw new Error(`Invalid exported asset ext "${ext}"`)
|
||||
}
|
||||
|
||||
return normalizedExt
|
||||
}
|
||||
|
||||
function resolveMobileProjectDir(projectDir) {
|
||||
if (projectDir) {
|
||||
return resolve(projectDir)
|
||||
}
|
||||
|
||||
const cwd = resolve(process.cwd())
|
||||
|
||||
if (existsSync(join(cwd, "package.json")) && existsSync(join(cwd, "scripts", "expo-update.ts"))) {
|
||||
return cwd
|
||||
}
|
||||
|
||||
if (existsSync(join(cwd, "apps", "mobile", "package.json"))) {
|
||||
return join(cwd, "apps", "mobile")
|
||||
}
|
||||
|
||||
return DEFAULT_MOBILE_PROJECT_DIR
|
||||
}
|
||||
|
||||
function resolveDesktopProjectDir(projectDir) {
|
||||
if (projectDir) {
|
||||
return resolve(projectDir)
|
||||
}
|
||||
|
||||
const cwd = resolve(process.cwd())
|
||||
|
||||
if (existsSync(join(cwd, "package.json")) && existsSync(join(cwd, "release.json"))) {
|
||||
return cwd
|
||||
}
|
||||
|
||||
if (existsSync(join(cwd, "apps", "desktop", "package.json"))) {
|
||||
return join(cwd, "apps", "desktop")
|
||||
}
|
||||
|
||||
return DEFAULT_DESKTOP_PROJECT_DIR
|
||||
}
|
||||
|
||||
function normalizeAssetPath(assetPath) {
|
||||
const normalized = assetPath
|
||||
.replaceAll("\\", "/")
|
||||
.replace(/^\/+/, "")
|
||||
.replace(/^(\.\/)+/, "")
|
||||
.replaceAll(/\/{2,}/g, "/")
|
||||
|
||||
if (!normalized || normalized.split("/").includes("..")) {
|
||||
throw new Error(`Invalid exported asset path "${assetPath}"`)
|
||||
}
|
||||
|
||||
return normalized
|
||||
}
|
||||
|
||||
function resolveContentType(asset) {
|
||||
const normalizedPath = String(asset.path).toLowerCase()
|
||||
const pathExtension = normalizedPath.endsWith(".tar.gz")
|
||||
? ".gz"
|
||||
: extname(normalizedPath).toLowerCase()
|
||||
const metadataExtension = asset.ext ? `.${asset.ext}` : ""
|
||||
const extension = pathExtension || metadataExtension
|
||||
|
||||
return CONTENT_TYPES.get(extension) ?? "application/octet-stream"
|
||||
}
|
||||
|
||||
async function createTarZstArchive({ distDir, archivePath }) {
|
||||
const zstdBinary = resolveZstdBinary()
|
||||
|
||||
await new Promise((resolvePromise, rejectPromise) => {
|
||||
let tarExited = false
|
||||
let zstdExited = false
|
||||
|
||||
const tarProcess = spawn("tar", ["-cf", "-", "-C", distDir, "."], {
|
||||
stdio: ["ignore", "pipe", "inherit"],
|
||||
})
|
||||
const zstdProcess = spawn(zstdBinary, ["-q", "-f", "-o", archivePath], {
|
||||
stdio: ["pipe", "inherit", "inherit"],
|
||||
})
|
||||
|
||||
const rejectOnce = once((error) => rejectPromise(error))
|
||||
const resolveIfComplete = () => {
|
||||
if (tarExited && zstdExited) {
|
||||
resolvePromise(void 0)
|
||||
}
|
||||
}
|
||||
|
||||
tarProcess.on("error", (error) => {
|
||||
rejectOnce(new Error(`Failed to run tar: ${error.message}`))
|
||||
})
|
||||
zstdProcess.on("error", (error) => {
|
||||
rejectOnce(new Error(`Failed to run zstd: ${error.message}`))
|
||||
})
|
||||
|
||||
tarProcess.stdout.on("error", (error) => {
|
||||
rejectOnce(new Error(`Failed to stream tar output: ${error.message}`))
|
||||
})
|
||||
zstdProcess.stdin.on("error", (error) => {
|
||||
rejectOnce(new Error(`Failed to stream zstd input: ${error.message}`))
|
||||
})
|
||||
|
||||
tarProcess.stdout.pipe(zstdProcess.stdin)
|
||||
|
||||
tarProcess.on("close", (code) => {
|
||||
if (code !== 0) {
|
||||
rejectOnce(new Error(`tar exited with code ${code}`))
|
||||
return
|
||||
}
|
||||
|
||||
tarExited = true
|
||||
resolveIfComplete()
|
||||
})
|
||||
|
||||
zstdProcess.on("close", (code) => {
|
||||
if (code !== 0) {
|
||||
rejectOnce(new Error(`zstd exited with code ${code}`))
|
||||
return
|
||||
}
|
||||
|
||||
zstdExited = true
|
||||
resolveIfComplete()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function resolveZstdBinary() {
|
||||
const candidates = [process.env.ZSTD_BIN, "zstd", "/opt/homebrew/bin/zstd"].filter(Boolean)
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const args = candidate === "/opt/homebrew/bin/zstd" ? ["--version"] : ["--version"]
|
||||
const result = spawnSync(candidate, args, { stdio: "ignore" })
|
||||
|
||||
if (result.status === 0) {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error('Unable to find "zstd". Set ZSTD_BIN or install zstd in PATH.')
|
||||
}
|
||||
|
||||
function execGit(args, cwd) {
|
||||
const result = spawnSync("git", args, {
|
||||
cwd,
|
||||
encoding: "utf8",
|
||||
})
|
||||
|
||||
if (result.status !== 0) {
|
||||
throw new Error(result.stderr?.trim() || `git ${args.join(" ")} failed`)
|
||||
}
|
||||
|
||||
return result.stdout.trim()
|
||||
}
|
||||
|
||||
async function readJson(path) {
|
||||
try {
|
||||
return JSON.parse(await readFile(path, "utf8"))
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error)
|
||||
throw new Error(`Failed to read JSON at ${path}: ${reason}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function collectDesktopRendererPayload(input) {
|
||||
const rendererManifestPath = join(input.projectDir, "dist", "manifest.yml")
|
||||
|
||||
if (!existsSync(rendererManifestPath)) {
|
||||
throw new Error(`Missing desktop renderer manifest at ${rendererManifestPath}`)
|
||||
}
|
||||
|
||||
const rendererManifest = parseYamlFile(rendererManifestPath)
|
||||
|
||||
if (typeof rendererManifest.version !== "string" || !rendererManifest.version) {
|
||||
throw new Error(`Desktop renderer manifest at ${rendererManifestPath} is missing version`)
|
||||
}
|
||||
|
||||
if (typeof rendererManifest.commit !== "string" || !rendererManifest.commit) {
|
||||
throw new Error(`Desktop renderer manifest at ${rendererManifestPath} is missing commit`)
|
||||
}
|
||||
|
||||
const filename =
|
||||
typeof rendererManifest.filename === "string" && rendererManifest.filename
|
||||
? rendererManifest.filename
|
||||
: "render-asset.tar.gz"
|
||||
const rendererArchivePath = join(input.projectDir, "dist", filename)
|
||||
|
||||
if (!existsSync(rendererArchivePath)) {
|
||||
throw new Error(`Missing desktop renderer archive at ${rendererArchivePath}`)
|
||||
}
|
||||
|
||||
return {
|
||||
version: rendererManifest.version,
|
||||
commit: rendererManifest.commit,
|
||||
manifest: {
|
||||
name: "manifest.yml",
|
||||
downloadUrl: buildGitHubAssetUrl({
|
||||
owner: input.owner,
|
||||
repo: input.repo,
|
||||
tag: input.gitTag,
|
||||
filename: "manifest.yml",
|
||||
}),
|
||||
},
|
||||
launchAsset: await resolveFileAsset({
|
||||
sourcePath: rendererArchivePath,
|
||||
metadataPath: filename,
|
||||
}),
|
||||
assets: [],
|
||||
}
|
||||
}
|
||||
|
||||
async function collectDesktopAppPayload(input) {
|
||||
const makeDir = join(input.projectDir, "out", "make")
|
||||
|
||||
if (!existsSync(makeDir)) {
|
||||
return null
|
||||
}
|
||||
|
||||
const platformEntries = await collectDesktopPlatformEntries({
|
||||
makeDir,
|
||||
owner: input.owner,
|
||||
repo: input.repo,
|
||||
gitTag: input.gitTag,
|
||||
})
|
||||
|
||||
if (Object.keys(platformEntries).length === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
platforms: platformEntries,
|
||||
}
|
||||
}
|
||||
|
||||
async function collectDesktopPlatformEntries(input) {
|
||||
/** @type {Record<string, any>} */
|
||||
const result = {}
|
||||
|
||||
for (const manifestPath of walkFiles(input.makeDir)) {
|
||||
const fileName = manifestPath.split("/").at(-1)
|
||||
if (!fileName || !DESKTOP_MANIFEST_FILE_NAMES.has(fileName)) {
|
||||
continue
|
||||
}
|
||||
|
||||
const manifest = parseYamlFile(manifestPath)
|
||||
const platformKey = inferDesktopPlatformKey(manifestPath, fileName)
|
||||
|
||||
if (!platformKey || !DESKTOP_PLATFORMS.has(platformKey)) {
|
||||
continue
|
||||
}
|
||||
|
||||
const files = normalizeDesktopManifestFiles(manifest.files, manifestPath)
|
||||
if (files.length === 0) {
|
||||
continue
|
||||
}
|
||||
|
||||
const nextEntry = {
|
||||
platform: inferDesktopPlatformIdentifier(platformKey, manifestPath),
|
||||
releaseDate: normalizeDesktopReleaseDate(manifest.releaseDate),
|
||||
manifest: {
|
||||
name: fileName,
|
||||
path: fileName,
|
||||
downloadUrl: buildGitHubAssetUrl({
|
||||
owner: input.owner,
|
||||
repo: input.repo,
|
||||
tag: input.gitTag,
|
||||
filename: fileName,
|
||||
}),
|
||||
},
|
||||
files: files.map((file) => ({
|
||||
filename: file.url,
|
||||
sha512: file.sha512,
|
||||
size: file.size,
|
||||
downloadUrl: buildGitHubAssetUrl({
|
||||
owner: input.owner,
|
||||
repo: input.repo,
|
||||
tag: input.gitTag,
|
||||
filename: file.url,
|
||||
}),
|
||||
})),
|
||||
}
|
||||
|
||||
result[platformKey] = result[platformKey]
|
||||
? mergeDesktopPlatformEntries(result[platformKey], nextEntry)
|
||||
: nextEntry
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
function inferDesktopPlatformKey(manifestPath, fileName) {
|
||||
const normalized = manifestPath.replaceAll("\\", "/").toLowerCase()
|
||||
|
||||
if (
|
||||
fileName === "latest-mac.yml" ||
|
||||
normalized.includes("/darwin") ||
|
||||
normalized.includes("/mac")
|
||||
) {
|
||||
return "macos"
|
||||
}
|
||||
|
||||
if (fileName === "latest-linux.yml" || normalized.includes("/linux")) {
|
||||
return "linux"
|
||||
}
|
||||
|
||||
if (
|
||||
fileName === "latest.yml" ||
|
||||
normalized.includes("/windows") ||
|
||||
normalized.includes("/squirrel.windows")
|
||||
) {
|
||||
return "windows"
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function inferDesktopPlatformIdentifier(platformKey, manifestPath) {
|
||||
const normalized = manifestPath.replaceAll("\\", "/").toLowerCase()
|
||||
const arch = normalized.includes("/arm64") ? "arm64" : normalized.includes("/x64") ? "x64" : null
|
||||
|
||||
if (!arch) {
|
||||
return platformKey
|
||||
}
|
||||
|
||||
return `${platformKey}-${arch}`
|
||||
}
|
||||
|
||||
function normalizeDesktopManifestFiles(files, manifestPath) {
|
||||
if (!Array.isArray(files)) {
|
||||
throw new TypeError(`Desktop manifest at ${manifestPath} is missing files`)
|
||||
}
|
||||
|
||||
return files.map((file, index) => {
|
||||
const url = typeof file?.url === "string" ? file.url : null
|
||||
const sha512 = typeof file?.sha512 === "string" ? file.sha512 : null
|
||||
const size =
|
||||
typeof file?.size === "number" ? file.size : Number.parseInt(String(file?.size ?? 0), 10)
|
||||
|
||||
if (!url || !sha512 || !Number.isFinite(size) || size < 0) {
|
||||
throw new Error(`Desktop manifest at ${manifestPath} has invalid files[${index}] entry`)
|
||||
}
|
||||
|
||||
return {
|
||||
url,
|
||||
sha512,
|
||||
size,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function normalizeDesktopReleaseDate(value) {
|
||||
if (typeof value === "string") {
|
||||
return value
|
||||
}
|
||||
|
||||
if (value instanceof Date) {
|
||||
return value.toISOString()
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function mergeDesktopPlatformEntries(currentEntry, nextEntry) {
|
||||
const fileByName = new Map(currentEntry.files.map((file) => [file.filename, file]))
|
||||
|
||||
for (const file of nextEntry.files) {
|
||||
fileByName.set(file.filename, file)
|
||||
}
|
||||
|
||||
const mergedReleaseDate = pickLatestReleaseDate(currentEntry.releaseDate, nextEntry.releaseDate)
|
||||
|
||||
return {
|
||||
platform:
|
||||
currentEntry.platform === nextEntry.platform
|
||||
? currentEntry.platform
|
||||
: (currentEntry.platform.split("-")[0] ?? currentEntry.platform),
|
||||
releaseDate: mergedReleaseDate,
|
||||
manifest: currentEntry.manifest,
|
||||
files: [...fileByName.values()],
|
||||
}
|
||||
}
|
||||
|
||||
function pickLatestReleaseDate(currentValue, nextValue) {
|
||||
const currentTime = currentValue ? Date.parse(currentValue) : Number.NaN
|
||||
const nextTime = nextValue ? Date.parse(nextValue) : Number.NaN
|
||||
|
||||
if (Number.isFinite(currentTime) && Number.isFinite(nextTime)) {
|
||||
return currentTime >= nextTime ? currentValue : nextValue
|
||||
}
|
||||
|
||||
return nextValue ?? currentValue ?? null
|
||||
}
|
||||
|
||||
function parseYamlFile(path) {
|
||||
try {
|
||||
const content = readFileSync(path, "utf8")
|
||||
return yaml.load(String(content)) ?? {}
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error)
|
||||
throw new Error(`Failed to parse YAML at ${path}: ${reason}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveFileAsset(input) {
|
||||
const buffer = await readFile(input.sourcePath)
|
||||
return {
|
||||
path: normalizeAssetPath(input.metadataPath),
|
||||
sha256: createHash("sha256").update(buffer).digest("hex"),
|
||||
contentType: resolveContentType({ path: input.metadataPath }),
|
||||
}
|
||||
}
|
||||
|
||||
function buildGitHubAssetUrl({ owner, repo, tag, filename }) {
|
||||
return `https://github.com/${owner}/${repo}/releases/download/${tag}/${filename}`
|
||||
}
|
||||
|
||||
function resolveRepository(options) {
|
||||
if (options.owner && options.repo) {
|
||||
return [options.owner, options.repo]
|
||||
}
|
||||
|
||||
const repository = process.env.GITHUB_REPOSITORY
|
||||
if (repository && repository.includes("/")) {
|
||||
return repository.split("/", 2)
|
||||
}
|
||||
|
||||
return ["RSSNext", "Folo"]
|
||||
}
|
||||
|
||||
function walkFiles(rootDir) {
|
||||
/** @type {string[]} */
|
||||
const results = []
|
||||
/** @type {string[]} */
|
||||
const pending = [rootDir]
|
||||
|
||||
while (pending.length > 0) {
|
||||
const current = pending.pop()
|
||||
if (!current) continue
|
||||
|
||||
for (const entryName of readdirSync(current)) {
|
||||
const entry = join(current, entryName)
|
||||
if (!existsSync(entry)) continue
|
||||
|
||||
if (statSync(entry).isDirectory()) {
|
||||
pending.push(entry)
|
||||
} else {
|
||||
results.push(entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return results.sort()
|
||||
}
|
||||
|
||||
function parseBooleanEnv(name, defaultValue) {
|
||||
const value = process.env[name]
|
||||
|
||||
if (value == null) {
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
if (value === "1" || value.toLowerCase() === "true") {
|
||||
return true
|
||||
}
|
||||
|
||||
if (value === "0" || value.toLowerCase() === "false") {
|
||||
return false
|
||||
}
|
||||
|
||||
throw new Error(`${name} must be "true", "false", "1", or "0"`)
|
||||
}
|
||||
|
||||
function parseNullableEnv(name) {
|
||||
const value = process.env[name]
|
||||
|
||||
if (value == null || value.length === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
function once(callback) {
|
||||
let called = false
|
||||
|
||||
return (...args) => {
|
||||
if (called) {
|
||||
return
|
||||
}
|
||||
|
||||
called = true
|
||||
callback(...args)
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) {
|
||||
await main()
|
||||
}
|
||||
@@ -0,0 +1,640 @@
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"
|
||||
import { tmpdir } from "node:os"
|
||||
|
||||
import { join } from "pathe"
|
||||
import { afterEach, describe, expect, it } from "vitest"
|
||||
|
||||
type InputAsset = string | { path: string; ext?: string }
|
||||
|
||||
const tempDirs: string[] = []
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
tempDirs.splice(0).map((directory) => rm(directory, { recursive: true, force: true })),
|
||||
)
|
||||
delete process.env.OTA_RELEASE_KIND
|
||||
delete process.env.OTA_RELEASE_VERSION
|
||||
delete process.env.OTA_RUNTIME_VERSION
|
||||
delete process.env.OTA_CHANNEL
|
||||
delete process.env.OTA_PRODUCT
|
||||
delete process.env.OTA_GIT_TAG
|
||||
delete process.env.OTA_GIT_COMMIT
|
||||
delete process.env.OTA_PUBLISHED_AT
|
||||
delete process.env.OTA_STORE_REQUIRED
|
||||
delete process.env.GITHUB_REPOSITORY
|
||||
})
|
||||
|
||||
describe("buildOtaMetadata", () => {
|
||||
it("preserves releaseVersion, runtimeVersion, and scoped git tag", async () => {
|
||||
const { buildOtaMetadata } = await import("./build-ota-release.mjs")
|
||||
|
||||
const result = await buildOtaMetadata({
|
||||
product: "mobile",
|
||||
channel: "production",
|
||||
releaseVersion: "0.4.2",
|
||||
releaseKind: "ota",
|
||||
runtimeVersion: "0.4.1",
|
||||
gitTag: "mobile/v0.4.2",
|
||||
gitCommit: "abcdef1234567890",
|
||||
publishedAt: "2026-04-10T12:00:00.000Z",
|
||||
policy: {
|
||||
storeRequired: false,
|
||||
minSupportedBinaryVersion: "0.4.1",
|
||||
message: null,
|
||||
},
|
||||
metadata: {
|
||||
fileMetadata: {
|
||||
ios: {
|
||||
bundle: "_expo/static/js/ios/main.hbc",
|
||||
assets: [],
|
||||
},
|
||||
android: {
|
||||
bundle: "_expo/static/js/android/main.hbc",
|
||||
assets: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
resolveAsset: async (asset: InputAsset) => {
|
||||
const assetPath = typeof asset === "string" ? asset : asset.path
|
||||
|
||||
return {
|
||||
path: assetPath,
|
||||
sha256: `${assetPath}-sha256`.padEnd(64, "0").slice(0, 64),
|
||||
contentType: "application/octet-stream",
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
expect(result.releaseVersion).toBe("0.4.2")
|
||||
expect(result.runtimeVersion).toBe("0.4.1")
|
||||
expect(result.git.tag).toBe("mobile/v0.4.2")
|
||||
expect(result.updateId).toMatch(
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
|
||||
)
|
||||
})
|
||||
|
||||
it("uses asset ext metadata when exported asset paths have no suffix", async () => {
|
||||
const { buildOtaMetadata } = await import("./build-ota-release.mjs")
|
||||
|
||||
const result = await buildOtaMetadata({
|
||||
product: "mobile",
|
||||
channel: "production",
|
||||
releaseVersion: "0.4.2",
|
||||
releaseKind: "ota",
|
||||
runtimeVersion: "0.4.1",
|
||||
gitTag: "mobile/v0.4.2",
|
||||
gitCommit: "abcdef1234567890",
|
||||
publishedAt: "2026-04-10T12:00:00.000Z",
|
||||
policy: {
|
||||
storeRequired: false,
|
||||
minSupportedBinaryVersion: "0.4.1",
|
||||
message: null,
|
||||
},
|
||||
metadata: {
|
||||
fileMetadata: {
|
||||
ios: {
|
||||
bundle: "_expo/static/js/ios/main.hbc",
|
||||
assets: [{ path: "assets/splash", ext: "png" }],
|
||||
},
|
||||
android: {
|
||||
bundle: "_expo/static/js/android/main.hbc",
|
||||
assets: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
resolveAsset: async (asset: InputAsset) => {
|
||||
const assetPath = typeof asset === "string" ? asset : asset.path
|
||||
const ext = typeof asset === "string" ? undefined : asset.ext
|
||||
|
||||
return {
|
||||
path: assetPath,
|
||||
sha256: `${assetPath}-sha256`.padEnd(64, "0").slice(0, 64),
|
||||
contentType: ext === "png" ? "image/png" : "application/octet-stream",
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
expect(result.platforms.ios.assets).toEqual([
|
||||
expect.objectContaining({
|
||||
path: "assets/splash",
|
||||
contentType: "image/png",
|
||||
}),
|
||||
])
|
||||
})
|
||||
|
||||
it("fails when a platform bundle is missing from export metadata", async () => {
|
||||
const { buildOtaMetadata } = await import("./build-ota-release.mjs")
|
||||
|
||||
await expect(
|
||||
buildOtaMetadata({
|
||||
product: "mobile",
|
||||
channel: "production",
|
||||
releaseVersion: "0.4.2",
|
||||
releaseKind: "ota",
|
||||
runtimeVersion: "0.4.1",
|
||||
gitTag: "mobile/v0.4.2",
|
||||
gitCommit: "abcdef1234567890",
|
||||
publishedAt: "2026-04-10T12:00:00.000Z",
|
||||
policy: {
|
||||
storeRequired: false,
|
||||
minSupportedBinaryVersion: "0.4.1",
|
||||
message: null,
|
||||
},
|
||||
metadata: {
|
||||
fileMetadata: {
|
||||
ios: {
|
||||
bundle: "_expo/static/js/ios/main.hbc",
|
||||
assets: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
resolveAsset: async (asset: InputAsset) => {
|
||||
const assetPath = typeof asset === "string" ? asset : asset.path
|
||||
|
||||
return {
|
||||
path: assetPath,
|
||||
sha256: `${assetPath}-sha256`.padEnd(64, "0").slice(0, 64),
|
||||
contentType: "application/octet-stream",
|
||||
}
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow(/android/i)
|
||||
})
|
||||
|
||||
it("fails when a platform assets array is missing from export metadata", async () => {
|
||||
const { buildOtaMetadata } = await import("./build-ota-release.mjs")
|
||||
|
||||
await expect(
|
||||
buildOtaMetadata({
|
||||
product: "mobile",
|
||||
channel: "production",
|
||||
releaseVersion: "0.4.2",
|
||||
releaseKind: "ota",
|
||||
runtimeVersion: "0.4.1",
|
||||
gitTag: "mobile/v0.4.2",
|
||||
gitCommit: "abcdef1234567890",
|
||||
publishedAt: "2026-04-10T12:00:00.000Z",
|
||||
policy: {
|
||||
storeRequired: false,
|
||||
minSupportedBinaryVersion: "0.4.1",
|
||||
message: null,
|
||||
},
|
||||
metadata: {
|
||||
fileMetadata: {
|
||||
ios: {
|
||||
bundle: "_expo/static/js/ios/main.hbc",
|
||||
},
|
||||
android: {
|
||||
bundle: "_expo/static/js/android/main.hbc",
|
||||
assets: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
resolveAsset: async (asset: InputAsset) => {
|
||||
const assetPath = typeof asset === "string" ? asset : asset.path
|
||||
|
||||
return {
|
||||
path: assetPath,
|
||||
sha256: `${assetPath}-sha256`.padEnd(64, "0").slice(0, 64),
|
||||
contentType: "application/octet-stream",
|
||||
}
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow(/ios.*assets/i)
|
||||
})
|
||||
|
||||
it("deduplicates repeated asset entries after path normalization", async () => {
|
||||
const { buildOtaMetadata } = await import("./build-ota-release.mjs")
|
||||
|
||||
const resolvedAssets: InputAsset[] = []
|
||||
|
||||
const result = await buildOtaMetadata({
|
||||
product: "mobile",
|
||||
channel: "production",
|
||||
releaseVersion: "0.4.2",
|
||||
releaseKind: "ota",
|
||||
runtimeVersion: "0.4.1",
|
||||
gitTag: "mobile/v0.4.2",
|
||||
gitCommit: "abcdef1234567890",
|
||||
publishedAt: "2026-04-10T12:00:00.000Z",
|
||||
policy: {
|
||||
storeRequired: false,
|
||||
minSupportedBinaryVersion: "0.4.1",
|
||||
message: null,
|
||||
},
|
||||
metadata: {
|
||||
fileMetadata: {
|
||||
ios: {
|
||||
bundle: "_expo/static/js/ios/main.hbc",
|
||||
assets: ["./assets/icon.png", { path: "assets/icon.png" }],
|
||||
},
|
||||
android: {
|
||||
bundle: "_expo/static/js/android/main.hbc",
|
||||
assets: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
resolveAsset: async (asset: InputAsset) => {
|
||||
resolvedAssets.push(asset)
|
||||
const assetPath = typeof asset === "string" ? asset : asset.path
|
||||
|
||||
return {
|
||||
path: assetPath,
|
||||
sha256: `${assetPath}-sha256`.padEnd(64, "0").slice(0, 64),
|
||||
contentType: "image/png",
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
expect(result.platforms.ios.assets).toHaveLength(1)
|
||||
expect(
|
||||
resolvedAssets.filter((asset) => {
|
||||
const assetPath = typeof asset === "string" ? asset : asset.path
|
||||
|
||||
return assetPath === "assets/icon.png"
|
||||
}),
|
||||
).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe("buildReleaseAssets", () => {
|
||||
it("builds metadata-only assets for store releases without Expo export output", async () => {
|
||||
const { buildReleaseAssets } = await import("./build-ota-release.mjs")
|
||||
|
||||
const projectDir = await mkdtemp(join(tmpdir(), "build-ota-release-store-test-"))
|
||||
tempDirs.push(projectDir)
|
||||
|
||||
await writeFile(
|
||||
join(projectDir, "package.json"),
|
||||
JSON.stringify({ name: "@follow/mobile-test", version: "0.4.3" }),
|
||||
"utf8",
|
||||
)
|
||||
|
||||
process.env.OTA_RELEASE_KIND = "store"
|
||||
process.env.OTA_RELEASE_VERSION = "0.4.3"
|
||||
process.env.OTA_RUNTIME_VERSION = "0.4.3"
|
||||
process.env.OTA_CHANNEL = "production"
|
||||
process.env.OTA_STORE_REQUIRED = "true"
|
||||
|
||||
const result = await buildReleaseAssets({ projectDir })
|
||||
|
||||
expect(result.otaMetadata.releaseKind).toBe("store")
|
||||
expect(result.otaMetadata.policy.storeRequired).toBe(true)
|
||||
expect(result.otaMetadata.platforms).toEqual({})
|
||||
expect(result.archivePath).toBeNull()
|
||||
})
|
||||
|
||||
it("includes the JSON file path when export metadata cannot be parsed", async () => {
|
||||
const { buildReleaseAssets } = await import("./build-ota-release.mjs")
|
||||
|
||||
const projectDir = await mkdtemp(join(tmpdir(), "build-ota-release-test-"))
|
||||
const distDir = join(projectDir, "dist")
|
||||
const metadataPath = join(distDir, "metadata.json")
|
||||
tempDirs.push(projectDir)
|
||||
|
||||
await mkdir(distDir, { recursive: true })
|
||||
await writeFile(
|
||||
join(projectDir, "package.json"),
|
||||
JSON.stringify({ name: "@follow/mobile-test", version: "0.4.2" }),
|
||||
"utf8",
|
||||
)
|
||||
await writeFile(metadataPath, "{invalid", "utf8")
|
||||
|
||||
await expect(buildReleaseAssets({ projectDir })).rejects.toThrow(metadataPath)
|
||||
})
|
||||
})
|
||||
|
||||
describe("buildDesktopReleaseAssets", () => {
|
||||
it("builds schemaVersion 2 desktop build metadata with direct app payloads only", async () => {
|
||||
const { buildDesktopReleaseAssets } = await import("./build-ota-release.mjs")
|
||||
const projectDir = await createDesktopProjectFixture({
|
||||
version: "1.5.1",
|
||||
releaseConfig: {
|
||||
version: "1.5.1",
|
||||
mode: "build",
|
||||
runtimeVersion: null,
|
||||
channel: null,
|
||||
},
|
||||
manifests: [
|
||||
{
|
||||
relativeDir: join("out", "make", "squirrel.windows", "x64"),
|
||||
manifestName: "latest.yml",
|
||||
contents: `
|
||||
version: 1.5.1
|
||||
files:
|
||||
- url: Folo-1.5.1-windows-x64.exe
|
||||
sha512: ${"a".repeat(88)}
|
||||
size: 123456
|
||||
releaseDate: 2026-04-11T10:00:00.000Z
|
||||
`,
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
const result = await buildDesktopReleaseAssets({
|
||||
projectDir,
|
||||
owner: "RSSNext",
|
||||
repo: "Folo",
|
||||
})
|
||||
|
||||
expect(result.otaMetadata.schemaVersion).toBe(2)
|
||||
expect(result.otaMetadata.product).toBe("desktop")
|
||||
expect(result.otaMetadata.releaseKind).toBe("binary")
|
||||
expect(result.otaMetadata.runtimeVersion).toBeNull()
|
||||
expect(result.otaMetadata.channel).toBe("stable")
|
||||
expect(result.otaMetadata.desktop.renderer).toBeNull()
|
||||
expect(result.otaMetadata.policy.distributions).toEqual({})
|
||||
expect(result.otaMetadata.desktop.app.platforms.windows).toEqual(
|
||||
expect.objectContaining({
|
||||
platform: "windows-x64",
|
||||
releaseDate: "2026-04-11T10:00:00.000Z",
|
||||
manifest: {
|
||||
name: "latest.yml",
|
||||
path: "latest.yml",
|
||||
downloadUrl: expect.stringContaining("/desktop/v1.5.1/latest.yml"),
|
||||
},
|
||||
files: [
|
||||
expect.objectContaining({
|
||||
filename: "Folo-1.5.1-windows-x64.exe",
|
||||
sha512: "a".repeat(88),
|
||||
size: 123456,
|
||||
downloadUrl: expect.stringContaining("/desktop/v1.5.1/Folo-1.5.1-windows-x64.exe"),
|
||||
}),
|
||||
],
|
||||
}),
|
||||
)
|
||||
expect(result.archivePath).toBeNull()
|
||||
|
||||
const written = JSON.parse(await readFile(result.outputPath, "utf8"))
|
||||
expect(written.schemaVersion).toBe(2)
|
||||
expect(written.desktop.renderer).toBeNull()
|
||||
})
|
||||
|
||||
it("builds schemaVersion 2 desktop ota metadata with renderer and direct app payloads", async () => {
|
||||
const { buildDesktopReleaseAssets } = await import("./build-ota-release.mjs")
|
||||
const projectDir = await createDesktopProjectFixture({
|
||||
version: "1.5.1",
|
||||
releaseConfig: {
|
||||
version: "1.5.1",
|
||||
mode: "ota",
|
||||
runtimeVersion: "1.5.0",
|
||||
channel: "stable",
|
||||
},
|
||||
rendererArchiveContents: "renderer archive",
|
||||
rendererManifestContents: `
|
||||
version: 1.5.1
|
||||
hash: ${"b".repeat(64)}
|
||||
mainHash: ${"c".repeat(40)}
|
||||
commit: abcdef1234567890
|
||||
filename: custom-renderer.tar.gz
|
||||
`,
|
||||
manifests: [
|
||||
{
|
||||
relativeDir: join("out", "make", "squirrel.windows", "x64"),
|
||||
manifestName: "latest.yml",
|
||||
contents: `
|
||||
version: 1.5.1
|
||||
files:
|
||||
- url: Folo-1.5.1-windows-x64.exe
|
||||
sha512: ${"d".repeat(88)}
|
||||
size: 654321
|
||||
releaseDate: 2026-04-11T10:00:00.000Z
|
||||
`,
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
const result = await buildDesktopReleaseAssets({
|
||||
projectDir,
|
||||
owner: "RSSNext",
|
||||
repo: "Folo",
|
||||
})
|
||||
|
||||
expect(result.otaMetadata.schemaVersion).toBe(2)
|
||||
expect(result.otaMetadata.releaseKind).toBe("ota")
|
||||
expect(result.otaMetadata.runtimeVersion).toBe("1.5.0")
|
||||
expect(result.otaMetadata.channel).toBe("stable")
|
||||
expect(result.otaMetadata.desktop.renderer).toEqual(
|
||||
expect.objectContaining({
|
||||
version: "1.5.1",
|
||||
commit: "abcdef1234567890",
|
||||
manifest: {
|
||||
name: "manifest.yml",
|
||||
downloadUrl:
|
||||
"https://github.com/RSSNext/Folo/releases/download/desktop/v1.5.1/manifest.yml",
|
||||
},
|
||||
launchAsset: expect.objectContaining({
|
||||
path: "custom-renderer.tar.gz",
|
||||
contentType: "application/gzip",
|
||||
}),
|
||||
}),
|
||||
)
|
||||
expect(result.otaMetadata.desktop.renderer.launchAsset.sha256).toHaveLength(64)
|
||||
expect(result.otaMetadata.desktop.app.platforms.windows.files[0]?.downloadUrl).toContain(
|
||||
"/desktop/v1.5.1/Folo-1.5.1-windows-x64.exe",
|
||||
)
|
||||
expect(result.archivePath).not.toBeNull()
|
||||
})
|
||||
|
||||
it("fails when a desktop manifest contains an invalid file entry", async () => {
|
||||
const { buildDesktopReleaseAssets } = await import("./build-ota-release.mjs")
|
||||
const projectDir = await createDesktopProjectFixture({
|
||||
version: "1.5.1",
|
||||
releaseConfig: {
|
||||
version: "1.5.1",
|
||||
mode: "build",
|
||||
runtimeVersion: null,
|
||||
channel: null,
|
||||
},
|
||||
manifests: [
|
||||
{
|
||||
relativeDir: join("out", "make", "squirrel.windows", "x64"),
|
||||
manifestName: "latest.yml",
|
||||
contents: `
|
||||
version: 1.5.1
|
||||
files:
|
||||
- url: Folo-1.5.1-windows-x64.exe
|
||||
size: 123456
|
||||
releaseDate: 2026-04-11T10:00:00.000Z
|
||||
`,
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
await expect(
|
||||
buildDesktopReleaseAssets({
|
||||
projectDir,
|
||||
owner: "RSSNext",
|
||||
repo: "Folo",
|
||||
}),
|
||||
).rejects.toThrow(/invalid files\[0\] entry/i)
|
||||
})
|
||||
|
||||
it("fails for build mode when direct installer manifests are missing", async () => {
|
||||
const { buildDesktopReleaseAssets } = await import("./build-ota-release.mjs")
|
||||
const projectDir = await createDesktopProjectFixture({
|
||||
version: "1.5.1",
|
||||
releaseConfig: {
|
||||
version: "1.5.1",
|
||||
mode: "build",
|
||||
runtimeVersion: null,
|
||||
channel: null,
|
||||
},
|
||||
})
|
||||
|
||||
await expect(
|
||||
buildDesktopReleaseAssets({
|
||||
projectDir,
|
||||
owner: "RSSNext",
|
||||
repo: "Folo",
|
||||
}),
|
||||
).rejects.toThrow(/requires direct installer manifests/i)
|
||||
})
|
||||
|
||||
it("fails for ota mode when direct installer manifests are missing", async () => {
|
||||
const { buildDesktopReleaseAssets } = await import("./build-ota-release.mjs")
|
||||
const projectDir = await createDesktopProjectFixture({
|
||||
version: "1.5.1",
|
||||
releaseConfig: {
|
||||
version: "1.5.1",
|
||||
mode: "ota",
|
||||
runtimeVersion: "1.5.0",
|
||||
channel: "stable",
|
||||
},
|
||||
rendererArchiveContents: "renderer archive",
|
||||
rendererManifestContents: `
|
||||
version: 1.5.1
|
||||
hash: ${"2".repeat(64)}
|
||||
mainHash: ${"3".repeat(40)}
|
||||
commit: abcdef1234567890
|
||||
filename: custom-renderer.tar.gz
|
||||
`,
|
||||
})
|
||||
|
||||
await expect(
|
||||
buildDesktopReleaseAssets({
|
||||
projectDir,
|
||||
owner: "RSSNext",
|
||||
repo: "Folo",
|
||||
}),
|
||||
).rejects.toThrow(/requires direct installer manifests/i)
|
||||
})
|
||||
|
||||
it("merges duplicate desktop platform manifests instead of overwriting them", async () => {
|
||||
const { buildDesktopReleaseAssets } = await import("./build-ota-release.mjs")
|
||||
const projectDir = await createDesktopProjectFixture({
|
||||
version: "1.5.1",
|
||||
releaseConfig: {
|
||||
version: "1.5.1",
|
||||
mode: "build",
|
||||
runtimeVersion: null,
|
||||
channel: null,
|
||||
},
|
||||
manifests: [
|
||||
{
|
||||
relativeDir: join("out", "make", "squirrel.windows", "x64"),
|
||||
manifestName: "latest.yml",
|
||||
contents: `
|
||||
version: 1.5.1
|
||||
files:
|
||||
- url: Folo-1.5.1-windows-x64.exe
|
||||
sha512: ${"e".repeat(88)}
|
||||
size: 123456
|
||||
releaseDate: 2026-04-11T10:00:00.000Z
|
||||
`,
|
||||
},
|
||||
{
|
||||
relativeDir: join("out", "make", "squirrel.windows", "arm64"),
|
||||
manifestName: "latest.yml",
|
||||
contents: `
|
||||
version: 1.5.1
|
||||
files:
|
||||
- url: Folo-1.5.1-windows-arm64.exe
|
||||
sha512: ${"f".repeat(88)}
|
||||
size: 234567
|
||||
releaseDate: 2026-04-11T11:00:00.000Z
|
||||
`,
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
const result = await buildDesktopReleaseAssets({
|
||||
projectDir,
|
||||
owner: "RSSNext",
|
||||
repo: "Folo",
|
||||
})
|
||||
|
||||
expect(result.otaMetadata.desktop.app.platforms.windows.files).toHaveLength(2)
|
||||
expect(result.otaMetadata.desktop.app.platforms.windows.releaseDate).toBe(
|
||||
"2026-04-11T11:00:00.000Z",
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
async function createDesktopProjectFixture(input: {
|
||||
version: string
|
||||
releaseConfig: {
|
||||
version: string
|
||||
mode: "build" | "ota"
|
||||
runtimeVersion: string | null
|
||||
channel: "stable" | "beta" | "alpha" | null
|
||||
}
|
||||
manifests?: Array<{
|
||||
relativeDir: string
|
||||
manifestName: string
|
||||
contents: string
|
||||
}>
|
||||
rendererArchiveContents?: string
|
||||
rendererManifestContents?: string
|
||||
}) {
|
||||
const projectDir = await mkdtemp(join(tmpdir(), "build-ota-release-desktop-test-"))
|
||||
tempDirs.push(projectDir)
|
||||
|
||||
await writeFile(
|
||||
join(projectDir, "package.json"),
|
||||
JSON.stringify({ name: "@follow/desktop-test", version: input.version }),
|
||||
"utf8",
|
||||
)
|
||||
await writeFile(
|
||||
join(projectDir, "release.json"),
|
||||
`${JSON.stringify(input.releaseConfig, null, 2)}\n`,
|
||||
"utf8",
|
||||
)
|
||||
|
||||
if (input.rendererArchiveContents != null || input.rendererManifestContents != null) {
|
||||
await mkdir(join(projectDir, "dist"), { recursive: true })
|
||||
}
|
||||
|
||||
if (input.rendererArchiveContents != null) {
|
||||
await writeFile(
|
||||
join(
|
||||
projectDir,
|
||||
"dist",
|
||||
input.rendererManifestContents?.includes("custom-renderer.tar.gz")
|
||||
? "custom-renderer.tar.gz"
|
||||
: "render-asset.tar.gz",
|
||||
),
|
||||
input.rendererArchiveContents,
|
||||
"utf8",
|
||||
)
|
||||
}
|
||||
|
||||
if (input.rendererManifestContents != null) {
|
||||
await writeFile(
|
||||
join(projectDir, "dist", "manifest.yml"),
|
||||
input.rendererManifestContents.trimStart(),
|
||||
"utf8",
|
||||
)
|
||||
}
|
||||
|
||||
for (const manifest of input.manifests ?? []) {
|
||||
await mkdir(join(projectDir, manifest.relativeDir), { recursive: true })
|
||||
await writeFile(
|
||||
join(projectDir, manifest.relativeDir, manifest.manifestName),
|
||||
manifest.contents.trimStart(),
|
||||
"utf8",
|
||||
)
|
||||
}
|
||||
|
||||
return projectDir
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { appendFileSync } from "node:fs"
|
||||
import { readFile } from "node:fs/promises"
|
||||
import { pathToFileURL } from "node:url"
|
||||
|
||||
const SEMVER_PATTERN = /^\d+\.\d+\.\d+$/
|
||||
const VALID_MODES = new Set(["build", "ota"])
|
||||
const VALID_CHANNELS = new Set(["stable", "beta", "alpha"])
|
||||
|
||||
export function resolveDesktopReleaseConfig(input) {
|
||||
const normalizedReleaseVersion = input.releaseVersion.replace(/^v/, "")
|
||||
const config = input.releaseConfig
|
||||
|
||||
if (config.version !== normalizedReleaseVersion) {
|
||||
throw new Error(
|
||||
`apps/desktop/release.json version ${config.version} does not match release version ${normalizedReleaseVersion}.`,
|
||||
)
|
||||
}
|
||||
|
||||
if (!VALID_MODES.has(config.mode)) {
|
||||
throw new Error("apps/desktop/release.json mode must be build or ota.")
|
||||
}
|
||||
|
||||
if (config.mode === "build") {
|
||||
if (config.runtimeVersion !== null || config.channel !== null) {
|
||||
throw new Error("desktop build mode must not set runtimeVersion or channel")
|
||||
}
|
||||
|
||||
return {
|
||||
triggerDirectBuild: true,
|
||||
triggerStoreBuilds: true,
|
||||
runtimeVersion: null,
|
||||
channel: null,
|
||||
releaseVersion: normalizedReleaseVersion,
|
||||
}
|
||||
}
|
||||
|
||||
if (config.mode === "ota") {
|
||||
if (!config.runtimeVersion || !SEMVER_PATTERN.test(config.runtimeVersion)) {
|
||||
throw new Error("apps/desktop/release.json runtimeVersion must be a plain x.y.z version.")
|
||||
}
|
||||
|
||||
if (!config.channel || !VALID_CHANNELS.has(config.channel)) {
|
||||
throw new Error("apps/desktop/release.json channel must be stable, beta, or alpha.")
|
||||
}
|
||||
|
||||
return {
|
||||
triggerDirectBuild: true,
|
||||
triggerStoreBuilds: true,
|
||||
runtimeVersion: config.runtimeVersion,
|
||||
channel: config.channel,
|
||||
releaseVersion: normalizedReleaseVersion,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function readReleaseConfig(path) {
|
||||
const raw = await readFile(path, "utf8")
|
||||
return JSON.parse(raw)
|
||||
}
|
||||
|
||||
function setGitHubOutput(key, value) {
|
||||
if (!process.env.GITHUB_OUTPUT) {
|
||||
return
|
||||
}
|
||||
|
||||
const delimiter = `__GITHUB_OUTPUT_${key}_${Date.now()}_${Math.random().toString(16).slice(2)}__`
|
||||
appendFileSync(process.env.GITHUB_OUTPUT, `${key}<<${delimiter}\n${value}\n${delimiter}\n`)
|
||||
}
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
const configPath = process.env.RELEASE_CONFIG_PATH ?? "apps/desktop/release.json"
|
||||
const releaseConfig = await readReleaseConfig(configPath)
|
||||
const result = resolveDesktopReleaseConfig({
|
||||
releaseVersion: process.env.RELEASE_VERSION ?? "",
|
||||
releaseConfig,
|
||||
})
|
||||
|
||||
setGitHubOutput("triggerDirectBuild", String(result.triggerDirectBuild))
|
||||
setGitHubOutput("triggerStoreBuilds", String(result.triggerStoreBuilds))
|
||||
setGitHubOutput("runtimeVersion", result.runtimeVersion ?? "")
|
||||
setGitHubOutput("channel", result.channel ?? "")
|
||||
setGitHubOutput("releaseVersion", result.releaseVersion)
|
||||
} catch (error) {
|
||||
console.error(error instanceof Error ? error.message : String(error))
|
||||
process.exitCode = 1
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
await main()
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { execFile } from "node:child_process"
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"
|
||||
import { tmpdir } from "node:os"
|
||||
import { promisify } from "node:util"
|
||||
|
||||
import { join } from "pathe"
|
||||
import { describe, expect, it } from "vitest"
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
describe("resolveDesktopReleaseConfig", () => {
|
||||
it("triggers direct and store builds for build mode", async () => {
|
||||
const { resolveDesktopReleaseConfig } = await import("./resolve-desktop-release-config.mjs")
|
||||
|
||||
expect(
|
||||
resolveDesktopReleaseConfig({
|
||||
releaseVersion: "v1.5.1",
|
||||
releaseConfig: {
|
||||
version: "1.5.1",
|
||||
mode: "build",
|
||||
runtimeVersion: null,
|
||||
channel: null,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
triggerDirectBuild: true,
|
||||
triggerStoreBuilds: true,
|
||||
runtimeVersion: null,
|
||||
channel: null,
|
||||
releaseVersion: "1.5.1",
|
||||
})
|
||||
})
|
||||
|
||||
it("triggers direct and store builds for ota mode", async () => {
|
||||
const { resolveDesktopReleaseConfig } = await import("./resolve-desktop-release-config.mjs")
|
||||
|
||||
expect(
|
||||
resolveDesktopReleaseConfig({
|
||||
releaseVersion: "v1.5.1",
|
||||
releaseConfig: {
|
||||
version: "1.5.1",
|
||||
mode: "ota",
|
||||
runtimeVersion: "1.5.0",
|
||||
channel: "stable",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
triggerDirectBuild: true,
|
||||
triggerStoreBuilds: true,
|
||||
runtimeVersion: "1.5.0",
|
||||
channel: "stable",
|
||||
releaseVersion: "1.5.1",
|
||||
})
|
||||
})
|
||||
|
||||
it("rejects a release config that does not match the release version", async () => {
|
||||
const { resolveDesktopReleaseConfig } = await import("./resolve-desktop-release-config.mjs")
|
||||
|
||||
expect(() =>
|
||||
resolveDesktopReleaseConfig({
|
||||
releaseVersion: "v1.5.2",
|
||||
releaseConfig: {
|
||||
version: "1.5.1",
|
||||
mode: "build",
|
||||
runtimeVersion: null,
|
||||
channel: null,
|
||||
},
|
||||
}),
|
||||
).toThrow(/does not match release version/i)
|
||||
})
|
||||
|
||||
it("rejects build mode when runtimeVersion or channel is set", async () => {
|
||||
const { resolveDesktopReleaseConfig } = await import("./resolve-desktop-release-config.mjs")
|
||||
|
||||
expect(() =>
|
||||
resolveDesktopReleaseConfig({
|
||||
releaseVersion: "v1.5.2",
|
||||
releaseConfig: {
|
||||
version: "1.5.2",
|
||||
mode: "build",
|
||||
runtimeVersion: "1.5.1",
|
||||
channel: "stable",
|
||||
},
|
||||
}),
|
||||
).toThrow(/must not set runtimeVersion or channel/i)
|
||||
})
|
||||
|
||||
it("writes GitHub outputs for ota mode", async () => {
|
||||
const projectDir = await mkdtemp(join(tmpdir(), "desktop-release-config-output-"))
|
||||
|
||||
try {
|
||||
const releaseConfigPath = join(projectDir, "release.json")
|
||||
const githubOutputPath = join(projectDir, "github-output.txt")
|
||||
|
||||
await writeFile(
|
||||
releaseConfigPath,
|
||||
`${JSON.stringify(
|
||||
{
|
||||
version: "1.5.2",
|
||||
mode: "ota",
|
||||
runtimeVersion: "1.5.1",
|
||||
channel: "beta",
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
"utf8",
|
||||
)
|
||||
|
||||
await execFileAsync("node", [".github/scripts/resolve-desktop-release-config.mjs"], {
|
||||
cwd: process.cwd(),
|
||||
env: {
|
||||
...process.env,
|
||||
RELEASE_VERSION: "1.5.2",
|
||||
RELEASE_CONFIG_PATH: releaseConfigPath,
|
||||
GITHUB_OUTPUT: githubOutputPath,
|
||||
},
|
||||
})
|
||||
|
||||
const output = await readFile(githubOutputPath, "utf8")
|
||||
|
||||
expect(output).toContain("triggerDirectBuild=true")
|
||||
expect(output).toContain("triggerStoreBuilds=true")
|
||||
expect(output).toContain("runtimeVersion<<")
|
||||
expect(output).toContain("1.5.1")
|
||||
expect(output).toContain("channel<<")
|
||||
expect(output).toContain("beta")
|
||||
} finally {
|
||||
await rm(projectDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { appendFileSync } from "node:fs"
|
||||
import { readFile } from "node:fs/promises"
|
||||
import { pathToFileURL } from "node:url"
|
||||
|
||||
const SEMVER_PATTERN = /^\d+\.\d+\.\d+$/
|
||||
const VALID_MODES = new Set(["store", "ota"])
|
||||
const VALID_CHANNELS = new Set(["production", "preview"])
|
||||
|
||||
export function resolveMobileReleaseConfig(input) {
|
||||
const normalizedReleaseVersion = input.releaseVersion.replace(/^v/, "")
|
||||
const config = input.releaseConfig
|
||||
|
||||
if (config.version !== normalizedReleaseVersion) {
|
||||
throw new Error(
|
||||
`apps/mobile/release.json version ${config.version} does not match release version ${normalizedReleaseVersion}.`,
|
||||
)
|
||||
}
|
||||
|
||||
if (!VALID_MODES.has(config.mode)) {
|
||||
throw new Error("apps/mobile/release.json mode must be store or ota.")
|
||||
}
|
||||
|
||||
if (config.mode === "store") {
|
||||
return {
|
||||
triggerStoreBuilds: true,
|
||||
triggerOtaPublish: false,
|
||||
runtimeVersion: null,
|
||||
channel: null,
|
||||
releaseVersion: normalizedReleaseVersion,
|
||||
}
|
||||
}
|
||||
|
||||
if (!config.runtimeVersion || !SEMVER_PATTERN.test(config.runtimeVersion)) {
|
||||
throw new Error("apps/mobile/release.json runtimeVersion must be a plain x.y.z version.")
|
||||
}
|
||||
|
||||
if (!config.channel || !VALID_CHANNELS.has(config.channel)) {
|
||||
throw new Error("apps/mobile/release.json channel must be production or preview.")
|
||||
}
|
||||
|
||||
return {
|
||||
triggerStoreBuilds: false,
|
||||
triggerOtaPublish: true,
|
||||
runtimeVersion: config.runtimeVersion,
|
||||
channel: config.channel,
|
||||
releaseVersion: normalizedReleaseVersion,
|
||||
}
|
||||
}
|
||||
|
||||
async function readReleaseConfig(path) {
|
||||
const raw = await readFile(path, "utf8")
|
||||
return JSON.parse(raw)
|
||||
}
|
||||
|
||||
function setGitHubOutput(key, value) {
|
||||
if (!process.env.GITHUB_OUTPUT) {
|
||||
return
|
||||
}
|
||||
|
||||
appendFileSync(process.env.GITHUB_OUTPUT, `${key}=${value}\n`)
|
||||
}
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
const configPath = process.env.RELEASE_CONFIG_PATH ?? "apps/mobile/release.json"
|
||||
const releaseConfig = await readReleaseConfig(configPath)
|
||||
const result = resolveMobileReleaseConfig({
|
||||
releaseVersion: process.env.RELEASE_VERSION ?? "",
|
||||
releaseConfig,
|
||||
})
|
||||
|
||||
setGitHubOutput("trigger_store_builds", String(result.triggerStoreBuilds))
|
||||
setGitHubOutput("trigger_ota_publish", String(result.triggerOtaPublish))
|
||||
setGitHubOutput("runtime_version", result.runtimeVersion ?? "")
|
||||
setGitHubOutput("channel", result.channel ?? "")
|
||||
setGitHubOutput("release_version", result.releaseVersion)
|
||||
} catch (error) {
|
||||
console.error(error instanceof Error ? error.message : String(error))
|
||||
process.exitCode = 1
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
await main()
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { describe, expect, it } from "vitest"
|
||||
|
||||
describe("resolveMobileReleaseConfig", () => {
|
||||
it("defaults to store builds when release.json mode is store", async () => {
|
||||
const { resolveMobileReleaseConfig } = await import("./resolve-mobile-release-config.mjs")
|
||||
|
||||
expect(
|
||||
resolveMobileReleaseConfig({
|
||||
releaseVersion: "v0.4.2",
|
||||
releaseConfig: {
|
||||
version: "0.4.2",
|
||||
mode: "store",
|
||||
runtimeVersion: null,
|
||||
channel: null,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
triggerStoreBuilds: true,
|
||||
triggerOtaPublish: false,
|
||||
runtimeVersion: null,
|
||||
channel: null,
|
||||
releaseVersion: "0.4.2",
|
||||
})
|
||||
})
|
||||
|
||||
it("triggers OTA publish only for ota mode", async () => {
|
||||
const { resolveMobileReleaseConfig } = await import("./resolve-mobile-release-config.mjs")
|
||||
|
||||
expect(
|
||||
resolveMobileReleaseConfig({
|
||||
releaseVersion: "v0.4.2",
|
||||
releaseConfig: {
|
||||
version: "0.4.2",
|
||||
mode: "ota",
|
||||
runtimeVersion: "0.4.1",
|
||||
channel: "production",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
triggerStoreBuilds: false,
|
||||
triggerOtaPublish: true,
|
||||
runtimeVersion: "0.4.1",
|
||||
channel: "production",
|
||||
releaseVersion: "0.4.2",
|
||||
})
|
||||
})
|
||||
|
||||
it("rejects a release config that does not match the release version", async () => {
|
||||
const { resolveMobileReleaseConfig } = await import("./resolve-mobile-release-config.mjs")
|
||||
|
||||
expect(() =>
|
||||
resolveMobileReleaseConfig({
|
||||
releaseVersion: "v0.4.4",
|
||||
releaseConfig: {
|
||||
version: "0.4.3",
|
||||
mode: "store",
|
||||
runtimeVersion: null,
|
||||
channel: null,
|
||||
},
|
||||
}),
|
||||
).toThrow(/does not match release version/i)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { pathToFileURL } from "node:url"
|
||||
|
||||
/**
|
||||
* @typedef {{
|
||||
* baseUrl: string
|
||||
* token: string
|
||||
* headerName: string
|
||||
* timeoutMs?: number
|
||||
* }} TriggerOtaSyncOptions
|
||||
*/
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 10_000
|
||||
|
||||
/**
|
||||
* @param {TriggerOtaSyncOptions} options
|
||||
*/
|
||||
export async function triggerOtaSync({
|
||||
baseUrl,
|
||||
token,
|
||||
headerName,
|
||||
timeoutMs = DEFAULT_TIMEOUT_MS,
|
||||
}) {
|
||||
if (!baseUrl) {
|
||||
throw new TypeError("OTA base URL is required")
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
throw new TypeError("OTA sync token is required")
|
||||
}
|
||||
|
||||
if (!headerName) {
|
||||
throw new TypeError("OTA sync header name is required")
|
||||
}
|
||||
|
||||
if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) {
|
||||
throw new TypeError("OTA sync timeout must be a positive integer")
|
||||
}
|
||||
|
||||
const normalizedBaseUrl = baseUrl.replace(/\/+$/, "")
|
||||
const controller = new AbortController()
|
||||
const timeoutError = new Error(`Timed out while triggering OTA sync after ${timeoutMs}ms`)
|
||||
const timeoutId = setTimeout(() => {
|
||||
controller.abort(timeoutError)
|
||||
}, timeoutMs)
|
||||
|
||||
try {
|
||||
const response = await fetch(`${normalizedBaseUrl}/internal/sync`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
[headerName]: token,
|
||||
},
|
||||
signal: controller.signal,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const responseText = await response.text()
|
||||
const detail = responseText ? `: ${responseText}` : ""
|
||||
|
||||
throw new Error(
|
||||
`Failed to trigger OTA sync (${response.status} ${response.statusText})${detail}`,
|
||||
)
|
||||
}
|
||||
|
||||
return response
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted && controller.signal.reason === timeoutError) {
|
||||
throw timeoutError
|
||||
}
|
||||
|
||||
throw error
|
||||
} finally {
|
||||
clearTimeout(timeoutId)
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
await triggerOtaSync({
|
||||
baseUrl: process.env.OTA_BASE_URL ?? "",
|
||||
token: process.env.OTA_SYNC_TOKEN ?? "",
|
||||
headerName: process.env.OTA_SYNC_TOKEN_HEADER ?? "",
|
||||
})
|
||||
|
||||
console.info("Triggered OTA sync successfully")
|
||||
} catch (error) {
|
||||
console.error(error instanceof Error ? error.message : String(error))
|
||||
process.exitCode = 1
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
await main()
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { createServer } from "node:http"
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest"
|
||||
|
||||
const activeServers = new Set<ReturnType<typeof createServer>>()
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
Array.from(
|
||||
activeServers,
|
||||
(server) =>
|
||||
new Promise<void>((resolve, reject) => {
|
||||
server.close((error) => {
|
||||
if (error) {
|
||||
reject(error)
|
||||
return
|
||||
}
|
||||
|
||||
resolve()
|
||||
})
|
||||
}),
|
||||
),
|
||||
)
|
||||
activeServers.clear()
|
||||
})
|
||||
|
||||
describe("triggerOtaSync", () => {
|
||||
it("POSTs to /internal/sync with the configured auth header", async () => {
|
||||
const requests: Array<{ method?: string; url?: string; headerValue?: string }> = []
|
||||
const headerName = "x-ota-sync-token"
|
||||
const token = "sync-token-value"
|
||||
|
||||
const server = createServer((request, response) => {
|
||||
requests.push({
|
||||
method: request.method,
|
||||
url: request.url,
|
||||
headerValue: request.headers[headerName],
|
||||
})
|
||||
|
||||
response.writeHead(204)
|
||||
response.end()
|
||||
})
|
||||
|
||||
activeServers.add(server)
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject)
|
||||
server.listen(0, "127.0.0.1", resolve)
|
||||
})
|
||||
|
||||
const address = server.address()
|
||||
if (!address || typeof address === "string") {
|
||||
throw new TypeError("Expected the test server to bind to an ephemeral TCP port")
|
||||
}
|
||||
|
||||
const { triggerOtaSync } = await import("./trigger-ota-sync.mjs")
|
||||
|
||||
await triggerOtaSync({
|
||||
baseUrl: `http://127.0.0.1:${address.port}`,
|
||||
token,
|
||||
headerName,
|
||||
})
|
||||
|
||||
expect(requests).toEqual([
|
||||
{
|
||||
method: "POST",
|
||||
url: "/internal/sync",
|
||||
headerValue: token,
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it("throws when the sync endpoint responds with a non-OK status", async () => {
|
||||
const headerName = "x-ota-sync-token"
|
||||
const token = "sync-token-value"
|
||||
|
||||
const server = createServer((_request, response) => {
|
||||
response.writeHead(503, { "content-type": "text/plain" })
|
||||
response.end("service unavailable")
|
||||
})
|
||||
|
||||
activeServers.add(server)
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject)
|
||||
server.listen(0, "127.0.0.1", resolve)
|
||||
})
|
||||
|
||||
const address = server.address()
|
||||
if (!address || typeof address === "string") {
|
||||
throw new TypeError("Expected the test server to bind to an ephemeral TCP port")
|
||||
}
|
||||
|
||||
const { triggerOtaSync } = await import("./trigger-ota-sync.mjs")
|
||||
|
||||
await expect(
|
||||
triggerOtaSync({
|
||||
baseUrl: `http://127.0.0.1:${address.port}`,
|
||||
token,
|
||||
headerName,
|
||||
}),
|
||||
).rejects.toThrow("Failed to trigger OTA sync (503 Service Unavailable): service unavailable")
|
||||
})
|
||||
|
||||
it("aborts the request when the timeout is exceeded", async () => {
|
||||
const headerName = "x-ota-sync-token"
|
||||
const token = "sync-token-value"
|
||||
|
||||
const server = createServer((_request, _response) => {
|
||||
// Intentionally never respond so the client must rely on the timeout.
|
||||
})
|
||||
|
||||
activeServers.add(server)
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject)
|
||||
server.listen(0, "127.0.0.1", resolve)
|
||||
})
|
||||
|
||||
const address = server.address()
|
||||
if (!address || typeof address === "string") {
|
||||
throw new TypeError("Expected the test server to bind to an ephemeral TCP port")
|
||||
}
|
||||
|
||||
const { triggerOtaSync } = await import("./trigger-ota-sync.mjs")
|
||||
|
||||
await expect(
|
||||
triggerOtaSync({
|
||||
baseUrl: `http://127.0.0.1:${address.port}`,
|
||||
token,
|
||||
headerName,
|
||||
timeoutMs: 25,
|
||||
}),
|
||||
).rejects.toThrow("Timed out while triggering OTA sync after 25ms")
|
||||
})
|
||||
})
|
||||
Executable
+98
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
pkg_path="${1:-}"
|
||||
|
||||
if [[ -z "$pkg_path" ]]; then
|
||||
echo "Usage: $0 <pkg-path>" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ ! -f "$pkg_path" ]]; then
|
||||
echo "Mac App Store package not found: $pkg_path" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! command -v xcrun >/dev/null 2>&1; then
|
||||
echo "xcrun is required to upload a Mac App Store package." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
upload_cmd=(
|
||||
xcrun
|
||||
altool
|
||||
--upload-package
|
||||
"$pkg_path"
|
||||
--wait
|
||||
--show-progress
|
||||
--output-format
|
||||
json
|
||||
)
|
||||
|
||||
if [[ -z "${APPLE_ID:-}" || -z "${APPLE_PASSWORD:-}" ]]; then
|
||||
echo "APPLE_ID and APPLE_PASSWORD must be set." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
upload_cmd+=(
|
||||
-u
|
||||
"$APPLE_ID"
|
||||
-p
|
||||
"@env:APPLE_PASSWORD"
|
||||
)
|
||||
|
||||
run_upload() {
|
||||
local output
|
||||
local exit_code
|
||||
|
||||
set +e
|
||||
output="$("${upload_cmd[@]}" 2>&1)"
|
||||
exit_code=$?
|
||||
set -e
|
||||
|
||||
printf '%s\n' "$output"
|
||||
return "$exit_code"
|
||||
}
|
||||
|
||||
echo "Uploading Mac App Store package with Apple ID: ${pkg_path}"
|
||||
if run_upload; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Upload failed without provider selection. Checking App Store Connect providers..."
|
||||
set +e
|
||||
providers_output="$(
|
||||
xcrun altool --list-providers -u "$APPLE_ID" -p "@env:APPLE_PASSWORD" 2>&1
|
||||
)"
|
||||
providers_exit=$?
|
||||
set -e
|
||||
|
||||
printf '%s\n' "$providers_output"
|
||||
|
||||
if [[ $providers_exit -ne 0 ]]; then
|
||||
echo "Failed to list providers after upload failure." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mapfile -t provider_ids < <(
|
||||
printf '%s\n' "$providers_output" \
|
||||
| perl -ne 'print "$1\n" if /publicid[^[:alnum:]]+([[:alnum:]-]+)/i' \
|
||||
| awk '!seen[$0]++'
|
||||
)
|
||||
|
||||
if [[ ${#provider_ids[@]} -ne 1 ]]; then
|
||||
cat >&2 <<'EOF'
|
||||
Unable to infer a single App Store Connect provider for this Apple ID.
|
||||
Use an Apple ID that only belongs to one provider, or upload once manually to confirm which provider should receive the build.
|
||||
EOF
|
||||
exit 1
|
||||
fi
|
||||
|
||||
upload_cmd+=(
|
||||
--provider-public-id
|
||||
"${provider_ids[0]}"
|
||||
)
|
||||
|
||||
echo "Retrying upload with detected provider: ${provider_ids[0]}"
|
||||
run_upload
|
||||
@@ -46,7 +46,7 @@ jobs:
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: 📦 Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
uses: pnpm/action-setup@v6
|
||||
|
||||
- name: 🏗 Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
@@ -61,7 +61,7 @@ jobs:
|
||||
distribution: "zulu"
|
||||
|
||||
- name: Setup Android SDK
|
||||
uses: android-actions/setup-android@v3
|
||||
uses: android-actions/setup-android@v4
|
||||
|
||||
- name: 📱 Setup EAS
|
||||
uses: expo/expo-github-action@v8
|
||||
@@ -75,6 +75,8 @@ jobs:
|
||||
- name: 🔨 Build Android app
|
||||
working-directory: apps/mobile
|
||||
run: eas build --platform android --profile ${{ github.event.inputs.profile || 'preview' }} --local --output=${{ github.workspace }}/build.${{ github.event.inputs.profile == 'production' && 'aab' || 'apk' }}
|
||||
env:
|
||||
EAS_NO_FROZEN_LOCKFILE: "1"
|
||||
|
||||
- name: 📤 Upload apk Artifact
|
||||
if: github.event.inputs.profile != 'production'
|
||||
@@ -126,7 +128,7 @@ jobs:
|
||||
|
||||
- name: Create Release Draft
|
||||
if: github.event.inputs.release == 'true'
|
||||
uses: softprops/action-gh-release@v2
|
||||
uses: softprops/action-gh-release@v3
|
||||
with:
|
||||
name: Mobile v${{ steps.version.outputs.APP_VERSION }}
|
||||
draft: true
|
||||
|
||||
@@ -17,6 +17,10 @@ on:
|
||||
store:
|
||||
type: boolean
|
||||
description: "Build for Mac App Store and Microsoft Store"
|
||||
upload_to_app_store:
|
||||
type: boolean
|
||||
description: "Upload the Mac App Store pkg to App Store Connect"
|
||||
default: true
|
||||
build_version:
|
||||
type: string
|
||||
description: "Build Version, only available when mas is true"
|
||||
@@ -68,7 +72,7 @@ jobs:
|
||||
lfs: true
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
uses: pnpm/action-setup@v6
|
||||
|
||||
- name: Use Node.js
|
||||
uses: actions/setup-node@v6
|
||||
@@ -210,6 +214,24 @@ jobs:
|
||||
apps/desktop/out/make/**/*.pkg
|
||||
retention-days: 90
|
||||
|
||||
- name: Upload Mac App Store package to App Store Connect
|
||||
if: runner.os == 'macOS' && github.event.inputs.store == 'true' && github.event.inputs.upload_to_app_store == 'true'
|
||||
env:
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
pkg_path="$(find apps/desktop/out/make -type f -name '*.pkg' | sort | head -n 1)"
|
||||
|
||||
if [ -z "$pkg_path" ]; then
|
||||
echo "No Mac App Store package found under apps/desktop/out/make" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
.github/scripts/upload-mas-pkg.sh "$pkg_path"
|
||||
|
||||
- name: Upload file (windows-x64-exe unsigned)
|
||||
uses: actions/upload-artifact@v7
|
||||
id: upload-unsigned-windows-x64-exe
|
||||
@@ -221,7 +243,7 @@ jobs:
|
||||
apps/desktop/out/make/**/latest.yml
|
||||
retention-days: 90
|
||||
|
||||
- uses: signpath/github-action-submit-signing-request@v2.0
|
||||
- uses: signpath/github-action-submit-signing-request@v2.1
|
||||
continue-on-error: true
|
||||
if: runner.os == 'windows' && env.RELEASE == 'true' && github.event.inputs.store != 'true'
|
||||
with:
|
||||
@@ -267,6 +289,47 @@ jobs:
|
||||
apps/desktop/out/make/**/latest-linux.yml
|
||||
retention-days: 90
|
||||
|
||||
- name: Prepare release assets for aggregation
|
||||
if: env.RELEASE == 'true'
|
||||
env:
|
||||
DESKTOP_RELEASE_ASSET_DIR: ${{ runner.temp }}/desktop-release-assets
|
||||
run: |
|
||||
node --input-type=module <<'EOF'
|
||||
import { cpSync, existsSync, mkdirSync, rmSync } from "node:fs"
|
||||
import { join } from "node:path"
|
||||
|
||||
const stageDir = process.env.DESKTOP_RELEASE_ASSET_DIR
|
||||
|
||||
if (!stageDir) {
|
||||
throw new Error("DESKTOP_RELEASE_ASSET_DIR is not set")
|
||||
}
|
||||
|
||||
rmSync(stageDir, { recursive: true, force: true })
|
||||
mkdirSync(join(stageDir, "apps", "desktop", "out"), { recursive: true })
|
||||
|
||||
const pathsToCopy = [
|
||||
["apps/desktop/out/make", join(stageDir, "apps", "desktop", "out", "make")],
|
||||
["apps/desktop/dist", join(stageDir, "apps", "desktop", "dist")],
|
||||
]
|
||||
|
||||
for (const [sourcePath, destinationPath] of pathsToCopy) {
|
||||
if (!existsSync(sourcePath)) {
|
||||
continue
|
||||
}
|
||||
|
||||
cpSync(sourcePath, destinationPath, { recursive: true })
|
||||
}
|
||||
EOF
|
||||
|
||||
- name: Upload release assets for aggregation
|
||||
if: env.RELEASE == 'true'
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: desktop-release-assets-${{ runner.os }}
|
||||
path: ${{ runner.temp }}/desktop-release-assets/apps
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
|
||||
- name: Generate artifact attestation
|
||||
if: env.RELEASE == 'true'
|
||||
continue-on-error: true
|
||||
@@ -281,21 +344,68 @@ jobs:
|
||||
apps/desktop/dist/manifest.yml
|
||||
apps/desktop/dist/*.tar.gz
|
||||
|
||||
publish-release:
|
||||
if: github.secret_source != 'None' && needs.release.result == 'success' && (github.event.inputs.tag_version == 'true' || github.ref_type == 'tag')
|
||||
needs: release
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
steps:
|
||||
- name: Check out Git repository Fully
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
lfs: true
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
|
||||
- name: Use Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
cache: "pnpm"
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm i
|
||||
|
||||
- name: Download release assets
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: desktop-release-assets-*
|
||||
path: .
|
||||
merge-multiple: true
|
||||
|
||||
- name: Ensure zstd
|
||||
shell: bash
|
||||
run: |
|
||||
if command -v zstd >/dev/null 2>&1; then
|
||||
zstd --version
|
||||
exit 0
|
||||
fi
|
||||
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y zstd
|
||||
|
||||
- name: Build desktop OTA release assets
|
||||
env:
|
||||
OTA_PRODUCT: desktop
|
||||
run: node .github/scripts/build-ota-release.mjs
|
||||
|
||||
- run: npx changelogithub
|
||||
if: env.RELEASE == 'true'
|
||||
continue-on-error: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
- name: Setup Version
|
||||
if: env.RELEASE == 'true'
|
||||
id: version
|
||||
uses: ./.github/actions/setup-version
|
||||
with:
|
||||
type: "desktop"
|
||||
|
||||
- name: Prepare Release Notes
|
||||
if: env.RELEASE == 'true'
|
||||
id: release_notes
|
||||
shell: bash
|
||||
run: |
|
||||
@@ -315,20 +425,39 @@ jobs:
|
||||
|
||||
echo "body_path=${release_notes_file}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Prepare release files
|
||||
id: release_files
|
||||
shell: bash
|
||||
run: |
|
||||
release_files="$RUNNER_TEMP/desktop-release-files.txt"
|
||||
|
||||
cat <<'EOF' > "$release_files"
|
||||
apps/desktop/out/make/**/Folo-*.dmg
|
||||
apps/desktop/out/make/**/Folo-*.zip
|
||||
apps/desktop/out/make/**/Folo-*.exe
|
||||
apps/desktop/out/make/**/Folo-*.AppImage
|
||||
apps/desktop/out/make/**/*.yml
|
||||
apps/desktop/dist/manifest.yml
|
||||
apps/desktop/dist/*.tar.gz
|
||||
apps/desktop/dist/ota-release.json
|
||||
EOF
|
||||
|
||||
if [ -f apps/desktop/dist.tar.zst ]; then
|
||||
echo "apps/desktop/dist.tar.zst" >> "$release_files"
|
||||
fi
|
||||
|
||||
{
|
||||
echo "files<<EOF"
|
||||
cat "$release_files"
|
||||
echo "EOF"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Create Release Draft
|
||||
if: env.RELEASE == 'true'
|
||||
uses: softprops/action-gh-release@v2
|
||||
uses: softprops/action-gh-release@v3
|
||||
with:
|
||||
name: Desktop v${{ steps.version.outputs.APP_VERSION }}
|
||||
draft: false
|
||||
prerelease: true
|
||||
tag_name: desktop/v${{ steps.version.outputs.APP_VERSION }}
|
||||
body_path: ${{ steps.release_notes.outputs.body_path }}
|
||||
files: |
|
||||
apps/desktop/out/make/**/Folo-*.dmg
|
||||
apps/desktop/out/make/**/Folo-*.zip
|
||||
apps/desktop/out/make/**/Folo-*.exe
|
||||
apps/desktop/out/make/**/Folo-*.AppImage
|
||||
apps/desktop/out/make/**/*.yml
|
||||
apps/desktop/dist/manifest.yml
|
||||
apps/desktop/dist/*.tar.gz
|
||||
files: ${{ steps.release_files.outputs.files }}
|
||||
|
||||
@@ -55,6 +55,7 @@ jobs:
|
||||
working-directory: apps/mobile
|
||||
run: eas build --platform ios --profile development --non-interactive --local --output=./build.ipa
|
||||
env:
|
||||
EAS_NO_FROZEN_LOCKFILE: "1"
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.RN_SENTRY_AUTH_TOKEN }}
|
||||
CI: true
|
||||
|
||||
@@ -84,7 +85,7 @@ jobs:
|
||||
uses: ./.github/actions/setup-xcode
|
||||
|
||||
- name: 📦 Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
uses: pnpm/action-setup@v6
|
||||
|
||||
- name: 🏗 Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
@@ -105,6 +106,7 @@ jobs:
|
||||
working-directory: apps/mobile
|
||||
run: eas build --platform ios --profile development --non-interactive --local --output=./build.ipa
|
||||
env:
|
||||
EAS_NO_FROZEN_LOCKFILE: "1"
|
||||
CI: true
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.RN_SENTRY_AUTH_TOKEN }}
|
||||
# Optional: Upload artifact
|
||||
@@ -128,7 +130,7 @@ jobs:
|
||||
uses: ./.github/actions/setup-xcode
|
||||
|
||||
- name: 📦 Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
uses: pnpm/action-setup@v6
|
||||
|
||||
- name: 🏗 Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
@@ -149,6 +151,7 @@ jobs:
|
||||
working-directory: apps/mobile
|
||||
run: eas build --platform ios --profile ios-simulator --non-interactive --local --output=./build-simulator.ipa
|
||||
env:
|
||||
EAS_NO_FROZEN_LOCKFILE: "1"
|
||||
CI: true
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.RN_SENTRY_AUTH_TOKEN }}
|
||||
# Optional: Upload artifact
|
||||
|
||||
@@ -63,6 +63,7 @@ jobs:
|
||||
working-directory: apps/mobile
|
||||
run: eas build --platform ios --profile ${{ github.event.inputs.profile || 'preview' }} --non-interactive --local --output=./build.ipa
|
||||
env:
|
||||
EAS_NO_FROZEN_LOCKFILE: "1"
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.RN_SENTRY_AUTH_TOKEN }}
|
||||
CI: true
|
||||
|
||||
@@ -97,7 +98,7 @@ jobs:
|
||||
uses: ./.github/actions/setup-xcode
|
||||
|
||||
- name: 📦 Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
uses: pnpm/action-setup@v6
|
||||
|
||||
- name: 🏗 Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
@@ -118,6 +119,7 @@ jobs:
|
||||
working-directory: apps/mobile
|
||||
run: eas build --platform ios --profile ${{ github.event.inputs.profile || 'preview' }} --non-interactive --local --output=./build.ipa
|
||||
env:
|
||||
EAS_NO_FROZEN_LOCKFILE: "1"
|
||||
CI: true
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.RN_SENTRY_AUTH_TOKEN }}
|
||||
# Optional: Upload artifact
|
||||
|
||||
@@ -31,7 +31,7 @@ jobs:
|
||||
- name: Checkout LFS objects
|
||||
run: git lfs checkout
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: pnpm/action-setup@v6
|
||||
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v6
|
||||
|
||||
@@ -32,7 +32,7 @@ jobs:
|
||||
restore-keys: |
|
||||
${{ runner.os }}-turbo-
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: pnpm/action-setup@v6
|
||||
|
||||
- name: Use Node.js LTS
|
||||
uses: actions/setup-node@v6
|
||||
|
||||
@@ -36,7 +36,7 @@ jobs:
|
||||
restore-keys: |
|
||||
${{ runner.os }}-turbo-
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: pnpm/action-setup@v6
|
||||
|
||||
- name: Use Node.js LTS
|
||||
uses: actions/setup-node@v6
|
||||
|
||||
@@ -39,7 +39,7 @@ jobs:
|
||||
restore-keys: |
|
||||
${{ runner.os }}-turbo-
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: pnpm/action-setup@v6
|
||||
|
||||
- name: Use Node.js LTS
|
||||
uses: actions/setup-node@v6
|
||||
|
||||
@@ -36,7 +36,7 @@ jobs:
|
||||
- name: Checkout LFS objects
|
||||
run: git lfs checkout
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: pnpm/action-setup@v6
|
||||
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v6
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
name: 📡 Publish OTA Release
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
release_version:
|
||||
type: string
|
||||
required: true
|
||||
description: "Release version without the v prefix"
|
||||
runtime_version:
|
||||
type: string
|
||||
required: true
|
||||
description: "Expo runtime version for the OTA bundle"
|
||||
channel:
|
||||
type: choice
|
||||
required: true
|
||||
options:
|
||||
- production
|
||||
- preview
|
||||
description: "OTA channel embedded in ota-release.json"
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
if: github.secret_source != 'None'
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
OTA_PRODUCT: mobile
|
||||
OTA_RELEASE_VERSION: ${{ inputs.release_version }}
|
||||
OTA_RUNTIME_VERSION: ${{ inputs.runtime_version }}
|
||||
OTA_CHANNEL: ${{ inputs.channel }}
|
||||
OTA_GIT_TAG: mobile/v${{ inputs.release_version }}
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Resolve target release tag
|
||||
run: |
|
||||
git fetch --tags --force
|
||||
|
||||
if ! git rev-parse --verify "refs/tags/${OTA_GIT_TAG}" >/dev/null 2>&1; then
|
||||
echo "::error::Required release tag ${OTA_GIT_TAG} does not exist. Create it before publishing OTA assets."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
git checkout --detach "refs/tags/${OTA_GIT_TAG}"
|
||||
echo "Checked out ${OTA_GIT_TAG} at $(git rev-list -n 1 "refs/tags/${OTA_GIT_TAG}")"
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
cache: "pnpm"
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Export OTA bundle assets
|
||||
working-directory: apps/mobile
|
||||
run: pnpm run update:export
|
||||
|
||||
- name: Build OTA release bundle
|
||||
run: node .github/scripts/build-ota-release.mjs
|
||||
|
||||
- name: Publish GitHub release assets
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
tag_name="mobile/v${OTA_RELEASE_VERSION}"
|
||||
release_title="Mobile v${OTA_RELEASE_VERSION}"
|
||||
ota_files=("apps/mobile/dist/ota-release.json")
|
||||
|
||||
if [ -f "apps/mobile/dist.tar.zst" ]; then
|
||||
ota_files+=("apps/mobile/dist.tar.zst")
|
||||
fi
|
||||
|
||||
if gh release view "$tag_name" >/dev/null 2>&1; then
|
||||
gh release upload "$tag_name" "${ota_files[@]}" --clobber
|
||||
else
|
||||
gh release create "$tag_name" "${ota_files[@]}" \
|
||||
--verify-tag \
|
||||
--title "$release_title" \
|
||||
--notes "OTA release assets for the ${OTA_CHANNEL} channel."
|
||||
fi
|
||||
|
||||
- name: Trigger OTA sync
|
||||
env:
|
||||
OTA_BASE_URL: ${{ secrets.OTA_BASE_URL }}
|
||||
OTA_SYNC_TOKEN: ${{ secrets.OTA_SYNC_TOKEN }}
|
||||
OTA_SYNC_TOKEN_HEADER: ${{ secrets.OTA_SYNC_TOKEN_HEADER }}
|
||||
run: node .github/scripts/trigger-ota-sync.mjs
|
||||
@@ -17,7 +17,7 @@ jobs:
|
||||
|
||||
- name: Prepare prompt variables
|
||||
id: prepare_input
|
||||
uses: actions/github-script@v8
|
||||
uses: actions/github-script@v9
|
||||
with:
|
||||
script: |
|
||||
const issue = context.payload.issue || {};
|
||||
@@ -45,7 +45,7 @@ jobs:
|
||||
|
||||
- name: Prepare comment body
|
||||
id: prepare
|
||||
uses: actions/github-script@v8
|
||||
uses: actions/github-script@v9
|
||||
env:
|
||||
AI_RESPONSE: ${{ steps.inference.outputs.response }}
|
||||
with:
|
||||
@@ -93,7 +93,7 @@ jobs:
|
||||
|
||||
- name: Comment similar issues
|
||||
if: steps.prepare.outputs.has_matches == 'true'
|
||||
uses: actions/github-script@v8
|
||||
uses: actions/github-script@v9
|
||||
with:
|
||||
script: |
|
||||
const body = ${{ toJson(steps.prepare.outputs.comment_body) }};
|
||||
|
||||
+29
-15
@@ -8,6 +8,7 @@ on:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
sync-to-dev:
|
||||
@@ -16,20 +17,33 @@ jobs:
|
||||
(github.ref == 'refs/heads/main' && contains(github.event.head_commit.message || '', 'release(desktop):')) ||
|
||||
(github.ref == 'refs/heads/mobile-main' && contains(github.event.head_commit.message || '', 'release(mobile):'))
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Git
|
||||
run: |
|
||||
git config --global user.name "github-actions[bot]"
|
||||
git config --global user.email "github-actions[bot]@users.noreply.github.com"
|
||||
|
||||
- name: Merge source branch into dev
|
||||
- name: Create or update sync pull request
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
source_branch="${GITHUB_REF_NAME}"
|
||||
git fetch origin main mobile-main dev
|
||||
git checkout dev
|
||||
git merge --no-ff "origin/${source_branch}" -m "chore(sync): merge ${source_branch} into dev"
|
||||
git push origin dev
|
||||
title="chore(sync): merge ${source_branch} into dev"
|
||||
body=$(cat <<EOF
|
||||
This pull request was created automatically after a release branch update.
|
||||
|
||||
- Source branch: \`${source_branch}\`
|
||||
- Target branch: \`dev\`
|
||||
EOF
|
||||
)
|
||||
|
||||
pr_number="$(gh pr list --base dev --head "${source_branch}" --state open --json number --jq '.[0].number')"
|
||||
|
||||
if [ -z "${pr_number}" ]; then
|
||||
pr_url="$(gh pr create --base dev --head "${source_branch}" --title "${title}" --body "${body}")"
|
||||
pr_number="$(gh pr view "${pr_url}" --json number --jq '.number')"
|
||||
echo "Created sync PR: ${pr_url}"
|
||||
else
|
||||
gh pr edit "${pr_number}" --title "${title}" --body "${body}"
|
||||
echo "Updated existing sync PR: #${pr_number}"
|
||||
fi
|
||||
|
||||
if gh pr merge "${pr_number}" --auto --merge; then
|
||||
echo "Enabled auto-merge for sync PR #${pr_number}"
|
||||
else
|
||||
echo "Could not enable auto-merge for sync PR #${pr_number}. Merge it manually after required checks pass."
|
||||
fi
|
||||
|
||||
+50
-11
@@ -73,6 +73,18 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
if: needs.create_tag.outputs.platform == 'mobile' && needs.create_tag.outputs.ref_name == 'mobile-main'
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Resolve Mobile Release Config
|
||||
id: release_mode
|
||||
if: needs.create_tag.outputs.platform == 'mobile' && needs.create_tag.outputs.ref_name == 'mobile-main'
|
||||
env:
|
||||
RELEASE_VERSION: ${{ needs.create_tag.outputs.version }}
|
||||
RELEASE_CONFIG_PATH: apps/mobile/release.json
|
||||
run: node .github/scripts/resolve-mobile-release-config.mjs
|
||||
|
||||
- name: Checkout repository
|
||||
if: needs.create_tag.outputs.platform == 'desktop' && needs.create_tag.outputs.ref_name == 'main'
|
||||
uses: actions/checkout@v6
|
||||
@@ -86,8 +98,16 @@ jobs:
|
||||
git config --global user.email "github-actions[bot]@users.noreply.github.com"
|
||||
|
||||
- name: Resolve desktop build version
|
||||
id: desktop_build_version
|
||||
if: needs.create_tag.outputs.platform == 'desktop' && needs.create_tag.outputs.ref_name == 'main'
|
||||
id: desktop_release_mode
|
||||
env:
|
||||
RELEASE_VERSION: ${{ needs.create_tag.outputs.version }}
|
||||
RELEASE_CONFIG_PATH: apps/desktop/release.json
|
||||
run: node .github/scripts/resolve-desktop-release-config.mjs
|
||||
|
||||
- name: Resolve desktop build version
|
||||
id: desktop_build_version
|
||||
if: needs.create_tag.outputs.platform == 'desktop' && needs.create_tag.outputs.ref_name == 'main' && steps.desktop_release_mode.outputs.triggerStoreBuilds == 'true'
|
||||
run: |
|
||||
git fetch --tags --force
|
||||
latest_tag="$(git tag -l 'desktop-build/v*' --sort=-v:refname | head -n 1)"
|
||||
@@ -111,8 +131,8 @@ jobs:
|
||||
echo "Desktop build version: ${next_build}"
|
||||
|
||||
- name: Trigger Desktop Tag Version Build
|
||||
if: needs.create_tag.outputs.platform == 'desktop' && needs.create_tag.outputs.ref_name == 'main'
|
||||
uses: actions/github-script@v8
|
||||
if: needs.create_tag.outputs.platform == 'desktop' && needs.create_tag.outputs.ref_name == 'main' && steps.desktop_release_mode.outputs.triggerDirectBuild == 'true'
|
||||
uses: actions/github-script@v9
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
script: |
|
||||
@@ -129,8 +149,8 @@ jobs:
|
||||
console.log('Desktop Tag Version build triggered successfully');
|
||||
|
||||
- name: Trigger Desktop Store Build
|
||||
if: needs.create_tag.outputs.platform == 'desktop' && needs.create_tag.outputs.ref_name == 'main'
|
||||
uses: actions/github-script@v8
|
||||
if: needs.create_tag.outputs.platform == 'desktop' && needs.create_tag.outputs.ref_name == 'main' && steps.desktop_release_mode.outputs.triggerStoreBuilds == 'true'
|
||||
uses: actions/github-script@v9
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
script: |
|
||||
@@ -148,8 +168,8 @@ jobs:
|
||||
console.log('Desktop store build triggered successfully');
|
||||
|
||||
- name: Trigger Mobile Preview Release Build
|
||||
if: needs.create_tag.outputs.platform == 'mobile' && needs.create_tag.outputs.ref_name == 'mobile-main'
|
||||
uses: actions/github-script@v8
|
||||
if: needs.create_tag.outputs.platform == 'mobile' && needs.create_tag.outputs.ref_name == 'mobile-main' && steps.release_mode.outputs.trigger_store_builds == 'true'
|
||||
uses: actions/github-script@v9
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
script: |
|
||||
@@ -166,8 +186,8 @@ jobs:
|
||||
console.log('Mobile preview release build triggered successfully');
|
||||
|
||||
- name: Trigger Mobile Production Android Build
|
||||
if: needs.create_tag.outputs.platform == 'mobile' && needs.create_tag.outputs.ref_name == 'mobile-main'
|
||||
uses: actions/github-script@v8
|
||||
if: needs.create_tag.outputs.platform == 'mobile' && needs.create_tag.outputs.ref_name == 'mobile-main' && steps.release_mode.outputs.trigger_store_builds == 'true'
|
||||
uses: actions/github-script@v9
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
script: |
|
||||
@@ -184,8 +204,8 @@ jobs:
|
||||
console.log('Mobile production Android build triggered successfully');
|
||||
|
||||
- name: Trigger Mobile Production iOS Build
|
||||
if: needs.create_tag.outputs.platform == 'mobile' && needs.create_tag.outputs.ref_name == 'mobile-main'
|
||||
uses: actions/github-script@v8
|
||||
if: needs.create_tag.outputs.platform == 'mobile' && needs.create_tag.outputs.ref_name == 'mobile-main' && steps.release_mode.outputs.trigger_store_builds == 'true'
|
||||
uses: actions/github-script@v9
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
script: |
|
||||
@@ -199,3 +219,22 @@ jobs:
|
||||
}
|
||||
});
|
||||
console.log('Mobile production iOS build triggered successfully');
|
||||
|
||||
- name: Trigger Mobile OTA Publish
|
||||
if: needs.create_tag.outputs.platform == 'mobile' && needs.create_tag.outputs.ref_name == 'mobile-main' && steps.release_mode.outputs.trigger_ota_publish == 'true'
|
||||
uses: actions/github-script@v9
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
script: |
|
||||
await github.rest.actions.createWorkflowDispatch({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
workflow_id: 'publish-ota.yml',
|
||||
ref: '${{ needs.create_tag.outputs.tag_version }}',
|
||||
inputs: {
|
||||
release_version: '${{ steps.release_mode.outputs.release_version }}',
|
||||
runtime_version: '${{ steps.release_mode.outputs.runtime_version }}',
|
||||
channel: '${{ steps.release_mode.outputs.channel }}'
|
||||
}
|
||||
});
|
||||
console.log('Mobile OTA publish workflow triggered successfully');
|
||||
|
||||
@@ -15,12 +15,14 @@
|
||||
<a href="https://status.follow.is/" target="_blank"><img src="https://status.follow.is/api/badge/18/uptime?color=%2344CC10&labelColor=black&style=flat-square"/></a>
|
||||
<a href="https://github.com/RSSNext/Folo/releases"><img src="https://img.shields.io/github/downloads/RSSNext/Folo/total?color=369eff&labelColor=black&logo=github&style=flat-square&label=Downloads" /></a>
|
||||
<a href="https://x.com/intent/follow?screen_name=folo_is"><img src="https://img.shields.io/badge/Follow-blue?color=1d9bf0&logo=x&labelColor=black&style=flat-square" /></a>
|
||||
<a href="https://discord.gg/AwWcAQ7euc" target="_blank"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fdiscord.com%2Fapi%2Finvites%2Ffollowapp%3Fwith_counts%3Dtrue&query=approximate_member_count&color=5865F2&label=Discord&labelColor=black&logo=discord&logoColor=white&style=flat-square"/></a>
|
||||
<a href="https://discord.gg/AwWcAQ7euc" target="_blank"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fdiscord.com%2Fapi%2Finvites%2FAwWcAQ7euc%3Fwith_counts%3Dtrue&query=approximate_member_count&color=5865F2&label=Discord&labelColor=black&logo=discord&logoColor=white&style=flat-square"/></a>
|
||||
<br />
|
||||
<a href="https://apps.apple.com/us/app/folo-follow-everything/id6739802604"><img src="https://img.shields.io/itunes/v/6739802604?style=flat-square&logo=apple&label=App%20Store&color=FF5C00&labelColor=black" /></a>
|
||||
<a href="https://play.google.com/store/apps/details?id=is.follow" target="_blank"><img src="https://img.shields.io/endpoint?url=https%3A%2F%2Fplay.cuzi.workers.dev%2Fplay%3Fi%3Dis.follow%26gl%3DUS%26hl%3Den%26l%3DAndroid%26m%3D%24version&style=flat-square&logo=google-play&label=Google%20Play&labelColor=black&color=FF5C00"/></a>
|
||||
<a href="https://apps.apple.com/us/app/folo-follow-everything/id6739802604"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fapi.folo.is%2Fupdates%2Fdistribution%2Fmas&query=data.storeVersion&prefix=v&style=flat-square&logo=apple&label=Mac%20App%20Store&labelColor=black&color=FF5C00&cacheSeconds=3600" /></a>
|
||||
<a href="https://apps.microsoft.com/detail/9nvfzpv0v0ht?mode=direct"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fapi.folo.is%2Fupdates%2Fdistribution%2Fmss&query=data.storeVersion&style=flat-square&logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIj48cGF0aCBmaWxsPSIjZmZmIiBkPSJNMyAzaDguNTN2OC41M0gzek0xMi40NjkgM2g4LjUzdjguNTNoLTguNTN6TTMgMTIuNDdoOC41M1YyMUgzek0xMi40NjkgMTIuNDdoOC41M1YyMWgtOC41M3oiLz48L3N2Zz4%3D&logoColor=white&label=Microsoft%20Store&labelColor=black&color=FF5C00&cacheSeconds=3600&prefix=v" /></a>
|
||||
<a href="https://apps.apple.com/us/app/folo-follow-everything/id6739802604"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fota.folo.is%2Fversions&query=%24.store.mobile.ios.version&prefix=v&style=flat-square&logo=apple&label=App%20Store&color=FF5C00&labelColor=black&cacheSeconds=600" /></a>
|
||||
<a href="https://play.google.com/store/apps/details?id=is.follow" target="_blank"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fota.folo.is%2Fversions&query=%24.store.mobile.android.version&prefix=v&style=flat-square&logo=google-play&label=Google%20Play&labelColor=black&color=FF5C00&cacheSeconds=600"/></a>
|
||||
<a href="https://apps.apple.com/us/app/folo-follow-everything/id6739802604"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fota.folo.is%2Fversions&query=%24.store.desktop.mas.version&prefix=v&style=flat-square&logo=apple&label=Mac%20App%20Store&labelColor=black&color=FF5C00&cacheSeconds=600" /></a>
|
||||
<a href="https://apps.microsoft.com/detail/9nvfzpv0v0ht?mode=direct"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fota.folo.is%2Fversions&query=%24.store.desktop.mss.version&prefix=v&style=flat-square&logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIj48cGF0aCBmaWxsPSIjZmZmIiBkPSJNMyAzaDguNTN2OC41M0gzek0xMi40NjkgM2g4LjUzdjguNTNoLTguNTN6TTMgMTIuNDdoOC41M1YyMUgzek0xMi40NjkgMTIuNDdoOC41M1YyMWgtOC41M3oiLz48L3N2Zz4%3D&logoColor=white&label=Microsoft%20Store&labelColor=black&color=FF5C00&cacheSeconds=600" /></a>
|
||||
<a href="https://github.com/RSSNext/Folo/releases"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fota.folo.is%2Fversions&query=%24.github.mobile.version&prefix=v&style=flat-square&logo=github&label=Mobile&labelColor=black&color=FF5C00&cacheSeconds=600" /></a>
|
||||
<a href="https://github.com/RSSNext/Folo/releases"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fota.folo.is%2Fversions&query=%24.github.desktop.version&prefix=v&style=flat-square&logo=github&label=Desktop&labelColor=black&color=FF5C00&cacheSeconds=600" /></a>
|
||||
<br />
|
||||
<br />
|
||||
<!-- <a href="https://github.com/RSSNext/Folo" target="_blank"><img src="https://github.com/user-attachments/assets/59b957fb-59ed-4ef0-994e-f6a402a6fe2b" alt="GitHub Trending" height="55"/></a>
|
||||
@@ -42,14 +44,14 @@ Whether for users or professional developers, Folo will be your open information
|
||||
|
||||
Feel free to try it using the following methods:
|
||||
|
||||
| Operating System | Source |
|
||||
| :--------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| Any | <a href="https://app.folo.is" target="_blank"><img src="https://github.com/user-attachments/assets/51ef7800-b683-4493-83e8-eb4752366997" alt="Browser" height="55"/></a> |
|
||||
| iOS | <a href="https://apps.apple.com/us/app/folo-follow-everything/id6739802604" target="_blank"><img src="https://github.com/user-attachments/assets/a94d8698-2a11-4f43-9b0a-b756b17b61f7" alt="App Store" height="55"/></a> |
|
||||
| Android | <a href="https://play.google.com/store/apps/details?id=is.follow" target="_blank"><img src="https://github.com/user-attachments/assets/0d178e0b-3ace-4f75-bbde-ab3c0a416ce8" alt="Google Play" height="55"/></a> <a href="https://github.com/RSSNext/Folo/releases/latest" target="_blank"><img src="https://github.com/user-attachments/assets/cf61e197-d756-4606-a8ad-fb591f79fdfc" alt="App Store" height="55"/></a> |
|
||||
| macOS | <a href="https://apps.apple.com/us/app/folo-follow-everything/id6739802604" target="_blank"><img src="https://github.com/user-attachments/assets/0d47f902-7fa3-494e-ad28-9ab11af5e6d4" alt="Microsoft Store" height="55"/></a> <a href="https://github.com/RSSNext/Folo/releases/latest" target="_blank"><img src="https://github.com/user-attachments/assets/cf61e197-d756-4606-a8ad-fb591f79fdfc" alt="App Store" height="55"/></a> |
|
||||
| Windows | <a href="https://apps.microsoft.com/detail/9nvfzpv0v0ht?mode=direct" target="_blank"><img src="https://github.com/user-attachments/assets/b3112bab-9dd0-4893-9488-890dcb368f70" alt="Microsoft Store" height="55"/></a> <a href="https://github.com/RSSNext/Folo/releases/latest" target="_blank"><img src="https://github.com/user-attachments/assets/cf61e197-d756-4606-a8ad-fb591f79fdfc" alt="App Store" height="55"/></a> |
|
||||
| Linux | <a href="https://github.com/RSSNext/Folo/releases/latest" target="_blank"><img src="https://github.com/user-attachments/assets/cf61e197-d756-4606-a8ad-fb591f79fdfc" alt="App Store" height="55"/></a> |
|
||||
| Operating System | Source |
|
||||
| :--------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Any | <a href="https://app.folo.is" target="_blank"><img src="https://github.com/user-attachments/assets/51ef7800-b683-4493-83e8-eb4752366997" alt="Browser" height="55"/></a> |
|
||||
| iOS | <a href="https://apps.apple.com/us/app/folo-follow-everything/id6739802604" target="_blank"><img src="https://github.com/user-attachments/assets/a94d8698-2a11-4f43-9b0a-b756b17b61f7" alt="App Store" height="55"/></a> |
|
||||
| Android | <a href="https://play.google.com/store/apps/details?id=is.follow" target="_blank"><img src="https://github.com/user-attachments/assets/0d178e0b-3ace-4f75-bbde-ab3c0a416ce8" alt="Google Play" height="55"/></a> <a href="https://github.com/RSSNext/Folo/releases/latest" target="_blank"><img src="https://github.com/user-attachments/assets/cf61e197-d756-4606-a8ad-fb591f79fdfc" alt="App Store" height="55"/></a> |
|
||||
| macOS | <a href="https://apps.apple.com/us/app/folo-follow-everything/id6739802604" target="_blank"><img src="https://github.com/user-attachments/assets/d8f8c877-4b1d-4a95-b400-30afe45d970e" alt="Mac App Store" height="55"/></a> <a href="https://github.com/RSSNext/Folo/releases/latest" target="_blank"><img src="https://github.com/user-attachments/assets/cf61e197-d756-4606-a8ad-fb591f79fdfc" alt="App Store" height="55"/></a> |
|
||||
| Windows | <a href="https://apps.microsoft.com/detail/9nvfzpv0v0ht?mode=direct" target="_blank"><img src="https://github.com/user-attachments/assets/f689d2dc-010d-432b-909e-99ab344ddbda" alt="Microsoft Store" height="55"/></a> <a href="https://github.com/RSSNext/Folo/releases/latest" target="_blank"><img src="https://github.com/user-attachments/assets/cf61e197-d756-4606-a8ad-fb591f79fdfc" alt="App Store" height="55"/></a> |
|
||||
| Linux | <a href="https://github.com/RSSNext/Folo/releases/latest" target="_blank"><img src="https://github.com/user-attachments/assets/cf61e197-d756-4606-a8ad-fb591f79fdfc" alt="App Store" height="55"/></a> |
|
||||
|
||||
You can also install using the following methods maintained by our community:
|
||||
|
||||
@@ -58,9 +60,9 @@ You can also install using the following methods maintained by our community:
|
||||
- If you are using macOS with [Homebrew](https://brew.sh), you can install the cask [folo](https://formulae.brew.sh/cask/folo) that is maintained by [realSunyz](https://github.com/realSunyz).
|
||||
- If you are using Windows with [Scoop](https://scoop.sh), you can install the manifest [folo](https://github.com/cscnk52/cetacea/blob/master/bucket/folo.json) that is maintained by [cscnk52](https://github.com/cscnk52).
|
||||
|
||||
| [](https://discord.gg/AwWcAQ7euc) | Join our Discord server to connect with developers, request features, and receive support. |
|
||||
| :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------- |
|
||||
| [](https://x.com/intent/follow?screen_name=folo_is) | Follow us on X/Twitter for product updates and to join in on reward activities. |
|
||||
| [](https://discord.gg/AwWcAQ7euc) | Join our Discord server to connect with developers, request features, and receive support. |
|
||||
| :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------- |
|
||||
| [](https://x.com/intent/follow?screen_name=folo_is) | Follow us on X/Twitter for product updates and to join in on reward activities. |
|
||||
|
||||
> \[!IMPORTANT]
|
||||
>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "folocli",
|
||||
"type": "module",
|
||||
"version": "0.0.4",
|
||||
"version": "0.0.5",
|
||||
"description": "Folo CLI for terminal workflows and automation",
|
||||
"author": "Folo Team",
|
||||
"license": "AGPL-3.0-only",
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import { Agent, request } from "node:http"
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest"
|
||||
|
||||
import { DEFAULT_VALUES } from "../../../packages/internal/shared/src/env.common"
|
||||
import { resolveBrowserLoginToken, resolveCLILoginUrl } from "./browser-login"
|
||||
import { loginWithBrowser, resolveBrowserLoginToken, resolveCLILoginUrl } from "./browser-login"
|
||||
import { CLIError } from "./output"
|
||||
|
||||
vi.mock("node:child_process", () => ({
|
||||
spawnSync: vi.fn(() => ({ status: 0 })),
|
||||
}))
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
@@ -52,6 +58,91 @@ describe("browser login helpers", () => {
|
||||
)
|
||||
})
|
||||
|
||||
it("resolves browser login without waiting on a kept-alive callback socket", async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
session: { token: "session-token" },
|
||||
user: { id: "user-1" },
|
||||
}),
|
||||
{
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
},
|
||||
),
|
||||
)
|
||||
vi.stubGlobal("fetch", fetchMock)
|
||||
|
||||
let loginUrl: string | undefined
|
||||
const loginPromise = loginWithBrowser({
|
||||
apiUrl: DEFAULT_VALUES.PROD.API_URL,
|
||||
timeoutMs: 1_000,
|
||||
onStatus: (message) => {
|
||||
const prefix = "Open this URL to sign in: "
|
||||
if (message.startsWith(prefix)) {
|
||||
loginUrl = message.slice(prefix.length)
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(loginUrl).toBeTruthy()
|
||||
})
|
||||
|
||||
const callbackUrl = new URL(loginUrl!).searchParams.get("cli_callback")
|
||||
expect(callbackUrl).toBeTruthy()
|
||||
|
||||
const callbackRequestUrl = new URL(callbackUrl!)
|
||||
callbackRequestUrl.searchParams.set("token", "one-time-token")
|
||||
|
||||
const agent = new Agent({ keepAlive: true })
|
||||
|
||||
try {
|
||||
const response = await new Promise<{ body: string; connectionHeader?: string }>(
|
||||
(resolve, reject) => {
|
||||
const req = request(
|
||||
callbackRequestUrl,
|
||||
{
|
||||
agent,
|
||||
headers: {
|
||||
Connection: "keep-alive",
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
let body = ""
|
||||
res.setEncoding("utf8")
|
||||
res.on("data", (chunk) => {
|
||||
body += chunk
|
||||
})
|
||||
res.on("end", () => {
|
||||
const connectionHeader = Array.isArray(res.headers.connection)
|
||||
? res.headers.connection[0]
|
||||
: res.headers.connection
|
||||
resolve({ body, connectionHeader })
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
req.on("error", reject)
|
||||
req.end()
|
||||
},
|
||||
)
|
||||
|
||||
expect(response.body).toContain("Folo CLI login complete")
|
||||
expect(response.connectionHeader).toBe("close")
|
||||
|
||||
await expect(loginPromise).resolves.toEqual(
|
||||
expect.objectContaining({
|
||||
token: "session-token",
|
||||
callbackUrl,
|
||||
loginUrl,
|
||||
}),
|
||||
)
|
||||
} finally {
|
||||
agent.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
it("exchanges one-time token for a session token", async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValueOnce(
|
||||
new Response(
|
||||
|
||||
@@ -308,6 +308,7 @@ export const loginWithBrowser = async (
|
||||
server.close(() => {
|
||||
handler()
|
||||
})
|
||||
server.closeIdleConnections?.()
|
||||
}
|
||||
|
||||
const server = createServer((req, res) => {
|
||||
@@ -316,6 +317,9 @@ export const loginWithBrowser = async (
|
||||
`http://${req.headers.host ?? LOCAL_CALLBACK_HOST}`,
|
||||
)
|
||||
|
||||
res.shouldKeepAlive = false
|
||||
res.setHeader("connection", "close")
|
||||
|
||||
if (requestUrl.pathname !== LOCAL_CALLBACK_PATH) {
|
||||
res.statusCode = 404
|
||||
res.end("Not Found")
|
||||
|
||||
@@ -11,7 +11,12 @@ export default defineConfig({
|
||||
"pnpm prettier --ignore-unknown --write package.json",
|
||||
"git add package.json",
|
||||
],
|
||||
trailing: ["git checkout -b release/desktop/${NEW_VERSION}"],
|
||||
trailing: [
|
||||
"tsx scripts/apply-release-config.ts ${NEW_VERSION}",
|
||||
"git add package.json",
|
||||
"git add release.json release-plan.json",
|
||||
"git checkout -b release/desktop/${NEW_VERSION}",
|
||||
],
|
||||
finally: [
|
||||
"git push origin release/desktop/${NEW_VERSION}",
|
||||
"gh pr create --title 'release(desktop): Release v${NEW_VERSION}' --body 'v${NEW_VERSION}' --base main --head release/desktop/${NEW_VERSION}",
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# What's new in v1.6.0
|
||||
|
||||
## Shiny new things
|
||||
|
||||
- Added Spotlight settings with refined highlighting controls
|
||||
- Unified desktop updates with the OTA service for more consistent delivery
|
||||
|
||||
## Improvements
|
||||
|
||||
- Moved desktop text-to-speech playback to the Folo service
|
||||
- Improved update compatibility handling and release metadata generation
|
||||
|
||||
## No longer broken
|
||||
|
||||
- Fixed regressions in desktop update and release flows
|
||||
- Fixed PDF export layout and branding
|
||||
- Fixed future credit reset dates in AI chat
|
||||
- Fixed PlayerProgress switching to hour formatting too late
|
||||
|
||||
## Thanks
|
||||
|
||||
Special thanks to volunteer contributor @kuishou68 for their valuable contribution
|
||||
@@ -43,7 +43,6 @@
|
||||
"ky": "1.14.3",
|
||||
"linkedom": "0.18.12",
|
||||
"lowdb": "7.0.1",
|
||||
"msedge-tts": "2.0.4",
|
||||
"node-machine-id": "1.1.12",
|
||||
"ofetch": "1.5.1",
|
||||
"pathe": "2.0.3",
|
||||
|
||||
@@ -5,13 +5,12 @@ import { readability } from "@follow-app/readability"
|
||||
import { app, BrowserWindow } from "electron"
|
||||
import type { IpcContext } from "electron-ipc-decorator"
|
||||
import { IpcMethod, IpcService } from "electron-ipc-decorator"
|
||||
import { MsEdgeTTS, OUTPUT_FORMAT } from "msedge-tts"
|
||||
import path from "pathe"
|
||||
import type { ModelResult } from "vscode-languagedetection"
|
||||
|
||||
import { detectCodeStringLanguage } from "../../modules/language-detection"
|
||||
|
||||
const tts = new MsEdgeTTS()
|
||||
const TTS_SERVICE_URL = "https://tts.folo.is"
|
||||
|
||||
interface ReadabilityInput {
|
||||
url: string
|
||||
@@ -21,13 +20,56 @@ interface ReadabilityInput {
|
||||
interface TtsInput {
|
||||
id: string
|
||||
text: string
|
||||
voice: string
|
||||
voice?: string
|
||||
}
|
||||
|
||||
interface DetectCodeStringLanguageInput {
|
||||
codeString: string
|
||||
}
|
||||
|
||||
interface TtsErrorResponse {
|
||||
error?: {
|
||||
message?: string
|
||||
}
|
||||
}
|
||||
|
||||
interface TtsVoiceResponse {
|
||||
voices: Array<{
|
||||
FriendlyName: string
|
||||
Gender: string
|
||||
Locale: string
|
||||
ShortName: string
|
||||
}>
|
||||
}
|
||||
|
||||
const readTtsErrorMessage = async (response: Response) => {
|
||||
try {
|
||||
const data = (await response.clone().json()) as TtsErrorResponse
|
||||
return data.error?.message || "TTS request failed"
|
||||
} catch {
|
||||
return "TTS request failed"
|
||||
}
|
||||
}
|
||||
|
||||
const showReaderToastError = (
|
||||
window: BrowserWindow | null,
|
||||
error: unknown,
|
||||
fallbackMessage: string,
|
||||
) => {
|
||||
if (!window) return
|
||||
|
||||
if (error instanceof Error) {
|
||||
void callWindowExpose(window).toast.error(error.message, {
|
||||
duration: 1000,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
void callWindowExpose(window).toast.error(fallbackMessage, {
|
||||
duration: 1000,
|
||||
})
|
||||
}
|
||||
|
||||
export class ReaderService extends IpcService {
|
||||
static override readonly groupName = "reader"
|
||||
|
||||
@@ -45,7 +87,10 @@ export class ReaderService extends IpcService {
|
||||
|
||||
@IpcMethod()
|
||||
async tts(context: IpcContext, input: TtsInput): Promise<string | null> {
|
||||
const { id, text, voice } = input
|
||||
const { id } = input
|
||||
const text = input.text.trim()
|
||||
const voice = input.voice?.trim()
|
||||
|
||||
if (!text) {
|
||||
return null
|
||||
}
|
||||
@@ -53,33 +98,35 @@ export class ReaderService extends IpcService {
|
||||
const window = BrowserWindow.fromWebContents(context.sender)
|
||||
if (!window) return null
|
||||
|
||||
try {
|
||||
await tts.setMetadata(voice, OUTPUT_FORMAT.AUDIO_24KHZ_96KBITRATE_MONO_MP3, {})
|
||||
} catch (error: unknown) {
|
||||
console.error("Failed to set voice", error)
|
||||
if (error instanceof Error) {
|
||||
callWindowExpose(window).toast.error(error.message, {
|
||||
duration: 1000,
|
||||
})
|
||||
} else {
|
||||
callWindowExpose(window).toast.error("Failed to set voice", {
|
||||
duration: 1000,
|
||||
})
|
||||
}
|
||||
return null
|
||||
const dirPath = path.join(app.getPath("userData"), "Cache", "tts", id)
|
||||
const filePath = path.join(dirPath, "audio.mp3")
|
||||
if (fs.existsSync(filePath)) {
|
||||
return filePath
|
||||
}
|
||||
|
||||
const dirPath = path.join(app.getPath("userData"), "Cache", "tts", id)
|
||||
const possibleFilePathList = ["mp3", "webm"].map((ext) => {
|
||||
return path.join(dirPath, `audio.${ext}`)
|
||||
})
|
||||
const filePath = possibleFilePathList.find((p) => fs.existsSync(p))
|
||||
if (filePath) {
|
||||
return filePath
|
||||
} else {
|
||||
try {
|
||||
const response = await fetch(`${TTS_SERVICE_URL}/tts`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
text,
|
||||
...(voice ? { voice } : {}),
|
||||
}),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(await readTtsErrorMessage(response))
|
||||
}
|
||||
|
||||
fs.mkdirSync(dirPath, { recursive: true })
|
||||
const { audioFilePath } = await tts.toFile(dirPath, text)
|
||||
return audioFilePath
|
||||
fs.writeFileSync(filePath, Buffer.from(await response.arrayBuffer()))
|
||||
return filePath
|
||||
} catch (error: unknown) {
|
||||
console.error("Failed to synthesize TTS", error)
|
||||
showReaderToastError(window, error, "Failed to synthesize TTS")
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,16 +134,16 @@ export class ReaderService extends IpcService {
|
||||
async getVoices(context: IpcContext) {
|
||||
const window = BrowserWindow.fromWebContents(context.sender)
|
||||
try {
|
||||
const voices = await tts.getVoices()
|
||||
return voices
|
||||
} catch (error) {
|
||||
console.error("Failed to get voices", error)
|
||||
if (!window) return
|
||||
if (error instanceof Error) {
|
||||
void callWindowExpose(window).toast.error(error.message, { duration: 1000 })
|
||||
return
|
||||
const response = await fetch(`${TTS_SERVICE_URL}/voices`)
|
||||
if (!response.ok) {
|
||||
throw new Error(await readTtsErrorMessage(response))
|
||||
}
|
||||
callWindowExpose(window).toast.error("Failed to get voices", { duration: 1000 })
|
||||
|
||||
const data = (await response.json()) as TtsVoiceResponse
|
||||
return data.voices
|
||||
} catch (error: unknown) {
|
||||
console.error("Failed to get voices", error)
|
||||
showReaderToastError(window, error, "Failed to get voices")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest"
|
||||
|
||||
vi.mock("@follow/shared/env.desktop", () => ({
|
||||
env: {
|
||||
VITE_OTA_URL: "https://ota.folo.is",
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock("@follow/utils/headers", () => ({
|
||||
createDesktopAPIHeaders: () => ({
|
||||
"X-App-Platform": "desktop/windows/exe",
|
||||
"X-App-Version": "1.5.0",
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock("@pkg", () => ({
|
||||
default: {
|
||||
version: "1.5.0",
|
||||
runtimeVersion: "1.5.0",
|
||||
},
|
||||
version: "1.5.0",
|
||||
runtimeVersion: "1.5.0",
|
||||
}))
|
||||
|
||||
vi.mock("../env", () => ({
|
||||
channel: "stable",
|
||||
}))
|
||||
|
||||
vi.mock("~/updater/hot-updater", () => ({
|
||||
getCurrentRendererManifest: () => null,
|
||||
}))
|
||||
|
||||
describe("desktop updater api", () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("fetch", vi.fn())
|
||||
})
|
||||
|
||||
it("returns null when desktop manifest responds 204", async () => {
|
||||
vi.mocked(fetch).mockResolvedValue(new Response(null, { status: 204 }))
|
||||
|
||||
const { fetchDesktopManifest } = await import("./api")
|
||||
const result = await fetchDesktopManifest()
|
||||
|
||||
expect(result).toBeNull()
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
new URL("/manifest", "https://ota.folo.is"),
|
||||
expect.objectContaining({
|
||||
headers: expect.objectContaining({
|
||||
"X-App-Platform": "desktop/windows/exe",
|
||||
"X-App-Version": "1.5.0",
|
||||
"X-App-Channel": "stable",
|
||||
"X-App-Runtime-Version": "1.5.0",
|
||||
"X-App-Renderer-Version": "1.5.0",
|
||||
}),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it("parses desktop manifest responses", async () => {
|
||||
vi.mocked(fetch).mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
id: "manifest-id",
|
||||
createdAt: "2026-04-11T10:00:00.000Z",
|
||||
product: "desktop",
|
||||
channel: "stable",
|
||||
runtimeVersion: "1.5.0",
|
||||
renderer: {
|
||||
releaseVersion: "1.5.1",
|
||||
version: "1.5.1",
|
||||
commit: "abcdef1234567890",
|
||||
launchAsset: {
|
||||
key: "custom-renderer",
|
||||
hash: "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqo",
|
||||
contentType: "application/gzip",
|
||||
url: "https://ota.folo.is/assets/desktop/stable/1.5.0/1.5.1/windows/renderer/custom-renderer.tar.gz",
|
||||
},
|
||||
assets: [],
|
||||
},
|
||||
app: null,
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } },
|
||||
),
|
||||
)
|
||||
|
||||
const { fetchDesktopManifest } = await import("./api")
|
||||
const result = await fetchDesktopManifest()
|
||||
|
||||
expect(result?.renderer?.version).toBe("1.5.1")
|
||||
expect(result?.app).toBeNull()
|
||||
})
|
||||
|
||||
it("parses desktop policy responses", async () => {
|
||||
vi.mocked(fetch).mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
action: "block",
|
||||
targetVersion: "1.5.1",
|
||||
message: "Install the latest desktop app.",
|
||||
distribution: "mas",
|
||||
downloadUrl: null,
|
||||
storeUrl: "https://apps.apple.com/app/id123456789",
|
||||
publishedAt: "2026-04-11T10:00:00.000Z",
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } },
|
||||
),
|
||||
)
|
||||
|
||||
const { fetchDesktopPolicy } = await import("./api")
|
||||
const result = await fetchDesktopPolicy()
|
||||
|
||||
expect(result).toEqual({
|
||||
action: "block",
|
||||
targetVersion: "1.5.1",
|
||||
message: "Install the latest desktop app.",
|
||||
distribution: "mas",
|
||||
downloadUrl: null,
|
||||
storeUrl: "https://apps.apple.com/app/id123456789",
|
||||
publishedAt: "2026-04-11T10:00:00.000Z",
|
||||
})
|
||||
})
|
||||
|
||||
it("converts desktop manifest hash values back to hex", async () => {
|
||||
const { manifestHashToHex } = await import("./api")
|
||||
|
||||
expect(manifestHashToHex("qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqo")).toBe(
|
||||
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,26 +1,239 @@
|
||||
import { env } from "@follow/shared/env.desktop"
|
||||
import { createDesktopAPIHeaders } from "@follow/utils/headers"
|
||||
import PKG, { runtimeVersion as configuredRuntimeVersion, version as appVersion } from "@pkg"
|
||||
import { gte } from "semver"
|
||||
|
||||
import { getCurrentRendererManifest } from "~/updater/hot-updater"
|
||||
|
||||
import { channel } from "../env"
|
||||
import type {
|
||||
DistributionStatusPayload,
|
||||
GetLatestReleaseQuery,
|
||||
LatestReleasePayload,
|
||||
} from "@follow-app/client-sdk"
|
||||
DesktopManifestResponse,
|
||||
DesktopPolicyResponse,
|
||||
DesktopRendererPayload,
|
||||
} from "./types"
|
||||
|
||||
import { apiClient } from "~/lib/api-client"
|
||||
export { manifestHashToHex } from "./types"
|
||||
|
||||
let cachedLatestRelease: LatestReleasePayload | null = null
|
||||
export const getDesktopRuntimeVersion = () => configuredRuntimeVersion ?? appVersion
|
||||
|
||||
export const getUpdateInfo = async (
|
||||
query: GetLatestReleaseQuery = {},
|
||||
): Promise<LatestReleasePayload> => {
|
||||
const response = await apiClient.updates.getLatestRelease(query)
|
||||
cachedLatestRelease = response.data
|
||||
return cachedLatestRelease
|
||||
export const getDesktopRendererVersion = () => {
|
||||
const rendererManifest = getCurrentRendererManifest()
|
||||
return gte(rendererManifest?.version ?? appVersion, appVersion)
|
||||
? (rendererManifest?.version ?? appVersion)
|
||||
: appVersion
|
||||
}
|
||||
|
||||
export const getDistributionUpdateInfo = async (): Promise<DistributionStatusPayload | null> => {
|
||||
const distribution = process.mas ? "mas" : process.windowsStore ? "mss" : undefined
|
||||
if (!distribution) {
|
||||
export const buildDesktopOtaHeaders = (includeRenderer = false): Record<string, string> => {
|
||||
const headers: Record<string, string> = {
|
||||
...createDesktopAPIHeaders({ version: PKG.version }),
|
||||
"X-App-Channel": channel,
|
||||
"X-App-Runtime-Version": getDesktopRuntimeVersion(),
|
||||
}
|
||||
|
||||
if (includeRenderer) {
|
||||
headers["X-App-Renderer-Version"] = getDesktopRendererVersion()
|
||||
}
|
||||
|
||||
return headers
|
||||
}
|
||||
|
||||
export const fetchDesktopManifest = async (): Promise<DesktopManifestResponse | null> => {
|
||||
const response = await fetch(new URL("/manifest", env.VITE_OTA_URL), {
|
||||
headers: buildDesktopOtaHeaders(true),
|
||||
cache: "no-store",
|
||||
})
|
||||
|
||||
if (response.status === 204) {
|
||||
return null
|
||||
}
|
||||
const response = await apiClient.updates.getDistributionStatus({ distribution })
|
||||
return response.data
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch desktop OTA manifest (${response.status})`)
|
||||
}
|
||||
|
||||
return parseDesktopManifest(await response.json())
|
||||
}
|
||||
|
||||
export const fetchDesktopPolicy = async (): Promise<DesktopPolicyResponse> => {
|
||||
const response = await fetch(new URL("/policy", env.VITE_OTA_URL), {
|
||||
headers: buildDesktopOtaHeaders(false),
|
||||
cache: "no-store",
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch desktop OTA policy (${response.status})`)
|
||||
}
|
||||
|
||||
return parseDesktopPolicy(await response.json())
|
||||
}
|
||||
|
||||
function parseDesktopManifest(payload: unknown): DesktopManifestResponse {
|
||||
if (!payload || typeof payload !== "object") {
|
||||
throw new Error("Invalid desktop OTA manifest response")
|
||||
}
|
||||
|
||||
const data = payload as Record<string, unknown>
|
||||
const { renderer, app } = data
|
||||
|
||||
if (
|
||||
data["product"] !== "desktop" ||
|
||||
typeof data["id"] !== "string" ||
|
||||
typeof data["createdAt"] !== "string" ||
|
||||
typeof data["channel"] !== "string" ||
|
||||
typeof data["runtimeVersion"] !== "string"
|
||||
) {
|
||||
throw new Error("Invalid desktop OTA manifest response")
|
||||
}
|
||||
|
||||
return {
|
||||
id: data["id"],
|
||||
createdAt: data["createdAt"],
|
||||
product: "desktop",
|
||||
channel: data["channel"],
|
||||
runtimeVersion: data["runtimeVersion"],
|
||||
renderer: renderer ? parseRendererPayload(renderer) : null,
|
||||
app: app ? parseAppPayload(app) : null,
|
||||
}
|
||||
}
|
||||
|
||||
function parseDesktopPolicy(payload: unknown): DesktopPolicyResponse {
|
||||
if (!payload || typeof payload !== "object") {
|
||||
throw new Error("Invalid desktop OTA policy response")
|
||||
}
|
||||
|
||||
const data = payload as Record<string, unknown>
|
||||
const { action, distribution } = data
|
||||
|
||||
if (action !== "none" && action !== "prompt" && action !== "block") {
|
||||
throw new Error("Invalid desktop OTA policy response")
|
||||
}
|
||||
|
||||
if (distribution !== "direct" && distribution !== "mas" && distribution !== "mss") {
|
||||
throw new Error("Invalid desktop OTA policy response")
|
||||
}
|
||||
|
||||
return {
|
||||
action,
|
||||
targetVersion: typeof data["targetVersion"] === "string" ? data["targetVersion"] : null,
|
||||
message: typeof data["message"] === "string" ? data["message"] : null,
|
||||
distribution,
|
||||
downloadUrl: typeof data["downloadUrl"] === "string" ? data["downloadUrl"] : null,
|
||||
storeUrl: typeof data["storeUrl"] === "string" ? data["storeUrl"] : null,
|
||||
publishedAt: typeof data["publishedAt"] === "string" ? data["publishedAt"] : null,
|
||||
}
|
||||
}
|
||||
|
||||
function parseRendererPayload(payload: unknown): DesktopRendererPayload {
|
||||
if (!payload || typeof payload !== "object") {
|
||||
throw new Error("Invalid desktop OTA manifest response")
|
||||
}
|
||||
|
||||
const data = payload as Record<string, unknown>
|
||||
const { launchAsset, assets } = data
|
||||
|
||||
if (
|
||||
typeof data["releaseVersion"] !== "string" ||
|
||||
typeof data["version"] !== "string" ||
|
||||
typeof data["commit"] !== "string" ||
|
||||
!launchAsset ||
|
||||
!Array.isArray(assets)
|
||||
) {
|
||||
throw new Error("Invalid desktop OTA manifest response")
|
||||
}
|
||||
|
||||
return {
|
||||
releaseVersion: data["releaseVersion"],
|
||||
version: data["version"],
|
||||
commit: data["commit"],
|
||||
launchAsset: parseManifestAsset(launchAsset),
|
||||
assets: assets.map((asset) => parseManifestAsset(asset)),
|
||||
}
|
||||
}
|
||||
|
||||
function parseAppPayload(payload: unknown) {
|
||||
if (!payload || typeof payload !== "object") {
|
||||
throw new Error("Invalid desktop OTA manifest response")
|
||||
}
|
||||
|
||||
const data = payload as Record<string, unknown>
|
||||
const { manifest, files } = data
|
||||
|
||||
if (
|
||||
typeof data["releaseVersion"] !== "string" ||
|
||||
typeof data["version"] !== "string" ||
|
||||
typeof data["platform"] !== "string" ||
|
||||
!manifest ||
|
||||
!Array.isArray(files)
|
||||
) {
|
||||
throw new Error("Invalid desktop OTA manifest response")
|
||||
}
|
||||
|
||||
if (
|
||||
typeof (manifest as Record<string, unknown>)["name"] !== "string" ||
|
||||
typeof (manifest as Record<string, unknown>)["downloadUrl"] !== "string"
|
||||
) {
|
||||
throw new TypeError("Invalid desktop OTA manifest response")
|
||||
}
|
||||
|
||||
return {
|
||||
releaseVersion: data["releaseVersion"],
|
||||
version: data["version"],
|
||||
platform: data["platform"],
|
||||
releaseDate: typeof data["releaseDate"] === "string" ? data["releaseDate"] : null,
|
||||
manifest: {
|
||||
name: (manifest as Record<string, unknown>)["name"] as string,
|
||||
downloadUrl: (manifest as Record<string, unknown>)["downloadUrl"] as string,
|
||||
...(typeof (manifest as Record<string, unknown>)["path"] === "string"
|
||||
? { path: (manifest as Record<string, unknown>)["path"] as string }
|
||||
: {}),
|
||||
},
|
||||
files: files.map((file) => parseAppFile(file)),
|
||||
}
|
||||
}
|
||||
|
||||
function parseManifestAsset(payload: unknown) {
|
||||
if (!payload || typeof payload !== "object") {
|
||||
throw new Error("Invalid desktop OTA manifest response")
|
||||
}
|
||||
|
||||
const data = payload as Record<string, unknown>
|
||||
if (
|
||||
typeof data["key"] !== "string" ||
|
||||
typeof data["hash"] !== "string" ||
|
||||
typeof data["contentType"] !== "string" ||
|
||||
typeof data["url"] !== "string"
|
||||
) {
|
||||
throw new TypeError("Invalid desktop OTA manifest response")
|
||||
}
|
||||
|
||||
return {
|
||||
key: data["key"],
|
||||
hash: data["hash"],
|
||||
contentType: data["contentType"],
|
||||
url: data["url"],
|
||||
...(typeof data["fileExtension"] === "string" ? { fileExtension: data["fileExtension"] } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
function parseAppFile(payload: unknown) {
|
||||
if (!payload || typeof payload !== "object") {
|
||||
throw new Error("Invalid desktop OTA manifest response")
|
||||
}
|
||||
|
||||
const data = payload as Record<string, unknown>
|
||||
if (
|
||||
typeof data["filename"] !== "string" ||
|
||||
typeof data["sha512"] !== "string" ||
|
||||
typeof data["size"] !== "number" ||
|
||||
typeof data["downloadUrl"] !== "string"
|
||||
) {
|
||||
throw new TypeError("Invalid desktop OTA manifest response")
|
||||
}
|
||||
|
||||
return {
|
||||
filename: data["filename"],
|
||||
sha512: data["sha512"],
|
||||
size: data["size"],
|
||||
downloadUrl: data["downloadUrl"],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
import { URL } from "node:url"
|
||||
|
||||
import type {
|
||||
AppUpdate,
|
||||
LatestReleasePayload,
|
||||
PlatformUpdate,
|
||||
PlatformUpdateFile,
|
||||
} from "@follow-app/client-sdk"
|
||||
import type { UpdateFileInfo, UpdateInfo } from "builder-util-runtime"
|
||||
import { newError } from "builder-util-runtime"
|
||||
import type { AppUpdater } from "electron-updater"
|
||||
@@ -14,15 +8,15 @@ import { Provider } from "electron-updater/out/providers/Provider"
|
||||
import type { ResolvedUpdateFileInfo } from "electron-updater/out/types"
|
||||
|
||||
import { logger } from "../logger"
|
||||
import { getUpdateInfo } from "./api"
|
||||
import { fetchDesktopManifest } from "./api"
|
||||
import type { DesktopAppPayload } from "./types"
|
||||
|
||||
interface FollowProviderOptions {
|
||||
provider: "custom"
|
||||
}
|
||||
|
||||
type FollowProviderContext = {
|
||||
payload: LatestReleasePayload
|
||||
platform: PlatformUpdate
|
||||
app: DesktopAppPayload
|
||||
}
|
||||
|
||||
export class FollowUpdateProvider extends Provider<UpdateInfo> {
|
||||
@@ -61,12 +55,12 @@ export class FollowUpdateProvider extends Provider<UpdateInfo> {
|
||||
}
|
||||
|
||||
private buildUpdateInfo(context: FollowProviderContext): UpdateInfo {
|
||||
const { payload, platform } = context
|
||||
const files = this.mapFiles(platform.files)
|
||||
const { app } = context
|
||||
const files = this.mapFiles(app.files)
|
||||
|
||||
if (files.length === 0) {
|
||||
throw newError(
|
||||
`No downloadable files found for platform ${platform.platform}`,
|
||||
`No downloadable files found for platform ${app.platform}`,
|
||||
"ERR_UPDATER_CHANNEL_FILE_NOT_FOUND",
|
||||
)
|
||||
}
|
||||
@@ -74,7 +68,7 @@ export class FollowUpdateProvider extends Provider<UpdateInfo> {
|
||||
const primaryFile = files[0]
|
||||
if (!primaryFile) {
|
||||
throw newError(
|
||||
`Platform ${platform.platform} provides no downloadable file`,
|
||||
`Platform ${app.platform} provides no downloadable file`,
|
||||
"ERR_UPDATER_CHANNEL_FILE_NOT_FOUND",
|
||||
)
|
||||
}
|
||||
@@ -88,20 +82,18 @@ export class FollowUpdateProvider extends Provider<UpdateInfo> {
|
||||
}
|
||||
}
|
||||
|
||||
const { release } = payload
|
||||
|
||||
return {
|
||||
version: platform.version,
|
||||
version: app.version,
|
||||
files,
|
||||
path: primaryPath,
|
||||
sha512: primaryFile.sha512,
|
||||
releaseName: release.name,
|
||||
releaseNotes: release.body,
|
||||
releaseDate: platform.releaseDate || release.publishedAt || new Date().toISOString(),
|
||||
releaseName: `Folo ${app.version}`,
|
||||
releaseNotes: null,
|
||||
releaseDate: app.releaseDate || new Date().toISOString(),
|
||||
}
|
||||
}
|
||||
|
||||
private mapFiles(files: PlatformUpdate["files"]): UpdateFileInfo[] {
|
||||
private mapFiles(files: DesktopAppPayload["files"]): UpdateFileInfo[] {
|
||||
if (!files) return []
|
||||
|
||||
return files
|
||||
@@ -109,7 +101,7 @@ export class FollowUpdateProvider extends Provider<UpdateInfo> {
|
||||
.filter((file): file is UpdateFileInfo => file !== null)
|
||||
}
|
||||
|
||||
private mapFile(file: PlatformUpdateFile): UpdateFileInfo | null {
|
||||
private mapFile(file: DesktopAppPayload["files"][number]): UpdateFileInfo | null {
|
||||
if (!file.downloadUrl || !file.sha512) {
|
||||
logger.warn("Skip platform file without downloadUrl or sha512", file)
|
||||
return null
|
||||
@@ -146,58 +138,16 @@ export class FollowUpdateProvider extends Provider<UpdateInfo> {
|
||||
}
|
||||
|
||||
private async fetchContext(): Promise<FollowProviderContext> {
|
||||
const payload = await getUpdateInfo({})
|
||||
const { decision } = payload
|
||||
const manifest = await fetchDesktopManifest()
|
||||
const app = manifest?.app
|
||||
|
||||
if (!decision || decision.type !== "app" || !decision.app) {
|
||||
if (!app) {
|
||||
throw newError(
|
||||
"No app update metadata available from provider",
|
||||
"ERR_UPDATER_NO_PUBLISHED_VERSIONS",
|
||||
)
|
||||
}
|
||||
|
||||
const platform = this.pickPlatform(decision.app)
|
||||
if (!platform) {
|
||||
throw newError(
|
||||
`No matching platform update for ${process.platform}/${process.arch}`,
|
||||
"ERR_UPDATER_CHANNEL_FILE_NOT_FOUND",
|
||||
)
|
||||
}
|
||||
|
||||
return { payload, platform }
|
||||
}
|
||||
|
||||
private pickPlatform(appDecision: AppUpdate): PlatformUpdate | null {
|
||||
const platforms = appDecision.platforms ?? []
|
||||
const selected = appDecision.selectedPlatform
|
||||
if (selected) {
|
||||
return selected
|
||||
}
|
||||
|
||||
const candidates = this.resolvePlatformCandidates()
|
||||
const matched = platforms.find((platform) =>
|
||||
candidates.includes(platform.platform.toLowerCase()),
|
||||
)
|
||||
|
||||
return matched ?? platforms[0] ?? null
|
||||
}
|
||||
|
||||
private resolvePlatformCandidates(): string[] {
|
||||
const base = new Set<string>()
|
||||
base.add(process.platform)
|
||||
base.add(`${process.platform}-${process.arch}`)
|
||||
base.add(process.arch)
|
||||
|
||||
if (process.platform === "darwin") {
|
||||
base.add("mac")
|
||||
base.add("macos")
|
||||
}
|
||||
|
||||
if (process.platform === "win32") {
|
||||
base.add("windows")
|
||||
base.add("win")
|
||||
}
|
||||
|
||||
return Array.from(base).map((value) => value.toLowerCase())
|
||||
return { app }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { existsSync, readFileSync } from "node:fs"
|
||||
import { mkdir, readdir, rename, rm, stat, writeFile } from "node:fs/promises"
|
||||
import { mkdir, mkdtemp, readdir, rename, rm, stat, writeFile } from "node:fs/promises"
|
||||
import os from "node:os"
|
||||
import { URL } from "node:url"
|
||||
|
||||
import { callWindowExpose } from "@follow/shared/bridge"
|
||||
import type { LatestReleasePayload, RendererUpdate } from "@follow-app/client-sdk"
|
||||
import { mainHash, version as appVersion } from "@pkg"
|
||||
import { runtimeVersion as configuredRuntimeVersion, version as appVersion } from "@pkg"
|
||||
import log from "electron-log"
|
||||
import { dump, load } from "js-yaml"
|
||||
import path from "pathe"
|
||||
@@ -15,11 +15,17 @@ import { downloadFileWithProgress } from "~/lib/download"
|
||||
import { WindowManager } from "~/manager/window"
|
||||
|
||||
import { appUpdaterConfig } from "./configs"
|
||||
import type { DesktopManifestResponse, DesktopRendererPayload } from "./types"
|
||||
import { manifestHashToHex } from "./types"
|
||||
|
||||
declare const GIT_COMMIT_HASH: string | undefined
|
||||
|
||||
export type RendererManifest = RendererUpdate & {
|
||||
export type RendererManifest = {
|
||||
runtimeVersion: string
|
||||
version: string
|
||||
releaseVersion: string
|
||||
commit: string
|
||||
downloadUrl: string
|
||||
hash: string
|
||||
filename: string
|
||||
downloadedAt?: string
|
||||
}
|
||||
|
||||
@@ -41,19 +47,17 @@ class RendererHotUpdater {
|
||||
private readonly tempDir = path.resolve(os.tmpdir(), "follow-render-update")
|
||||
private readonly manifestPath = path.resolve(HOTUPDATE_RENDER_ENTRY_DIR, "manifest.yml")
|
||||
|
||||
extractManifest(payload: LatestReleasePayload | null): RendererManifest | null {
|
||||
extractManifest(payload: DesktopManifestResponse | null): RendererManifest | null {
|
||||
if (!payload) return null
|
||||
|
||||
const { decision } = payload
|
||||
if (!decision || decision.type !== "renderer") {
|
||||
return null
|
||||
}
|
||||
|
||||
return this.toManifest(decision.renderer)
|
||||
return this.toManifest(payload.renderer, payload.runtimeVersion)
|
||||
}
|
||||
|
||||
extractManifestFromRendererUpdate(renderer: RendererUpdate | null): RendererManifest | null {
|
||||
return this.toManifest(renderer)
|
||||
extractManifestFromRendererUpdate(
|
||||
renderer: DesktopRendererPayload | null,
|
||||
runtimeVersion: string,
|
||||
): RendererManifest | null {
|
||||
return this.toManifest(renderer, runtimeVersion)
|
||||
}
|
||||
|
||||
evaluateManifest(manifest: RendererManifest | null): RendererEligibilityResult {
|
||||
@@ -61,11 +65,12 @@ class RendererHotUpdater {
|
||||
return { status: RendererEligibilityStatus.NoManifest }
|
||||
}
|
||||
|
||||
if (manifest.mainHash && manifest.mainHash !== mainHash) {
|
||||
const appRuntimeVersion = configuredRuntimeVersion ?? appVersion
|
||||
if (manifest.runtimeVersion !== appRuntimeVersion) {
|
||||
return {
|
||||
status: RendererEligibilityStatus.RequiresFullAppUpdate,
|
||||
manifest,
|
||||
reason: `Renderer payload requires main hash ${manifest.mainHash}, current main hash is ${mainHash}`,
|
||||
reason: `Renderer payload requires runtimeVersion ${manifest.runtimeVersion}, current runtimeVersion is ${appRuntimeVersion}`,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,31 +81,11 @@ class RendererHotUpdater {
|
||||
}
|
||||
}
|
||||
|
||||
if (manifest.commit && GIT_COMMIT_HASH && manifest.commit === GIT_COMMIT_HASH) {
|
||||
const installedManifest = this.getCurrentManifest()
|
||||
if (installedManifest && installedManifest.version === manifest.version) {
|
||||
return {
|
||||
status: RendererEligibilityStatus.AlreadyCurrent,
|
||||
reason: "Renderer commit matches current main commit",
|
||||
}
|
||||
}
|
||||
|
||||
const installedManifest = this.getCurrentManifest()
|
||||
if (installedManifest) {
|
||||
if (installedManifest.version === manifest.version) {
|
||||
return {
|
||||
status: RendererEligibilityStatus.AlreadyCurrent,
|
||||
reason: "Installed renderer manifest already at target version",
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
installedManifest.commit &&
|
||||
manifest.commit &&
|
||||
installedManifest.commit === manifest.commit
|
||||
) {
|
||||
return {
|
||||
status: RendererEligibilityStatus.AlreadyCurrent,
|
||||
reason: "Installed renderer manifest commit matches target commit",
|
||||
}
|
||||
reason: "Installed renderer manifest already at target version",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,30 +95,39 @@ class RendererHotUpdater {
|
||||
}
|
||||
}
|
||||
|
||||
private toManifest(renderer: RendererUpdate | null): RendererManifest | null {
|
||||
private toManifest(
|
||||
renderer: DesktopRendererPayload | null,
|
||||
runtimeVersion: string,
|
||||
): RendererManifest | null {
|
||||
if (!renderer) {
|
||||
this.logger.debug("Renderer decision payload missing renderer field")
|
||||
return null
|
||||
}
|
||||
|
||||
if (!renderer.downloadUrl) {
|
||||
if (!renderer.launchAsset?.url) {
|
||||
this.logger.warn("Renderer decision missing downloadUrl, skip renderer hot update")
|
||||
return null
|
||||
}
|
||||
|
||||
if (!renderer.filename) {
|
||||
const filename = this.resolveFilename(renderer.launchAsset.url)
|
||||
if (!filename) {
|
||||
this.logger.warn("Renderer decision missing filename, skip renderer hot update")
|
||||
return null
|
||||
}
|
||||
|
||||
if (!renderer.hash) {
|
||||
if (!renderer.launchAsset.hash) {
|
||||
this.logger.warn("Renderer decision missing hash, skip renderer hot update")
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
...renderer,
|
||||
downloadUrl: renderer.downloadUrl,
|
||||
runtimeVersion,
|
||||
version: renderer.version,
|
||||
releaseVersion: renderer.releaseVersion,
|
||||
commit: renderer.commit,
|
||||
downloadUrl: renderer.launchAsset.url,
|
||||
filename,
|
||||
hash: manifestHashToHex(renderer.launchAsset.hash),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,16 +138,18 @@ class RendererHotUpdater {
|
||||
}
|
||||
|
||||
const archivePath = await this.downloadArchive(manifest)
|
||||
const stagingRoot = await mkdtemp(path.resolve(this.tempDir, "extract-"))
|
||||
const stagingDir = path.resolve(stagingRoot, "content")
|
||||
|
||||
await mkdir(HOTUPDATE_RENDER_ENTRY_DIR, { recursive: true })
|
||||
this.logger.info(`Extracting renderer bundle to ${HOTUPDATE_RENDER_ENTRY_DIR}`)
|
||||
await mkdir(stagingDir, { recursive: true })
|
||||
this.logger.info(`Extracting renderer bundle to ${stagingDir}`)
|
||||
|
||||
await x({
|
||||
f: archivePath,
|
||||
cwd: HOTUPDATE_RENDER_ENTRY_DIR,
|
||||
cwd: stagingDir,
|
||||
})
|
||||
|
||||
const extractedDir = path.resolve(HOTUPDATE_RENDER_ENTRY_DIR, "renderer")
|
||||
const extractedDir = path.resolve(stagingDir, "renderer")
|
||||
const targetDir = path.resolve(HOTUPDATE_RENDER_ENTRY_DIR, manifest.version)
|
||||
|
||||
const extractedStats = await stat(extractedDir).catch(() => null)
|
||||
@@ -162,6 +158,7 @@ class RendererHotUpdater {
|
||||
}
|
||||
|
||||
await rm(targetDir, { recursive: true, force: true })
|
||||
await mkdir(HOTUPDATE_RENDER_ENTRY_DIR, { recursive: true })
|
||||
await rename(extractedDir, targetDir)
|
||||
|
||||
await this.writeManifest({ ...manifest, downloadedAt: new Date().toISOString() })
|
||||
@@ -172,6 +169,12 @@ class RendererHotUpdater {
|
||||
this.logger.warn("Failed to clean renderer archive", error)
|
||||
}
|
||||
|
||||
try {
|
||||
await rm(stagingRoot, { recursive: true, force: true })
|
||||
} catch (error) {
|
||||
this.logger.warn("Failed to clean renderer staging directory", error)
|
||||
}
|
||||
|
||||
this.logger.info(`Renderer hot update applied successfully: ${manifest.version}`)
|
||||
|
||||
const mainWindow = WindowManager.getMainWindow()
|
||||
@@ -231,7 +234,6 @@ class RendererHotUpdater {
|
||||
|
||||
const manifest = this.getCurrentManifest()
|
||||
if (!manifest) return
|
||||
if (manifest.mainHash && manifest.mainHash !== mainHash) return
|
||||
|
||||
const dir = path.resolve(HOTUPDATE_RENDER_ENTRY_DIR, manifest.version)
|
||||
const entryFile = path.resolve(dir, "index.html")
|
||||
@@ -264,6 +266,14 @@ class RendererHotUpdater {
|
||||
private async writeManifest(manifest: RendererManifest) {
|
||||
await writeFile(this.manifestPath, dump(manifest), "utf-8")
|
||||
}
|
||||
|
||||
private resolveFilename(url: string) {
|
||||
try {
|
||||
return new URL(url).pathname.split("/").pop() ?? null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const rendererUpdater = new RendererHotUpdater()
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
import { describe, expect, it, vi } from "vitest"
|
||||
|
||||
vi.mock("@follow/shared/bridge", () => ({
|
||||
callWindowExpose: () => ({
|
||||
distributionUpdateAvailable: vi.fn(),
|
||||
updateDownloaded: vi.fn(),
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock("@follow/shared/constants", () => ({
|
||||
DEV: false,
|
||||
}))
|
||||
|
||||
vi.mock("@pkg", () => ({
|
||||
version: "1.5.0",
|
||||
}))
|
||||
|
||||
vi.mock("electron-log", () => ({
|
||||
default: {
|
||||
scope: () => ({
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
}),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock("electron-updater", () => ({
|
||||
autoUpdater: {
|
||||
setFeedURL: vi.fn(),
|
||||
on: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock("../env", () => ({
|
||||
channel: "stable",
|
||||
isWindows: false,
|
||||
}))
|
||||
|
||||
vi.mock("./api", () => ({
|
||||
fetchDesktopManifest: vi.fn(),
|
||||
fetchDesktopPolicy: vi.fn(),
|
||||
getDesktopRuntimeVersion: () => "1.5.0",
|
||||
}))
|
||||
|
||||
vi.mock("./configs", () => ({
|
||||
appUpdaterConfig: {
|
||||
enableRenderHotUpdate: true,
|
||||
enableCoreUpdate: true,
|
||||
enableAppUpdate: true,
|
||||
enableDistributionStoreUpdate: false,
|
||||
app: {
|
||||
autoCheckUpdate: false,
|
||||
autoDownloadUpdate: false,
|
||||
checkUpdateInterval: 900000,
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock("./follow-update-provider", () => ({
|
||||
FollowUpdateProvider: class {},
|
||||
}))
|
||||
|
||||
vi.mock("./windows-updater", () => ({
|
||||
WindowsUpdater: class {},
|
||||
}))
|
||||
|
||||
vi.mock("~/manager/window", () => ({
|
||||
WindowManager: {
|
||||
getMainWindow: () => null,
|
||||
destroyMainWindow: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock("~/updater/hot-updater", () => ({
|
||||
rendererUpdater: {},
|
||||
RendererEligibilityStatus: {
|
||||
NoManifest: 0,
|
||||
RequiresFullAppUpdate: 1,
|
||||
AlreadyCurrent: 2,
|
||||
Eligible: 3,
|
||||
},
|
||||
}))
|
||||
|
||||
describe("finalizeDirectUpdateResult", () => {
|
||||
it("prefers a successful renderer update result", async () => {
|
||||
const { finalizeDirectUpdateResult } = await import("./index")
|
||||
|
||||
expect(
|
||||
finalizeDirectUpdateResult({
|
||||
rendererResult: { hasUpdate: true },
|
||||
appResult: { hasUpdate: false },
|
||||
policy: {
|
||||
action: "none",
|
||||
targetVersion: null,
|
||||
message: null,
|
||||
distribution: "direct",
|
||||
downloadUrl: null,
|
||||
storeUrl: null,
|
||||
publishedAt: null,
|
||||
},
|
||||
}),
|
||||
).toEqual({ hasUpdate: true })
|
||||
})
|
||||
|
||||
it("falls back to a successful app update result", async () => {
|
||||
const { finalizeDirectUpdateResult } = await import("./index")
|
||||
|
||||
expect(
|
||||
finalizeDirectUpdateResult({
|
||||
rendererResult: { hasUpdate: false, error: "renderer failed" },
|
||||
appResult: { hasUpdate: true },
|
||||
policy: {
|
||||
action: "none",
|
||||
targetVersion: null,
|
||||
message: null,
|
||||
distribution: "direct",
|
||||
downloadUrl: null,
|
||||
storeUrl: null,
|
||||
publishedAt: null,
|
||||
},
|
||||
}),
|
||||
).toEqual({ hasUpdate: true })
|
||||
})
|
||||
|
||||
it("preserves errors when both renderer and app attempts fail", async () => {
|
||||
const { finalizeDirectUpdateResult } = await import("./index")
|
||||
|
||||
expect(
|
||||
finalizeDirectUpdateResult({
|
||||
rendererResult: { hasUpdate: false, error: "renderer failed" },
|
||||
appResult: { hasUpdate: false, error: "app failed" },
|
||||
policy: {
|
||||
action: "none",
|
||||
targetVersion: null,
|
||||
message: null,
|
||||
distribution: "direct",
|
||||
downloadUrl: null,
|
||||
storeUrl: null,
|
||||
publishedAt: null,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
hasUpdate: false,
|
||||
error: "app failed",
|
||||
})
|
||||
})
|
||||
|
||||
it("surfaces direct policy availability when no payload can be applied", async () => {
|
||||
const { finalizeDirectUpdateResult } = await import("./index")
|
||||
|
||||
expect(
|
||||
finalizeDirectUpdateResult({
|
||||
rendererResult: { hasUpdate: false },
|
||||
appResult: { hasUpdate: false },
|
||||
policy: {
|
||||
action: "block",
|
||||
targetVersion: "1.5.1",
|
||||
message: "Install the latest desktop app.",
|
||||
distribution: "direct",
|
||||
downloadUrl: "https://ota.folo.is/Folo-1.5.1.exe",
|
||||
storeUrl: null,
|
||||
publishedAt: "2026-04-11T10:00:00.000Z",
|
||||
},
|
||||
}),
|
||||
).toEqual({ hasUpdate: true })
|
||||
})
|
||||
|
||||
it("drops stale renderer and app errors once a direct policy provides an update path", async () => {
|
||||
const { finalizeDirectUpdateResult } = await import("./index")
|
||||
|
||||
expect(
|
||||
finalizeDirectUpdateResult({
|
||||
rendererResult: { hasUpdate: false, error: "renderer failed" },
|
||||
appResult: { hasUpdate: false, error: "app failed" },
|
||||
policy: {
|
||||
action: "prompt",
|
||||
targetVersion: "1.5.1",
|
||||
message: "Install the latest desktop app.",
|
||||
distribution: "direct",
|
||||
downloadUrl: "https://ota.folo.is/Folo-1.5.1.exe",
|
||||
storeUrl: null,
|
||||
publishedAt: "2026-04-11T10:00:00.000Z",
|
||||
},
|
||||
}),
|
||||
).toEqual({ hasUpdate: true })
|
||||
})
|
||||
})
|
||||
@@ -2,27 +2,21 @@ import { fileURLToPath } from "node:url"
|
||||
|
||||
import { callWindowExpose } from "@follow/shared/bridge"
|
||||
import { DEV } from "@follow/shared/constants"
|
||||
import type {
|
||||
DistributionStatusPayload,
|
||||
LatestReleasePayload,
|
||||
PlatformUpdate,
|
||||
RendererUpdate,
|
||||
} from "@follow-app/client-sdk"
|
||||
import { mainHash, version as appVersion } from "@pkg"
|
||||
import { version as appVersion } from "@pkg"
|
||||
import log from "electron-log"
|
||||
import type { AppUpdater } from "electron-updater"
|
||||
import { autoUpdater as defaultAutoUpdater } from "electron-updater"
|
||||
import { join } from "pathe"
|
||||
import { gt, valid as isValidSemver } from "semver"
|
||||
|
||||
import { WindowManager } from "~/manager/window"
|
||||
import type { RendererManifest } from "~/updater/hot-updater"
|
||||
import { RendererEligibilityStatus, rendererUpdater } from "~/updater/hot-updater"
|
||||
|
||||
import { channel, isWindows } from "../env"
|
||||
import { getDistributionUpdateInfo, getUpdateInfo } from "./api"
|
||||
import { fetchDesktopManifest, fetchDesktopPolicy, getDesktopRuntimeVersion } from "./api"
|
||||
import { appUpdaterConfig } from "./configs"
|
||||
import { FollowUpdateProvider } from "./follow-update-provider"
|
||||
import type { DesktopAppPayload, DesktopManifestResponse, DesktopPolicyResponse } from "./types"
|
||||
import { WindowsUpdater } from "./windows-updater"
|
||||
|
||||
const logger = log.scope("app-updater")
|
||||
@@ -74,7 +68,7 @@ class FollowUpdater {
|
||||
this.registerAutoUpdaterEvents()
|
||||
|
||||
if (appUpdaterConfig.app.autoCheckUpdate) {
|
||||
logger.info("Initial update check, mainHash:", mainHash)
|
||||
logger.info("Initial update check, runtimeVersion:", getDesktopRuntimeVersion())
|
||||
void this.checkForUpdates().catch((error) =>
|
||||
logger.error("Initial update check failed", error),
|
||||
)
|
||||
@@ -97,7 +91,7 @@ class FollowUpdater {
|
||||
this.pollingTimer = setInterval(updatePollingHandler, appUpdaterConfig.app.checkUpdateInterval)
|
||||
}
|
||||
|
||||
async checkForUpdates(options: UpdateCheckOptions = {}): Promise<UpdateCheckResult> {
|
||||
async checkForUpdates(_options: UpdateCheckOptions = {}): Promise<UpdateCheckResult> {
|
||||
if (this.disabled) {
|
||||
return { hasUpdate: false }
|
||||
}
|
||||
@@ -110,14 +104,14 @@ class FollowUpdater {
|
||||
this.checkingUpdate = true
|
||||
|
||||
try {
|
||||
const [manifest, policy] = await Promise.all([fetchDesktopManifest(), fetchDesktopPolicy()])
|
||||
|
||||
if (appUpdaterConfig.enableDistributionStoreUpdate) {
|
||||
logger.info("Distribution store update enabled, checking for distribution update")
|
||||
return this.handleDistributionAppDecision()
|
||||
logger.info("Distribution store update enabled, checking ota manifest and store policy")
|
||||
return this.handleDistributionAppDecision(manifest, policy)
|
||||
}
|
||||
|
||||
const payload = await getUpdateInfo(options.refresh ? { refresh: true } : {})
|
||||
|
||||
return this.handleDirectAppDecision(payload)
|
||||
return this.handleDirectAppDecision(manifest, policy)
|
||||
} catch (error) {
|
||||
logger.error("Failed to check for updates", error)
|
||||
return { hasUpdate: false, error: error instanceof Error ? error.message : "Unknown error" }
|
||||
@@ -126,26 +120,51 @@ class FollowUpdater {
|
||||
}
|
||||
}
|
||||
|
||||
async handleDirectAppDecision(payload: LatestReleasePayload): Promise<UpdateCheckResult> {
|
||||
const { decision } = payload
|
||||
async handleDirectAppDecision(
|
||||
manifest: DesktopManifestResponse | null,
|
||||
policy: DesktopPolicyResponse,
|
||||
): Promise<UpdateCheckResult> {
|
||||
let rendererResult: UpdateCheckResult | null = null
|
||||
let appResult: UpdateCheckResult | null = null
|
||||
|
||||
if (!decision || decision.type === "none") {
|
||||
logger.info("Update decision: none")
|
||||
return { hasUpdate: false }
|
||||
}
|
||||
|
||||
if (decision.type === "renderer") {
|
||||
if (manifest?.renderer) {
|
||||
logger.info("Update decision: renderer")
|
||||
return await this.handleRendererDecision(payload)
|
||||
rendererResult = await this.handleRendererDecision(manifest, manifest.app)
|
||||
if (rendererResult.hasUpdate) {
|
||||
return rendererResult
|
||||
}
|
||||
}
|
||||
|
||||
if (decision.type === "app") {
|
||||
if (manifest?.app) {
|
||||
logger.info("Update decision: app")
|
||||
return await this.handleAppDecision(payload)
|
||||
appResult = await this.handleAppDecision(manifest.app)
|
||||
if (appResult.hasUpdate) {
|
||||
return appResult
|
||||
}
|
||||
}
|
||||
|
||||
logger.warn("Unknown update decision type", { type: decision.type })
|
||||
return { hasUpdate: false }
|
||||
const result = finalizeDirectUpdateResult({
|
||||
rendererResult,
|
||||
appResult,
|
||||
policy,
|
||||
})
|
||||
|
||||
if (result.hasUpdate && policy.distribution === "direct" && policy.downloadUrl) {
|
||||
logger.info("Direct binary policy available", {
|
||||
action: policy.action,
|
||||
downloadUrl: policy.downloadUrl,
|
||||
})
|
||||
await this.notifyDistributionUpdate(policy)
|
||||
} else if (result.hasUpdate && policy.distribution === "direct") {
|
||||
logger.info("Direct binary policy available", {
|
||||
action: policy.action,
|
||||
downloadUrl: null,
|
||||
})
|
||||
} else if (!result.hasUpdate) {
|
||||
logger.info("Update decision: none")
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
async downloadAppUpdate(): Promise<void> {
|
||||
@@ -176,49 +195,9 @@ class FollowUpdater {
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
private resolvePlatformCandidates() {
|
||||
const base = new Set<string>()
|
||||
base.add(process.platform)
|
||||
base.add(`${process.platform}-${process.arch}`)
|
||||
base.add(process.arch)
|
||||
|
||||
if (process.platform === "darwin") {
|
||||
base.add("mac")
|
||||
base.add("macos")
|
||||
}
|
||||
|
||||
if (process.platform === "win32") {
|
||||
base.add("windows")
|
||||
base.add("win")
|
||||
}
|
||||
|
||||
return Array.from(base).map((value) => value.toLowerCase())
|
||||
}
|
||||
|
||||
private pickPlatformUpdate(
|
||||
platforms: PlatformUpdate[] | null | undefined,
|
||||
selected?: PlatformUpdate | null,
|
||||
): PlatformUpdate | null {
|
||||
if (!platforms || platforms.length === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (selected) {
|
||||
return selected
|
||||
}
|
||||
|
||||
const candidates = this.resolvePlatformCandidates()
|
||||
|
||||
const matched = platforms.find((platform) =>
|
||||
candidates.includes(platform.platform.toLowerCase()),
|
||||
)
|
||||
|
||||
return matched ?? platforms[0] ?? null
|
||||
}
|
||||
|
||||
private async handleAppDecision(payload: LatestReleasePayload): Promise<UpdateCheckResult> {
|
||||
const appDecision = payload.decision.app
|
||||
|
||||
private async handleAppDecision(
|
||||
appDecision: DesktopAppPayload | null,
|
||||
): Promise<UpdateCheckResult> {
|
||||
if (!appUpdaterConfig.enableCoreUpdate) {
|
||||
logger.info("Core app update disabled by configuration")
|
||||
return { hasUpdate: false }
|
||||
@@ -229,23 +208,12 @@ class FollowUpdater {
|
||||
return { hasUpdate: false, error: "App update metadata unavailable" }
|
||||
}
|
||||
|
||||
const platformUpdate = this.pickPlatformUpdate(
|
||||
appDecision.platforms,
|
||||
appDecision.selectedPlatform,
|
||||
)
|
||||
if (!platformUpdate) {
|
||||
logger.warn("No matching platform update found", {
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
})
|
||||
return { hasUpdate: false, error: "No installer available for this platform" }
|
||||
}
|
||||
|
||||
FollowUpdateProvider.setContext({ payload, platform: platformUpdate })
|
||||
logger.info("FollowUpdateProvider context set", { platform: platformUpdate.platform })
|
||||
FollowUpdateProvider.setContext({ app: appDecision })
|
||||
logger.info("FollowUpdateProvider context set", { platform: appDecision.platform })
|
||||
|
||||
try {
|
||||
await this.autoUpdater.checkForUpdates()
|
||||
const result = await this.autoUpdater.checkForUpdates()
|
||||
return { hasUpdate: result?.isUpdateAvailable ?? false }
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
"autoUpdater.checkForUpdates failed after preparing FollowUpdateProvider context",
|
||||
@@ -258,38 +226,29 @@ class FollowUpdater {
|
||||
} finally {
|
||||
FollowUpdateProvider.clearContext()
|
||||
}
|
||||
|
||||
return { hasUpdate: true }
|
||||
}
|
||||
|
||||
private async handleDistributionAppDecision(): Promise<UpdateCheckResult> {
|
||||
private async handleDistributionAppDecision(
|
||||
manifest: DesktopManifestResponse | null,
|
||||
policy: DesktopPolicyResponse,
|
||||
): Promise<UpdateCheckResult> {
|
||||
try {
|
||||
if (!appUpdaterConfig.enableDistributionStoreUpdate) {
|
||||
return { hasUpdate: false }
|
||||
}
|
||||
|
||||
const info = await getDistributionUpdateInfo()
|
||||
|
||||
if (!info) {
|
||||
logger.info(
|
||||
"Distribution update info unavailable for current build, falling back to direct app decision",
|
||||
)
|
||||
const payload = await getUpdateInfo()
|
||||
return this.handleDirectAppDecision(payload)
|
||||
}
|
||||
|
||||
const rendererResult = await this.tryDistributionRendererUpdate(info.rendererUpdate)
|
||||
const rendererResult = await this.tryDistributionRendererUpdate(manifest)
|
||||
if (rendererResult) {
|
||||
return rendererResult
|
||||
}
|
||||
|
||||
if (!this.shouldPromptDistributionStoreUpdate(info)) {
|
||||
if (!this.shouldPromptDistributionStoreUpdate(policy)) {
|
||||
logger.info("Distribution update does not require store action")
|
||||
return { hasUpdate: false }
|
||||
}
|
||||
|
||||
logger.info("Distribution store update required")
|
||||
return await this.notifyDistributionUpdate(info)
|
||||
return await this.notifyDistributionUpdate(policy)
|
||||
} catch (error) {
|
||||
logger.error("Failed to handle distribution app update", error)
|
||||
return {
|
||||
@@ -300,8 +259,9 @@ class FollowUpdater {
|
||||
}
|
||||
|
||||
private async tryDistributionRendererUpdate(
|
||||
renderer: RendererUpdate | null,
|
||||
manifestResponse: DesktopManifestResponse | null,
|
||||
): Promise<UpdateCheckResult | null> {
|
||||
const renderer = manifestResponse?.renderer ?? null
|
||||
if (!renderer) {
|
||||
return null
|
||||
}
|
||||
@@ -311,7 +271,10 @@ class FollowUpdater {
|
||||
return null
|
||||
}
|
||||
|
||||
const manifest = this.renderer.extractManifestFromRendererUpdate(renderer)
|
||||
const manifest = this.renderer.extractManifestFromRendererUpdate(
|
||||
renderer,
|
||||
manifestResponse?.runtimeVersion ?? getDesktopRuntimeVersion(),
|
||||
)
|
||||
if (!manifest) {
|
||||
logger.warn("Distribution renderer update missing manifest")
|
||||
return null
|
||||
@@ -369,7 +332,11 @@ class FollowUpdater {
|
||||
}
|
||||
}
|
||||
|
||||
private shouldPromptDistributionStoreUpdate(info: DistributionStatusPayload): boolean {
|
||||
private shouldPromptDistributionStoreUpdate(info: DesktopPolicyResponse): boolean {
|
||||
if (info.distribution === "direct") {
|
||||
return false
|
||||
}
|
||||
|
||||
if (!info.storeUrl) {
|
||||
logger.info("Distribution store update skipped: missing store URL", {
|
||||
distribution: info.distribution,
|
||||
@@ -377,55 +344,20 @@ class FollowUpdater {
|
||||
return false
|
||||
}
|
||||
|
||||
const { storeVersion } = info
|
||||
|
||||
const currentVersion = appVersion
|
||||
|
||||
if (!storeVersion) {
|
||||
logger.info("Distribution store update skipped: missing store version")
|
||||
return false
|
||||
}
|
||||
|
||||
if (!currentVersion) {
|
||||
return true
|
||||
}
|
||||
|
||||
const storeValid = isValidSemver(storeVersion)
|
||||
const currentValid = isValidSemver(currentVersion)
|
||||
|
||||
if (storeValid && currentValid) {
|
||||
const needsUpdate = gt(storeVersion, currentVersion)
|
||||
if (!needsUpdate) {
|
||||
logger.info("Distribution store version matches current version", {
|
||||
storeVersion,
|
||||
currentVersion,
|
||||
})
|
||||
}
|
||||
return needsUpdate
|
||||
}
|
||||
|
||||
if (storeVersion === currentVersion) {
|
||||
logger.info("Distribution store version identical to current version", {
|
||||
storeVersion,
|
||||
currentVersion,
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
return info.action !== "none"
|
||||
}
|
||||
|
||||
private async notifyDistributionUpdate(
|
||||
info: DistributionStatusPayload,
|
||||
): Promise<UpdateCheckResult> {
|
||||
private async notifyDistributionUpdate(info: DesktopPolicyResponse): Promise<UpdateCheckResult> {
|
||||
const mainWindow = WindowManager.getMainWindow()
|
||||
if (!mainWindow) {
|
||||
logger.warn("Main window unavailable when notifying distribution update")
|
||||
return { hasUpdate: true }
|
||||
}
|
||||
|
||||
if (!info.storeUrl) {
|
||||
logger.warn("Distribution update missing store URL", {
|
||||
const targetUrl = info.distribution === "direct" ? info.downloadUrl : info.storeUrl
|
||||
|
||||
if (!targetUrl) {
|
||||
logger.warn("Distribution update missing target URL", {
|
||||
distribution: info.distribution,
|
||||
})
|
||||
return { hasUpdate: false }
|
||||
@@ -433,24 +365,27 @@ class FollowUpdater {
|
||||
|
||||
await callWindowExpose(mainWindow).distributionUpdateAvailable({
|
||||
distribution: info.distribution,
|
||||
storeUrl: info.storeUrl,
|
||||
storeVersion: info.storeVersion ?? null,
|
||||
targetUrl,
|
||||
storeVersion: info.targetVersion ?? null,
|
||||
currentVersion: appVersion,
|
||||
})
|
||||
|
||||
return { hasUpdate: true }
|
||||
}
|
||||
|
||||
private async handleRendererDecision(payload: LatestReleasePayload): Promise<UpdateCheckResult> {
|
||||
private async handleRendererDecision(
|
||||
manifestResponse: DesktopManifestResponse | null,
|
||||
fallbackApp: DesktopAppPayload | null,
|
||||
): Promise<UpdateCheckResult> {
|
||||
if (!appUpdaterConfig.enableRenderHotUpdate) {
|
||||
logger.info("Renderer hot update disabled; falling back to app decision if present")
|
||||
if (payload.decision.app) {
|
||||
return this.handleAppDecision(payload)
|
||||
if (fallbackApp) {
|
||||
return this.handleAppDecision(fallbackApp)
|
||||
}
|
||||
return { hasUpdate: false }
|
||||
}
|
||||
|
||||
const manifest = this.renderer.extractManifest(payload)
|
||||
const manifest = this.renderer.extractManifest(manifestResponse)
|
||||
const eligibility = this.renderer.evaluateManifest(manifest)
|
||||
|
||||
switch (eligibility.status) {
|
||||
@@ -471,8 +406,8 @@ class FollowUpdater {
|
||||
|
||||
"Renderer payload requires main process update, delegating to app updater",
|
||||
)
|
||||
if (payload.decision.app) {
|
||||
return this.handleAppDecision(payload)
|
||||
if (fallbackApp) {
|
||||
return this.handleAppDecision(fallbackApp)
|
||||
}
|
||||
logger.warn("Renderer update requested full app upgrade but no app payload provided")
|
||||
return { hasUpdate: false, error: "Renderer update requires full app upgrade" }
|
||||
@@ -544,6 +479,32 @@ class FollowUpdater {
|
||||
const autoUpdater = isWindows ? new WindowsUpdater() : defaultAutoUpdater
|
||||
const followUpdater = new FollowUpdater(autoUpdater)
|
||||
|
||||
export function finalizeDirectUpdateResult(input: {
|
||||
rendererResult?: UpdateCheckResult | null
|
||||
appResult?: UpdateCheckResult | null
|
||||
policy: DesktopPolicyResponse
|
||||
}) {
|
||||
if (input.rendererResult?.hasUpdate) {
|
||||
return input.rendererResult
|
||||
}
|
||||
|
||||
if (input.appResult?.hasUpdate) {
|
||||
return input.appResult
|
||||
}
|
||||
|
||||
const lastError = input.appResult?.error ?? input.rendererResult?.error
|
||||
|
||||
if (
|
||||
input.policy.action !== "none" &&
|
||||
input.policy.distribution === "direct" &&
|
||||
input.policy.downloadUrl
|
||||
) {
|
||||
return { hasUpdate: true }
|
||||
}
|
||||
|
||||
return { hasUpdate: false, ...(lastError ? { error: lastError } : {}) }
|
||||
}
|
||||
|
||||
export const registerUpdater = () => {
|
||||
followUpdater.register()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
export type DesktopDistribution = "direct" | "mas" | "mss"
|
||||
|
||||
export interface DesktopManifestAsset {
|
||||
key: string
|
||||
hash: string
|
||||
fileExtension?: string
|
||||
contentType: string
|
||||
url: string
|
||||
}
|
||||
|
||||
export interface DesktopRendererPayload {
|
||||
releaseVersion: string
|
||||
version: string
|
||||
commit: string
|
||||
launchAsset: DesktopManifestAsset
|
||||
assets: DesktopManifestAsset[]
|
||||
}
|
||||
|
||||
export interface DesktopAppFile {
|
||||
filename: string
|
||||
sha512: string
|
||||
size: number
|
||||
downloadUrl: string
|
||||
}
|
||||
|
||||
export interface DesktopAppPayload {
|
||||
releaseVersion: string
|
||||
version: string
|
||||
platform: string
|
||||
releaseDate: string | null
|
||||
manifest: {
|
||||
name: string
|
||||
path?: string
|
||||
downloadUrl: string
|
||||
}
|
||||
files: DesktopAppFile[]
|
||||
}
|
||||
|
||||
export interface DesktopManifestResponse {
|
||||
id: string
|
||||
createdAt: string
|
||||
product: "desktop"
|
||||
channel: string
|
||||
runtimeVersion: string
|
||||
renderer: DesktopRendererPayload | null
|
||||
app: DesktopAppPayload | null
|
||||
}
|
||||
|
||||
export interface DesktopPolicyResponse {
|
||||
action: "none" | "prompt" | "block"
|
||||
targetVersion: string | null
|
||||
message: string | null
|
||||
distribution: DesktopDistribution
|
||||
downloadUrl: string | null
|
||||
storeUrl: string | null
|
||||
publishedAt: string | null
|
||||
}
|
||||
|
||||
export function manifestHashToHex(hash: string) {
|
||||
const normalized = hash.replaceAll("-", "+").replaceAll("_", "/")
|
||||
const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "=")
|
||||
return Buffer.from(padded, "base64").toString("hex")
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { createSettingAtom } from "@follow/atoms/helper/setting.js"
|
||||
import type { SpotlightSettings } from "@follow/shared/spotlight"
|
||||
import { defaultSpotlightSettings } from "@follow/shared/spotlight"
|
||||
|
||||
export const createDefaultSpotlightSettings = (): SpotlightSettings => ({
|
||||
...defaultSpotlightSettings,
|
||||
})
|
||||
|
||||
export const {
|
||||
useSettingKey: useSpotlightSettingKey,
|
||||
useSettingSelector: useSpotlightSettingSelector,
|
||||
setSetting: setSpotlightSetting,
|
||||
getSettings: getSpotlightSettings,
|
||||
initializeDefaultSettings: initializeDefaultSpotlightSettings,
|
||||
settingAtom: __spotlightSettingAtom,
|
||||
} = createSettingAtom("spotlight", createDefaultSpotlightSettings)
|
||||
|
||||
export const spotlightServerSyncWhiteListKeys: (keyof SpotlightSettings)[] = ["spotlights"]
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { StoreDistribution } from "@follow-app/client-sdk"
|
||||
import type { DesktopUpdateDistribution } from "@follow/shared/bridge"
|
||||
import { atom } from "jotai"
|
||||
|
||||
import { createAtomHooks } from "~/lib/jotai"
|
||||
@@ -19,8 +19,8 @@ type RendererUpdaterStatus = BaseUpdaterStatus<"renderer">
|
||||
type PwaUpdaterStatus = BaseUpdaterStatus<"pwa">
|
||||
|
||||
type DistributionUpdaterStatus = BaseUpdaterStatus<"distribution"> & {
|
||||
distribution: StoreDistribution
|
||||
storeUrl: string
|
||||
distribution: DesktopUpdateDistribution
|
||||
targetUrl: string
|
||||
storeVersion: string | null
|
||||
currentVersion: string | null
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import root from "react-shadow"
|
||||
|
||||
import { useUISettingKeys } from "~/atoms/settings/ui"
|
||||
import { useReduceMotion } from "~/hooks/biz/useReduceMotion"
|
||||
import { buildAppFontFamily } from "~/lib/font-family"
|
||||
import type { TextSelectionEvent } from "~/lib/simple-text-selection"
|
||||
import { addTextSelectionListener } from "~/lib/simple-text-selection"
|
||||
|
||||
@@ -120,7 +121,7 @@ export const ShadowDOM: FC<
|
||||
<div
|
||||
style={useMemo(
|
||||
() => ({
|
||||
fontFamily: `${uiFont},"SN Pro", system-ui, sans-serif`,
|
||||
fontFamily: buildAppFontFamily(uiFont),
|
||||
"--pointer": usePointerCursor ? "pointer" : "default",
|
||||
"--fo-a": hexToHslString(getAccentColorValue(accentColor)[dark ? "dark" : "light"]),
|
||||
}),
|
||||
|
||||
@@ -6,6 +6,7 @@ import type { ReactNode } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
|
||||
import { useIsPaymentEnabled } from "~/atoms/server-configs"
|
||||
import { useSpotlightSettingKey } from "~/atoms/settings/spotlight"
|
||||
import { CopyButton } from "~/components/ui/button/CopyButton"
|
||||
import { Markdown } from "~/components/ui/markdown/Markdown"
|
||||
import { useFeature } from "~/hooks/biz/useFeature"
|
||||
@@ -109,6 +110,7 @@ export const AISummaryCardBase: React.FC<AISummaryCardBaseProps> = ({
|
||||
}) => {
|
||||
const { t } = useTranslation("app")
|
||||
const aiEnabled = useFeature("ai")
|
||||
const spotlightRules = useSpotlightSettingKey("spotlights")
|
||||
|
||||
const hasContent = !isLoading && content
|
||||
const shouldSuggestUpgrade =
|
||||
@@ -218,7 +220,9 @@ export const AISummaryCardBase: React.FC<AISummaryCardBaseProps> = ({
|
||||
{isLoading ? (
|
||||
loadingComponent || <DefaultLoadingState />
|
||||
) : hasContent ? (
|
||||
<Markdown className="prose-sm max-w-none prose-p:m-0">{String(content)}</Markdown>
|
||||
<Markdown className="prose-sm max-w-none prose-p:m-0" spotlightRules={spotlightRules}>
|
||||
{String(content)}
|
||||
</Markdown>
|
||||
) : shouldSuggestUpgrade ? (
|
||||
<DefaultEmptyState
|
||||
message={t("ai.summary_upgrade_required_title")}
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { Provider } from "jotai"
|
||||
import * as React from "react"
|
||||
import { act } from "react"
|
||||
import type { Root } from "react-dom/client"
|
||||
import { createRoot } from "react-dom/client"
|
||||
import { afterEach, beforeAll, describe, expect, test, vi } from "vitest"
|
||||
|
||||
import { jotaiStore } from "~/lib/jotai"
|
||||
|
||||
import { AISummaryCardBase } from "./AISummaryCardBase"
|
||||
|
||||
const { markdownMock } = vi.hoisted(() => ({
|
||||
markdownMock: vi.fn(() => null),
|
||||
}))
|
||||
|
||||
vi.mock("~/atoms/server-configs", () => ({
|
||||
useIsPaymentEnabled: vi.fn(() => false),
|
||||
}))
|
||||
|
||||
vi.mock("~/atoms/settings/spotlight", () => ({
|
||||
useSpotlightSettingKey: vi.fn(() => [
|
||||
{
|
||||
id: "rule-1",
|
||||
enabled: true,
|
||||
pattern: "alpha",
|
||||
patternType: "keyword",
|
||||
caseSensitive: false,
|
||||
color: "#FDE68A",
|
||||
},
|
||||
]),
|
||||
}))
|
||||
|
||||
vi.mock("~/components/ui/markdown/Markdown", () => ({
|
||||
Markdown: markdownMock,
|
||||
}))
|
||||
|
||||
vi.mock("~/hooks/biz/useFeature", () => ({
|
||||
useFeature: vi.fn(() => false),
|
||||
}))
|
||||
|
||||
vi.mock("~/modules/settings/modal/useSettingModal", () => ({
|
||||
useSettingModal: vi.fn(() => vi.fn()),
|
||||
}))
|
||||
|
||||
vi.mock("react-i18next", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("react-i18next")>()
|
||||
|
||||
return {
|
||||
...actual,
|
||||
useTranslation: vi.fn(() => ({
|
||||
t: (key: string) => key,
|
||||
})),
|
||||
}
|
||||
})
|
||||
|
||||
const renderSummary = async (element: React.ReactNode) => {
|
||||
const container = document.createElement("div")
|
||||
document.body.append(container)
|
||||
|
||||
const root = createRoot(container)
|
||||
|
||||
await act(async () => {
|
||||
root.render(<Provider store={jotaiStore}>{element}</Provider>)
|
||||
})
|
||||
|
||||
return { container, root }
|
||||
}
|
||||
|
||||
describe("AISummaryCardBase spotlight", () => {
|
||||
let root: Root | null = null
|
||||
let container: HTMLElement | null = null
|
||||
|
||||
beforeAll(() => {
|
||||
;(globalThis as typeof globalThis & { React: typeof React }).React = React
|
||||
;(
|
||||
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
if (root) {
|
||||
await act(async () => {
|
||||
root?.unmount()
|
||||
})
|
||||
}
|
||||
|
||||
container?.remove()
|
||||
root = null
|
||||
container = null
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
test("passes spotlight rules to the summary markdown renderer", async () => {
|
||||
;({ container, root } = await renderSummary(<AISummaryCardBase content="alpha beta" />))
|
||||
|
||||
expect(markdownMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
spotlightRules: [
|
||||
expect.objectContaining({
|
||||
id: "rule-1",
|
||||
pattern: "alpha",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
undefined,
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,5 @@
|
||||
import { MemoedDangerousHTMLStyle } from "@follow/components/common/MemoedDangerousHTMLStyle.js"
|
||||
import type { SpotlightRule } from "@follow/shared/spotlight"
|
||||
import katexStyle from "katex/dist/katex.min.css?raw"
|
||||
import {
|
||||
createElement,
|
||||
@@ -30,11 +31,13 @@ export type HTMLProps<A extends keyof JSX.IntrinsicElements = "div"> = {
|
||||
} & JSX.IntrinsicElements[A] &
|
||||
Partial<{
|
||||
renderInlineStyle: boolean
|
||||
spotlightRules: SpotlightRule[]
|
||||
}>
|
||||
const HTMLImpl = <A extends keyof JSX.IntrinsicElements = "div">(props: HTMLProps<A>) => {
|
||||
const {
|
||||
children,
|
||||
renderInlineStyle,
|
||||
spotlightRules,
|
||||
as = "div",
|
||||
accessory,
|
||||
noMedia,
|
||||
@@ -45,19 +48,22 @@ const HTMLImpl = <A extends keyof JSX.IntrinsicElements = "div">(props: HTMLProp
|
||||
const [remarkOptions, setRemarkOptions] = useState({
|
||||
renderInlineStyle,
|
||||
noMedia,
|
||||
spotlightRules,
|
||||
})
|
||||
const [shouldForceReMountKey, setShouldForceReMountKey] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
setRemarkOptions((options) => {
|
||||
if (JSON.stringify(options) === JSON.stringify({ renderInlineStyle, noMedia })) {
|
||||
if (
|
||||
JSON.stringify(options) === JSON.stringify({ renderInlineStyle, noMedia, spotlightRules })
|
||||
) {
|
||||
return options
|
||||
}
|
||||
|
||||
setShouldForceReMountKey((key) => key + 1)
|
||||
return { ...options, renderInlineStyle, noMedia }
|
||||
return { ...options, renderInlineStyle, noMedia, spotlightRules }
|
||||
})
|
||||
}, [renderInlineStyle, noMedia])
|
||||
}, [renderInlineStyle, noMedia, spotlightRules])
|
||||
|
||||
const [refElement, setRefElement] = useState<HTMLElement | null>(null)
|
||||
useImperativeHandle(ref as any, () => refElement)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { SpotlightRule } from "@follow/shared/spotlight"
|
||||
import { cn } from "@follow/utils/utils"
|
||||
import { useMemo, useState } from "react"
|
||||
|
||||
@@ -9,9 +10,13 @@ import { MarkdownRenderContainerRefContext } from "./context"
|
||||
export const Markdown: Component<
|
||||
{
|
||||
children: string
|
||||
spotlightRules?: SpotlightRule[]
|
||||
} & Partial<RemarkOptions>
|
||||
> = ({ children, components, className, applyMiddleware }) => {
|
||||
const stableRemarkOptions = useState({ components, applyMiddleware })[0]
|
||||
> = ({ children, components, className, applyMiddleware, rehypePlugins, spotlightRules }) => {
|
||||
const stableRemarkOptions = useMemo(
|
||||
() => ({ components, applyMiddleware, rehypePlugins, spotlightRules }),
|
||||
[applyMiddleware, components, rehypePlugins, spotlightRules],
|
||||
)
|
||||
|
||||
const markdownElement = useMemo(
|
||||
() => parseMarkdown(children, { ...stableRemarkOptions }).content,
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import type { SpotlightRule } from "@follow/shared/spotlight"
|
||||
import { Provider } from "jotai"
|
||||
import * as React from "react"
|
||||
import { act } from "react"
|
||||
import type { Root } from "react-dom/client"
|
||||
import { createRoot } from "react-dom/client"
|
||||
import { afterEach, beforeAll, describe, expect, test, vi } from "vitest"
|
||||
|
||||
import { jotaiStore } from "~/lib/jotai"
|
||||
|
||||
import { HTML } from "./HTML"
|
||||
import { Markdown } from "./Markdown"
|
||||
|
||||
const { getWrappedElementSizeMock } = vi.hoisted(() => ({
|
||||
getWrappedElementSizeMock: () => ({ h: 0, w: 0 }),
|
||||
}))
|
||||
|
||||
vi.mock("~/providers/wrapped-element-provider", () => ({
|
||||
useWrappedElementSize: getWrappedElementSizeMock,
|
||||
}))
|
||||
|
||||
const rule: SpotlightRule = {
|
||||
id: "rule-1",
|
||||
enabled: true,
|
||||
pattern: "alpha",
|
||||
patternType: "keyword",
|
||||
caseSensitive: false,
|
||||
color: "#FDE68A",
|
||||
}
|
||||
|
||||
const renderMarkdownComponent = async (element: React.ReactNode) => {
|
||||
const container = document.createElement("div")
|
||||
document.body.append(container)
|
||||
|
||||
const root = createRoot(container)
|
||||
|
||||
await act(async () => {
|
||||
root.render(<Provider store={jotaiStore}>{element}</Provider>)
|
||||
})
|
||||
|
||||
return { container, root }
|
||||
}
|
||||
|
||||
describe("markdown spotlight rendering", () => {
|
||||
let root: Root | null = null
|
||||
let container: HTMLElement | null = null
|
||||
|
||||
beforeAll(() => {
|
||||
;(globalThis as typeof globalThis & { React: typeof React }).React = React
|
||||
;(
|
||||
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
if (root) {
|
||||
await act(async () => {
|
||||
root?.unmount()
|
||||
})
|
||||
}
|
||||
|
||||
container?.remove()
|
||||
root = null
|
||||
container = null
|
||||
})
|
||||
|
||||
test("HTML applies spotlight rules to rendered content", async () => {
|
||||
;({ container, root } = await renderMarkdownComponent(
|
||||
<HTML as="div" spotlightRules={[rule]}>
|
||||
{"<p>alpha beta</p>"}
|
||||
</HTML>,
|
||||
))
|
||||
|
||||
expect(container?.querySelector('[data-spotlight-rule-id="rule-1"]')?.textContent).toBe("alpha")
|
||||
})
|
||||
|
||||
test("Markdown applies spotlight rules to rendered content", async () => {
|
||||
;({ container, root } = await renderMarkdownComponent(
|
||||
<Markdown spotlightRules={[rule]}>{"alpha beta"}</Markdown>,
|
||||
))
|
||||
|
||||
expect(container?.querySelector('[data-spotlight-rule-id="rule-1"]')?.textContent).toBe("alpha")
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,5 @@
|
||||
export const ElECTRON_CUSTOM_TITLEBAR_HEIGHT = 30
|
||||
// export const ELECTRON_WINDOWS_RADIUS = 12
|
||||
|
||||
export const readableContentMaxWidthClassName = "max-w-[clamp(45ch,60vw,65ch)]"
|
||||
export const readableContentMaxWidthClassName =
|
||||
"max-w-[clamp(45ch,60vw,65ch)] print:max-w-[calc(100vw-2rem)]"
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, it } from "vitest"
|
||||
|
||||
import { buildAppFontFamily } from "../font-family"
|
||||
|
||||
describe("buildAppFontFamily", () => {
|
||||
it("keeps generic families unquoted and adds CJK fallbacks", () => {
|
||||
expect(buildAppFontFamily("system-ui")).toBe(
|
||||
'system-ui, "SN Pro", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif',
|
||||
)
|
||||
})
|
||||
|
||||
it("deduplicates preferred fonts that already exist in the fallback stack", () => {
|
||||
expect(buildAppFontFamily("PingFang SC")).toBe(
|
||||
'"PingFang SC", "SN Pro", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", system-ui, sans-serif',
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,61 @@
|
||||
const GENERIC_FONT_FAMILIES = new Set([
|
||||
"cursive",
|
||||
"emoji",
|
||||
"fangsong",
|
||||
"fantasy",
|
||||
"math",
|
||||
"monospace",
|
||||
"sans-serif",
|
||||
"serif",
|
||||
"system-ui",
|
||||
"ui-monospace",
|
||||
"ui-rounded",
|
||||
"ui-sans-serif",
|
||||
"ui-serif",
|
||||
])
|
||||
|
||||
const CJK_FONT_FALLBACKS = [
|
||||
"PingFang SC",
|
||||
"Hiragino Sans GB",
|
||||
"Microsoft YaHei",
|
||||
"Noto Sans CJK SC",
|
||||
]
|
||||
|
||||
const APP_FONT_FALLBACKS = ["SN Pro", ...CJK_FONT_FALLBACKS, "system-ui", "sans-serif"]
|
||||
|
||||
const normalizeFontFamily = (value: string) => {
|
||||
return value.trim().replaceAll(/^['"]|['"]$/g, "")
|
||||
}
|
||||
|
||||
const serializeFontFamily = (value: string) => {
|
||||
const normalizedValue = normalizeFontFamily(value)
|
||||
|
||||
if (GENERIC_FONT_FAMILIES.has(normalizedValue)) {
|
||||
return normalizedValue
|
||||
}
|
||||
|
||||
return `"${normalizedValue.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`
|
||||
}
|
||||
|
||||
export const buildAppFontFamily = (preferred?: string) => {
|
||||
const families = [preferred, ...APP_FONT_FALLBACKS]
|
||||
const seen = new Set<string>()
|
||||
|
||||
return families
|
||||
.map((family) => family?.trim() ?? "")
|
||||
.filter(Boolean)
|
||||
.filter((family) => {
|
||||
const normalizedValue = normalizeFontFamily(family).toLowerCase()
|
||||
|
||||
if (seen.has(normalizedValue)) {
|
||||
return false
|
||||
}
|
||||
|
||||
seen.add(normalizedValue)
|
||||
return true
|
||||
})
|
||||
.map(serializeFontFamily)
|
||||
.join(", ")
|
||||
}
|
||||
|
||||
export const DEFAULT_APP_FONT_FAMILY = buildAppFontFamily("system-ui")
|
||||
@@ -1,8 +1,9 @@
|
||||
import { MemoedDangerousHTMLStyle } from "@follow/components/common/MemoedDangerousHTMLStyle.jsx"
|
||||
import { Checkbox } from "@follow/components/ui/checkbox/index.jsx"
|
||||
import { LazyKateX } from "@follow/components/ui/katex/lazy.js"
|
||||
import { parseHtml as parseHtmlGeneral } from "@follow/utils/html"
|
||||
import type { Element } from "hast"
|
||||
import type { SpotlightRule } from "@follow/shared/spotlight"
|
||||
import { applySpotlightToHast, parseHtml as parseHtmlGeneral } from "@follow/utils/html"
|
||||
import type { Element, Root } from "hast"
|
||||
import type { Components } from "hast-util-to-jsx-runtime"
|
||||
import { createElement } from "react"
|
||||
import { renderToString } from "react-dom/server"
|
||||
@@ -28,10 +29,25 @@ export const parseHtml = (
|
||||
options?: Partial<{
|
||||
renderInlineStyle: boolean
|
||||
noMedia?: boolean
|
||||
spotlightRules?: SpotlightRule[]
|
||||
hastTransform?: (tree: Root) => void
|
||||
}>,
|
||||
) => {
|
||||
const spotlightRules = options?.spotlightRules
|
||||
const hastTransform = options?.hastTransform
|
||||
|
||||
return parseHtmlGeneral(content, {
|
||||
...options,
|
||||
hastTransform:
|
||||
spotlightRules?.length || hastTransform
|
||||
? (tree) => {
|
||||
if (spotlightRules?.length) {
|
||||
applySpotlightToHast(tree, spotlightRules)
|
||||
}
|
||||
|
||||
hastTransform?.(tree)
|
||||
}
|
||||
: undefined,
|
||||
components: {
|
||||
a: ({ node, ...props }) => {
|
||||
// markInlineImage(node)
|
||||
|
||||
@@ -1,14 +1,32 @@
|
||||
import type { RemarkOptions } from "@follow/components/utils/parse-markdown.js"
|
||||
import { parseMarkdown as parseMarkdownImpl } from "@follow/components/utils/parse-markdown.js"
|
||||
import type { SpotlightRule } from "@follow/shared/spotlight"
|
||||
import { applySpotlightToHast } from "@follow/utils/html"
|
||||
import { createElement } from "react"
|
||||
|
||||
import { MarkdownLink } from "~/components/ui/markdown/renderers/MarkdownLink"
|
||||
import { VideoPlayer } from "~/components/ui/media/VideoPlayer"
|
||||
|
||||
export const parseMarkdown = (content: string, options?: Partial<RemarkOptions>) => {
|
||||
export const parseMarkdown = (
|
||||
content: string,
|
||||
options?: Partial<RemarkOptions> & { spotlightRules?: SpotlightRule[] },
|
||||
) => {
|
||||
const videoExts = ["mp4", "webm"]
|
||||
const spotlightRules = options?.spotlightRules
|
||||
const rehypePlugins = [
|
||||
...(options?.rehypePlugins ?? []),
|
||||
...(spotlightRules?.length
|
||||
? [
|
||||
() => (tree: Parameters<typeof applySpotlightToHast>[0]) => {
|
||||
applySpotlightToHast(tree, spotlightRules)
|
||||
},
|
||||
]
|
||||
: []),
|
||||
]
|
||||
|
||||
return parseMarkdownImpl(content, {
|
||||
...options,
|
||||
rehypePlugins,
|
||||
components: {
|
||||
a: ({ node, ...props }) => createElement(MarkdownLink, { ...props } as any),
|
||||
img: ({ node, ...props }) => {
|
||||
|
||||
+9
-1
@@ -2,6 +2,9 @@ import { useEntry } from "@follow/store/entry/hooks"
|
||||
import { useFeedsByIds } from "@follow/store/feed/hooks"
|
||||
import * as React from "react"
|
||||
|
||||
import { useSpotlightSettingKey } from "~/atoms/settings/spotlight"
|
||||
import { HighlightedText } from "~/modules/spotlight/HighlightedText"
|
||||
|
||||
interface TitleProps {
|
||||
fallback: string
|
||||
}
|
||||
@@ -19,12 +22,17 @@ interface FeedTitleProps extends TitleProps {
|
||||
*/
|
||||
export const EntryTitle: React.FC<EntryTitleProps> = React.memo(({ entryId, fallback }) => {
|
||||
const entryTitle = useEntry(entryId!, (e) => e?.title)
|
||||
const spotlightRules = useSpotlightSettingKey("spotlights")
|
||||
|
||||
if (!entryId || !entryTitle) {
|
||||
return <span className="text-text-tertiary">{fallback}</span>
|
||||
}
|
||||
|
||||
return <span title={entryTitle}>{entryTitle}</span>
|
||||
return (
|
||||
<span title={entryTitle}>
|
||||
<HighlightedText rules={spotlightRules} text={entryTitle} />
|
||||
</span>
|
||||
)
|
||||
})
|
||||
|
||||
EntryTitle.displayName = "EntryTitle"
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
|
||||
|
||||
import { computeRateLimitMessage } from "./rate-limit"
|
||||
|
||||
vi.mock("~/i18n", () => ({
|
||||
getI18n: () => ({
|
||||
language: "en-GB",
|
||||
resolvedLanguage: "en-GB",
|
||||
t: (key: string, options?: Record<string, unknown>) => {
|
||||
switch (key) {
|
||||
case "rate_limit.depleted": {
|
||||
return "AI credits depleted"
|
||||
}
|
||||
case "rate_limit.minute": {
|
||||
return "minute"
|
||||
}
|
||||
case "rate_limit.minutes": {
|
||||
return "minutes"
|
||||
}
|
||||
case "rate_limit.resets_at": {
|
||||
return `resets at ${options?.time as string}`
|
||||
}
|
||||
case "rate_limit.resets_in": {
|
||||
return `resets in ${options?.value as string}`
|
||||
}
|
||||
case "rate_limit.credits_left": {
|
||||
return `${options?.count as number} credits left`
|
||||
}
|
||||
case "rate_limit.upgrade_to_get_more": {
|
||||
return "Start free trial to get more AI credits."
|
||||
}
|
||||
default: {
|
||||
return key
|
||||
}
|
||||
}
|
||||
},
|
||||
}),
|
||||
}))
|
||||
|
||||
describe("computeRateLimitMessage", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it("shows only the time when credits reset later today", () => {
|
||||
vi.setSystemTime(new Date(2026, 3, 10, 8, 0))
|
||||
|
||||
const message = computeRateLimitMessage(undefined, {
|
||||
usage: {
|
||||
total: 5_000_000,
|
||||
used: 5_000_000,
|
||||
remaining: 0,
|
||||
resetAt: new Date(2026, 3, 10, 20, 45),
|
||||
},
|
||||
})
|
||||
|
||||
expect(message).toBe("AI credits depleted · resets at 20:45")
|
||||
})
|
||||
|
||||
it("includes the date when credits reset on a future day", () => {
|
||||
vi.setSystemTime(new Date(2026, 3, 10, 8, 0))
|
||||
|
||||
const message = computeRateLimitMessage(undefined, {
|
||||
usage: {
|
||||
total: 5_000_000,
|
||||
used: 5_000_000,
|
||||
remaining: 0,
|
||||
resetAt: new Date(2026, 3, 12, 20, 45),
|
||||
},
|
||||
})
|
||||
|
||||
expect(message).toBe("AI credits depleted · resets at 12 Apr, 20:45")
|
||||
})
|
||||
})
|
||||
@@ -20,6 +20,7 @@ const formatResetTime = (windowResetTime: Date) => {
|
||||
const now = new Date()
|
||||
const diffMs = resetDate.getTime() - now.getTime()
|
||||
const diffMinutes = Math.ceil(diffMs / (1000 * 60))
|
||||
const locale = i18n.language || i18n.resolvedLanguage || undefined
|
||||
|
||||
if (diffMinutes < 60 && diffMinutes > 0) {
|
||||
const unit =
|
||||
@@ -30,12 +31,31 @@ const formatResetTime = (windowResetTime: Date) => {
|
||||
return t("rate_limit.resets_in", { ns: "ai", value })
|
||||
}
|
||||
|
||||
const timeFormatter = new Intl.DateTimeFormat("en-GB", {
|
||||
const isSameCalendarDay =
|
||||
resetDate.getFullYear() === now.getFullYear() &&
|
||||
resetDate.getMonth() === now.getMonth() &&
|
||||
resetDate.getDate() === now.getDate()
|
||||
|
||||
const time = new Intl.DateTimeFormat(locale, {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
hour12: false,
|
||||
})
|
||||
return t("rate_limit.resets_at", { ns: "ai", time: timeFormatter.format(resetDate) })
|
||||
}).format(resetDate)
|
||||
|
||||
if (isSameCalendarDay) {
|
||||
return t("rate_limit.resets_at", { ns: "ai", time })
|
||||
}
|
||||
|
||||
const dateTime = new Intl.DateTimeFormat(locale, {
|
||||
...(resetDate.getFullYear() !== now.getFullYear() ? { year: "numeric" as const } : {}),
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
hour12: false,
|
||||
}).format(resetDate)
|
||||
|
||||
return t("rate_limit.resets_at", { ns: "ai", time: dateTime })
|
||||
}
|
||||
|
||||
export function computeIsRateLimited(
|
||||
|
||||
+5
-1
@@ -218,6 +218,7 @@ const AIEnhancedTimelineLayoutImpl = () => {
|
||||
<AppLayoutGridContainerProvider>
|
||||
<div ref={layoutContainerRef} className="flex h-full min-w-0">
|
||||
<div
|
||||
data-hide-in-print={showEntryDetailsColumn ? true : undefined}
|
||||
className={cn(
|
||||
"relative flex h-full flex-col overflow-hidden",
|
||||
shouldShowEntryBorder && "border-r",
|
||||
@@ -273,9 +274,12 @@ const AIEnhancedTimelineLayoutImpl = () => {
|
||||
{splitter}
|
||||
|
||||
<div
|
||||
data-hide-in-print={
|
||||
!showEntryContentOnRight && shouldShowFixedAI ? true : undefined
|
||||
}
|
||||
className={cn(
|
||||
"relative flex h-full min-w-0 flex-col overflow-hidden bg-theme-background",
|
||||
showEntryDetailsColumn ? "flex-1" : "flex-none",
|
||||
showEntryDetailsColumn ? "flex-1 print:w-full" : "flex-none",
|
||||
)}
|
||||
style={rightColumnStyle}
|
||||
>
|
||||
|
||||
@@ -25,9 +25,14 @@ export const AIIndicator: FC = () => {
|
||||
return (
|
||||
<>
|
||||
<AnimatePresence>
|
||||
{shouldShow && !showSplineButton && <AISmartSidebar />}
|
||||
{shouldShow && !showSplineButton && (
|
||||
<div data-hide-in-print>
|
||||
<AISmartSidebar />
|
||||
</div>
|
||||
)}
|
||||
{shouldShow && showSplineButton && (
|
||||
<m.button
|
||||
data-hide-in-print
|
||||
key="ai-spline-button"
|
||||
initial={{ scale: 0, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
|
||||
@@ -1,18 +1,9 @@
|
||||
import type { UniqueIdentifier } from "@dnd-kit/core"
|
||||
import { useSortable } from "@dnd-kit/sortable"
|
||||
import { CSS } from "@dnd-kit/utilities"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipPortal,
|
||||
TooltipTrigger,
|
||||
} from "@follow/components/ui/tooltip/index.js"
|
||||
import { IN_ELECTRON } from "@follow/shared"
|
||||
import type { ReactNode } from "react"
|
||||
import { useMemo } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
|
||||
import { COMMAND_ID } from "../command/commands/id"
|
||||
import { getCommand } from "../command/hooks/use-command"
|
||||
import type { FollowCommandId } from "../command/types"
|
||||
|
||||
@@ -49,25 +40,8 @@ const SortableItem = ({ id, children }: { id: UniqueIdentifier; children: ReactN
|
||||
)
|
||||
}
|
||||
|
||||
const warningActionButton: Partial<
|
||||
Record<
|
||||
FollowCommandId,
|
||||
{
|
||||
show: boolean
|
||||
info: string
|
||||
}
|
||||
>
|
||||
> = {
|
||||
[COMMAND_ID.entry.tts]: {
|
||||
show: !IN_ELECTRON,
|
||||
info: "entry_actions.warn_info_for_desktop",
|
||||
},
|
||||
}
|
||||
|
||||
export const SortableActionButton = ({ id }: { id: UniqueIdentifier }) => {
|
||||
const cmd = getCommand(id as FollowCommandId)
|
||||
const warnInfo = warningActionButton[id as FollowCommandId]
|
||||
const { t } = useTranslation()
|
||||
if (!cmd) return null
|
||||
return (
|
||||
<SortableItem id={id}>
|
||||
@@ -75,19 +49,7 @@ export const SortableActionButton = ({ id }: { id: UniqueIdentifier }) => {
|
||||
<div className="flex size-8 items-center justify-center text-xl">
|
||||
{typeof cmd.icon === "function" ? cmd.icon({ isActive: false }) : cmd.icon}
|
||||
</div>
|
||||
<div className="mt-1 text-center text-callout text-text-secondary">
|
||||
{warnInfo?.show && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger>
|
||||
<i className="i-mgc-information-cute-re mr-1 translate-y-[2px]" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPortal>
|
||||
<TooltipContent>{t(warnInfo.info as any)}</TooltipContent>
|
||||
</TooltipPortal>
|
||||
</Tooltip>
|
||||
)}
|
||||
{cmd.label.title}
|
||||
</div>
|
||||
<div className="mt-1 text-center text-callout text-text-secondary">{cmd.label.title}</div>
|
||||
</div>
|
||||
</SortableItem>
|
||||
)
|
||||
|
||||
@@ -20,6 +20,7 @@ import { titleCase } from "title-case"
|
||||
|
||||
import { AudioPlayer, useAudioPlayerAtomSelector } from "~/atoms/player"
|
||||
import { useGeneralSettingKey } from "~/atoms/settings/general"
|
||||
import { useSpotlightSettingKey } from "~/atoms/settings/spotlight"
|
||||
import { RelativeTime } from "~/components/ui/datetime"
|
||||
import { FEED_COLLECTION_LIST } from "~/constants"
|
||||
import { useEntryIsRead } from "~/hooks/biz/useAsRead"
|
||||
@@ -28,6 +29,7 @@ import { EntryTranslation } from "~/modules/entry-column/translation"
|
||||
import type { FeedIconEntry } from "~/modules/feed/feed-icon"
|
||||
import { FeedIcon } from "~/modules/feed/feed-icon"
|
||||
import { FeedTitle } from "~/modules/feed/feed-title"
|
||||
import { HighlightedText } from "~/modules/spotlight/HighlightedText"
|
||||
import { getPreferredTitle } from "~/store/feed/hooks"
|
||||
|
||||
import { StarIcon } from "../star-icon"
|
||||
@@ -208,6 +210,8 @@ export function AllItem({ entryId, translation, currentFeedTitle }: UniversalIte
|
||||
AllItem.wrapperClassName = "pl-5 pr-4 @[700px]:pl-6 @[1024px]:pr-5"
|
||||
|
||||
export function AllItemStateLess({ entry, feed }: EntryItemStatelessProps) {
|
||||
const spotlightRules = useSpotlightSettingKey("spotlights")
|
||||
|
||||
return (
|
||||
<div className="group relative flex cursor-menu py-4">
|
||||
<FeedIcon target={feed} fallback className="mr-2 size-5" />
|
||||
@@ -218,7 +222,7 @@ export function AllItemStateLess({ entry, feed }: EntryItemStatelessProps) {
|
||||
<span>{!!entry.publishedAt && <RelativeTime date={entry.publishedAt} />}</span>
|
||||
</div>
|
||||
<div className="relative my-0.5 truncate break-words font-medium text-text">
|
||||
{entry.title}
|
||||
<HighlightedText rules={spotlightRules} text={entry.title} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { Provider } from "jotai"
|
||||
import * as React from "react"
|
||||
import { act } from "react"
|
||||
import type { Root } from "react-dom/client"
|
||||
import { createRoot } from "react-dom/client"
|
||||
import { afterEach, beforeAll, describe, expect, test, vi } from "vitest"
|
||||
|
||||
import { jotaiStore } from "~/lib/jotai"
|
||||
|
||||
import { EntryTranslation } from "./translation"
|
||||
|
||||
vi.mock("~/atoms/settings/general", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("~/atoms/settings/general")>()
|
||||
|
||||
return {
|
||||
...actual,
|
||||
useGeneralSettingKey: vi.fn(() => "translation"),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock("~/atoms/settings/spotlight", () => ({
|
||||
useSpotlightSettingKey: vi.fn(() => [
|
||||
{
|
||||
id: "rule-1",
|
||||
enabled: true,
|
||||
pattern: "alpha",
|
||||
patternType: "keyword",
|
||||
caseSensitive: false,
|
||||
color: "#FDE68A",
|
||||
},
|
||||
]),
|
||||
}))
|
||||
|
||||
const renderTranslation = async (element: React.ReactNode) => {
|
||||
const container = document.createElement("div")
|
||||
document.body.append(container)
|
||||
|
||||
const root = createRoot(container)
|
||||
|
||||
await act(async () => {
|
||||
root.render(<Provider store={jotaiStore}>{element}</Provider>)
|
||||
})
|
||||
|
||||
return { container, root }
|
||||
}
|
||||
|
||||
describe("EntryTranslation spotlight", () => {
|
||||
let root: Root | null = null
|
||||
let container: HTMLElement | null = null
|
||||
|
||||
beforeAll(() => {
|
||||
;(globalThis as typeof globalThis & { React: typeof React }).React = React
|
||||
;(
|
||||
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
if (root) {
|
||||
await act(async () => {
|
||||
root?.unmount()
|
||||
})
|
||||
}
|
||||
|
||||
container?.remove()
|
||||
root = null
|
||||
container = null
|
||||
})
|
||||
|
||||
test("highlights matching plain-text entry titles", async () => {
|
||||
;({ container, root } = await renderTranslation(
|
||||
<EntryTranslation source="alpha beta" target={null} />,
|
||||
))
|
||||
|
||||
expect(container?.querySelector('[data-spotlight-rule-id="rule-1"]')?.textContent).toBe("alpha")
|
||||
})
|
||||
})
|
||||
@@ -2,7 +2,9 @@ import { cn } from "@follow/utils/utils"
|
||||
import { useMemo } from "react"
|
||||
|
||||
import { useGeneralSettingKey } from "~/atoms/settings/general"
|
||||
import { useSpotlightSettingKey } from "~/atoms/settings/spotlight"
|
||||
import { HTML } from "~/components/ui/markdown/HTML"
|
||||
import { HighlightedText } from "~/modules/spotlight/HighlightedText"
|
||||
|
||||
export const EntryTranslation: Component<{
|
||||
source?: string | null
|
||||
@@ -12,6 +14,7 @@ export const EntryTranslation: Component<{
|
||||
bilingual?: boolean
|
||||
}> = ({ source, target, className, isHTML, inline = true, bilingual }) => {
|
||||
const bilingualFinal = useGeneralSettingKey("translationMode") === "bilingual" || bilingual
|
||||
const spotlightRules = useSpotlightSettingKey("spotlights")
|
||||
|
||||
const nextTarget = useMemo(() => {
|
||||
if (!target || source === target) {
|
||||
@@ -28,11 +31,18 @@ export const EntryTranslation: Component<{
|
||||
return (
|
||||
<div>
|
||||
{isHTML ? (
|
||||
<HTML as="div" className={cn("prose dark:prose-invert", className)} noMedia>
|
||||
<HTML
|
||||
as="div"
|
||||
className={cn("prose dark:prose-invert", className)}
|
||||
noMedia
|
||||
spotlightRules={spotlightRules}
|
||||
>
|
||||
{nextTarget || source}
|
||||
</HTML>
|
||||
) : (
|
||||
<div className={className}>{nextTarget || source}</div>
|
||||
<div className={className}>
|
||||
<HighlightedText rules={spotlightRules} text={nextTarget || source} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
@@ -43,19 +53,32 @@ export const EntryTranslation: Component<{
|
||||
return (
|
||||
<>
|
||||
{isHTML ? (
|
||||
<HTML as="div" className={cn("prose dark:prose-invert", className)} noMedia>
|
||||
<HTML
|
||||
as="div"
|
||||
className={cn("prose dark:prose-invert", className)}
|
||||
noMedia
|
||||
spotlightRules={spotlightRules}
|
||||
>
|
||||
{nextTarget || source}
|
||||
</HTML>
|
||||
) : (
|
||||
<div className={cn(inline && "inline align-middle", className)}>
|
||||
{nextTarget && inline && (
|
||||
<>
|
||||
<span className="align-middle">{nextTarget}</span>
|
||||
<span className="align-middle">
|
||||
<HighlightedText rules={spotlightRules} text={nextTarget} />
|
||||
</span>
|
||||
<i className="i-mgc-translate-2-ai-cute-re mx-2 align-middle" />
|
||||
</>
|
||||
)}
|
||||
<SourceTag className={cn(inline && "align-middle")}>{source}</SourceTag>
|
||||
{nextTarget && !inline && <p>{nextTarget}</p>}
|
||||
<SourceTag className={cn(inline && "align-middle")}>
|
||||
<HighlightedText rules={spotlightRules} text={source} />
|
||||
</SourceTag>
|
||||
{nextTarget && !inline && (
|
||||
<p>
|
||||
<HighlightedText rules={spotlightRules} text={nextTarget} />
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -42,6 +42,7 @@ import { EntryNoContent } from "./components/entry-content/EntryNoContent"
|
||||
import { EntryScrollingAndNavigationHandler } from "./components/entry-content/EntryScrollingAndNavigationHandler.js"
|
||||
import { EntryTitleMetaHandler } from "./components/entry-content/EntryTitleMetaHandler"
|
||||
import type { EntryContentProps } from "./components/entry-content/types"
|
||||
import { EntryPrintHeader } from "./components/EntryPrintHeader"
|
||||
import { getEntryContentLayout } from "./components/layouts"
|
||||
import type { EntryLayoutProps } from "./components/layouts/types"
|
||||
import { SourceContentPanel } from "./components/SourceContentView"
|
||||
@@ -152,7 +153,7 @@ const EntryContentImpl: Component<EntryContentProps> = ({
|
||||
title: entryTranslation.title ?? undefined,
|
||||
}
|
||||
: undefined,
|
||||
[entryTranslation?.content, entryTranslation?.title],
|
||||
[entryTranslation],
|
||||
)
|
||||
return (
|
||||
<div className={cn(className, "flex flex-col @container")}>
|
||||
@@ -212,9 +213,10 @@ const EntryContentImpl: Component<EntryContentProps> = ({
|
||||
<article
|
||||
data-testid="entry-render"
|
||||
onContextMenu={stopPropagation}
|
||||
className={"relative w-full min-w-0 pb-10 pt-12"}
|
||||
className={"relative w-full min-w-0 pb-10 pt-12 print:pt-0"}
|
||||
>
|
||||
<ApplyEntryActions entryId={entryId} key={entryId} />
|
||||
<EntryPrintHeader entryId={entryId} />
|
||||
|
||||
{!content && !isInReadabilityMode ? (
|
||||
<div className="center mt-16 min-w-0">
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { Folo } from "@follow/components/icons/folo.js"
|
||||
import { Logo } from "@follow/components/icons/logo.jsx"
|
||||
import { useEntry } from "@follow/store/entry/hooks"
|
||||
import { useFeedById } from "@follow/store/feed/hooks"
|
||||
import { useInboxById } from "@follow/store/inbox/hooks"
|
||||
import { cn } from "@follow/utils/utils"
|
||||
|
||||
import { readableContentMaxWidthClassName } from "~/constants/ui"
|
||||
|
||||
const PRINT_HOMEPAGE = "https://folo.is"
|
||||
const PRINT_HOMEPAGE_LABEL = "folo.is"
|
||||
|
||||
export const EntryPrintHeader = ({ entryId }: { entryId: string }) => {
|
||||
const entry = useEntry(entryId, (state) => ({
|
||||
feedId: state.feedId,
|
||||
inboxId: state.inboxHandle,
|
||||
}))
|
||||
|
||||
const feed = useFeedById(entry?.feedId)
|
||||
const inbox = useInboxById(entry?.inboxId)
|
||||
const sourceTitle = feed?.title || inbox?.title
|
||||
|
||||
return (
|
||||
<div className={cn("hidden print:block", readableContentMaxWidthClassName, "mx-auto px-4")}>
|
||||
<div className="mb-8 border-b border-border pb-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Logo className="size-4 shrink-0" />
|
||||
<Folo className="h-4 w-auto shrink-0 text-text" />
|
||||
</div>
|
||||
|
||||
<a
|
||||
href={PRINT_HOMEPAGE}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="text-xs font-medium text-text-secondary no-underline"
|
||||
>
|
||||
{PRINT_HOMEPAGE_LABEL}
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div className="mt-3 space-y-1.5">
|
||||
<p className="text-sm font-medium text-text-secondary">
|
||||
The AI Reader that reads the internet for you
|
||||
</p>
|
||||
{sourceTitle ? (
|
||||
<p className="text-sm text-text-secondary">Source: {sourceTitle}</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+1
-1
@@ -58,7 +58,7 @@ export const ArticleLayout: React.FC<EntryLayoutProps> = ({
|
||||
|
||||
return (
|
||||
<div className={cn(readableContentMaxWidthClassName, "mx-auto mt-1 px-4")}>
|
||||
<EntryTitle entryId={entryId} compact={compact} containerClassName="mt-12" />
|
||||
<EntryTitle entryId={entryId} compact={compact} containerClassName="mt-12 print:mt-6" />
|
||||
|
||||
<ArticleAudioPlayer entryId={entryId} />
|
||||
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ export const SocialMediaLayout: React.FC<EntryLayoutProps> = ({
|
||||
if (!entry || !feed) return null
|
||||
|
||||
return (
|
||||
<div className={cn(readableContentMaxWidthClassName, "mx-auto space-y-5 pt-12")}>
|
||||
<div className={cn(readableContentMaxWidthClassName, "mx-auto space-y-5 pt-12 print:pt-6")}>
|
||||
{/* Single Author header without avatar */}
|
||||
<AuthorHeader entryId={entryId} />
|
||||
|
||||
|
||||
+3
@@ -1,6 +1,7 @@
|
||||
import { useEntry } from "@follow/store/entry/hooks"
|
||||
import { cn } from "@follow/utils/utils"
|
||||
|
||||
import { useSpotlightSettingKey } from "~/atoms/settings/spotlight"
|
||||
import { HTML } from "~/components/ui/markdown/HTML"
|
||||
import { readableContentMaxWidthClassName } from "~/constants/ui"
|
||||
import { useRenderStyle } from "~/hooks/biz/useRenderStyle"
|
||||
@@ -32,6 +33,7 @@ export const ContentBody: React.FC<ContentBodyProps> = ({
|
||||
baseFontSize: compact ? 14 : 16,
|
||||
baseLineHeight: compact ? 1.625 : 1.7,
|
||||
})
|
||||
const spotlightRules = useSpotlightSettingKey("spotlights")
|
||||
|
||||
if (!entry) return null
|
||||
|
||||
@@ -51,6 +53,7 @@ export const ContentBody: React.FC<ContentBodyProps> = ({
|
||||
className,
|
||||
)}
|
||||
noMedia={noMedia}
|
||||
spotlightRules={spotlightRules}
|
||||
style={renderStyle}
|
||||
>
|
||||
{content}
|
||||
|
||||
+4
-1
@@ -9,6 +9,7 @@ import { useHover } from "@use-gesture/react"
|
||||
import { useEffect, useMemo, useRef, useState } from "react"
|
||||
|
||||
import { AudioPlayer } from "~/atoms/player"
|
||||
import { useSpotlightSettingKey } from "~/atoms/settings/spotlight"
|
||||
import { m } from "~/components/common/Motion"
|
||||
import { HTML } from "~/components/ui/markdown/HTML"
|
||||
import { Media } from "~/components/ui/media/Media"
|
||||
@@ -72,7 +73,7 @@ export const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
lang,
|
||||
}),
|
||||
],
|
||||
[entry?.attachments, entry?.url],
|
||||
[entry?.attachments, entry?.url, lang],
|
||||
)
|
||||
|
||||
const modalStack = useModalStack()
|
||||
@@ -186,6 +187,7 @@ const PreviewVideoModalContent: ModalContentComponent<{
|
||||
|
||||
const content = translation?.content || entry?.content
|
||||
const currentAudioPlayerIsPlay = useRef(AudioPlayer.get().status === "playing")
|
||||
const spotlightRules = useSpotlightSettingKey("spotlights")
|
||||
|
||||
const renderStyle = useRenderStyle()
|
||||
|
||||
@@ -221,6 +223,7 @@ const PreviewVideoModalContent: ModalContentComponent<{
|
||||
as="div"
|
||||
className="prose !max-w-full dark:prose-invert"
|
||||
noMedia
|
||||
spotlightRules={spotlightRules}
|
||||
style={renderStyle}
|
||||
>
|
||||
{content}
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
import { defaultGeneralSettings } from "@follow/shared/settings/defaults"
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
|
||||
|
||||
import { playEntryTts } from "./entry-tts"
|
||||
|
||||
const {
|
||||
getEntryMock,
|
||||
getGeneralSettingsMock,
|
||||
getReadabilityStatusMock,
|
||||
legacyTtsMock,
|
||||
mountMock,
|
||||
toastFetchErrorMock,
|
||||
} = vi.hoisted(() => ({
|
||||
getEntryMock: vi.fn(),
|
||||
getGeneralSettingsMock: vi.fn(),
|
||||
getReadabilityStatusMock: vi.fn(),
|
||||
legacyTtsMock: vi.fn(),
|
||||
mountMock: vi.fn(),
|
||||
toastFetchErrorMock: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock("@follow/store/entry/getter", () => ({
|
||||
getEntry: getEntryMock,
|
||||
}))
|
||||
|
||||
vi.mock("~/atoms/readability", () => ({
|
||||
ReadabilityStatus: {
|
||||
INITIAL: 1,
|
||||
WAITING: 2,
|
||||
SUCCESS: 3,
|
||||
FAILURE: 4,
|
||||
},
|
||||
getReadabilityStatus: getReadabilityStatusMock,
|
||||
}))
|
||||
|
||||
vi.mock("~/atoms/settings/general", () => ({
|
||||
getGeneralSettings: getGeneralSettingsMock,
|
||||
}))
|
||||
|
||||
vi.mock("~/atoms/player", () => ({
|
||||
AudioPlayer: {
|
||||
mount: mountMock,
|
||||
},
|
||||
getAudioPlayerAtomValue: vi.fn(() => ({})),
|
||||
setAudioPlayerAtomValue: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock("~/lib/api-client", () => ({
|
||||
followClient: {
|
||||
api: {
|
||||
ai: {
|
||||
tts: legacyTtsMock,
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock("~/lib/error-parser", () => ({
|
||||
toastFetchError: toastFetchErrorMock,
|
||||
}))
|
||||
|
||||
describe("entry tts", () => {
|
||||
const fetchMock = vi.fn<typeof fetch>()
|
||||
const createObjectURLMock = vi.fn(() => "blob:tts-audio")
|
||||
const revokeObjectURLMock = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("fetch", fetchMock)
|
||||
vi.stubGlobal(
|
||||
"URL",
|
||||
Object.assign(URL, {
|
||||
createObjectURL: createObjectURLMock,
|
||||
revokeObjectURL: revokeObjectURLMock,
|
||||
}),
|
||||
)
|
||||
|
||||
getEntryMock.mockReturnValue({
|
||||
id: "entry-1",
|
||||
title: "",
|
||||
content: "Hello world",
|
||||
readabilityContent: "",
|
||||
description: "",
|
||||
})
|
||||
getGeneralSettingsMock.mockReturnValue({
|
||||
voice: "en-US-AvaMultilingualNeural",
|
||||
})
|
||||
getReadabilityStatusMock.mockReturnValue({})
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(new Blob(["audio"], { type: "audio/mpeg" }), {
|
||||
headers: {
|
||||
"content-type": "audio/mpeg",
|
||||
},
|
||||
status: 200,
|
||||
}),
|
||||
)
|
||||
legacyTtsMock.mockRejectedValue(new Error("legacy api should not be used"))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it("requests entry tts from the new service", async () => {
|
||||
await playEntryTts("entry-1", { toastTitle: "Play TTS" })
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"https://tts.folo.is/tts",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
signal: expect.any(AbortSignal),
|
||||
}),
|
||||
)
|
||||
|
||||
const requestInit = fetchMock.mock.calls[0]?.[1]
|
||||
expect(requestInit).toBeDefined()
|
||||
expect(JSON.parse(String(requestInit?.body))).toEqual({
|
||||
text: "Hello world",
|
||||
voice: "en-US-AvaMultilingualNeural",
|
||||
})
|
||||
|
||||
expect(legacyTtsMock).not.toHaveBeenCalled()
|
||||
expect(mountMock).toHaveBeenCalledWith({
|
||||
currentTime: 0,
|
||||
entryId: "entry-1",
|
||||
src: "blob:tts-audio",
|
||||
type: "audio",
|
||||
})
|
||||
})
|
||||
|
||||
it("uses the new default voice", () => {
|
||||
expect(defaultGeneralSettings.voice).toBe("en-US-AvaMultilingualNeural")
|
||||
})
|
||||
})
|
||||
@@ -1,7 +1,12 @@
|
||||
import { getEntry } from "@follow/store/entry/getter"
|
||||
|
||||
import { AudioPlayer, getAudioPlayerAtomValue, setAudioPlayerAtomValue } from "~/atoms/player"
|
||||
import { followClient } from "~/lib/api-client"
|
||||
import { getReadabilityStatus, ReadabilityStatus } from "~/atoms/readability"
|
||||
import { getGeneralSettings } from "~/atoms/settings/general"
|
||||
import { toastFetchError } from "~/lib/error-parser"
|
||||
|
||||
import { getEntryTtsText, requestTts } from "./tts-service"
|
||||
|
||||
const TTS_MIME_FALLBACK = "audio/ogg; codecs=opus"
|
||||
const STREAM_PLACEHOLDER_SRC = "about:blank"
|
||||
|
||||
@@ -318,7 +323,24 @@ export const playEntryTts = async (entryId: string, { toastTitle }: { toastTitle
|
||||
activeTtsAbortController = abortController
|
||||
|
||||
try {
|
||||
const response = await followClient.api.ai.tts({ entryId }, { signal: abortController.signal })
|
||||
const entry = getEntry(entryId)
|
||||
if (!entry) {
|
||||
throw new Error("Entry not found")
|
||||
}
|
||||
|
||||
const preferReadability = getReadabilityStatus()[entryId] === ReadabilityStatus.SUCCESS
|
||||
const text = getEntryTtsText(entry, { preferReadability })
|
||||
|
||||
if (!text) {
|
||||
throw new Error("No content available for TTS")
|
||||
}
|
||||
|
||||
const { voice } = getGeneralSettings()
|
||||
const response = await requestTts({
|
||||
text,
|
||||
voice,
|
||||
signal: abortController.signal,
|
||||
})
|
||||
|
||||
let handled = false
|
||||
if (response.body && getAudioContextConstructor()) {
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import type { EntryModel } from "@follow/store/entry/types"
|
||||
import { parseHtml } from "@follow/utils/html"
|
||||
|
||||
export const TTS_SERVICE_URL = "https://tts.folo.is"
|
||||
export const DEFAULT_TTS_VOICE = "en-US-AvaMultilingualNeural"
|
||||
|
||||
export interface TtsVoice {
|
||||
FriendlyName: string
|
||||
Gender: string
|
||||
Locale: string
|
||||
ShortName: string
|
||||
}
|
||||
|
||||
interface TtsVoiceResponse {
|
||||
voices: TtsVoice[]
|
||||
}
|
||||
|
||||
interface TtsErrorResponse {
|
||||
error?: {
|
||||
message?: string
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeTtsText = (value: string) =>
|
||||
value
|
||||
.replaceAll("\r\n", "\n")
|
||||
.replaceAll(/[^\S\n]+/g, " ")
|
||||
.replaceAll(/\n{3,}/g, "\n\n")
|
||||
.trim()
|
||||
|
||||
const toPlainText = (value: string) => normalizeTtsText(parseHtml(value).toText())
|
||||
|
||||
export const getEntryTtsText = (
|
||||
entry: Pick<EntryModel, "content" | "description" | "readabilityContent" | "title">,
|
||||
options?: {
|
||||
preferReadability?: boolean
|
||||
},
|
||||
) => {
|
||||
const { preferReadability = false } = options ?? {}
|
||||
|
||||
const title = normalizeTtsText(entry.title || "")
|
||||
const bodySource = preferReadability
|
||||
? entry.readabilityContent || entry.content || entry.description || ""
|
||||
: entry.content || entry.description || entry.readabilityContent || ""
|
||||
const body = bodySource ? toPlainText(bodySource) : ""
|
||||
|
||||
return [title, body].filter(Boolean).join("\n\n")
|
||||
}
|
||||
|
||||
const readTtsErrorMessage = async (response: Response) => {
|
||||
try {
|
||||
const data = (await response.clone().json()) as TtsErrorResponse
|
||||
return data?.error?.message || "TTS request failed"
|
||||
} catch {
|
||||
return "TTS request failed"
|
||||
}
|
||||
}
|
||||
|
||||
export const fetchTtsVoices = async (signal?: AbortSignal) => {
|
||||
const response = await fetch(`${TTS_SERVICE_URL}/voices`, { signal })
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(await readTtsErrorMessage(response))
|
||||
}
|
||||
|
||||
const data = (await response.json()) as TtsVoiceResponse
|
||||
return data.voices ?? []
|
||||
}
|
||||
|
||||
export const requestTts = async ({
|
||||
signal,
|
||||
text,
|
||||
voice,
|
||||
}: {
|
||||
text: string
|
||||
voice?: string
|
||||
signal?: AbortSignal
|
||||
}) => {
|
||||
const normalizedText = normalizeTtsText(text)
|
||||
if (!normalizedText) {
|
||||
throw new Error("Text is required")
|
||||
}
|
||||
|
||||
const normalizedVoice = voice?.trim()
|
||||
|
||||
const response = await fetch(`${TTS_SERVICE_URL}/tts`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
text: normalizedText,
|
||||
...(normalizedVoice ? { voice: normalizedVoice } : {}),
|
||||
}),
|
||||
signal,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(await readTtsErrorMessage(response))
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { getFeedById } from "@follow/store/feed/getter"
|
||||
import { useMemo } from "react"
|
||||
import type { JSX } from "react/jsx-runtime"
|
||||
|
||||
import { useSpotlightSettingKey } from "~/atoms/settings/spotlight"
|
||||
import {
|
||||
MarkdownImageRecordContext,
|
||||
MarkdownRenderActionContext,
|
||||
@@ -23,6 +24,7 @@ export function EntryContentHTMLRenderer<AS extends keyof JSX.IntrinsicElements
|
||||
children,
|
||||
...props
|
||||
}: EntryContentRendererProps & HTMLProps<AS>) {
|
||||
const spotlightRules = useSpotlightSettingKey("spotlights")
|
||||
const entry = useEntry(entryId, (state) => {
|
||||
const images =
|
||||
state.media?.reduce(
|
||||
@@ -68,7 +70,9 @@ export function EntryContentHTMLRenderer<AS extends keyof JSX.IntrinsicElements
|
||||
<MarkdownRenderActionContext value={actions}>
|
||||
<EntryInfoContext value={useMemo(() => ({ feedId, entryId }), [feedId, entryId])}>
|
||||
{/* @ts-expect-error */}
|
||||
<HTML {...props}>{children}</HTML>
|
||||
<HTML {...props} spotlightRules={spotlightRules}>
|
||||
{children}
|
||||
</HTML>
|
||||
</EntryInfoContext>
|
||||
</MarkdownRenderActionContext>
|
||||
</MarkdownImageRecordContext.Provider>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { getFeedById } from "@follow/store/feed/getter"
|
||||
import type { ComponentProps } from "react"
|
||||
import { useMemo } from "react"
|
||||
|
||||
import { useSpotlightSettingKey } from "~/atoms/settings/spotlight"
|
||||
import {
|
||||
MarkdownImageRecordContext,
|
||||
MarkdownRenderActionContext,
|
||||
@@ -24,6 +25,7 @@ export function EntryContentMarkdownRenderer({
|
||||
children,
|
||||
...props
|
||||
}: EntryContentRendererProps & MarkdownProps) {
|
||||
const spotlightRules = useSpotlightSettingKey("spotlights")
|
||||
const entry = useEntry(entryId, (state) => {
|
||||
const images =
|
||||
state.media?.reduce(
|
||||
@@ -69,7 +71,9 @@ export function EntryContentMarkdownRenderer({
|
||||
<MarkdownImageRecordContext.Provider value={images}>
|
||||
<MarkdownRenderActionContext value={actions}>
|
||||
<EntryInfoContext value={useMemo(() => ({ feedId, entryId }), [feedId, entryId])}>
|
||||
<Markdown {...props}>{children ?? ""}</Markdown>
|
||||
<Markdown {...props} spotlightRules={spotlightRules}>
|
||||
{children ?? ""}
|
||||
</Markdown>
|
||||
</EntryInfoContext>
|
||||
</MarkdownRenderActionContext>
|
||||
</MarkdownImageRecordContext.Provider>
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
import { FeedViewType } from "@follow/constants"
|
||||
import { Provider } from "jotai"
|
||||
import * as React from "react"
|
||||
import { act } from "react"
|
||||
import type { Root } from "react-dom/client"
|
||||
import { createRoot } from "react-dom/client"
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, test, vi } from "vitest"
|
||||
|
||||
import { initializeDefaultSpotlightSettings, setSpotlightSetting } from "~/atoms/settings/spotlight"
|
||||
import { jotaiStore } from "~/lib/jotai"
|
||||
|
||||
import { EntryContentHTMLRenderer } from "./html"
|
||||
import { EntryContentMarkdownRenderer } from "./markdown"
|
||||
|
||||
const { htmlMock, markdownMock, useEntryMock, getFeedByIdMock } = vi.hoisted(() => ({
|
||||
htmlMock: vi.fn(() => null),
|
||||
markdownMock: vi.fn(() => null),
|
||||
useEntryMock: vi.fn(),
|
||||
getFeedByIdMock: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock("@follow/store/entry/hooks", () => ({
|
||||
useEntry: useEntryMock,
|
||||
}))
|
||||
|
||||
vi.mock("@follow/store/feed/getter", () => ({
|
||||
getFeedById: getFeedByIdMock,
|
||||
}))
|
||||
|
||||
vi.mock("~/components/ui/markdown/HTML", () => ({
|
||||
HTML: htmlMock,
|
||||
}))
|
||||
|
||||
vi.mock("~/components/ui/markdown/Markdown", () => ({
|
||||
Markdown: markdownMock,
|
||||
}))
|
||||
|
||||
const rule = {
|
||||
id: "rule-1",
|
||||
enabled: true,
|
||||
pattern: "alpha",
|
||||
patternType: "keyword" as const,
|
||||
caseSensitive: false,
|
||||
color: "#FDE68A",
|
||||
}
|
||||
|
||||
const renderComponent = async (element: React.ReactNode) => {
|
||||
const container = document.createElement("div")
|
||||
document.body.append(container)
|
||||
|
||||
const root = createRoot(container)
|
||||
|
||||
await act(async () => {
|
||||
root.render(<Provider store={jotaiStore}>{element}</Provider>)
|
||||
})
|
||||
|
||||
return { container, root }
|
||||
}
|
||||
|
||||
describe("entry content spotlight plumbing", () => {
|
||||
let root: Root | null = null
|
||||
let container: HTMLElement | null = null
|
||||
|
||||
beforeAll(() => {
|
||||
;(globalThis as typeof globalThis & { React: typeof React }).React = React
|
||||
;(
|
||||
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
const eventTarget = new EventTarget()
|
||||
Object.defineProperties(window, {
|
||||
addEventListener: {
|
||||
configurable: true,
|
||||
value: eventTarget.addEventListener.bind(eventTarget),
|
||||
},
|
||||
removeEventListener: {
|
||||
configurable: true,
|
||||
value: eventTarget.removeEventListener.bind(eventTarget),
|
||||
},
|
||||
dispatchEvent: {
|
||||
configurable: true,
|
||||
value: eventTarget.dispatchEvent.bind(eventTarget),
|
||||
},
|
||||
})
|
||||
|
||||
useEntryMock.mockReturnValue({
|
||||
images: {},
|
||||
url: "https://example.com/post",
|
||||
})
|
||||
getFeedByIdMock.mockReturnValue(null)
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
if (root) {
|
||||
await act(async () => {
|
||||
root?.unmount()
|
||||
})
|
||||
}
|
||||
|
||||
container?.remove()
|
||||
root = null
|
||||
container = null
|
||||
|
||||
initializeDefaultSpotlightSettings()
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
test("EntryContentHTMLRenderer passes spotlight rules to HTML", async () => {
|
||||
initializeDefaultSpotlightSettings()
|
||||
setSpotlightSetting("spotlights", [rule])
|
||||
;({ container, root } = await renderComponent(
|
||||
<EntryContentHTMLRenderer
|
||||
view={FeedViewType.Articles}
|
||||
feedId="feed-1"
|
||||
entryId="entry-1"
|
||||
as="article"
|
||||
>
|
||||
{"<p>alpha beta</p>"}
|
||||
</EntryContentHTMLRenderer>,
|
||||
))
|
||||
|
||||
expect(htmlMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
spotlightRules: [rule],
|
||||
}),
|
||||
undefined,
|
||||
)
|
||||
})
|
||||
|
||||
test("EntryContentMarkdownRenderer passes spotlight rules to Markdown", async () => {
|
||||
initializeDefaultSpotlightSettings()
|
||||
setSpotlightSetting("spotlights", [rule])
|
||||
;({ container, root } = await renderComponent(
|
||||
<EntryContentMarkdownRenderer view={FeedViewType.Articles} feedId="feed-1" entryId="entry-1">
|
||||
{"alpha beta"}
|
||||
</EntryContentMarkdownRenderer>,
|
||||
))
|
||||
|
||||
expect(markdownMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
spotlightRules: [rule],
|
||||
}),
|
||||
undefined,
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,152 @@
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"
|
||||
|
||||
import {
|
||||
getSpotlightSettings,
|
||||
initializeDefaultSpotlightSettings,
|
||||
setSpotlightSetting,
|
||||
} from "~/atoms/settings/spotlight"
|
||||
import { initializeDefaultUISettings } from "~/atoms/settings/ui"
|
||||
|
||||
import { settingSyncQueue } from "./sync-queue"
|
||||
|
||||
const { settingsPrefetchMock, settingsUpdateMock, whoamiMock } = vi.hoisted(() => ({
|
||||
settingsPrefetchMock: vi.fn(),
|
||||
settingsUpdateMock: vi.fn(),
|
||||
whoamiMock: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock("@follow/store/user/getters", () => ({
|
||||
whoami: whoamiMock,
|
||||
}))
|
||||
|
||||
vi.mock("@follow/tracker", () => ({
|
||||
tracker: {
|
||||
manager: {
|
||||
captureException: vi.fn(),
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock("~/lib/api-client", () => ({
|
||||
followClient: {
|
||||
api: {
|
||||
settings: {
|
||||
update: settingsUpdateMock,
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock("~/queries/settings", () => ({
|
||||
settings: {
|
||||
get: () => ({
|
||||
prefetch: settingsPrefetchMock,
|
||||
}),
|
||||
},
|
||||
}))
|
||||
|
||||
const createRule = () => ({
|
||||
id: "rule-1",
|
||||
enabled: true,
|
||||
pattern: "alpha",
|
||||
patternType: "keyword" as const,
|
||||
caseSensitive: false,
|
||||
color: "#FDE68A",
|
||||
})
|
||||
|
||||
describe("desktop spotlight setting sync", () => {
|
||||
beforeEach(() => {
|
||||
const eventTarget = new EventTarget()
|
||||
Object.defineProperties(window, {
|
||||
addEventListener: {
|
||||
configurable: true,
|
||||
value: eventTarget.addEventListener.bind(eventTarget),
|
||||
},
|
||||
removeEventListener: {
|
||||
configurable: true,
|
||||
value: eventTarget.removeEventListener.bind(eventTarget),
|
||||
},
|
||||
dispatchEvent: {
|
||||
configurable: true,
|
||||
value: eventTarget.dispatchEvent.bind(eventTarget),
|
||||
},
|
||||
})
|
||||
|
||||
whoamiMock.mockReturnValue({ id: "user-1" })
|
||||
settingsUpdateMock.mockResolvedValue({ code: 0 })
|
||||
settingsPrefetchMock.mockResolvedValue({
|
||||
code: 0,
|
||||
settings: {},
|
||||
updated: {},
|
||||
})
|
||||
|
||||
initializeDefaultUISettings()
|
||||
initializeDefaultSpotlightSettings()
|
||||
localStorage.clear()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
vi.clearAllMocks()
|
||||
settingSyncQueue.teardown()
|
||||
settingSyncQueue.queue = []
|
||||
localStorage.clear()
|
||||
initializeDefaultUISettings()
|
||||
initializeDefaultSpotlightSettings()
|
||||
})
|
||||
|
||||
test("syncLocal hydrates spotlight rules from remote appearance settings", async () => {
|
||||
const rule = createRule()
|
||||
settingsPrefetchMock.mockResolvedValue({
|
||||
code: 0,
|
||||
settings: {
|
||||
appearance: {
|
||||
spotlights: [rule],
|
||||
spotlightsUpdated: 1710000000100,
|
||||
},
|
||||
},
|
||||
updated: {
|
||||
appearance: "2026-04-14T12:00:00.000Z",
|
||||
},
|
||||
})
|
||||
|
||||
await settingSyncQueue.syncLocal()
|
||||
|
||||
expect(getSpotlightSettings()).toMatchObject({
|
||||
updated: 1710000000100,
|
||||
spotlights: [rule],
|
||||
})
|
||||
})
|
||||
|
||||
test("changing spotlight settings syncs them through the appearance tab", async () => {
|
||||
vi.useFakeTimers()
|
||||
|
||||
const rule = createRule()
|
||||
settingsPrefetchMock.mockResolvedValue({
|
||||
code: 0,
|
||||
settings: {
|
||||
appearance: {
|
||||
uiFontFamily: "system-ui",
|
||||
spotlights: [],
|
||||
},
|
||||
},
|
||||
updated: {
|
||||
appearance: "2026-04-14T12:00:00.000Z",
|
||||
},
|
||||
})
|
||||
|
||||
await settingSyncQueue.init()
|
||||
|
||||
setSpotlightSetting("spotlights", [rule])
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1000)
|
||||
await Promise.resolve()
|
||||
|
||||
expect(settingsUpdateMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
tab: "appearance",
|
||||
spotlights: [rule],
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,10 @@
|
||||
import type { AISettings, GeneralSettings, UISettings } from "@follow/shared/settings/interface"
|
||||
import type { SpotlightSettings } from "@follow/shared/spotlight"
|
||||
import {
|
||||
mergeAppearancePayloadWithSpotlightSettings,
|
||||
pickSpotlightPayloadFromRemoteAppearance,
|
||||
toAppearanceSpotlightPayload,
|
||||
} from "@follow/shared/spotlight"
|
||||
import { whoami } from "@follow/store/user/getters"
|
||||
import { tracker } from "@follow/tracker"
|
||||
import { EventBus } from "@follow/utils/event-bus"
|
||||
@@ -14,6 +20,11 @@ import {
|
||||
generalServerSyncWhiteListKeys,
|
||||
getGeneralSettings,
|
||||
} from "~/atoms/settings/general"
|
||||
import {
|
||||
__spotlightSettingAtom,
|
||||
getSpotlightSettings,
|
||||
spotlightServerSyncWhiteListKeys,
|
||||
} from "~/atoms/settings/spotlight"
|
||||
import { __uiSettingAtom, getUISettings, uiServerSyncWhiteListKeys } from "~/atoms/settings/ui"
|
||||
import { followClient } from "~/lib/api-client"
|
||||
import { jotaiStore } from "~/lib/jotai"
|
||||
@@ -23,7 +34,10 @@ type SettingMapping = {
|
||||
appearance: UISettings
|
||||
general: GeneralSettings
|
||||
ai: AISettings
|
||||
spotlight: SpotlightSettings
|
||||
}
|
||||
type SettingDomain = keyof SettingMapping
|
||||
type RemoteSettingsTab = "appearance" | "general" | "ai"
|
||||
|
||||
const pickSyncPayload = <T extends object>(payload: T, keys: readonly (keyof T | string)[]) => {
|
||||
const nextPayload = {} as Partial<T>
|
||||
@@ -42,6 +56,7 @@ const localSettingGetterMap = {
|
||||
appearance: () => getUISettings(),
|
||||
general: () => getGeneralSettings(),
|
||||
ai: () => getAISettings(),
|
||||
spotlight: () => getSpotlightSettings(),
|
||||
}
|
||||
|
||||
const createInternalSetter =
|
||||
@@ -55,18 +70,121 @@ const localSettingSetterMap = {
|
||||
appearance: createInternalSetter(__uiSettingAtom),
|
||||
general: createInternalSetter(__generalSettingAtom),
|
||||
ai: createInternalSetter(__aiSettingAtom),
|
||||
spotlight: createInternalSetter(__spotlightSettingAtom),
|
||||
}
|
||||
|
||||
const settingWhiteListMap = {
|
||||
appearance: uiServerSyncWhiteListKeys,
|
||||
general: generalServerSyncWhiteListKeys,
|
||||
ai: aiServerSyncWhiteListKeys,
|
||||
spotlight: spotlightServerSyncWhiteListKeys,
|
||||
}
|
||||
|
||||
const remoteTabMap: Record<SettingDomain, RemoteSettingsTab> = {
|
||||
appearance: "appearance",
|
||||
general: "general",
|
||||
ai: "ai",
|
||||
spotlight: "appearance",
|
||||
}
|
||||
|
||||
const remoteTabToDomainMap: Record<RemoteSettingsTab, SettingDomain[]> = {
|
||||
appearance: ["appearance", "spotlight"],
|
||||
general: ["general"],
|
||||
ai: ["ai"],
|
||||
}
|
||||
|
||||
const bizSettingKeyToTabMapping = {
|
||||
ui: "appearance",
|
||||
general: "general",
|
||||
ai: "ai",
|
||||
spotlight: "spotlight",
|
||||
} as const
|
||||
|
||||
const getSettingUpdated = (payload: Record<string, unknown>) =>
|
||||
typeof payload.updated === "number" ? payload.updated : undefined
|
||||
|
||||
const getLocalUpdated = (payload: object) =>
|
||||
typeof (payload as { updated?: unknown }).updated === "number"
|
||||
? (payload as { updated: number }).updated
|
||||
: undefined
|
||||
|
||||
const getLocalAppearancePayload = () =>
|
||||
pickSyncPayload(localSettingGetterMap.appearance(), settingWhiteListMap.appearance)
|
||||
|
||||
const getLocalSpotlightSnapshot = () =>
|
||||
localSettingGetterMap.spotlight() as SpotlightSettings & { updated?: number }
|
||||
|
||||
const payloadForRemote = (
|
||||
domain: SettingDomain,
|
||||
payload: Record<string, unknown>,
|
||||
): Record<string, unknown> =>
|
||||
domain === "spotlight"
|
||||
? toAppearanceSpotlightPayload(
|
||||
payload as unknown as SpotlightSettings,
|
||||
getSettingUpdated(payload),
|
||||
)
|
||||
: pickSyncPayload(payload, settingWhiteListMap[domain])
|
||||
|
||||
const buildFullLocalAppearancePayload = () => {
|
||||
const spotlightSettings = getLocalSpotlightSnapshot()
|
||||
return mergeAppearancePayloadWithSpotlightSettings(
|
||||
getLocalAppearancePayload(),
|
||||
spotlightSettings,
|
||||
getSettingUpdated(spotlightSettings as unknown as Record<string, unknown>),
|
||||
)
|
||||
}
|
||||
|
||||
const mergeAppearancePayloadWithLocalChanges = (
|
||||
basePayload: Record<string, unknown>,
|
||||
options: {
|
||||
appearancePayload?: Record<string, unknown>
|
||||
spotlightSettings?: (SpotlightSettings & { updated?: number }) | null
|
||||
},
|
||||
) => {
|
||||
let nextPayload = { ...basePayload }
|
||||
|
||||
if (options.appearancePayload) {
|
||||
nextPayload = {
|
||||
...nextPayload,
|
||||
...options.appearancePayload,
|
||||
}
|
||||
}
|
||||
|
||||
if (options.spotlightSettings) {
|
||||
nextPayload = mergeAppearancePayloadWithSpotlightSettings(
|
||||
nextPayload,
|
||||
options.spotlightSettings,
|
||||
getSettingUpdated(options.spotlightSettings as unknown as Record<string, unknown>),
|
||||
)
|
||||
}
|
||||
|
||||
return nextPayload
|
||||
}
|
||||
|
||||
const getLocalPayloadForRemoteTab = (remoteTab: Exclude<RemoteSettingsTab, "appearance">) =>
|
||||
payloadForRemote(
|
||||
remoteTab,
|
||||
localSettingGetterMap[remoteTab]() as unknown as Record<string, unknown>,
|
||||
)
|
||||
|
||||
const payloadFromRemote = (
|
||||
domain: SettingDomain,
|
||||
payload: Record<string, unknown>,
|
||||
updated: number,
|
||||
): Record<string, unknown> | null => {
|
||||
if (domain === "spotlight") {
|
||||
return pickSpotlightPayloadFromRemoteAppearance(payload, updated)
|
||||
}
|
||||
|
||||
const nextPayload = pickSyncPayload(payload, settingWhiteListMap[domain])
|
||||
if (isEmptyObject(nextPayload)) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
...nextPayload,
|
||||
updated,
|
||||
}
|
||||
}
|
||||
|
||||
const isUnauthorizedError = (error: unknown) => {
|
||||
@@ -81,7 +199,7 @@ const isUnauthorizedError = (error: unknown) => {
|
||||
return false
|
||||
}
|
||||
|
||||
export type SettingSyncTab = keyof SettingMapping
|
||||
export type SettingSyncTab = SettingDomain
|
||||
export interface SettingSyncQueueItem<T extends SettingSyncTab = SettingSyncTab> {
|
||||
tab: T
|
||||
payload: Partial<SettingMapping[T]>
|
||||
@@ -219,6 +337,39 @@ class SettingSyncQueue {
|
||||
private threshold = 1000
|
||||
private flushScheduled = false
|
||||
|
||||
private pendingPromise: Promise<{
|
||||
code: 0
|
||||
settings: Record<string, any>
|
||||
updated: Record<string, string>
|
||||
}> | null = null
|
||||
|
||||
private fetchSettingRemote() {
|
||||
if (this.pendingPromise) {
|
||||
return this.pendingPromise
|
||||
}
|
||||
|
||||
const promise = settings.get().prefetch() as Promise<{
|
||||
code: 0
|
||||
settings: Record<string, any>
|
||||
updated: Record<string, string>
|
||||
}>
|
||||
|
||||
this.pendingPromise = promise.finally(() => {
|
||||
this.pendingPromise = null
|
||||
})
|
||||
|
||||
return this.pendingPromise
|
||||
}
|
||||
|
||||
private async fetchRemoteAppearancePayload() {
|
||||
const remoteSettings = await this.fetchSettingRemote()
|
||||
const remoteAppearancePayload = remoteSettings.settings?.appearance
|
||||
|
||||
return remoteAppearancePayload && typeof remoteAppearancePayload === "object"
|
||||
? { ...(remoteAppearancePayload as Record<string, unknown>) }
|
||||
: {}
|
||||
}
|
||||
|
||||
async enqueue<T extends SettingSyncTab>(tab: T, payload: Partial<SettingMapping[T]>) {
|
||||
const currentUserId = this.getCurrentUserId()
|
||||
if (!currentUserId) {
|
||||
@@ -265,39 +416,67 @@ class SettingSyncQueue {
|
||||
return
|
||||
}
|
||||
|
||||
const groupedTab = {} as Record<SettingSyncTab, any>
|
||||
|
||||
const referenceMap = {} as Record<SettingSyncTab, Set<SettingSyncQueueItem>>
|
||||
const changedDomainsByRemoteTab = {} as Partial<Record<RemoteSettingsTab, Set<SettingDomain>>>
|
||||
const domainOverrides = {} as Partial<Record<SettingDomain, Record<string, unknown>>>
|
||||
const referenceMap = {} as Partial<Record<RemoteSettingsTab, Set<SettingSyncQueueItem>>>
|
||||
for (const item of this.queue) {
|
||||
if (!groupedTab[item.tab]) {
|
||||
groupedTab[item.tab] = {}
|
||||
const remoteTab = remoteTabMap[item.tab]
|
||||
changedDomainsByRemoteTab[remoteTab] ||= new Set()
|
||||
changedDomainsByRemoteTab[remoteTab].add(item.tab)
|
||||
|
||||
referenceMap[remoteTab] ||= new Set()
|
||||
referenceMap[remoteTab].add(item)
|
||||
|
||||
domainOverrides[item.tab] = {
|
||||
...domainOverrides[item.tab],
|
||||
...payloadForRemote(item.tab, item.payload as unknown as Record<string, unknown>),
|
||||
}
|
||||
}
|
||||
|
||||
referenceMap[item.tab] ||= new Set()
|
||||
referenceMap[item.tab].add(item)
|
||||
let remoteAppearancePayload = {} as Record<string, unknown>
|
||||
if (changedDomainsByRemoteTab.appearance?.size) {
|
||||
try {
|
||||
remoteAppearancePayload = await this.fetchRemoteAppearancePayload()
|
||||
} catch (error) {
|
||||
if (isUnauthorizedError(error)) {
|
||||
this.queue = []
|
||||
this.ownerUserId = currentUserId
|
||||
return
|
||||
}
|
||||
|
||||
groupedTab[item.tab] = {
|
||||
...groupedTab[item.tab],
|
||||
...item.payload,
|
||||
this.reportSyncError("flush", error)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const promises = [] as Promise<any>[]
|
||||
for (const tab in groupedTab) {
|
||||
const json = pickSyncPayload(groupedTab[tab], settingWhiteListMap[tab])
|
||||
for (const tab in changedDomainsByRemoteTab) {
|
||||
const remoteTab = tab as RemoteSettingsTab
|
||||
const changedDomains = changedDomainsByRemoteTab[remoteTab]
|
||||
const json =
|
||||
remoteTab === "appearance"
|
||||
? mergeAppearancePayloadWithLocalChanges(remoteAppearancePayload, {
|
||||
appearancePayload: changedDomains?.has("appearance")
|
||||
? domainOverrides.appearance
|
||||
: undefined,
|
||||
spotlightSettings: changedDomains?.has("spotlight")
|
||||
? getLocalSpotlightSnapshot()
|
||||
: undefined,
|
||||
})
|
||||
: domainOverrides[remoteTab]
|
||||
|
||||
if (isEmptyObject(json)) {
|
||||
if (!json || isEmptyObject(json)) {
|
||||
continue
|
||||
}
|
||||
|
||||
const promise = followClient.api.settings
|
||||
.update({
|
||||
tab: tab as SettingsTab,
|
||||
tab: remoteTab as SettingsTab,
|
||||
...json,
|
||||
})
|
||||
.then(() => {
|
||||
// remove from queue
|
||||
for (const item of referenceMap[tab]) {
|
||||
for (const item of referenceMap[remoteTab] ?? []) {
|
||||
const index = this.queue.indexOf(item)
|
||||
if (index !== -1) {
|
||||
this.queue.splice(index, 1)
|
||||
@@ -330,29 +509,39 @@ class SettingSyncQueue {
|
||||
this.bindQueueOwner(currentUserId)
|
||||
|
||||
if (!tab) {
|
||||
const promises = [] as Promise<any>[]
|
||||
for (const tab in localSettingGetterMap) {
|
||||
const payload = pickSyncPayload(localSettingGetterMap[tab](), settingWhiteListMap[tab])
|
||||
|
||||
const promise = followClient.api.settings.update({
|
||||
tab: tab as SettingsTab,
|
||||
...payload,
|
||||
})
|
||||
|
||||
promises.push(promise)
|
||||
}
|
||||
const promises = [
|
||||
followClient.api.settings.update({
|
||||
tab: "appearance",
|
||||
...buildFullLocalAppearancePayload(),
|
||||
}),
|
||||
followClient.api.settings.update({
|
||||
tab: "general",
|
||||
...getLocalPayloadForRemoteTab("general"),
|
||||
}),
|
||||
followClient.api.settings.update({
|
||||
tab: "ai",
|
||||
...getLocalPayloadForRemoteTab("ai"),
|
||||
}),
|
||||
]
|
||||
|
||||
this.chain = this.chain.finally(() => Promise.all(promises))
|
||||
return this.chain
|
||||
} else {
|
||||
const payload = pickSyncPayload(localSettingGetterMap[tab](), settingWhiteListMap[tab])
|
||||
this.chain = this.chain.finally(async () => {
|
||||
const remoteTab = remoteTabMap[tab]
|
||||
const payload =
|
||||
remoteTab === "appearance"
|
||||
? mergeAppearancePayloadWithLocalChanges(await this.fetchRemoteAppearancePayload(), {
|
||||
appearancePayload: tab === "appearance" ? getLocalAppearancePayload() : undefined,
|
||||
spotlightSettings: tab === "spotlight" ? getLocalSpotlightSnapshot() : undefined,
|
||||
})
|
||||
: getLocalPayloadForRemoteTab(remoteTab)
|
||||
|
||||
this.chain = this.chain.finally(() =>
|
||||
followClient.api.settings.update({
|
||||
tab: tab as SettingsTab,
|
||||
return followClient.api.settings.update({
|
||||
tab: remoteTab as SettingsTab,
|
||||
...payload,
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
return this.chain
|
||||
}
|
||||
@@ -364,27 +553,25 @@ class SettingSyncQueue {
|
||||
|
||||
this.bindQueueOwner(currentUserId)
|
||||
|
||||
const remoteSettings = await settings
|
||||
.get()
|
||||
.prefetch()
|
||||
.catch((error) => {
|
||||
if (isUnauthorizedError(error)) {
|
||||
this.queue = []
|
||||
this.ownerUserId = currentUserId
|
||||
return null
|
||||
}
|
||||
|
||||
this.reportSyncError("syncLocal", error)
|
||||
const remoteSettings = await this.fetchSettingRemote().catch((error) => {
|
||||
if (isUnauthorizedError(error)) {
|
||||
this.queue = []
|
||||
this.ownerUserId = currentUserId
|
||||
return null
|
||||
})
|
||||
}
|
||||
|
||||
this.reportSyncError("syncLocal", error)
|
||||
return null
|
||||
})
|
||||
|
||||
if (!remoteSettings) return
|
||||
|
||||
if (isEmptyObject(remoteSettings.settings)) return
|
||||
|
||||
for (const tab in remoteSettings.settings) {
|
||||
const remoteSettingPayload = remoteSettings.settings[tab]
|
||||
const updated = remoteSettings.updated[tab]
|
||||
const remoteTab = tab as RemoteSettingsTab
|
||||
const remoteSettingPayload = remoteSettings.settings[remoteTab]
|
||||
const updated = remoteSettings.updated[remoteTab]
|
||||
|
||||
if (!updated) {
|
||||
continue
|
||||
@@ -392,21 +579,20 @@ class SettingSyncQueue {
|
||||
|
||||
const remoteUpdatedDate = new Date(updated).getTime()
|
||||
|
||||
const localSettings = localSettingGetterMap[tab]()
|
||||
const localSettingsUpdated = localSettings.updated
|
||||
for (const domain of remoteTabToDomainMap[remoteTab] ?? []) {
|
||||
const localSettings = localSettingGetterMap[domain]()
|
||||
const localSettingsUpdated = getLocalUpdated(localSettings)
|
||||
|
||||
if (!localSettingsUpdated || remoteUpdatedDate > localSettingsUpdated) {
|
||||
// Use remote and update local
|
||||
const nextPayload = pickSyncPayload(remoteSettingPayload, settingWhiteListMap[tab])
|
||||
|
||||
if (isEmptyObject(nextPayload)) {
|
||||
if (localSettingsUpdated && remoteUpdatedDate <= localSettingsUpdated) {
|
||||
continue
|
||||
}
|
||||
|
||||
const setter = localSettingSetterMap[tab]
|
||||
|
||||
nextPayload.updated = remoteUpdatedDate
|
||||
const nextPayload = payloadFromRemote(domain, remoteSettingPayload, remoteUpdatedDate)
|
||||
if (!nextPayload || isEmptyObject(nextPayload)) {
|
||||
continue
|
||||
}
|
||||
|
||||
const setter = localSettingSetterMap[domain]
|
||||
setter(nextPayload)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ import { useMinimizeToTrayValue, useSetMinimizeToTray } from "~/hooks/biz/useTra
|
||||
import { fallbackLanguage } from "~/i18n"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
import { setTranslationCache } from "~/modules/entry-content/atoms"
|
||||
import { fetchTtsVoices } from "~/modules/player/tts-service"
|
||||
|
||||
import { PaidBadge, SettingDescription, SettingInput, SettingSwitch } from "../control"
|
||||
import { createSetting } from "../helper/builder"
|
||||
@@ -162,7 +163,7 @@ export const SettingGeneral = () => {
|
||||
|
||||
{ type: "title", value: "TTS" },
|
||||
|
||||
IN_ELECTRON && VoiceSelector,
|
||||
VoiceSelector,
|
||||
|
||||
{ type: "title", value: t("general.network") },
|
||||
IN_ELECTRON && NettingSetting,
|
||||
@@ -198,7 +199,7 @@ const VoiceSelector = () => {
|
||||
const { t } = useTranslation("settings")
|
||||
|
||||
const { data } = useQuery({
|
||||
queryFn: () => ipcServices?.reader.getVoices(),
|
||||
queryFn: ({ signal }) => fetchTtsVoices(signal),
|
||||
queryKey: ["voices"],
|
||||
meta: {
|
||||
persist: true,
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
import { defaultSpotlightColor } from "@follow/shared/spotlight"
|
||||
import commonEn from "@locales/common/en.json"
|
||||
import settingsEn from "@locales/settings/en.json"
|
||||
import { Provider } from "jotai"
|
||||
import * as React from "react"
|
||||
import { act } from "react"
|
||||
import type { Root } from "react-dom/client"
|
||||
import { createRoot } from "react-dom/client"
|
||||
import { afterEach, beforeAll, describe, expect, test, vi } from "vitest"
|
||||
|
||||
import {
|
||||
getSpotlightSettings,
|
||||
initializeDefaultSpotlightSettings,
|
||||
setSpotlightSetting,
|
||||
} from "~/atoms/settings/spotlight"
|
||||
import { jotaiStore } from "~/lib/jotai"
|
||||
|
||||
import { SettingSpotlight } from "./spotlight"
|
||||
|
||||
vi.mock("react-i18next", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("react-i18next")>()
|
||||
const mockedTranslation = () => ({
|
||||
t: (key: keyof typeof settingsEn | keyof typeof commonEn) =>
|
||||
settingsEn[key as keyof typeof settingsEn] ?? commonEn[key as keyof typeof commonEn] ?? key,
|
||||
})
|
||||
|
||||
return {
|
||||
...actual,
|
||||
useTranslation: mockedTranslation,
|
||||
}
|
||||
})
|
||||
|
||||
const renderSpotlightTab = async () => {
|
||||
const container = document.createElement("div")
|
||||
document.body.append(container)
|
||||
|
||||
const root = createRoot(container)
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<Provider store={jotaiStore}>
|
||||
<SettingSpotlight />
|
||||
</Provider>,
|
||||
)
|
||||
})
|
||||
|
||||
return { container, root }
|
||||
}
|
||||
|
||||
const getButtonByText = (
|
||||
container: HTMLElement,
|
||||
text: string,
|
||||
options?: { enabledOnly?: boolean; index?: number },
|
||||
) => {
|
||||
const { enabledOnly = false, index = 0 } = options ?? {}
|
||||
const button = Array.from(container.querySelectorAll("button")).filter(
|
||||
(element) =>
|
||||
element.textContent?.trim() === text &&
|
||||
(!enabledOnly || !(element as HTMLButtonElement).disabled),
|
||||
)[index]
|
||||
|
||||
if (!button) {
|
||||
throw new Error(`Button not found: ${text}`)
|
||||
}
|
||||
|
||||
return button as HTMLButtonElement
|
||||
}
|
||||
|
||||
const getInputByIdPrefix = (container: HTMLElement, prefix: string, index = 0) => {
|
||||
const input = Array.from(container.querySelectorAll("input")).filter((element) =>
|
||||
element.id.startsWith(prefix),
|
||||
)[index]
|
||||
|
||||
if (!input) {
|
||||
throw new Error(`Input not found: ${prefix}`)
|
||||
}
|
||||
|
||||
return input as HTMLInputElement
|
||||
}
|
||||
|
||||
const getElementByIdPrefix = (container: HTMLElement, prefix: string, index = 0) => {
|
||||
const element = Array.from(container.querySelectorAll<HTMLElement>(`[id^="${prefix}"]`))[index]
|
||||
|
||||
if (!element) {
|
||||
throw new Error(`Element not found: ${prefix}`)
|
||||
}
|
||||
|
||||
return element
|
||||
}
|
||||
|
||||
const getColorButtonByValue = (container: HTMLElement, value: string, index = 0) => {
|
||||
const button = Array.from(
|
||||
container.querySelectorAll<HTMLButtonElement>(`[data-spotlight-color-option="${value}"]`),
|
||||
)[index]
|
||||
|
||||
if (!button) {
|
||||
throw new Error(`Color button not found: ${value}`)
|
||||
}
|
||||
|
||||
return button
|
||||
}
|
||||
|
||||
const getReactProps = <T extends object>(element: HTMLElement): T => {
|
||||
const reactPropsKey = Object.keys(element).find((key) => key.startsWith("__reactProps"))
|
||||
if (!reactPropsKey) {
|
||||
throw new Error("React props key not found")
|
||||
}
|
||||
|
||||
return (element as unknown as Record<string, T>)[reactPropsKey] as T
|
||||
}
|
||||
|
||||
const setInputValue = async (input: HTMLInputElement, value: string) => {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")
|
||||
expect(descriptor?.set).toBeDefined()
|
||||
|
||||
await act(async () => {
|
||||
input.focus()
|
||||
descriptor!.set!.call(input, value)
|
||||
input.setAttribute("value", value)
|
||||
input.dispatchEvent(
|
||||
new InputEvent("input", { bubbles: true, data: value, inputType: "insertText" }),
|
||||
)
|
||||
input.dispatchEvent(new Event("change", { bubbles: true }))
|
||||
const reactProps = getReactProps<{ onChange?: (event: { target: HTMLInputElement }) => void }>(
|
||||
input,
|
||||
)
|
||||
reactProps.onChange?.({
|
||||
target: input,
|
||||
})
|
||||
input.blur()
|
||||
await Promise.resolve()
|
||||
})
|
||||
}
|
||||
|
||||
const click = async (element: HTMLElement) => {
|
||||
await act(async () => {
|
||||
element.dispatchEvent(new MouseEvent("click", { bubbles: true }))
|
||||
})
|
||||
}
|
||||
|
||||
const overrideDispatchEvent = (dispatchEvent: typeof window.dispatchEvent) => {
|
||||
Object.defineProperty(window, "dispatchEvent", {
|
||||
configurable: true,
|
||||
value: dispatchEvent,
|
||||
})
|
||||
}
|
||||
|
||||
const restoreDispatchEvent = (dispatchEvent: typeof window.dispatchEvent | undefined) => {
|
||||
if (dispatchEvent) {
|
||||
overrideDispatchEvent(dispatchEvent)
|
||||
return
|
||||
}
|
||||
|
||||
Reflect.deleteProperty(window, "dispatchEvent")
|
||||
}
|
||||
|
||||
describe("SettingSpotlight", () => {
|
||||
let root: Root | null = null
|
||||
let container: HTMLElement | null = null
|
||||
let previousDispatchEvent: typeof window.dispatchEvent | undefined
|
||||
|
||||
beforeAll(() => {
|
||||
;(globalThis as typeof globalThis & { React: typeof React }).React = React
|
||||
;(
|
||||
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
if (root) {
|
||||
await act(async () => {
|
||||
root?.unmount()
|
||||
})
|
||||
}
|
||||
container?.remove()
|
||||
root = null
|
||||
container = null
|
||||
|
||||
initializeDefaultSpotlightSettings()
|
||||
setSpotlightSetting("spotlights", [])
|
||||
restoreDispatchEvent(previousDispatchEvent)
|
||||
})
|
||||
|
||||
test("updates spotlight settings when adding and editing a rule", async () => {
|
||||
initializeDefaultSpotlightSettings()
|
||||
previousDispatchEvent = window.dispatchEvent
|
||||
overrideDispatchEvent(vi.fn() as typeof window.dispatchEvent)
|
||||
;({ container, root } = await renderSpotlightTab())
|
||||
|
||||
await click(getButtonByText(container!, "Add rule"))
|
||||
|
||||
let rules = getSpotlightSettings().spotlights
|
||||
expect(rules).toHaveLength(1)
|
||||
expect(rules[0]).toMatchObject({
|
||||
pattern: "",
|
||||
patternType: "keyword",
|
||||
caseSensitive: false,
|
||||
color: defaultSpotlightColor,
|
||||
})
|
||||
|
||||
await setInputValue(getInputByIdPrefix(container!, "spotlight-pattern-"), "alpha")
|
||||
rules = getSpotlightSettings().spotlights
|
||||
expect(rules[0]?.pattern).toBe("alpha")
|
||||
|
||||
await click(getButtonByText(container!, "Regex"))
|
||||
rules = getSpotlightSettings().spotlights
|
||||
expect(rules[0]?.patternType).toBe("regex")
|
||||
|
||||
await click(getElementByIdPrefix(container!, "spotlight-enabled-"))
|
||||
rules = getSpotlightSettings().spotlights
|
||||
expect(rules[0]?.enabled).toBe(false)
|
||||
|
||||
await click(getElementByIdPrefix(container!, "spotlight-case-sensitive-"))
|
||||
rules = getSpotlightSettings().spotlights
|
||||
expect(rules[0]?.caseSensitive).toBe(true)
|
||||
|
||||
await click(getColorButtonByValue(container!, "#60A5FA"))
|
||||
rules = getSpotlightSettings().spotlights
|
||||
expect(rules[0]?.color).toBe("#60A5FA")
|
||||
})
|
||||
|
||||
test("renders an inline error when a regex pattern is invalid", async () => {
|
||||
initializeDefaultSpotlightSettings()
|
||||
previousDispatchEvent = window.dispatchEvent
|
||||
overrideDispatchEvent(vi.fn() as typeof window.dispatchEvent)
|
||||
;({ container, root } = await renderSpotlightTab())
|
||||
|
||||
await click(getButtonByText(container!, "Add rule"))
|
||||
await click(getButtonByText(container!, "Regex"))
|
||||
await setInputValue(getInputByIdPrefix(container!, "spotlight-pattern-"), "[")
|
||||
|
||||
expect(container!.textContent).toContain("Invalid regex")
|
||||
})
|
||||
|
||||
test("reorders spotlight rules when move buttons are clicked", async () => {
|
||||
initializeDefaultSpotlightSettings()
|
||||
previousDispatchEvent = window.dispatchEvent
|
||||
overrideDispatchEvent(vi.fn() as typeof window.dispatchEvent)
|
||||
;({ container, root } = await renderSpotlightTab())
|
||||
|
||||
await click(getButtonByText(container!, "Add rule"))
|
||||
await click(getButtonByText(container!, "Add rule"))
|
||||
|
||||
const initialIds = getSpotlightSettings().spotlights.map((rule) => rule.id)
|
||||
expect(initialIds).toHaveLength(2)
|
||||
|
||||
await click(getButtonByText(container!, "Move down", { enabledOnly: true }))
|
||||
expect(getSpotlightSettings().spotlights.map((rule) => rule.id)).toEqual([
|
||||
initialIds[1]!,
|
||||
initialIds[0]!,
|
||||
])
|
||||
|
||||
await click(getButtonByText(container!, "Move up", { enabledOnly: true }))
|
||||
expect(getSpotlightSettings().spotlights.map((rule) => rule.id)).toEqual(initialIds)
|
||||
})
|
||||
|
||||
test("deletes the selected spotlight rule", async () => {
|
||||
initializeDefaultSpotlightSettings()
|
||||
previousDispatchEvent = window.dispatchEvent
|
||||
overrideDispatchEvent(vi.fn() as typeof window.dispatchEvent)
|
||||
;({ container, root } = await renderSpotlightTab())
|
||||
|
||||
await click(getButtonByText(container!, "Add rule"))
|
||||
await click(getButtonByText(container!, "Add rule"))
|
||||
|
||||
expect(getSpotlightSettings().spotlights).toHaveLength(2)
|
||||
|
||||
await click(getButtonByText(container!, "Delete", { index: 0 }))
|
||||
|
||||
expect(getSpotlightSettings().spotlights).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,232 @@
|
||||
import { Button } from "@follow/components/ui/button/index.js"
|
||||
import { Input } from "@follow/components/ui/input/index.js"
|
||||
import { Label } from "@follow/components/ui/label/index.jsx"
|
||||
import { SegmentGroup, SegmentItem } from "@follow/components/ui/segment/index.jsx"
|
||||
import { Switch } from "@follow/components/ui/switch/index.jsx"
|
||||
import type { SpotlightColorPreset, SpotlightRule } from "@follow/shared/spotlight"
|
||||
import {
|
||||
defaultSpotlightColor,
|
||||
getSpotlightColorChoices,
|
||||
moveSpotlightRule,
|
||||
} from "@follow/shared/spotlight"
|
||||
import { validateSpotlightPattern } from "@follow/utils/spotlight"
|
||||
import { nanoid } from "nanoid"
|
||||
import { useTranslation } from "react-i18next"
|
||||
|
||||
import { setSpotlightSetting, useSpotlightSettingKey } from "~/atoms/settings/spotlight"
|
||||
|
||||
import { SettingDescription } from "../control"
|
||||
|
||||
const createSpotlightRule = (): SpotlightRule => ({
|
||||
id: nanoid(),
|
||||
enabled: true,
|
||||
pattern: "",
|
||||
patternType: "keyword",
|
||||
caseSensitive: false,
|
||||
color: defaultSpotlightColor,
|
||||
})
|
||||
|
||||
const updateRuleAtIndex = (
|
||||
rules: SpotlightRule[],
|
||||
index: number,
|
||||
updater: (rule: SpotlightRule) => SpotlightRule,
|
||||
) => {
|
||||
setSpotlightSetting(
|
||||
"spotlights",
|
||||
rules.map((rule, currentIndex) => (currentIndex === index ? updater(rule) : rule)),
|
||||
)
|
||||
}
|
||||
|
||||
const deleteRuleAtIndex = (rules: SpotlightRule[], index: number) => {
|
||||
setSpotlightSetting(
|
||||
"spotlights",
|
||||
rules.filter((_, currentIndex) => currentIndex !== index),
|
||||
)
|
||||
}
|
||||
|
||||
export const SettingSpotlight = () => {
|
||||
const { t } = useTranslation("settings")
|
||||
const rules = useSpotlightSettingKey("spotlights")
|
||||
|
||||
return (
|
||||
<div className="mt-4 space-y-4">
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setSpotlightSetting("spotlights", [...rules, createSpotlightRule()])
|
||||
}}
|
||||
>
|
||||
{t("spotlight.add_rule")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{rules.map((rule, index) => (
|
||||
<SpotlightRuleEditor
|
||||
key={rule.id}
|
||||
isFirst={index === 0}
|
||||
isLast={index === rules.length - 1}
|
||||
rule={rule}
|
||||
onUpdate={(updater) => {
|
||||
updateRuleAtIndex(rules, index, updater)
|
||||
}}
|
||||
onMove={(direction) => {
|
||||
setSpotlightSetting("spotlights", moveSpotlightRule(rules, index, direction))
|
||||
}}
|
||||
onDelete={() => {
|
||||
deleteRuleAtIndex(rules, index)
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const SpotlightRuleEditor = ({
|
||||
rule,
|
||||
isFirst,
|
||||
isLast,
|
||||
onUpdate,
|
||||
onMove,
|
||||
onDelete,
|
||||
}: {
|
||||
rule: SpotlightRule
|
||||
isFirst: boolean
|
||||
isLast: boolean
|
||||
onUpdate: (updater: (rule: SpotlightRule) => SpotlightRule) => void
|
||||
onMove: (direction: -1 | 1) => void
|
||||
onDelete: () => void
|
||||
}) => {
|
||||
const { t } = useTranslation("settings")
|
||||
const validation = validateSpotlightPattern(rule.pattern, rule.patternType)
|
||||
const showRegexError = rule.patternType === "regex" && !validation.valid
|
||||
const colorChoices = getSpotlightColorChoices(rule.color)
|
||||
|
||||
const patternInputId = `spotlight-pattern-${rule.id}`
|
||||
const enabledInputId = `spotlight-enabled-${rule.id}`
|
||||
const caseSensitiveInputId = `spotlight-case-sensitive-${rule.id}`
|
||||
|
||||
return (
|
||||
<div className="space-y-4 rounded-xl border border-fill-secondary bg-material-ultra-thin p-4">
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm font-medium" htmlFor={patternInputId}>
|
||||
{t("spotlight.pattern")}
|
||||
</Label>
|
||||
<Input
|
||||
id={patternInputId}
|
||||
value={rule.pattern}
|
||||
onChange={(event) => {
|
||||
const pattern = event.target.value
|
||||
onUpdate((currentRule) => ({ ...currentRule, pattern }))
|
||||
}}
|
||||
/>
|
||||
{showRegexError && (
|
||||
<SettingDescription className="w-full text-red">
|
||||
{t("spotlight.invalid_regex", { error: validation.error })}
|
||||
</SettingDescription>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm font-medium">{t("spotlight.type")}</Label>
|
||||
<SegmentGroup
|
||||
className="h-9"
|
||||
value={rule.patternType}
|
||||
onValueChanged={(value) => {
|
||||
if (value !== "keyword" && value !== "regex") return
|
||||
onUpdate((currentRule) => ({ ...currentRule, patternType: value }))
|
||||
}}
|
||||
>
|
||||
<SegmentItem value="keyword" label={t("spotlight.keyword")} />
|
||||
<SegmentItem value="regex" label={t("spotlight.regex")} />
|
||||
</SegmentGroup>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm font-medium">{t("spotlight.color")}</Label>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{colorChoices.map((preset) => (
|
||||
<SpotlightColorButton
|
||||
key={preset.value}
|
||||
preset={preset}
|
||||
selected={preset.value.toUpperCase() === rule.color.toUpperCase()}
|
||||
onClick={() => {
|
||||
onUpdate((currentRule) => ({ ...currentRule, color: preset.value }))
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<Label className="text-sm font-medium" htmlFor={enabledInputId}>
|
||||
{t("spotlight.enabled")}
|
||||
</Label>
|
||||
<Switch
|
||||
id={enabledInputId}
|
||||
checked={rule.enabled}
|
||||
onCheckedChange={(enabled) => {
|
||||
onUpdate((currentRule) => ({ ...currentRule, enabled }))
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<Label className="text-sm font-medium" htmlFor={caseSensitiveInputId}>
|
||||
{t("spotlight.case_sensitive")}
|
||||
</Label>
|
||||
<Switch
|
||||
id={caseSensitiveInputId}
|
||||
checked={rule.caseSensitive}
|
||||
onCheckedChange={(caseSensitive) => {
|
||||
onUpdate((currentRule) => ({ ...currentRule, caseSensitive }))
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap justify-end gap-2">
|
||||
<Button size="sm" variant="outline" onClick={onDelete}>
|
||||
{t("words.delete", { ns: "common" })}
|
||||
</Button>
|
||||
<Button disabled={isFirst} size="sm" variant="outline" onClick={() => onMove(-1)}>
|
||||
{t("spotlight.move_up")}
|
||||
</Button>
|
||||
<Button disabled={isLast} size="sm" variant="outline" onClick={() => onMove(1)}>
|
||||
{t("spotlight.move_down")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const SpotlightColorButton = ({
|
||||
preset,
|
||||
selected,
|
||||
onClick,
|
||||
}: {
|
||||
preset: SpotlightColorPreset
|
||||
selected: boolean
|
||||
onClick: () => void
|
||||
}) => {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
data-spotlight-color-option={preset.value}
|
||||
aria-label={`Select highlight color ${preset.value}`}
|
||||
className="relative size-9 rounded-full border border-fill-secondary shadow-sm transition-transform duration-200 hover:scale-105 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/40 focus-visible:ring-offset-2"
|
||||
style={{
|
||||
backgroundColor: preset.value,
|
||||
boxShadow: selected ? "0 0 0 2px hsl(var(--fo-a) / 0.8)" : undefined,
|
||||
}}
|
||||
onClick={onClick}
|
||||
>
|
||||
{selected && (
|
||||
<span className="center absolute -bottom-1 -right-1 size-5 rounded-full bg-blue text-white shadow-sm">
|
||||
<i className="i-mgc-check-cute-re text-xs" />
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { SpotlightRule } from "@follow/shared/spotlight"
|
||||
import { spotlightHighlightOpacityHex } from "@follow/shared/spotlight"
|
||||
import { buildHighlightSegments, compileSpotlightRules } from "@follow/utils/spotlight"
|
||||
import { useMemo } from "react"
|
||||
|
||||
const toHighlightStyle = (color: string): React.CSSProperties => ({
|
||||
backgroundColor: `${color}${spotlightHighlightOpacityHex}`,
|
||||
borderRadius: 4,
|
||||
paddingInline: 1,
|
||||
})
|
||||
|
||||
export const HighlightedText = ({
|
||||
text,
|
||||
rules,
|
||||
}: {
|
||||
text?: string | null
|
||||
rules: SpotlightRule[]
|
||||
}) => {
|
||||
const compiledRules = useMemo(() => compileSpotlightRules(rules), [rules])
|
||||
const segments = useMemo(
|
||||
() => buildHighlightSegments(text ?? "", compiledRules),
|
||||
[compiledRules, text],
|
||||
)
|
||||
const keyedSegments = useMemo(() => {
|
||||
let offset = 0
|
||||
|
||||
return segments.map((segment) => {
|
||||
const key = segment.highlight ? `${offset}-${segment.highlight.ruleId}-${segment.text}` : null
|
||||
offset += segment.text.length
|
||||
return { key, segment }
|
||||
})
|
||||
}, [segments])
|
||||
|
||||
return (
|
||||
<>
|
||||
{keyedSegments.map(({ key, segment }) =>
|
||||
segment.highlight ? (
|
||||
<span
|
||||
key={key}
|
||||
data-spotlight-color={segment.highlight.color}
|
||||
data-spotlight-rule-id={segment.highlight.ruleId}
|
||||
style={toHighlightStyle(segment.highlight.color)}
|
||||
>
|
||||
{segment.text}
|
||||
</span>
|
||||
) : (
|
||||
segment.text
|
||||
),
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -33,11 +33,11 @@ export const UpdateNotice = () => {
|
||||
break
|
||||
}
|
||||
case "distribution": {
|
||||
if (status.storeUrl) {
|
||||
if (status.targetUrl) {
|
||||
if (ipcServices?.app.openExternal) {
|
||||
void ipcServices.app.openExternal(status.storeUrl)
|
||||
void ipcServices.app.openExternal(status.targetUrl)
|
||||
} else {
|
||||
window.open(status.storeUrl, "_blank")
|
||||
window.open(status.targetUrl, "_blank")
|
||||
}
|
||||
}
|
||||
break
|
||||
@@ -55,6 +55,9 @@ export const UpdateNotice = () => {
|
||||
const { distribution } = updaterStatus
|
||||
|
||||
switch (distribution) {
|
||||
case "direct": {
|
||||
return null
|
||||
}
|
||||
case "mas": {
|
||||
return t("notify.store.mas")
|
||||
}
|
||||
@@ -81,7 +84,9 @@ export const UpdateNotice = () => {
|
||||
return t("notify.update_info_3")
|
||||
}
|
||||
case "distribution": {
|
||||
return t("notify.update_info_store", { store: storeName ?? "" })
|
||||
return updaterStatus.distribution === "direct"
|
||||
? t("notify.update_info_direct")
|
||||
: t("notify.update_info_store", { store: storeName ?? "" })
|
||||
}
|
||||
default: {
|
||||
return null
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { SettingSpotlight } from "~/modules/settings/tabs/spotlight"
|
||||
import { SettingsTitle } from "~/modules/settings/title"
|
||||
import { defineSettingPageData } from "~/modules/settings/utils"
|
||||
|
||||
const iconName = "i-mgc-flashlight-cute-re"
|
||||
const priority = (1000 << 1) + 20
|
||||
|
||||
// eslint-disable-next-line react-refresh/only-export-components
|
||||
export const loader = defineSettingPageData({
|
||||
icon: iconName,
|
||||
name: "titles.spotlight",
|
||||
priority,
|
||||
})
|
||||
|
||||
export function Component() {
|
||||
return (
|
||||
<>
|
||||
<SettingsTitle />
|
||||
<SettingSpotlight />
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -47,7 +47,7 @@ export const ExtensionExposeProvider = () => {
|
||||
type: "distribution",
|
||||
status: "ready",
|
||||
distribution: payload.distribution,
|
||||
storeUrl: payload.storeUrl,
|
||||
targetUrl: payload.targetUrl,
|
||||
storeVersion: payload.storeVersion,
|
||||
currentVersion: payload.currentVersion,
|
||||
})
|
||||
|
||||
@@ -15,6 +15,7 @@ import { useReduceMotion } from "~/hooks/biz/useReduceMotion"
|
||||
import { useSyncTheme } from "~/hooks/common"
|
||||
import { langChain } from "~/i18n"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
import { buildAppFontFamily } from "~/lib/font-family"
|
||||
import { loadLanguageAndApply } from "~/lib/load-language"
|
||||
|
||||
const useUpdateDockBadge = (setting: UISettings) => {
|
||||
@@ -66,8 +67,7 @@ const useUISettingSync = () => {
|
||||
|
||||
useInsertionEffect(() => {
|
||||
const root = document.documentElement
|
||||
// https://developer.mozilla.org/en-US/docs/Web/CSS/font-family#valid_family_names
|
||||
const fontCss = `"${setting.uiFontFamily}", system-ui, sans-serif`
|
||||
const fontCss = buildAppFontFamily(setting.uiFontFamily)
|
||||
|
||||
Object.assign(root.style, {
|
||||
fontFamily: fontCss,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
html,
|
||||
#shadow-html {
|
||||
--fo-font-family: "SN Pro", system-ui, sans-serif;
|
||||
--fo-font-family:
|
||||
"SN Pro", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", system-ui,
|
||||
sans-serif;
|
||||
}
|
||||
|
||||
html {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "Folo",
|
||||
"type": "module",
|
||||
"version": "1.5.0",
|
||||
"version": "1.6.0",
|
||||
"private": true,
|
||||
"description": "Follow everything in one place",
|
||||
"author": "Folo Team",
|
||||
@@ -13,6 +13,7 @@
|
||||
"main": "./dist/main/index.js",
|
||||
"scripts": {
|
||||
"analyze:web": "cross-env analyzer=1 WEB_BUILD=1 vite build",
|
||||
"apply:release-config": "tsx scripts/apply-release-config.ts",
|
||||
"build:electron": "pnpm run build:electron-vite && electron-forge make",
|
||||
"build:electron-forge": "electron-forge make",
|
||||
"build:electron-forge:macos": "electron-forge make --arch=x64 --platform=darwin && electron-forge make --arch=arm64 --platform=darwin && tsx scripts/merge-yml.ts",
|
||||
@@ -61,6 +62,7 @@
|
||||
"@playwright/test": "1.58.2",
|
||||
"@types/html-minifier-terser": "7.0.2",
|
||||
"@types/js-yaml": "4.0.9",
|
||||
"@types/semver": "7.7.1",
|
||||
"@vitejs/plugin-legacy": "7.2.1",
|
||||
"@vitejs/plugin-react": "5.1.4",
|
||||
"async-es": "3.2.6",
|
||||
@@ -82,6 +84,7 @@
|
||||
"pathe": "2.0.3",
|
||||
"react": "19.0.0",
|
||||
"react-dom": "19.0.0",
|
||||
"semver": "7.7.4",
|
||||
"tailwindcss": "3.4.17",
|
||||
"tailwindcss-content-visibility": "1.0.2",
|
||||
"tailwindcss-multi": "0.4.6",
|
||||
@@ -93,6 +96,7 @@
|
||||
"vite-plugin-route-builder": "0.4.1",
|
||||
"vite-tsconfig-paths": "6.1.1"
|
||||
},
|
||||
"runtimeVersion": "1.6.0",
|
||||
"productName": "Folo",
|
||||
"mainHash": "4778cc1cb43d08ed2a5edf391f0d22694641dc15eb27eaefb45bfa09ff176091"
|
||||
"mainHash": "a146c17f95d7c9383634b40eb933d796eae25c079bba41a0e4a3cdfc62f2dace"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"mode": "build",
|
||||
"runtimeVersion": null,
|
||||
"channel": null
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"version": "1.6.0",
|
||||
"mode": "build",
|
||||
"runtimeVersion": null,
|
||||
"channel": null
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { readFile, writeFile } from "node:fs/promises"
|
||||
|
||||
import { join } from "pathe"
|
||||
|
||||
const semverPattern = /^\d+\.\d+\.\d+$/
|
||||
const validModes = new Set(["build", "ota"])
|
||||
const validChannels = new Set(["stable", "beta", "alpha"])
|
||||
|
||||
export interface DesktopReleasePlan {
|
||||
mode: "build" | "ota"
|
||||
runtimeVersion: string | null
|
||||
channel: "stable" | "beta" | "alpha" | null
|
||||
}
|
||||
|
||||
interface DesktopPackageJson {
|
||||
runtimeVersion?: string
|
||||
version: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export async function applyReleaseConfig(input: { projectDir: string; version: string }) {
|
||||
if (!input.version || !semverPattern.test(input.version)) {
|
||||
throw new Error("Expected a plain x.y.z version argument")
|
||||
}
|
||||
|
||||
const releasePlanPath = join(input.projectDir, "release-plan.json")
|
||||
const releaseConfigPath = join(input.projectDir, "release.json")
|
||||
const packageJsonPath = join(input.projectDir, "package.json")
|
||||
const plan = await readReleasePlan(releasePlanPath)
|
||||
validateReleasePlan(plan)
|
||||
|
||||
const packageJson = JSON.parse(await readFile(packageJsonPath, "utf8")) as DesktopPackageJson
|
||||
packageJson.runtimeVersion = plan.mode === "ota" ? plan.runtimeVersion! : input.version
|
||||
|
||||
await writeFile(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}\n`, "utf8")
|
||||
await writeFile(
|
||||
releaseConfigPath,
|
||||
`${JSON.stringify(
|
||||
{
|
||||
version: input.version,
|
||||
...plan,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
"utf8",
|
||||
)
|
||||
await writeFile(
|
||||
releasePlanPath,
|
||||
`${JSON.stringify(createDefaultReleasePlan(), null, 2)}\n`,
|
||||
"utf8",
|
||||
)
|
||||
}
|
||||
|
||||
async function readReleasePlan(path: string): Promise<DesktopReleasePlan> {
|
||||
return JSON.parse(await readFile(path, "utf8")) as DesktopReleasePlan
|
||||
}
|
||||
|
||||
function validateReleasePlan(plan: DesktopReleasePlan) {
|
||||
if (!validModes.has(plan.mode)) {
|
||||
throw new Error("release-plan.json mode must be build or ota")
|
||||
}
|
||||
|
||||
if (plan.channel !== null && !validChannels.has(plan.channel)) {
|
||||
throw new Error("release-plan.json channel must be stable, beta, alpha, or null")
|
||||
}
|
||||
|
||||
if (plan.mode === "build") {
|
||||
if (plan.runtimeVersion !== null || plan.channel !== null) {
|
||||
throw new Error("desktop build mode must not set runtimeVersion or channel")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (plan.mode === "ota") {
|
||||
if (!plan.runtimeVersion || !semverPattern.test(plan.runtimeVersion)) {
|
||||
throw new Error("desktop ota mode requires a plain x.y.z runtimeVersion")
|
||||
}
|
||||
if (!plan.channel) {
|
||||
throw new Error("desktop ota mode requires a channel")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function createDefaultReleasePlan(): DesktopReleasePlan {
|
||||
return {
|
||||
mode: "build",
|
||||
runtimeVersion: null,
|
||||
channel: null,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"
|
||||
import { tmpdir } from "node:os"
|
||||
|
||||
import { join } from "pathe"
|
||||
import { afterEach, describe, expect, it } from "vitest"
|
||||
|
||||
const tempDirs: string[] = []
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
tempDirs.splice(0).map((directory) => rm(directory, { recursive: true, force: true })),
|
||||
)
|
||||
})
|
||||
|
||||
describe("applyDesktopReleaseConfig", () => {
|
||||
it("writes release.json for ota mode, resets release-plan.json, and persists the plan runtimeVersion", async () => {
|
||||
const projectDir = await mkdtemp(join(tmpdir(), "desktop-release-config-"))
|
||||
tempDirs.push(projectDir)
|
||||
|
||||
await writeFile(
|
||||
join(projectDir, "package.json"),
|
||||
`${JSON.stringify({ name: "Folo", version: "1.5.0" }, null, 2)}\n`,
|
||||
"utf8",
|
||||
)
|
||||
await writeFile(
|
||||
join(projectDir, "release-plan.json"),
|
||||
`${JSON.stringify(
|
||||
{
|
||||
mode: "ota",
|
||||
runtimeVersion: "1.5.0",
|
||||
channel: "stable",
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
"utf8",
|
||||
)
|
||||
|
||||
const { applyReleaseConfig } = await import("./apply-release-config.impl.ts")
|
||||
|
||||
await applyReleaseConfig({ projectDir, version: "1.5.1" })
|
||||
|
||||
await expect(readFile(join(projectDir, "release.json"), "utf8")).resolves.toContain(
|
||||
'"mode": "ota"',
|
||||
)
|
||||
await expect(readFile(join(projectDir, "release.json"), "utf8")).resolves.toContain(
|
||||
'"runtimeVersion": "1.5.0"',
|
||||
)
|
||||
await expect(readFile(join(projectDir, "release-plan.json"), "utf8")).resolves.toContain(
|
||||
'"mode": "build"',
|
||||
)
|
||||
await expect(readFile(join(projectDir, "package.json"), "utf8")).resolves.toContain(
|
||||
'"runtimeVersion": "1.5.0"',
|
||||
)
|
||||
})
|
||||
|
||||
it("persists the new app version as runtimeVersion for build mode", async () => {
|
||||
const projectDir = await mkdtemp(join(tmpdir(), "desktop-release-config-"))
|
||||
tempDirs.push(projectDir)
|
||||
|
||||
await writeFile(
|
||||
join(projectDir, "package.json"),
|
||||
`${JSON.stringify({ name: "Folo", version: "1.5.0", runtimeVersion: "1.4.9" }, null, 2)}\n`,
|
||||
"utf8",
|
||||
)
|
||||
await writeFile(
|
||||
join(projectDir, "release-plan.json"),
|
||||
`${JSON.stringify(
|
||||
{
|
||||
mode: "build",
|
||||
runtimeVersion: null,
|
||||
channel: null,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
"utf8",
|
||||
)
|
||||
|
||||
const { applyReleaseConfig } = await import("./apply-release-config.impl.ts")
|
||||
|
||||
await applyReleaseConfig({ projectDir, version: "1.5.1" })
|
||||
|
||||
await expect(readFile(join(projectDir, "package.json"), "utf8")).resolves.toContain(
|
||||
'"runtimeVersion": "1.5.1"',
|
||||
)
|
||||
})
|
||||
|
||||
it("rejects ota mode when the channel is missing", async () => {
|
||||
const projectDir = await mkdtemp(join(tmpdir(), "desktop-release-config-"))
|
||||
tempDirs.push(projectDir)
|
||||
|
||||
await writeFile(
|
||||
join(projectDir, "package.json"),
|
||||
`${JSON.stringify({ name: "Folo", version: "1.5.0" }, null, 2)}\n`,
|
||||
"utf8",
|
||||
)
|
||||
await writeFile(
|
||||
join(projectDir, "release-plan.json"),
|
||||
`${JSON.stringify(
|
||||
{
|
||||
mode: "ota",
|
||||
runtimeVersion: "1.5.0",
|
||||
channel: null,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
"utf8",
|
||||
)
|
||||
|
||||
const { applyReleaseConfig } = await import("./apply-release-config.impl.ts")
|
||||
|
||||
await expect(() => applyReleaseConfig({ projectDir, version: "1.5.1" })).rejects.toThrow(
|
||||
/desktop ota mode requires a channel/i,
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,16 @@
|
||||
import { fileURLToPath } from "node:url"
|
||||
|
||||
import { dirname } from "pathe"
|
||||
|
||||
import { applyReleaseConfig } from "./apply-release-config.impl"
|
||||
|
||||
const projectDir = dirname(dirname(fileURLToPath(import.meta.url)))
|
||||
|
||||
async function main() {
|
||||
await applyReleaseConfig({
|
||||
projectDir,
|
||||
version: process.argv[2] ?? "",
|
||||
})
|
||||
}
|
||||
|
||||
void main()
|
||||
@@ -69,7 +69,7 @@
|
||||
"@tailwindcss/typography": "0.5.19",
|
||||
"@tanstack/react-query-devtools": "5.90.2",
|
||||
"@types/node": "24.9.1",
|
||||
"@types/react": "19.1.17",
|
||||
"@types/react": "19.2.14",
|
||||
"@types/react-dom": "19.2.3",
|
||||
"@vitejs/plugin-rsc": "0.5.21",
|
||||
"autoprefixer": "10.4.21",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { ConfigContext, ExpoConfig } from "expo/config"
|
||||
import { resolve } from "pathe"
|
||||
|
||||
import PKG from "./package.json"
|
||||
const PKG = require("./package.json") as typeof import("./package.json")
|
||||
|
||||
// const roundedIconPath = resolve(__dirname, "../../resources/icon.png")
|
||||
const iconPathMap = {
|
||||
@@ -16,8 +16,51 @@ const adaptiveIconPath = resolve(__dirname, "./assets/adaptive-icon.png")
|
||||
const splashIconPath = resolve(__dirname, "./assets/splash-icon.png")
|
||||
|
||||
const isDev = process.env.NODE_ENV === "development"
|
||||
const semverPattern = /^\d+\.\d+\.\d+$/
|
||||
const channelNameMap = {
|
||||
development: "development",
|
||||
"ios-simulator": "development",
|
||||
preview: "preview",
|
||||
"e2e-android": "preview",
|
||||
"e2e-ios-simulator": "preview",
|
||||
production: "production",
|
||||
} as Record<string, string>
|
||||
|
||||
export const resolveRuntimeVersion = ({
|
||||
isDevelopment,
|
||||
packageVersion,
|
||||
otaRuntimeVersionOverride,
|
||||
}: {
|
||||
isDevelopment: boolean
|
||||
packageVersion: string
|
||||
otaRuntimeVersionOverride?: string | null
|
||||
}) => {
|
||||
if (isDevelopment) {
|
||||
return "0.0.0-dev"
|
||||
}
|
||||
|
||||
if (otaRuntimeVersionOverride) {
|
||||
if (!semverPattern.test(otaRuntimeVersionOverride)) {
|
||||
throw new Error(
|
||||
`Expected OTA_RUNTIME_VERSION to be a plain x.y.z version, got ${otaRuntimeVersionOverride}`,
|
||||
)
|
||||
}
|
||||
|
||||
return otaRuntimeVersionOverride
|
||||
}
|
||||
|
||||
return packageVersion
|
||||
}
|
||||
|
||||
export default ({ config }: ConfigContext): ExpoConfig => {
|
||||
const profile = process.env.PROFILE || "production"
|
||||
const channelName = channelNameMap[profile] || channelNameMap.production
|
||||
const runtimeVersion = resolveRuntimeVersion({
|
||||
isDevelopment: isDev,
|
||||
packageVersion: PKG.version,
|
||||
otaRuntimeVersionOverride: process.env.OTA_RUNTIME_VERSION ?? null,
|
||||
})
|
||||
|
||||
const result: ExpoConfig = {
|
||||
...config,
|
||||
|
||||
@@ -29,16 +72,19 @@ export default ({ config }: ConfigContext): ExpoConfig => {
|
||||
e2eLanguage: process.env.EXPO_PUBLIC_E2E_LANGUAGE ?? null,
|
||||
},
|
||||
owner: "follow",
|
||||
// disable expo updates for now, https://github.com/expo/expo/issues/29630
|
||||
// updates: {
|
||||
// url: "https://folo-custom-expo-updates.vercel.app/api/manifest",
|
||||
// codeSigningCertificate: "./code-signing/certificate.pem",
|
||||
// codeSigningMetadata: {
|
||||
// keyid: "main",
|
||||
// alg: "rsa-v1_5-sha256",
|
||||
// },
|
||||
// },
|
||||
runtimeVersion: isDev ? "0.0.0-dev" : PKG.version,
|
||||
updates: {
|
||||
url: "https://ota.folo.is/manifest",
|
||||
requestHeaders: {
|
||||
"expo-channel-name": channelName,
|
||||
},
|
||||
codeSigningCertificate: "./code-signing/certificate.pem",
|
||||
codeSigningMetadata: {
|
||||
keyid: "main",
|
||||
alg: "rsa-v1_5-sha256",
|
||||
},
|
||||
checkAutomatically: "NEVER",
|
||||
},
|
||||
runtimeVersion,
|
||||
|
||||
name: "Folo",
|
||||
slug: "follow",
|
||||
@@ -47,7 +93,6 @@ export default ({ config }: ConfigContext): ExpoConfig => {
|
||||
icon: iconPath,
|
||||
scheme: ["follow", "folo"],
|
||||
userInterfaceStyle: "automatic" as const,
|
||||
newArchEnabled: true,
|
||||
ios: {
|
||||
supportsTablet: true,
|
||||
bundleIdentifier: "is.follow",
|
||||
@@ -66,9 +111,6 @@ export default ({ config }: ConfigContext): ExpoConfig => {
|
||||
},
|
||||
android: {
|
||||
package: "is.follow",
|
||||
// Suppress warning about EDGE_TO_EDGE_PLUGIN
|
||||
// Learn more: https://expo.dev/blog/edge-to-edge-display-now-streamlined-for-android
|
||||
edgeToEdgeEnabled: true,
|
||||
adaptiveIcon: {
|
||||
foregroundImage: adaptiveIconPath,
|
||||
monochromeImage: adaptiveIconPath,
|
||||
@@ -76,9 +118,6 @@ export default ({ config }: ConfigContext): ExpoConfig => {
|
||||
},
|
||||
googleServicesFile: "./build/google-services.json",
|
||||
},
|
||||
androidStatusBar: {
|
||||
translucent: true,
|
||||
},
|
||||
// web: {
|
||||
// bundler: "metro",
|
||||
// output: "static",
|
||||
@@ -105,7 +144,10 @@ export default ({ config }: ConfigContext): ExpoConfig => {
|
||||
"expo-build-properties",
|
||||
{
|
||||
ios: {
|
||||
// Expo SDK 55 archive builds regress with use_frameworks + prebuilt RN core.
|
||||
buildReactNativeFromSource: true,
|
||||
useFrameworks: "static",
|
||||
forceStaticLinking: ["RNFBApp", "RNFBAnalytics", "RNFBMessaging", "RNFBAppCheck"],
|
||||
},
|
||||
},
|
||||
],
|
||||
@@ -120,6 +162,8 @@ export default ({ config }: ConfigContext): ExpoConfig => {
|
||||
],
|
||||
"expo-apple-authentication",
|
||||
"expo-web-browser",
|
||||
"expo-image",
|
||||
"expo-sharing",
|
||||
[
|
||||
"expo-video",
|
||||
{
|
||||
@@ -134,6 +178,8 @@ export default ({ config }: ConfigContext): ExpoConfig => {
|
||||
assetsPath: resolve(__dirname, "..", "..", "out", "rn-web"),
|
||||
},
|
||||
],
|
||||
require("./plugins/with-follow-ios-resources.js"),
|
||||
require("./plugins/with-rnfb-build-properties.js"),
|
||||
|
||||
require("./plugins/with-gradle-jvm-heap-size-increase.js"),
|
||||
require("./plugins/with-android-jdk-21.js"),
|
||||
@@ -0,0 +1,3 @@
|
||||
require("tsx/cjs")
|
||||
|
||||
module.exports = require("./app.config.base.ts").default
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"info": {
|
||||
"author": "xcode",
|
||||
"version": 1
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"images": [
|
||||
{
|
||||
"filename": "black_board_2_cute_fi.pdf",
|
||||
"idiom": "universal"
|
||||
}
|
||||
],
|
||||
"info": {
|
||||
"author": "xcode",
|
||||
"version": 1
|
||||
},
|
||||
"properties": {
|
||||
"template-rendering-intent": "template"
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
+15
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"images": [
|
||||
{
|
||||
"filename": "black_board_2_cute_re.pdf",
|
||||
"idiom": "universal"
|
||||
}
|
||||
],
|
||||
"info": {
|
||||
"author": "xcode",
|
||||
"version": 1
|
||||
},
|
||||
"properties": {
|
||||
"template-rendering-intent": "template"
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"images": [
|
||||
{
|
||||
"filename": "home_5_cute_fi.pdf",
|
||||
"idiom": "universal"
|
||||
}
|
||||
],
|
||||
"info": {
|
||||
"author": "xcode",
|
||||
"version": 1
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user