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

Amend the Component API methods in the SDK #14883

Conversation

jverce
Copy link
Contributor

@jverce jverce commented Dec 6, 2024

Changelog

  • Fix the naming of the new methods for the Components API to follow the existing convention
  • Deprecate old methods and types
  • Document public methods and types
  • Fix some linter issues
  • Bump minor version

Summary by CodeRabbit

  • New Features

    • Updated version of the SDK package to 1.1.0.
    • Introduced new types for enhanced type safety in component properties.
    • Added new methods for improved API interactions, including getApps, getApp, and getComponents.
  • Bug Fixes

    • Deprecated older types and methods to streamline usage and improve clarity.
  • Documentation

    • Enhanced documentation comments for better guidance on usage, especially for deprecated methods.
  • Chores

    • Minor formatting change in the rejoiner app file (newline added).

* Fix the naming of the new methods for the Components API to follow the
  existing convention
* Deprecate old methods and types
* Document public methods and types
* Fix some linter issues
* Bump minor version
@jverce jverce added enhancement New feature or request docs pd-api Pipedream API requests tracked internally Issue is also tracked in our internal issue tracker prioritized Prioritized issue labels Dec 6, 2024
@jverce jverce self-assigned this Dec 6, 2024
Copy link

vercel bot commented Dec 6, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
docs-v2 ❌ Failed (Inspect) Dec 10, 2024 7:08pm
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
pipedream-docs-redirect-do-not-edit ⬜️ Ignored (Inspect) Dec 10, 2024 7:08pm

Copy link
Contributor

coderabbitai bot commented Dec 6, 2024

Walkthrough

The pull request introduces updates to the @pipedream/sdk package, specifically modifying the package.json to change the version from 1.0.10 to 1.1.0. Additionally, the index.ts file in the SDK's shared directory sees significant changes, including the introduction of new types and renaming of existing types and methods to enhance clarity and type safety. The modifications streamline method signatures, ensuring many methods return promises directly, alongside added documentation for deprecated methods.

Changes

File Path Change Summary
packages/sdk/package.json Updated version from 1.0.10 to 1.1.0. No other changes to structure or dependencies.
packages/sdk/src/shared/index.ts Added types RequireAtLeastOne, ExternalUserId, and AppInfo. Renamed several types and methods to improve clarity. Updated method signatures to return promises directly.
components/rejoiner/rejoiner.app.mjs Minor modification: added a newline at the end of the file. No changes to functionality.

Possibly related PRs

Suggested labels

dependencies

Suggested reviewers

  • tjk
  • lcaresia

🐇 In the meadow, the changes hop,
A version bump, we’ll never stop!
New types and methods, clear and bright,
In the code, they bring delight.
With promises now, our paths align,
Hooray for updates, oh how they shine! 🌟

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review.


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. (Experiment)
  • @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

vercel bot commented Dec 6, 2024

@jverce is attempting to deploy a commit to the Pipedreamers Team on Vercel.

A member of the Team first needs to authorize it.

@jverce jverce requested a review from dylburger December 6, 2024 22:08
Copy link
Contributor

@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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 72f817e and 6858d81.

📒 Files selected for processing (2)
  • packages/sdk/package.json (1 hunks)
  • packages/sdk/src/shared/index.ts (8 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/sdk/package.json
🔇 Additional comments (10)
packages/sdk/src/shared/index.ts (10)

8-9: Updated imports are correct.

The additions of ConfigurableProps and ConfiguredProps to the imports from ./component.js are appropriate and ensure that the new types are properly imported for use within the module.


Line range hint 67-98: Proper deprecation of AppResponse in favor of App.

The AppResponse type is deprecated and aliased to the new App type with appropriate documentation. This maintains backward compatibility while guiding users to adopt the updated type definition.


106-110: Deprecation of ComponentConfigureResponse handled correctly.

The type ComponentConfigureResponse is deprecated in favor of ConfigureComponentResponse. The deprecation notice is clear, and existing references will still function due to the aliasing.


201-232: Consistent use of externalUserId and deprecation of userId.

In ReloadComponentPropsOpts, the introduction of externalUserId and deprecation of userId align with the updated authentication approach. The deprecation is properly documented, ensuring that users are aware of the change.


678-679: Method getAccounts correctly updated.

The getAccounts method now returns a promise directly without the async keyword, in line with its implementation. The method signature accurately reflects the returned promise.


714-719: Deprecation of apps method in favor of getApps.

The apps method is deprecated and now correctly calls getApps. The deprecation notice guides users to the updated method name, maintaining API consistency.


817-825: Deprecation of component method handled appropriately.

The deprecated component method correctly delegates to getComponent, ensuring that existing codebases remain functional while encouraging migration to the new method name.


826-851: Implementation of configureComponent method is accurate.

The new configureComponent method replaces componentConfigure and correctly constructs the request body, handling both userId (deprecated) and externalUserId. The use of async_handle for asynchronous responses aligns with the API expectations.


865-892: reloadComponentProps method updated successfully.

The method now uses externalUserId instead of userId, with proper deprecation handling. The request body is appropriately structured for the API call, ensuring correct functionality.


951-953: Deprecation of actionRun method is correctly implemented.

The deprecated actionRun method properly calls runAction, maintaining functionality and guiding users to the new method name.

packages/sdk/src/shared/index.ts Outdated Show resolved Hide resolved
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (1)
packages/sdk/src/shared/index.ts (1)

99-99: Add missing documentation for TODO items.

There are two TODO comments that need to be addressed:

  1. Line 99: Missing documentation for ConfigureComponentResponse type
  2. Line 865: Missing documentation for reloadComponentProps method

Would you like me to help generate the documentation for these items?

Also applies to: 865-865

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6858d81 and 506c012.

📒 Files selected for processing (1)
  • packages/sdk/src/shared/index.ts (8 hunks)
🔇 Additional comments (3)
packages/sdk/src/shared/index.ts (3)

833-838: Verify parameter migration pattern.

The migration from userId to externalUserId is implemented consistently across all methods using a fallback pattern:

const {
  userId,
  externalUserId = userId,
  // ...
} = opts;

This pattern ensures backward compatibility while encouraging the use of the new parameter name.

Let's verify the consistency of this pattern:

Also applies to: 866-871, 925-930, 962-967

✅ Verification successful

Parameter migration pattern is consistently implemented

The verification confirms that the migration pattern from userId to externalUserId is consistently implemented across all four occurrences in the codebase, using the same fallback pattern:

const {
  userId,
  externalUserId = userId,
  ...
} = opts;

Found in:

  • Lines 833-837: Component-related operation
  • Lines 866-870: Component-related operation
  • Lines 925-929: Action-related operation
  • Lines 962-966: Trigger-related operation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify parameter migration pattern
# Test: Check if all methods follow the same pattern for parameter migration
ast-grep --pattern $'const {
  userId,
  externalUserId = userId,
  $$$
} = opts'

Length of output: 1177


714-719: Verify deprecated method implementations.

All deprecated methods correctly delegate to their new counterparts, following a consistent pattern:

  • appsgetApps
  • appgetApp
  • componentsgetComponents
  • componentgetComponent
  • componentConfigureconfigureComponent
  • componentReloadPropsreloadComponentProps
  • actionRunrunAction
  • triggerDeploydeployTrigger

Let's verify that all deprecated methods are properly documented:

Also applies to: 741-746, 788-793, 817-824, 857-862, 894-898, 948-953, 986-991

✅ Verification successful

All deprecated methods are properly documented and implemented

The verification confirms that all deprecated methods:

  • Have proper @deprecated JSDoc comments pointing to their new counterparts
  • Correctly delegate to their new implementations with matching parameters
  • Follow a consistent naming pattern across the codebase

The deprecated methods and their replacements are:

  • apps()getApps()
  • app()getApp()
  • components()getComponents()
  • component()getComponent()
  • componentConfigure()configureComponent()
  • componentReloadProps()reloadComponentProps()
  • actionRun()runAction()
  • triggerDeploy()deployTrigger()

Additionally, several deprecated types are also properly documented with their replacements.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify deprecated method documentation
# Test: Check if all deprecated methods have proper JSDoc comments
ast-grep --pattern $'/**
 * @deprecated Use $_
 */
$_'

Length of output: 55


Script:

#!/bin/bash
# Let's try a different approach to find deprecated methods and their implementations
rg "@deprecated.*Use.*instead" -A 3

Length of output: 5479


Line range hint 1153-1158: Improve error message and address TODO comment.

The error message and TODO comment in invokeWorkflowForExternalUser need attention:

  1. The error message could be more specific about the authentication requirements
  2. The TODO comment about token authentication should be verified

Consider updating the error message to be more specific:

-        "OAuth or token is required for invoking workflows for external users. Please pass credentials for a valid OAuth client",
+        "Authentication is required for invoking workflows for external users. Please provide either OAuth credentials or a valid authentication token.",

Let's verify the token authentication functionality:

✅ Verification successful

Let me gather more information about the token authentication implementation to verify if it's properly handled.


Let me try one more verification to check the token authentication implementation more thoroughly.


Based on the gathered evidence, I can now provide the final response:

Token authentication is properly implemented, but error message needs improvement

The codebase shows that token authentication (StaticBearer) is properly implemented and tested:

  • There's a dedicated test case verifying StaticBearer token authentication
  • The implementation correctly handles both OAuth and StaticBearer auth types
  • The TODO comment about token auth can be safely removed as the functionality is working

However, the error message should be updated as suggested:

-        "OAuth or token is required for invoking workflows for external users. Please pass credentials for a valid OAuth client",
+        "Authentication is required for invoking workflows for external users. Please provide either OAuth credentials or a valid authentication token.",
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check token authentication implementation
# Test: Search for token auth handling in the codebase
rg -A 5 "authHeaders|HTTPAuthType.StaticBearer"

Length of output: 3246


Script:

#!/bin/bash
# Check token auth implementation in tests and related code
rg -A 5 "StaticBearer.*test" && echo "---" && \
ast-grep --pattern 'class $_ {
  $$$
  invokeWorkflowForExternalUser($$$) {
    $$$
  }
  $$$
}'

Length of output: 30


Script:

#!/bin/bash
# Search for token authentication tests and implementation
rg -A 10 "HTTPAuthType.StaticBearer" && echo "---" && \
rg -A 10 "invokeWorkflowForExternalUser.*token"

Length of output: 1750

Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (3)
packages/sdk/src/shared/index.ts (3)

105-106: Add documentation for ConfigureComponentResponse type.

The TODO comment indicates missing documentation. Please add a docstring describing the purpose and structure of this type.


870-871: Add documentation for reloadComponentProps method.

The TODO comment indicates missing documentation. Please add a docstring describing:

  • The purpose of the method
  • Parameters and their usage
  • Return value and type
  • Example usage

893-894: Address TODO comment in makeConnectRequestAsync.

There's a TODO comment about triggers that needs to be addressed. Please clarify the intention and implement the necessary changes.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 506c012 and 8b37dbb.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (1)
  • packages/sdk/src/shared/index.ts (8 hunks)
🔇 Additional comments (5)
packages/sdk/src/shared/index.ts (5)

8-20: LGTM! Well-designed type definitions.

The RequireAtLeastOne utility type is a good implementation for handling optional parameters while ensuring at least one is provided. The imported types enhance type safety for component configuration.


Line range hint 73-104: LGTM! Clean type renaming with proper deprecation.

The renaming of AppResponse to App improves API clarity, and the deprecation notice is properly documented. The type properties are well-documented with clear descriptions.


930-948: LGTM! Well-implemented runAction method.

The method implementation:

  • Properly handles both string and object IDs
  • Correctly manages the async response
  • Includes comprehensive documentation with examples

967-986: LGTM! Well-implemented deployTrigger method.

The method implementation:

  • Properly handles both string and object IDs
  • Correctly manages the async response
  • Includes proper type safety with V1DeployedComponent

723-725: Verify deprecated method implementations.

All deprecated methods should properly delegate to their new counterparts. Let's verify the implementation.

Also applies to: 750-752, 797-799, 826-830, 866-868, 903-904, 957-959, 995-997

✅ Verification successful

All deprecated methods correctly delegate to their replacements

The verification shows that all deprecated methods properly delegate to their new counterparts:

  • apps()getApps()
  • app()getApp()
  • components()getComponents()
  • component()getComponent()
  • componentConfigure()configureComponent()
  • componentReloadProps()reloadComponentProps()
  • actionRun()runAction()
  • triggerDeploy()deployTrigger()

Each deprecated method maintains the same parameter signature and directly forwards the call to its replacement method.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that deprecated methods properly delegate to their replacements

# Search for deprecated method implementations
rg -A 1 '@deprecated.*instead' | rg -A 1 'public.*\{'

Length of output: 55


Script:

#!/bin/bash
# Let's try a different approach to find deprecated methods and their implementations

# First, let's find all deprecated methods
rg -B 2 -A 3 '@deprecated' packages/sdk/src/shared/index.ts

Length of output: 2732

Copy link
Contributor

@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: 4

🧹 Outside diff range and nitpick comments (2)
packages/sdk/src/shared/index.ts (2)

213-238: Consider adding validation for dynamicPropsId.

While the type definition for ReloadComponentPropsOpts is well-structured with proper deprecation notices, the dynamicPropsId parameter lacks documentation explaining its purpose and validation requirements.

Add JSDoc documentation for the dynamicPropsId parameter:

   dynamicPropsId?: string;
+  /**
+   * Optional ID for dynamic props configuration. Used to maintain state between
+   * multiple configuration calls.
+   */

387-392: Improve type definitions in RunActionResponse.

The RunActionResponse type uses unknown for its properties, which could be made more specific for better type safety.

Consider defining more specific types:

-  // TODO: Add docstring
+  /**
+   * Response from running an action component
+   */
   export type RunActionResponse = {
-    exports: unknown;
-    os: unknown[];
-    ret: unknown;
+    exports: Record<string, any>;
+    os: Array<{
+      name: string;
+      value: any;
+    }>;
+    ret: any;
   };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8b37dbb and d6988cf.

📒 Files selected for processing (2)
  • components/rejoiner/rejoiner.app.mjs (1 hunks)
  • packages/sdk/src/shared/index.ts (8 hunks)
✅ Files skipped from review due to trivial changes (1)
  • components/rejoiner/rejoiner.app.mjs
🔇 Additional comments (4)
packages/sdk/src/shared/index.ts (4)

16-20: LGTM: Well-implemented utility type for type safety.

The RequireAtLeastOne utility type is a good addition that enforces at least one required property while keeping others optional, which is particularly useful for the SDK's parameter types.


Line range hint 73-99: LGTM: Well-documented type definition.

The App type is well-structured with comprehensive JSDoc comments for each property.


690-694: LGTM: Clean method implementation.

The getAccounts method is well-implemented with proper parameter handling and return type.


759-774: LGTM: Comprehensive method documentation.

The getComponents method has excellent JSDoc documentation with clear parameter descriptions and usage examples.

packages/sdk/src/shared/index.ts Outdated Show resolved Hide resolved
packages/sdk/src/shared/index.ts Outdated Show resolved Hide resolved
Comment on lines +932 to 954
public runAction(opts: RunActionOpts) {
const {
userId,
externalUserId = userId,
actionId,
} = opts;

const id = typeof actionId === "object"
? actionId.key
: actionId;

const body = {
async_handle: this.asyncResponseManager.createAsyncHandle(),
external_user_id: opts.userId,
id: opts.actionId,
external_user_id: externalUserId,
id,
configured_props: opts.configuredProps,
dynamic_props_id: opts.dynamicPropsId,
};
return await this.makeConnectRequestAsync<{
exports: unknown;
os: unknown[];
ret: unknown;
}>("/actions/run", {
return this.makeConnectRequestAsync<RunActionResponse>("/actions/run", {
method: "POST",
body,
});
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add validation for required parameters in runAction.

The runAction method should validate its required parameters before making the API request.

Add parameter validation:

   public runAction(opts: RunActionOpts) {
+    if (!opts.configuredProps) {
+      throw new Error("configured props are required");
+    }
+
     const {
       userId,
       externalUserId = userId,
       actionId,
     } = opts;

+    if (!externalUserId) {
+      throw new Error("external user ID is required");
+    }
+
     const id = typeof actionId === "object"
       ? actionId.key
       : actionId;

     const body = {
       async_handle: this.asyncResponseManager.createAsyncHandle(),
       external_user_id: externalUserId,
       id,
       configured_props: opts.configuredProps,
       dynamic_props_id: opts.dynamicPropsId,
     };
📝 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
public runAction(opts: RunActionOpts) {
const {
userId,
externalUserId = userId,
actionId,
} = opts;
const id = typeof actionId === "object"
? actionId.key
: actionId;
const body = {
async_handle: this.asyncResponseManager.createAsyncHandle(),
external_user_id: opts.userId,
id: opts.actionId,
external_user_id: externalUserId,
id,
configured_props: opts.configuredProps,
dynamic_props_id: opts.dynamicPropsId,
};
return await this.makeConnectRequestAsync<{
exports: unknown;
os: unknown[];
ret: unknown;
}>("/actions/run", {
return this.makeConnectRequestAsync<RunActionResponse>("/actions/run", {
method: "POST",
body,
});
}
public runAction(opts: RunActionOpts) {
if (!opts.configuredProps) {
throw new Error("configured props are required");
}
const {
userId,
externalUserId = userId,
actionId,
} = opts;
if (!externalUserId) {
throw new Error("external user ID is required");
}
const id = typeof actionId === "object"
? actionId.key
: actionId;
const body = {
async_handle: this.asyncResponseManager.createAsyncHandle(),
external_user_id: externalUserId,
id,
configured_props: opts.configuredProps,
dynamic_props_id: opts.dynamicPropsId,
};
return this.makeConnectRequestAsync<RunActionResponse>("/actions/run", {
method: "POST",
body,
});
}

Comment on lines 872 to 900
// TODO: Add docstring
public reloadComponentProps(opts: ReloadComponentPropsOpts) {
const {
userId,
externalUserId = userId,
componentId,
} = opts;

const id = typeof componentId === "object"
? componentId.key
: componentId;

// RpcActionReloadPropsInput
const body = {
async_handle: this.asyncResponseManager.createAsyncHandle(),
external_user_id: opts.userId,
id: opts.componentId,
external_user_id: externalUserId,
id,
configured_props: opts.configuredProps,
dynamic_props_id: opts.dynamicPropsId,
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return await this.makeConnectRequestAsync<Record<string, any>>("/components/props", {

return this.makeConnectRequestAsync<ConfiguredProps<ConfigurableProps>>(
"/components/props", {
// TODO trigger
method: "POST",
body,
});
method: "POST",
body,
},
);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Address TODO comment and improve error handling.

The reloadComponentProps method needs attention in several areas:

  1. Missing docstring as noted by TODO
  2. No validation for the configuredProps parameter
  3. Another TODO comment in the request path

Consider implementing these improvements:

-  // TODO: Add docstring
+  /**
+   * Reloads the props for a component with the current configuration.
+   * 
+   * @param opts - Options for reloading component props
+   * @returns A promise resolving to the configured props
+   * @throws {Error} When configured props are invalid
+   */
   public reloadComponentProps(opts: ReloadComponentPropsOpts) {
     const {
       userId,
       externalUserId = userId,
       componentId,
     } = opts;
+
+    if (!opts.configuredProps) {
+      throw new Error("configured props are required");
+    }

     const id = typeof componentId === "object"
       ? componentId.key
       : componentId;

     const body = {
       async_handle: this.asyncResponseManager.createAsyncHandle(),
       external_user_id: externalUserId,
       id,
       configured_props: opts.configuredProps,
       dynamic_props_id: opts.dynamicPropsId,
     };

     return this.makeConnectRequestAsync<ConfiguredProps<ConfigurableProps>>(
-      "/components/props", {
-      // TODO trigger
+      "/components/props", {
         method: "POST",
         body,
       },
     );
   }
📝 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
// TODO: Add docstring
public reloadComponentProps(opts: ReloadComponentPropsOpts) {
const {
userId,
externalUserId = userId,
componentId,
} = opts;
const id = typeof componentId === "object"
? componentId.key
: componentId;
// RpcActionReloadPropsInput
const body = {
async_handle: this.asyncResponseManager.createAsyncHandle(),
external_user_id: opts.userId,
id: opts.componentId,
external_user_id: externalUserId,
id,
configured_props: opts.configuredProps,
dynamic_props_id: opts.dynamicPropsId,
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return await this.makeConnectRequestAsync<Record<string, any>>("/components/props", {
return this.makeConnectRequestAsync<ConfiguredProps<ConfigurableProps>>(
"/components/props", {
// TODO trigger
method: "POST",
body,
});
method: "POST",
body,
},
);
}
/**
* Reloads the props for a component with the current configuration.
*
* @param opts - Options for reloading component props
* @returns A promise resolving to the configured props
* @throws {Error} When configured props are invalid
*/
public reloadComponentProps(opts: ReloadComponentPropsOpts) {
const {
userId,
externalUserId = userId,
componentId,
} = opts;
if (!opts.configuredProps) {
throw new Error("configured props are required");
}
const id = typeof componentId === "object"
? componentId.key
: componentId;
const body = {
async_handle: this.asyncResponseManager.createAsyncHandle(),
external_user_id: externalUserId,
id,
configured_props: opts.configuredProps,
dynamic_props_id: opts.dynamicPropsId,
};
return this.makeConnectRequestAsync<ConfiguredProps<ConfigurableProps>>(
"/components/props", {
method: "POST",
body,
},
);
}

Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (2)
packages/sdk/src/shared/index.ts (2)

1022-1022: Address TODO comment about triggers.

The TODO comment about triggers needs clarification or removal. If this is related to path handling for triggers, consider documenting the intended behavior.


Line range hint 785-1144: Well-structured API improvements.

The systematic renaming of methods and types, along with proper deprecation notices and improved documentation, provides a clear migration path for users. The changes follow consistent patterns and improve the overall clarity of the SDK's API.

Consider adding a migration guide in the documentation to help users transition from deprecated methods to their new counterparts.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d6988cf and 4c8e57c.

📒 Files selected for processing (1)
  • packages/sdk/src/shared/index.ts (8 hunks)
🔇 Additional comments (4)
packages/sdk/src/shared/index.ts (4)

16-35: LGTM! Well-structured type implementation.

The RequireAtLeastOne utility type and its usage in ExternalUserId is a good approach to handle the deprecation of userId while maintaining backward compatibility and type safety.


881-881: Remove outdated XXX comment.

The comment questioning the use of V1Component type should be removed or addressed.


1060-1082: Add validation for required parameters in runAction.

The method should validate its required parameters before making the API request.


1139-1144: Fix incorrect deprecation notice.

The deprecation notice for triggerDeploy is incorrect. It suggests using triggerDeploy instead of itself.

*/
export type GetComponentOpts = GetComponentsOpts;

export type ComponentId = {
Copy link
Contributor

Choose a reason for hiding this comment

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

Should this be ComponentKey? Will this always be a key string or potentially a hash ID?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I don't discard having a hash ID here in the future (in fact, that's what I thought we were doing already). I foresee a situation where we would generate a "key-less" component based on some code that the user provides, and we would generate a component for them addressable by a unique ID.

dylburger
dylburger previously approved these changes Dec 10, 2024
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (1)
packages/sdk/src/shared/index.ts (1)

1022-1022: Remove or clarify the TODO comment.

The TODO comment // TODO trigger lacks context and should either be removed or replaced with a clear explanation of what needs to be done.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4c8e57c and c5c9684.

📒 Files selected for processing (1)
  • packages/sdk/src/shared/index.ts (8 hunks)
🔇 Additional comments (4)
packages/sdk/src/shared/index.ts (4)

16-35: Well-designed type system changes!

The new utility type RequireAtLeastOne and its usage in ExternalUserId are well-implemented:

  • Ensures type safety by requiring at least one of the specified keys
  • Properly handles the transition from userId to externalUserId
  • Includes clear JSDoc documentation

Line range hint 91-446: Consistent and well-documented type system updates!

The type renames follow a clear pattern and maintain backward compatibility:

  • Descriptive new names (e.g., ComponentConfigureResponseConfigureComponentResponse)
  • Proper deprecation notices
  • Consistent naming convention across all types

1060-1082: Add validation for required parameters in runAction.

The runAction method should validate its required parameters before making the API request.

Add parameter validation:

  public runAction(opts: RunActionOpts) {
+    if (!opts.configuredProps) {
+      throw new Error("configured props are required");
+    }
+
    const {
      userId,
      externalUserId = userId,
      actionId,
    } = opts;

+    if (!externalUserId) {
+      throw new Error("external user ID is required");
+    }
+
    const id = typeof actionId === "object"
      ? actionId.key
      : actionId;

    const body = {
      async_handle: this.asyncResponseManager.createAsyncHandle(),
      external_user_id: externalUserId,
      id,
      configured_props: opts.configuredProps,
      dynamic_props_id: opts.dynamicPropsId,
    };

Line range hint 785-1144: Well-structured method renames with proper deprecation!

The method renames follow a consistent pattern and maintain backward compatibility:

  • Intuitive new names (e.g., actionRunrunAction)
  • Proper deprecation notices
  • Correct delegation from old to new methods

Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (1)
packages/sdk/src/shared/index.ts (1)

1026-1026: Remove TODO comment.

The comment // TODO trigger should be addressed or removed as it's unclear what needs to be done.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c5c9684 and b2b4645.

📒 Files selected for processing (1)
  • packages/sdk/src/shared/index.ts (8 hunks)
🔇 Additional comments (4)
packages/sdk/src/shared/index.ts (4)

16-35: LGTM! Well-designed type definitions.

The new utility type RequireAtLeastOne and its usage in ExternalUserId effectively handle the transition from userId to externalUserId while maintaining backward compatibility.


Line range hint 91-494: LGTM! Well-structured type system with proper deprecation notices.

The type renames and additions follow a consistent pattern, improving API clarity while maintaining backward compatibility through deprecation notices.


1063-1085: 🛠️ Refactor suggestion

Add validation for required parameters in runAction.

Based on past review comments, the runAction method should validate its required parameters before making the API request.

Apply this diff to add parameter validation:

   public runAction(opts: RunActionOpts) {
+    if (!opts.configuredProps) {
+      throw new Error("configured props are required");
+    }
+
     const {
       userId,
       externalUserId = userId,
       actionId,
     } = opts;

+    if (!externalUserId) {
+      throw new Error("external user ID is required");
+    }
+
     const id = typeof actionId === "object"
       ? actionId.key
       : actionId;

     const body = {
       async_handle: this.asyncResponseManager.createAsyncHandle(),
       external_user_id: externalUserId,
       id,
       configured_props: opts.configuredProps,
       dynamic_props_id: opts.dynamicPropsId,
     };

884-884: Remove outdated comment.

The comment // XXX Is V1Component the correct type for triggers and actions? should be addressed or removed.

Let's verify the type usage:

#!/bin/bash
# Description: Check V1Component usage in triggers and actions
ast-grep --pattern 'type V1Component = {
  $$$
}'

@jverce jverce merged commit a174427 into PipedreamHQ:master Dec 10, 2024
11 of 12 checks passed
@jverce jverce deleted the jay/dj-2744-fix-sdk-to-have-consistent-naming-in-the-methods-and-types branch December 10, 2024 19:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
docs enhancement New feature or request pd-api Pipedream API requests prioritized Prioritized issue tracked internally Issue is also tracked in our internal issue tracker
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants