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

Support dependency map in resource config #2476

Merged
merged 32 commits into from
Jan 2, 2025
Merged

Conversation

johanzhu
Copy link
Contributor

@johanzhu johanzhu commented Dec 25, 2024

Please check if the PR fulfills these requirements

  • The commit message follows our guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)

What kind of change does this PR introduce? (Bug fix, feature, docs update, ...)

What is the current behavior? (You can also link to an open issue here)

What is the new behavior (if this is a feature change)?

Does this PR introduce a breaking change? (What changes might users need to make in their application due to this PR?)

Other information:

Summary by CodeRabbit

  • New Features

    • Enhanced resource management capabilities with improved mapping of virtual paths and resource IDs
    • Added support for tracking dependent assets within resource items
  • Refactor

    • Updated resource management structure to provide more flexible and detailed resource tracking

Copy link

coderabbitai bot commented Dec 25, 2024

Walkthrough

The pull request introduces modifications to the ResourceManager class in the core asset management module. The changes focus on enhancing resource path and dependency tracking by introducing two new maps: _virtualPathResourceMap and _idResourceMap. These maps replace previous mapping mechanisms and provide more robust tracking of resources using EditorResourceItem objects. The EditorResourceItem type is also extended to include an optional dependentAssetMap for improved resource dependency management.

Changes

File Change Summary
packages/core/src/asset/ResourceManager.ts - Added _virtualPathResourceMap for mapping virtual paths to resources
- Added _idResourceMap for mapping resource IDs to resources
- Updated _getRemoteUrl method to use new mapping
- Modified initVirtualResources to populate new maps
- Extended EditorResourceItem type with optional dependentAssetMap

Poem

🐰 Hop, hop, through resource lanes so bright,
Maps and paths now aligned just right,
Virtual trails, dependencies clear,
A rabbit's code with technical cheer!
Resource management takes its flight! 🚀


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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. (Beta)
  • @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.

Copy link

codecov bot commented Dec 25, 2024

Codecov Report

Attention: Patch coverage is 85.71429% with 3 lines in your changes missing coverage. Please review.

Project coverage is 68.38%. Comparing base (ab48451) to head (5aaf315).
Report is 4 commits behind head on dev/1.4.

Files with missing lines Patch % Lines
packages/core/src/asset/ResourceManager.ts 85.71% 3 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           dev/1.4    #2476      +/-   ##
===========================================
- Coverage    68.42%   68.38%   -0.04%     
===========================================
  Files          923      923              
  Lines        95940    95904      -36     
  Branches      8140     8134       -6     
===========================================
- Hits         65647    65588      -59     
- Misses       30040    30062      +22     
- Partials       253      254       +1     
Flag Coverage Δ
unittests 68.38% <85.71%> (-0.04%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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: 2

🧹 Nitpick comments (1)
packages/core/src/asset/ResourceManager.ts (1)

559-560: Add checks or validations for the _dependencyMap usage.

While this property correctly tracks resource dependencies mapped to their references, consider adding runtime checks when assigning or retrieving its entries. This prevents unexpected errors if a key is not found or if a value is incorrectly typed (e.g., null or undefined).

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 90c3228 and d79fd47.

📒 Files selected for processing (1)
  • packages/core/src/asset/ResourceManager.ts (3 hunks)
🧰 Additional context used
🪛 eslint
packages/core/src/asset/ResourceManager.ts

[error] 637-637: Replace ·virtualPath:·string;·path:·string;·type:·string;·id:·string,·depndentAssets:·{·[key:·string]:·string·}· with ⏎··virtualPath:·string;⏎··path:·string;⏎··type:·string;⏎··id:·string;⏎··depndentAssets:·{·[key:·string]:·string·};⏎

(prettier/prettier)

🪛 GitHub Check: lint
packages/core/src/asset/ResourceManager.ts

[failure] 637-637:
Replace ·virtualPath:·string;·path:·string;·type:·string;·id:·string,·depndentAssets:·{·[key:·string]:·string·}· with ⏎··virtualPath:·string;⏎··path:·string;⏎··type:·string;⏎··id:·string;⏎··depndentAssets:·{·[key:·string]:·string·};⏎

@@ -631,7 +634,7 @@
"g"
);

type EditorResourceItem = { virtualPath: string; path: string; type: string; id: string };
type EditorResourceItem = { virtualPath: string; path: string; type: string; id: string, depndentAssets: { [key: string]: string } };
Copy link

@coderabbitai coderabbitai bot Dec 25, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Address ESLint’s formatting recommendations and fix the property name.

Use multiline for readability, and correct the property name to dependentAssets.

Below is a suggested diff:

- type EditorResourceItem = { virtualPath: string; path: string; type: string; id: string, depndentAssets: { [key: string]: string } };
+ type EditorResourceItem = {
+   virtualPath: string;
+   path: string;
+   type: string;
+   id: string;
+   dependentAssets: { [key: string]: string };
+ };
📝 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
type EditorResourceItem = { virtualPath: string; path: string; type: string; id: string, depndentAssets: { [key: string]: string } };
type EditorResourceItem = {
virtualPath: string;
path: string;
type: string;
id: string;
dependentAssets: { [key: string]: string };
};
🧰 Tools
🪛 eslint

[error] 637-637: Replace ·virtualPath:·string;·path:·string;·type:·string;·id:·string,·depndentAssets:·{·[key:·string]:·string·}· with ⏎··virtualPath:·string;⏎··path:·string;⏎··type:·string;⏎··id:·string;⏎··depndentAssets:·{·[key:·string]:·string·};⏎

(prettier/prettier)

🪛 GitHub Check: lint

[failure] 637-637:
Replace ·virtualPath:·string;·path:·string;·type:·string;·id:·string,·depndentAssets:·{·[key:·string]:·string·}· with ⏎··virtualPath:·string;⏎··path:·string;⏎··type:·string;⏎··id:·string;⏎··depndentAssets:·{·[key:·string]:·string·};⏎

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done

Copy link

Choose a reason for hiding this comment

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

@johanzhu, thanks for confirming everything is done!


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

@@ -593,6 +595,7 @@
initVirtualResources(config: EditorResourceItem[]): void {
config.forEach((element) => {
this._virtualPathMap[element.virtualPath] = element.path;
this._dependencyMap[element.virtualPath] = element.depndentAssets;
Copy link

@coderabbitai coderabbitai bot Dec 25, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Spelling mismatch in the key property depndentAssets.

It appears the property name is missing an “e.” Renaming it to dependentAssets throughout the code helps with clarity and consistency, since “depndent” could be mistaken for a typographical error.

Apply the following diff to rename the property:

- this._dependencyMap[element.virtualPath] = element.depndentAssets;
+ this._dependencyMap[element.virtualPath] = element.dependentAssets;
📝 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
this._dependencyMap[element.virtualPath] = element.depndentAssets;
this._dependencyMap[element.virtualPath] = element.dependentAssets;

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done

Copy link

Choose a reason for hiding this comment

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

@johanzhu Great! Thanks for handling it. Let me know if there's anything else you need.


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

@@ -593,6 +595,7 @@ export class ResourceManager {
initVirtualResources(config: EditorResourceItem[]): void {
config.forEach((element) => {
this._virtualPathMap[element.virtualPath] = element.path;
this._dependencyMap[element.virtualPath] = element.depndentAssets;
Copy link
Contributor

Choose a reason for hiding this comment

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

What's the value of element.dependentAssets if asset has not dependentAssets. if it is undefined, still set?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done

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)
packages/core/src/asset/ResourceManager.ts (1)

559-560: Consider adding JSDoc comments for the dependency map.

Since this is a critical feature for internal editor use, consider adding detailed JSDoc comments explaining:

  • The structure and format of the dependency map
  • The relationship between virtual paths and their dependencies
  • Usage examples and constraints

Add documentation like this:

  /** @internal */
+ /**
+  * Maps virtual paths to their dependent assets.
+  * @example
+  * {
+  *   "virtualPath/to/asset": {
+  *     "dependency1": "path/to/dependency1",
+  *     "dependency2": "path/to/dependency2"
+  *   }
+  * }
+  */
  _dependencyMap: Record<string, { [key: string]: string }> = Object.create(null);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d79fd47 and b54f336.

📒 Files selected for processing (1)
  • packages/core/src/asset/ResourceManager.ts (3 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/core/src/asset/ResourceManager.ts

[error] 598-598: Invalid assignment to element.depndentAssets && this._dependencyMap[element.virtualPath]

This expression cannot be assigned to

(parse)

🔇 Additional comments (2)
packages/core/src/asset/ResourceManager.ts (2)

559-560: LGTM! Property declaration follows class conventions.

The _dependencyMap property is well-typed and consistently initialized using Object.create(null).


637-638: Fix type definition formatting and property name.

The type definition needs formatting improvements and the property name should be corrected from "depndent" to "dependent".

@@ -593,6 +595,7 @@ export class ResourceManager {
initVirtualResources(config: EditorResourceItem[]): void {
config.forEach((element) => {
this._virtualPathMap[element.virtualPath] = element.path;
element.depndentAssets && this._dependencyMap[element.virtualPath] = element.depndentAssets;
Copy link

@coderabbitai coderabbitai bot Dec 26, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix assignment syntax and add null check.

The current implementation has several issues:

  1. The assignment syntax is incorrect
  2. Missing null check before accessing depndentAssets
  3. Property name has a typo ("depndent" should be "dependent")

Apply this diff to fix the issues:

-      element.depndentAssets && this._dependencyMap[element.virtualPath] = element.depndentAssets;
+      if (element.dependentAssets) {
+        this._dependencyMap[element.virtualPath] = element.dependentAssets;
+      }
📝 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
element.depndentAssets && this._dependencyMap[element.virtualPath] = element.depndentAssets;
if (element.dependentAssets) {
this._dependencyMap[element.virtualPath] = element.dependentAssets;
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 598-598: Invalid assignment to element.depndentAssets && this._dependencyMap[element.virtualPath]

This expression cannot be assigned to

(parse)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done

Copy link

Choose a reason for hiding this comment

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

@johanzhu, thanks for confirming the fix has been applied! Nice work.


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

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 (1)
package.json (1)

66-69: Modernize lint-staged configuration

The lint-staged configuration uses older syntax with explicit git add. Modern versions of lint-staged automatically stage files after fixes.

   "lint-staged": {
-    "*.{ts,tsx}": [
-      "eslint --fix",
-      "git add"
-    ]
+    "*.{ts,tsx}": "eslint --fix"
   }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b54f336 and 6b1c196.

📒 Files selected for processing (2)
  • package.json (1 hunks)
  • packages/core/src/asset/ResourceManager.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/core/src/asset/ResourceManager.ts
🔇 Additional comments (1)
package.json (1)

66-66: Verify the necessity of adding TSX support

Let's verify if this change is related to the dependency map feature and if there are any TSX files in the codebase.

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 (2)
packages/core/src/asset/ResourceManager.ts (2)

599-601: Add documentation and validation for dependency mapping.

While the implementation is correct, consider:

  1. Adding JSDoc comments explaining the purpose and structure of dependencies
  2. Adding validation for the dependency map contents

Example documentation:

+ /**
+  * Maps virtual paths to their dependent assets.
+  * @param element.dependentAssetMap - Map of asset keys to their dependency paths
+  */
  if (element.dependentAssetMap) {
    this._dependencyMap[element.virtualPath] = element.dependentAssetMap;
  }

639-645: Enhance type definition with documentation and specific types.

Consider improving the type definition:

  1. Add TSDoc comments for the type and its properties
  2. Make dependentAssetMap type more specific than { [key: string]: string }
+/**
+ * Configuration for editor-specific resource items.
+ */
 type EditorResourceItem = {
+  /** Virtual path used for resource mapping */
   virtualPath: string;
+  /** Actual file system path */
   path: string;
+  /** Resource type identifier */
   type: string;
+  /** Unique identifier for the resource */
   id: string;
+  /** Map of asset identifiers to their dependency paths */
-  dependentAssetMap: { [key: string]: string };
+  dependentAssetMap: Record<AssetKey, DependencyPath>;
 };

+/** Asset identifier type */
+type AssetKey = string;
+
+/** Path to a dependency resource */
+type DependencyPath = string;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6b1c196 and 4155cc1.

📒 Files selected for processing (1)
  • packages/core/src/asset/ResourceManager.ts (3 hunks)
🔇 Additional comments (2)
packages/core/src/asset/ResourceManager.ts (2)

559-560: LGTM! Property declaration follows best practices.

The _dependencyMap property is well-typed and follows the established patterns in the codebase for internal map properties.


Line range hint 559-601: Verify dependency cleanup in resource destruction.

The _destroy() method should be updated to clean up the _dependencyMap. Let's verify the current implementation:

Consider adding cleanup in the _destroy() method:

 private _destroy(): void {
   this.cancelNotLoaded();
   this._gc(true);
   this._assetPool = null;
   this._assetUrlPool = null;
   this._referResourcePool = null;
   this._graphicResourcePool = null;
   this._contentRestorerPool = null;
   this._loadingPromises = null;
+  this._dependencyMap = 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: 1

🧹 Nitpick comments (2)
packages/core/src/asset/ResourceManager.ts (2)

597-601: Consider enhancing the method documentation.

While the implementation is solid, the method's documentation could be improved to explain:

  • The purpose of dependentAssetMap
  • The relationship between virtual paths and dependencies
  • Usage examples for editor integration

Add JSDoc comments like this:

  /**
   * @internal
   * @beta Just for internal editor, not recommended for developers.
+  * @param config - Array of editor resource items
+  * @remarks
+  * This method initializes the virtual resource system by:
+  * 1. Mapping virtual paths to actual resources
+  * 2. Storing resource configurations by ID
+  * 3. Setting up dependency relationships between assets
   */

639-645: Consider making some properties optional for better flexibility.

The type definition is well-structured, but consider making dependentAssetMap optional since not all resources will have dependencies.

Apply this diff:

 type EditorResourceItem = {
   virtualPath: string;
   path: string;
   type: string;
   id: string;
-  dependentAssetMap: { [key: string]: string };
+  dependentAssetMap?: { [key: string]: string };
 };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4155cc1 and 14a9db9.

📒 Files selected for processing (1)
  • packages/core/src/asset/ResourceManager.ts (4 hunks)
🔇 Additional comments (1)
packages/core/src/asset/ResourceManager.ts (1)

558-560: LGTM! Well-structured property declarations.

Good practices observed:

  • Using Object.create(null) for map-like objects
  • Clear type definitions
  • Proper internal marking

@@ -184,7 +184,7 @@ export class ResourceManager {
* @internal
*/
_getRemoteUrl(url: string): string {
return this._virtualPathMap[url] ?? url;
return this._virtualPathMap[url].path ?? url;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add null check to prevent potential runtime errors.

The current implementation might throw if virtualPathMap[url] is undefined.

Apply this diff to add null checks:

- return this._virtualPathMap[url].path ?? url;
+ return this._virtualPathMap[url]?.path ?? url;
📝 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
return this._virtualPathMap[url].path ?? url;
return this._virtualPathMap[url]?.path ?? url;

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 (2)
packages/core/src/asset/ResourceManager.ts (2)

558-560: Consider adding JSDoc comments for the new properties.

While these properties are marked as @internal, adding detailed JSDoc comments would help other developers understand their purpose and usage.

  /** @internal */
+ /** Map of virtual paths to their corresponding resource configurations */
  _virtualPathMap: EditorResourceConfig = Object.create(null);
  /** @internal */
+ /** Map of virtual paths to their dependent asset configurations */
  _dependencyMap: Record<string, { [key: string]: string }> = Object.create(null);

639-645: Consider strengthening the EditorResourceItem type.

The type definition could be improved in several ways:

  1. Add readonly modifiers to prevent accidental modifications
  2. Consider using a more specific type for dependentAssetMap values
  3. Add JSDoc comments for better documentation
 type EditorResourceItem = {
-  virtualPath: string;
-  path: string;
-  type: string;
-  id: string;
-  dependentAssetMap: { [key: string]: string };
+  /** Virtual path used for resource identification */
+  readonly virtualPath: string;
+  /** Actual file system path or URL */
+  readonly path: string;
+  /** Resource type identifier */
+  readonly type: string;
+  /** Unique identifier for the resource */
+  readonly id: string;
+  /** Map of dependent asset identifiers to their paths */
+  readonly dependentAssetMap: Readonly<Record<string, string>>;
 };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 14a9db9 and 101e8c8.

📒 Files selected for processing (1)
  • packages/core/src/asset/ResourceManager.ts (6 hunks)
🔇 Additional comments (3)
packages/core/src/asset/ResourceManager.ts (3)

187-187: LGTM: Improved null safety with optional chaining.

The use of optional chaining (?.) here properly handles cases where _virtualPathMap[url] might be undefined.


209-209: LGTM: Consistent null safety pattern.

The optional chaining pattern is consistently applied here, matching the implementation in _getRemoteUrl.


364-364: LGTM: Maintained consistency in remote URL handling.

The same null-safe pattern is correctly applied here, maintaining consistency across the codebase.

Comment on lines 597 to 601
this._virtualPathMap[element.virtualPath] = element;
this._editorResourceConfig[element.id] = element;
if (element.dependentAssetMap) {
this._dependencyMap[element.virtualPath] = element.dependentAssetMap;
}
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Add cleanup mechanism and validation for dependent assets

Based on the verification results, there are legitimate concerns:

  1. The dependentAssetMap lacks runtime validation before being added to _dependencyMap
  2. There's no cleanup mechanism for _dependencyMap entries when resources are removed
  3. The _destroy() method doesn't clear the _dependencyMap

Suggested improvements:

  • Add runtime validation for dependentAssetMap structure before assignment
  • Implement cleanup for _dependencyMap entries when resources are removed
  • Include _dependencyMap cleanup in the _destroy() method
🔗 Analysis chain

Verify dependent asset initialization.

The code now handles dependent assets, but there are a few considerations:

  1. No validation is performed on the dependentAssetMap structure
  2. The dependency map could grow unbounded as more virtual resources are added

Consider adding validation and implementing a cleanup mechanism.


Let me gather more information about the cleanup mechanisms and validation.


Let me check one more aspect about resource cleanup and the relationship between virtual paths and resources.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential memory leaks by finding all calls that might add to _dependencyMap
ast-grep --pattern 'this._dependencyMap[$_] = $_'

# Look for any cleanup calls
rg -A 5 '_dependencyMap.*=.*null' 

Length of output: 650


Script:

#!/bin/bash
# Check for cleanup methods in ResourceManager
ast-grep --pattern 'function $_($$$) {
  $$$
  this._dependencyMap[$$$] = $$$
  $$$
}'

# Look for methods that might handle resource removal
rg -A 10 "removeResource|destroy|dispose|clear" packages/core/src/asset/ResourceManager.ts

# Check if there's validation for dependentAssetMap
ast-grep --pattern 'interface $_Resource {
  $$$
  dependentAssetMap$_
  $$$
}'

Length of output: 852


Script:

#!/bin/bash
# Check for virtual path cleanup
rg -A 5 "_virtualPathMap.*=.*null|delete.*_virtualPathMap|delete.*_dependencyMap" packages/core/src/asset/ResourceManager.ts

# Look for resource removal or cleanup methods
ast-grep --pattern 'function $_($$$) {
  $$$
  delete this._virtualPathMap[$_]
  $$$
}'

# Check the type definition of dependentAssetMap
rg -A 3 "dependentAssetMap.*:" packages/core/src/asset/ResourceManager.ts

Length of output: 637

Copy link
Member

@singlecoder singlecoder left a comment

Choose a reason for hiding this comment

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

+1

package.json Outdated
@@ -63,7 +63,7 @@
"vitest": "2.1.3"
},
"lint-staged": {
"*.{ts}": [
"*.{ts,tsx}": [
Copy link
Member

Choose a reason for hiding this comment

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

Delete tsx

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done

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

🔭 Outside diff range comments (1)
packages/core/src/asset/ResourceManager.ts (1)

Line range hint 479-486: Add cleanup for new resource maps in _destroy method.

The _destroy method should clean up all class properties, including the newly added resource maps.

   _destroy(): void {
     this.cancelNotLoaded();
     this._gc(true);
     this._assetPool = null;
     this._assetUrlPool = null;
     this._referResourcePool = null;
     this._graphicResourcePool = null;
     this._contentRestorerPool = null;
     this._loadingPromises = null;
+    this._virtualPathResourceMap = null;
+    this._idResourceMap = null;
   }
🧹 Nitpick comments (3)
packages/core/src/asset/ResourceManager.ts (3)

187-187: Add null check to prevent potential runtime errors.

The optional chaining operator is correctly used for the path property, but we should also add a null check for _virtualPathResourceMap[url] itself.

-    return this._virtualPathResourceMap[url]?.path ?? url;
+    return this._virtualPathResourceMap?.[url]?.path ?? url;

556-558: Consider adding runtime type validation for map entries.

The maps are initialized with Object.create(null), which is good for avoiding prototype pollution. However, consider adding runtime type validation when entries are added to these maps to ensure type safety.

Consider creating a validation helper:

private _validateEditorResourceItem(item: EditorResourceItem): void {
  if (!item.virtualPath || !item.path || !item.type || !item.id) {
    throw new Error('Invalid EditorResourceItem: missing required properties');
  }
}

571-573: Enhance error handling with more descriptive messages.

The warning message could be more informative by including additional context about the resource being requested.

-        Logger.warn(`refId:${refId} is not find in this._idResourceMap.`);
+        Logger.warn(
+          `Resource not found: refId "${refId}" does not exist in resource map.` +
+          ` Available resources: ${Object.keys(this._idResourceMap).length}`
+        );
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 101e8c8 and 5aaf315.

📒 Files selected for processing (1)
  • packages/core/src/asset/ResourceManager.ts (7 hunks)

Comment on lines +595 to +599
this._virtualPathResourceMap[element.virtualPath] = element;
this._idResourceMap[element.id] = element;
if (element.dependentAssetMap) {
this._virtualPathResourceMap[element.virtualPath].dependentAssetMap = element.dependentAssetMap;
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add input validation and cleanup mechanism.

The current implementation has several potential issues:

  1. No validation of the input array
  2. No cleanup of existing entries before initialization
  3. Redundant assignment of dependentAssetMap

Consider this improved implementation:

 initVirtualResources(config: EditorResourceItem[]): void {
+  if (!Array.isArray(config)) {
+    throw new Error('Config must be an array of EditorResourceItem');
+  }
+  // Clear existing entries
+  this._virtualPathResourceMap = Object.create(null);
+  this._idResourceMap = Object.create(null);
+
   config.forEach((element) => {
+    this._validateEditorResourceItem(element);
     this._virtualPathResourceMap[element.virtualPath] = element;
     this._idResourceMap[element.id] = element;
-    if (element.dependentAssetMap) {
-      this._virtualPathResourceMap[element.virtualPath].dependentAssetMap = element.dependentAssetMap;
-    }
   });
 }

Committable suggestion skipped: line range outside the PR's diff.

@GuoLei1990 GuoLei1990 changed the title Feat: Add dependency map Support dependency map in resource config Jan 2, 2025
@GuoLei1990 GuoLei1990 added enhancement New feature or request ignore for release ignore for release labels Jan 2, 2025
@GuoLei1990 GuoLei1990 merged commit 70af4ee into dev/1.4 Jan 2, 2025
8 of 9 checks passed
@johanzhu johanzhu deleted the feat/add-dependencyMap branch January 3, 2025 02:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request ignore for release ignore for release
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants