Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(config-json): Only either bundle or load from remote #291

Merged
merged 8 commits into from
Mar 4, 2025

Conversation

zardoy
Copy link
Owner

@zardoy zardoy commented Feb 27, 2025

PR Type

Enhancement, Bug fix


Description

  • Introduced conditional handling for bundled or remote config.json.

  • Added a new AppConfig type and refactored its usage across modules.

  • Replaced appLoaded state with fsReady for better clarity.

  • Improved watchValue utility to support unsubscribing.


Changes walkthrough 📝

Relevant files
Enhancement
10 files
rsbuild.config.ts
Conditional handling for bundled or remote `config.json` 
+4/-2     
appConfig.ts
Added `AppConfig` type and loading logic                                 
+59/-0   
browserfs.ts
Replaced `appLoaded` with `fsReady` state                               
+2/-2     
customChannels.ts
Updated packet structure for custom channels                         
+3/-3     
globalState.ts
Refactored `AppConfig` type and state management                 
+2/-39   
index.ts
Adjusted app initialization to use `fsReady` and `AppConfig`
+3/-13   
optionsStorage.ts
Enhanced `watchValue` utility with unsubscribe support     
+14/-5   
panorama.ts
Updated panorama logic to use `fsReady`                                   
+1/-1     
MainMenuRenderApp.tsx
Updated main menu rendering logic with `fsReady`                 
+3/-3     
config.json
Added `configSource` field to configuration                           
+1/-0     

Need help?
  • Type /help how to ... in the comments thread for any questions about Qodo Merge usage.
  • Check out the documentation for more information.
  • Summary by CodeRabbit

    • New Features

      • Enhanced configuration management now supports flexible sourcing, improving startup reliability.
      • The main menu display now activates after file system readiness, resulting in smoother user experience.
    • Chores

      • Streamlined state management and subscription cleanup for improved performance.
      • Updated build parameters to enable dynamic configuration injection during builds.
      • Introduced a new function to retrieve the Git repository name for improved release information handling.
      • Added environment variables to build workflows to enhance configuration context during builds.

    Copy link

    codesandbox bot commented Feb 27, 2025

    Review or Edit in CodeSandbox

    Open the branch in Web EditorVS CodeInsiders

    Open Preview

    Copy link

    coderabbitai bot commented Feb 27, 2025

    Walkthrough

    This pull request refines configuration handling and state management across the codebase. A new module now defines configuration types and loading logic, allowing the application to use either an inline (bundled) configuration or fetch remotely. The changes include renaming state flags from appLoaded to fsReady, updating type definitions, and adjusting conditional flows. Additionally, the build process now accepts a CONFIG_JSON_SOURCE argument, and repository information is extracted during the Docker preparation process.

    Changes

    File(s) Change Summary
    rsbuild.config.ts Introduces githubRepositoryFallback and configSource for conditional assignment of process.env.INLINED_APP_CONFIG and restricts writing to config.json based on the configuration source.
    src/appConfig.ts New file defining the AppConfig type and the loadAppConfig function; handles merging of configurations from an inline source or a fetched remote file, including forced settings logic.
    src/browserfs.ts, src/panorama.ts, src/react/MainMenuRenderApp.tsx Replaces the state flag appLoaded with fsReady and updates corresponding conditional logic in asynchronous callbacks and UI rendering.
    src/globalState.ts, src/index.ts, src/appParams.ts Removes the AppConfig type and loadAppConfig function from global state; updates imports and conditions to utilize the new configuration module and the fsReady flag.
    src/customChannels.ts Updates the packet structure fields (id, categoryTitle, items) from a simple 'pstring' type to an array format combining a string with an object specifying a count type ('i16').
    src/optionsStorage.ts Changes the import for AppConfig (from globalState to appConfig) and updates the WatchValue type signature to return an unsubscribe function through an array of subscriptions.
    Dockerfile, scripts/dockerPrepare.mjs Adds a build argument CONFIG_JSON_SOURCE in the Dockerfile and updates its build command; introduces the getGitRepository function to extract repository information and include it in release.json.
    .github/workflows/*.yml Introduces CONFIG_JSON_SOURCE environment variable with value BUNDLED in various workflow files to modify build context.

    Suggested labels

    Review effort 4/5

    Poem

    I'm a coding rabbit, hopping in delight,
    Chewing on configs from morning 'til night.
    With flags renamed and types all bright,
    My code hops cleanly, oh what a sight!
    In Docker and scripts, I skip with glee,
    Celebrating each change—happy as can be!
    🐇💻

    ✨ Finishing Touches
    • 📝 Generate Docstrings

    🪧 Tips

    Chat

    There are 3 ways to chat with CodeRabbit:

    • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
      • I pushed a fix in commit <commit_id>, please review it.
      • Generate unit testing code for this file.
      • Open a follow-up GitHub issue for this discussion.
    • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
      • @coderabbitai generate unit testing code for this file.
      • @coderabbitai modularize this function.
    • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
      • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
      • @coderabbitai read src/utils.ts and generate unit testing code.
      • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
      • @coderabbitai help me debug CodeRabbit configuration file.

    Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

    CodeRabbit Commands (Invoked using PR comments)

    • @coderabbitai pause to pause the reviews on a PR.
    • @coderabbitai resume to resume the paused reviews.
    • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
    • @coderabbitai full review to do a full review from scratch and review all the files again.
    • @coderabbitai summary to regenerate the summary of the PR.
    • @coderabbitai generate docstrings to generate docstrings for this PR.
    • @coderabbitai resolve resolve all the CodeRabbit review comments.
    • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
    • @coderabbitai help to get help.

    Other keywords and placeholders

    • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
    • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
    • Add @coderabbitai anywhere in the PR title to generate the title automatically.

    CodeRabbit Configuration File (.coderabbit.yaml)

    • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
    • Please see the configuration documentation for more information.
    • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

    Documentation and Community

    • Visit our Documentation for detailed information on how to use CodeRabbit.
    • Join our Discord Community to get help, request features, and share feedback.
    • Follow us on X/Twitter for updates and announcements.

    Sorry, something went wrong.

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
    🧪 No relevant tests
    🔒 No security concerns identified
    ⚡ Recommended focus areas for review

    Logic Bug

    The disabled settings logic in loadAppConfig seems reversed - settings are added to disabledSettings when value is true but deleted when false, which appears to be the opposite of intended behavior

    fov: 75,
    guiScale: 3,
    autoRequestCompletions: true,
    touchButtonsSize: 40,
    touchButtonsOpacity: 80,
    touchButtonsPosition: 12,
    touchControlsPositions: getDefaultTouchControlsPositions(),
    touchMovementType: 'modern' as 'modern' | 'classic',
    touchInteractionType: 'classic' as 'classic' | 'buttons',
    gpuPreference: 'default' as 'default' | 'high-performance' | 'low-power',
    backgroundRendering: '20fps' as 'full' | '20fps' | '5fps',
    Error Handling

    The fetch error handling for config.json could be improved - it shows an error message but still proceeds to load an empty config which may cause issues

    void window.fetch('config.json').then(async res => res.json()).then(c => c, (error) => {
    // console.warn('Failed to load optional app config.json', error)
    // return {}
      setLoadingScreenStatus('Failed to load app config.json', true)
    }).then((config: AppConfig | {}) => {
      loadAppConfig(config)
    })

    Copy link

    qodo-merge-pro-for-open-source bot commented Feb 27, 2025

    PR Code Suggestions ✨

    No code suggestions found for the PR.

    Copy link

    @coderabbitai coderabbitai bot left a comment

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    Actionable comments posted: 1

    🧹 Nitpick comments (1)
    src/appConfig.ts (1)

    52-59: Improve error handling for remote configuration loading

    While the code sets a loading screen status on fetch failure, it would be better to provide more robust error handling with potential fallbacks.

    - void window.fetch('config.json').then(async res => res.json()).then(c => c, (error) => {
    -   setLoadingScreenStatus('Failed to load app config.json', true)
    - }).then((config: AppConfig | {}) => {
    -   loadAppConfig(config)
    - })
    + void window.fetch('config.json')
    +   .then(async res => {
    +     if (!res.ok) {
    +       throw new Error(`Failed to fetch config.json: ${res.status} ${res.statusText}`)
    +     }
    +     return res.json()
    +   })
    +   .then(
    +     (config: AppConfig) => {
    +       loadAppConfig(config)
    +     },
    +     (error) => {
    +       console.warn('Failed to load optional app config.json', error)
    +       setLoadingScreenStatus('Failed to load app config.json', true)
    +       // Load with empty config as fallback
    +       loadAppConfig({})
    +     }
    +   )
    🧰 Tools
    🪛 Biome (1.9.4)

    [error] 56-56: Don't use '{}' as a type.

    Prefer explicitly define the object shape. '{}' means "any non-nullable value".

    (lint/complexity/noBannedTypes)

    📜 Review details

    Configuration used: CodeRabbit UI
    Review profile: CHILL
    Plan: Pro

    📥 Commits

    Reviewing files that changed from the base of the PR and between dffadbb and c4d8b5a.

    📒 Files selected for processing (10)
    • config.json (1 hunks)
    • rsbuild.config.ts (2 hunks)
    • src/appConfig.ts (1 hunks)
    • src/browserfs.ts (1 hunks)
    • src/customChannels.ts (1 hunks)
    • src/globalState.ts (2 hunks)
    • src/index.ts (1 hunks)
    • src/optionsStorage.ts (3 hunks)
    • src/panorama.ts (1 hunks)
    • src/react/MainMenuRenderApp.tsx (1 hunks)
    🧰 Additional context used
    🪛 Biome (1.9.4)
    src/appConfig.ts

    [error] 56-56: Don't use '{}' as a type.

    Prefer explicitly define the object shape. '{}' means "any non-nullable value".

    (lint/complexity/noBannedTypes)

    🔇 Additional comments (18)
    config.json (1)

    3-3: Good addition of configuration source property

    This new property "configSource": "bundled" clearly indicates that the configuration is meant to be bundled with the application rather than loaded from a remote source. This aligns with the PR title to ensure only either bundle or load from remote.

    src/panorama.ts (1)

    51-51: State management improvement

    Good change from m.appLoaded to m.fsReady. This makes the condition more specific and accurate, as it's checking for file system readiness rather than general app loading. This aligns with similar changes across the codebase.

    src/browserfs.ts (2)

    44-44: State management consistency change

    Changed from miscUiState.appLoaded = true to miscUiState.fsReady = true, which is part of the systematic update to state management across the application. This makes the state variable name more accurately reflect what it's representing.


    50-50: State management consistency change

    Changed from miscUiState.appLoaded = true to miscUiState.fsReady = true, maintaining consistency with the error case above and the rest of the codebase.

    src/customChannels.ts (1)

    88-88: Enhanced type definitions for protocol fields

    The changes to these three fields (id, categoryTitle, and items) enhance the protocol definition by specifying a count type of 'i16' (16-bit integer) for the string length. This makes the protocol definition more precise and helps ensure correct data handling.

    These changes align with the existing type definition pattern used elsewhere in the file (see line 22 and 38).

    Also applies to: 92-92, 96-96

    rsbuild.config.ts (2)

    75-75: Improved configuration loading logic with conditional inlining.

    The change conditionally inlines the app configuration based on configSource, ensuring bundled configurations are included while remote configurations remain separate. This is cleaner than always inlining all configurations.


    112-114: Consistent with configuration source strategy.

    This change ensures the config.json file is only written to the output directory when using the "remote" configuration source. This prevents duplicating configuration data and maintains a single source of truth based on the configured strategy.

    src/globalState.ts (2)

    8-8: Imported AppConfig from new dedicated file.

    You've moved the AppConfig type from this file to a dedicated appConfig.ts file, which improves code organization and separates concerns.


    128-128: Renamed state property from appLoaded to fsReady.

    Changed state property name from appLoaded to fsReady to better reflect its purpose - tracking the readiness of the file system rather than the general app loading state. This naming is more precise and aligns with its actual usage.

    src/react/MainMenuRenderApp.tsx (2)

    78-78: Updated state destructuring to use fsReady.

    Consistently updated to use the renamed state property fsReady instead of appLoaded in the destructuring assignment from miscUiState.


    80-80: Updated conditional logic to use fsReady.

    All usages of appLoaded have been correctly replaced with fsReady in the component's conditional logic, maintaining consistent behavior with the renamed state property.

    Also applies to: 83-83

    src/index.ts (1)

    916-919: Enhanced initialization condition.

    The condition for triggering subsequent initialization has been improved to check for both fsReady and appConfig being truthy. This ensures the application only proceeds when both the file system is ready and the configuration is loaded, providing a more robust initialization sequence.

    src/appConfig.ts (3)

    5-23: Well-structured AppConfig type definition

    The AppConfig type is well-defined with clear documentation comments for some fields. The commented-out properties suggest future extensions or deprecated options.


    25-45: Robust configuration loading with appropriate fallbacks

    The loadAppConfig function handles both new and existing configurations properly. It correctly merges new config with existing one and handles forced settings by either adding them to disabled settings or removing them as appropriate.


    47-51: Type-safe handling of bundled configuration

    The implementation checks for bundled config presence and loads it correctly.

    src/optionsStorage.ts (3)

    8-8: Correct import path for AppConfig type

    The import has been updated to use the new location of the AppConfig type from './appConfig' instead of './globalState', which aligns with the reorganization of the configuration management.


    190-190: Enhanced WatchValue type signature with cleanup capability

    The WatchValue type now returns a function to unsubscribe, which is a good practice for managing resources and preventing memory leaks.


    200-213:

    ❓ Verification inconclusive

    Improved subscription management with cleanup

    The implementation now properly collects unsubscribe functions and provides a way to clean them up, which is an excellent enhancement for resource management.

    However, ensure that all existing uses of watchValue are updated to properly use the returned unsubscribe function where needed to prevent memory leaks.


    🏁 Script executed:

    #!/bin/bash
    # Find all usages of watchValue in the codebase
    rg "watchValue\(" --type ts

    Length of output: 1182


    Subscription cleanup improved in src/optionsStorage.ts – well done on aggregating and returning unsubscribe functions for proper resource management.

    The new implementation (lines 200–213 in src/optionsStorage.ts) correctly collects unsubscribe functions and provides a cleanup routine. However, multiple calls to watchValue exist throughout the codebase (e.g., in src/watchOptions.ts, src/panorama.ts, src/react files, etc.) that don’t appear to capture or use the returned unsubscribe functions. Please review these usages to ensure they either store and invoke the unsubscribe when appropriate or that their lifecycle management inherently prevents memory leaks.

    zardoy and others added 2 commits February 27, 2025 04:09

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature.
    Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
    @zardoy
    Copy link
    Owner Author

    zardoy commented Feb 27, 2025

    have an idea to cache config.json in localStorage and display prompt to use cached config if available instead of just an error screen

    if (isBundledConfigUsed) {
    loadAppConfig(process.env.INLINED_APP_CONFIG as AppConfig ?? {})
    } else {
    void window.fetch('config.json').then(async res => res.json()).then(c => c, (error) => {

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    This should probably use await not void to ensure the config was loaded before the client continues to load.

    Copy link
    Owner Author

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    Hm, I was avoiding any usage of top level awaits because I think it can break the app in some unexpected way and don't really see any benefit of using it

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    Well I don't really see what is stopping the client from using the bundled config.json values until the remote one is loaded and imo await is the proper way to force async queries to block the app until it's loaded? If it really breaks something then that would be a bug elsewhere (and if it fails to load the file then it should of course break as the app doesn't work without the config)

    @@ -72,7 +72,7 @@ const appConfig = defineConfig({
    'process.env.RELEASE_LINK': JSON.stringify(releaseLink),
    'process.env.RELEASE_CHANGELOG': JSON.stringify(releaseChangelog),
    'process.env.DISABLE_SERVICE_WORKER': JSON.stringify(disableServiceWorker),
    'process.env.INLINED_APP_CONFIG': JSON.stringify(configJson),
    'process.env.INLINED_APP_CONFIG': JSON.stringify(configJson.configSource === 'bundled' ? configJson : null),

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    Defining this value in the same config which one wants to switch the behaviour of seems like a roundabout way. (As you would need to manually modify the config before building)

    I would expect it to be toggleable at built time without modifying the checked out source e.g. via a build param, feature flag, custom goal, or environment variable.

    Copy link
    Owner Author

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    Yes, you are absolutely right, it affects only bundling process and should work like in the same way as disabling service worker works

    Copy link
    Owner Author

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    Though I put it here to make it noticeable. Imagine you don't know about the build flag, anyway, I'm not sure what behaviour I should use in repo by default (remote I guess?)

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    Well remote would make more sense to keep the behaviour compatible with the previous one.

    Copy link
    Owner Author

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    The previous behavior didn't make app menu delay to load before config.json is set, that's why I'm so unsure

    @Phoenix616
    Copy link

    Phoenix616 commented Feb 27, 2025

    have an idea to cache config.json in localStorage and display prompt to use cached config if available instead of just an error screen

    That feels unnecessary as the browser would already cache it. Also whether or not it should be cached should be defined by the server imo. The user should not have any direct say about which server-enforced config options should be uset.

    disabledSettings.value.add(key)
    // since the setting is forced, we need to set it to that value
    if (appConfig.defaultSettings?.[key]) {
    options[key] = appConfig.defaultSettings[key]
    Copy link
    Owner Author

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    Will break setting from qs params , eed to fix

    @Phoenix616
    Copy link

    Phoenix616 commented Feb 27, 2025

    Another idea that I had which kinda gets back the previous behaviour: Have it check for a config.js in a separate (non-git-included) directory on build and merge it into the bundled config.json similarly to how the public/config.json was included previously when fetched from the remote.

    Another approach could be to always bundle the config.json but still fetch public/config.json and merge that. (Which is kinda what I actually would've expected this code to do but it didn't:

    void window.fetch('config.json').then(async res => res.json()).then(c => c, (error) => {
    console.warn('Failed to load optional app config.json', error)
    return {}
    }).then((config: AppConfig | {}) => {
    loadAppConfig(config)
    })

    @zardoy
    Copy link
    Owner Author

    zardoy commented Feb 27, 2025

    Another idea that I had which kinda gets back the previous behaviour: Have it check for a config.js in a separate (non-git-included) directory on build and merge it into the bundled config.json similarly to how the public/config.json was included previously when fetched from the remote.

    Another approach could be to always bundle the config.json but still fetch public/config.json and merge that. (Which is kinda what I actually would've expected this code to do but it didn't:

    I didn't get what you meant, it all already worked before like you described, but merging the config was happening later (since the config json would be available instantly). The whole purpose of this pr so we don't have to think about race conditions like that anymore. I will introduce the build ENV param INLINE_CONFIG_JSON (that would be false by default), thus delay app loading before config.json is fetched

    @Phoenix616
    Copy link

    I didn't get what you meant

    Which part of it?

    it all already worked before like you described, but merging the config was happening later

    I don't think so? The current state on next without this PR is that it will only use the bundled, none of the queried values of the config.json seem to apply. (Even though it still seems to download and load it here This sure looks like it is supposed to work like my second paragraph but it simply doesn't.

    I will introduce the build ENV param INLINE_CONFIG_JSON (that would be false by default), thus delay app loading before config.json is fetched

    Sounds like a good solution

    @zardoy
    Copy link
    Owner Author

    zardoy commented Feb 28, 2025

    i already received like 5 complains because of this breakage needs to be merged asap

    @zardoy
    Copy link
    Owner Author

    zardoy commented Mar 3, 2025

    i already received like 5 complains because of this breakage needs to be merged asap

    even worse, because the default was an empty string before, now using ||= assignment logic, the wrong proxy server will be saved in cache of your users that loaded the page before, even after fixing this issue. Yes definitely using an empty string to indicate using of proxy from the same origin was not the best UX decision, but I didn't find a better one

    @zardoy
    Copy link
    Owner Author

    zardoy commented Mar 3, 2025

    I don't think so? The current state on next without this PR is that it will only use the bundled, none of the queried values of the config.json seem to apply. (Even though it still seems to download and load it here This sure looks like it is supposed to work like my second paragraph but it simply doesn't.

    I already answered this part a few times. The config values are applied but not at time when server connect UI was displayed and autoConnect option along with default proxy option was checked

    if (s.appLoaded) { // fs ready
    . The correct config from the server was loaded too late. It was fine only for some options

    @zardoy zardoy requested review from Phoenix616 and removed request for Phoenix616 March 3, 2025 11:42
    zardoy added 2 commits March 3, 2025 14:43
    Copy link

    @coderabbitai coderabbitai bot left a comment

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    Actionable comments posted: 1

    🧹 Nitpick comments (3)
    scripts/dockerPrepare.mjs (3)

    21-27: Handle null repository values more gracefully.

    The current implementation always includes the repository property in the release.json file, even when it's null. This could cause issues if other parts of the application expect valid repository information.

    Consider conditionally adding the repository field:

    // write release tag and repository info
    const commitShort = execSync('git rev-parse --short HEAD').toString().trim()
    const repository = getGitRepository()
    -fs.writeFileSync('./assets/release.json', JSON.stringify({
    -    latestTag: `${commitShort} (docker)`,
    -    repository
    -}), 'utf8')
    +const releaseInfo = {
    +    latestTag: `${commitShort} (docker)`
    +}
    +if (repository) {
    +    releaseInfo.repository = repository
    +}
    +fs.writeFileSync('./assets/release.json', JSON.stringify(releaseInfo), 'utf8')

    7-19: Add validation for the extracted repository name format.

    The extracted repository name should follow the format owner/repo, but there's no validation to ensure this pattern is correctly extracted.

    Add a validation step to ensure the extracted repository follows the expected pattern:

    const getGitRepository = () => {
        try {
            const gitConfig = fs.readFileSync('.git/config', 'utf8')
            const originUrlMatch = gitConfig.match(/\[remote "origin"\][\s\S]*?url = .*?github\.com[:/](.*?)(\.git)?\n/m)
            if (originUrlMatch) {
    -            return originUrlMatch[1]
    +            const repo = originUrlMatch[1]
    +            // Validate repo format (owner/repo)
    +            if (/^[^/]+\/[^/]+$/.test(repo)) {
    +                return repo
    +            }
    +            console.warn('Extracted repository name does not match expected format (owner/repo):', repo)
            }
        } catch (err) {
            console.warn('Failed to read git repository from config:', err)
        }
        return null
    }

    7-19:

    ❓ Verification inconclusive

    Add support for non-GitHub repository hosts.

    The current implementation only works with GitHub repositories. If your project might be hosted on other platforms like GitLab or Bitbucket in the future, you might want to add support for those as well.

    Let's check if the project uses other git hosts elsewhere in the codebase:


    🏁 Script executed:

    #!/bin/bash
    # Search for references to different git hosting services
    echo "Searching for references to different git hosting services..."
    rg -i "github\.com|gitlab\.com|bitbucket\.org" --type js --type ts --type json

    Length of output: 1294


    Expand Repository Host Support Consideration

    The repository extraction logic in scripts/dockerPrepare.mjs (lines 7–19) currently relies on a regex that targets GitHub URLs. Our search confirms that all existing references in the codebase point exclusively to GitHub. If there’s any possibility of hosting on platforms like GitLab or Bitbucket in the future, please consider one of the following:

    • Generalize the Regex: Update the logic to also match repository URLs for GitLab, Bitbucket, etc.
    • Document the Limitation: If the project is intended to be GitHub-only, add a comment explaining this design choice for future maintainers.
    📜 Review details

    Configuration used: CodeRabbit UI
    Review profile: CHILL
    Plan: Pro

    📥 Commits

    Reviewing files that changed from the base of the PR and between d6e5450 and 976c4de.

    📒 Files selected for processing (3)
    • Dockerfile (2 hunks)
    • rsbuild.config.ts (4 hunks)
    • scripts/dockerPrepare.mjs (1 hunks)
    🚧 Files skipped from review as they are similar to previous changes (1)
    • rsbuild.config.ts
    ⏰ Context from checks skipped due to timeout of 90000ms (1)
    • GitHub Check: build-and-deploy
    🔇 Additional comments (2)
    Dockerfile (2)

    12-12: Add CONFIG_JSON_SOURCE Build Argument
    The introduction of the build argument CONFIG_JSON_SOURCE (defaulting to REMOTE) aligns well with the PR objective of conditionally loading configuration from either bundled or remote sources. Ensure that this default value is consistent with your intended deployment behavior.


    26-27: Propagate Configuration Variables in the Build Command
    The updated RUN command now passes both DISABLE_SERVICE_WORKER and CONFIG_JSON_SOURCE environment variables to the build process. This change enables the build system to dynamically control service worker disabling and configuration sourcing, ensuring that the build reflects the updated logic in rsbuild.config.ts. Please verify that downstream scripts (e.g., pnpm run build) correctly reference these environment variables for proper configuration handling.

    Comment on lines +7 to +19
    // Get repository from git config
    const getGitRepository = () => {
    try {
    const gitConfig = fs.readFileSync('.git/config', 'utf8')
    const originUrlMatch = gitConfig.match(/\[remote "origin"\][\s\S]*?url = .*?github\.com[:/](.*?)(\.git)?\n/m)
    if (originUrlMatch) {
    return originUrlMatch[1]
    }
    } catch (err) {
    console.warn('Failed to read git repository from config:', err)
    }
    return null
    }
    Copy link

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    🛠️ Refactor suggestion

    Use native git commands instead of parsing config file.

    The function attempts to extract the repository information by parsing the git config file directly with regex, which is fragile and may break with different git configurations or formats.

    I recommend using git commands directly through execSync, which would be more robust:

    // Get repository from git config
    const getGitRepository = () => {
        try {
    -        const gitConfig = fs.readFileSync('.git/config', 'utf8')
    -        const originUrlMatch = gitConfig.match(/\[remote "origin"\][\s\S]*?url = .*?github\.com[:/](.*?)(\.git)?\n/m)
    -        if (originUrlMatch) {
    -            return originUrlMatch[1]
    -        }
    +        const remoteUrl = execSync('git config --get remote.origin.url').toString().trim()
    +        // Extract repo from GitHub URL format (handles both HTTPS and SSH formats)
    +        const githubRepoMatch = remoteUrl.match(/github\.com[:/](.*?)(\.git)?$/)
    +        if (githubRepoMatch) {
    +            return githubRepoMatch[1]
    +        }
    +        console.warn('Remote URL does not appear to be a GitHub repository:', remoteUrl)
        } catch (err) {
            console.warn('Failed to read git repository from config:', err)
        }
        return null
    }
    📝 Committable suggestion

    ‼️ IMPORTANT
    Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    Suggested change
    // Get repository from git config
    const getGitRepository = () => {
    try {
    const gitConfig = fs.readFileSync('.git/config', 'utf8')
    const originUrlMatch = gitConfig.match(/\[remote "origin"\][\s\S]*?url = .*?github\.com[:/](.*?)(\.git)?\n/m)
    if (originUrlMatch) {
    return originUrlMatch[1]
    }
    } catch (err) {
    console.warn('Failed to read git repository from config:', err)
    }
    return null
    }
    // Get repository from git config
    const getGitRepository = () => {
    try {
    const remoteUrl = execSync('git config --get remote.origin.url').toString().trim()
    // Extract repo from GitHub URL format (handles both HTTPS and SSH formats)
    const githubRepoMatch = remoteUrl.match(/github\.com[:/](.*?)(\.git)?$/)
    if (githubRepoMatch) {
    return githubRepoMatch[1]
    }
    console.warn('Remote URL does not appear to be a GitHub repository:', remoteUrl)
    } catch (err) {
    console.warn('Failed to read git repository from config:', err)
    }
    return null
    }

    Copy link

    @coderabbitai coderabbitai bot left a comment

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    Actionable comments posted: 0

    🧹 Nitpick comments (3)
    src/appConfig.ts (3)

    5-23: Consider defining a more explicit structure for promoteServers.
    Inline types such as { ip, description, version? } may reduce clarity and type safety. Declaring a dedicated interface or specifying the field types (e.g. ip: string) can improve readability and correctness.


    25-30: Perform a deep merge if nested objects need merging.
    Using Object.assign only merges top-level properties. If appConfig contains nested objects, updates in deeper levels could be lost or incorrectly overridden. Consider implementing or utilizing a deep-merge approach if that scenario is expected.


    32-44: Double-check logic for forced settings versus disabled settings.
    When forcing a setting (i.e., value is true), you disable user modifications and also assign a default value. If the intent is to prevent changes and always override with defaults, this is fine. Otherwise, consider clarifying the distinction between forcing and disabling a setting.

    📜 Review details

    Configuration used: CodeRabbit UI
    Review profile: CHILL
    Plan: Pro

    📥 Commits

    Reviewing files that changed from the base of the PR and between 9735b17 and d0f937f.

    📒 Files selected for processing (1)
    • src/appConfig.ts (1 hunks)
    ⏰ Context from checks skipped due to timeout of 90000ms (1)
    • GitHub Check: build-and-deploy
    🔇 Additional comments (3)
    src/appConfig.ts (3)

    49-51: Validate environment config shape.
    Casting process.env.INLINED_APP_CONFIG to AppConfig may be risky if it doesn't match the expected shape. Consider parsing or validating the environment config object to avoid runtime inconsistencies.


    52-52: Use await to block application load until config is fetched.
    This mirrors an existing suggestion to replace void with await, ensuring the remote config is loaded before continuing.


    52-58: Handle the possibility of config being null or undefined.
    When fetching config.json fails, the code sets a loading screen status but still proceeds to call loadAppConfig(config). Ensure config is defined and valid, or provide a fallback for partial or missing config objects.

    @zardoy
    Copy link
    Owner Author

    zardoy commented Mar 4, 2025

    @ Phoenix616 thanks

    @zardoy zardoy merged commit 1c700aa into next Mar 4, 2025
    3 checks passed
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    None yet

    2 participants