Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 8 additions & 10 deletions lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,15 @@
export const api = async (
method: 'GET' | 'POST' | 'PATCH' | 'DELETE',
host: string | API_REGION,
resource: string,
path: string,
clientId: string,
userId: string,
hashedUserId?: string,
data?: any,

Check warning on line 11 in lib/api.ts

View workflow job for this annotation

GitHub Actions / pull_request_pipeline

Unexpected any. Specify a different type

Check warning on line 11 in lib/api.ts

View workflow job for this annotation

GitHub Actions / pull_request_pipeline

Argument 'data' should be typed with a non-any type
logger?: Logger
): Promise<any> => {

Check warning on line 13 in lib/api.ts

View workflow job for this annotation

GitHub Actions / pull_request_pipeline

Unexpected any. Specify a different type
const token = generateBasicTokenForUser(clientId, userId, hashedUserId);
const url = `https://${host}/${clientId}/users/${encodeURIComponent(
userId
)}/${resource}`;
const url = `https://${host}${path.startsWith('/') ? path : `/${path}`}`;

const headers = {
Authorization: `Basic ${token}`
Expand All @@ -34,7 +32,7 @@
try {
const res = await fetch(url, {
method,
body: JSON.stringify(data),
...(data !== undefined ? { body: JSON.stringify(data) } : {}),
headers
});

Expand Down Expand Up @@ -72,14 +70,14 @@
}
};

export const generateBasicTokenForUser = (

Check warning on line 73 in lib/api.ts

View workflow job for this annotation

GitHub Actions / pull_request_pipeline

Missing return type on function
clientId: string,
userId: string,
hashedUserId?: string
) => {
const token = hashedUserId
? btoa(clientId + ':' + userId + ':' + hashedUserId)
: btoa(clientId + ':' + userId);

return token;
// Always send the 3-part widget token (clientId:userId:hashedUserId). The
// hash slot stays empty when secureMode is off. The trailing colon is what
// lets the backend distinguish a widget token from a server
// clientId:clientSecret token.
return btoa(clientId + ':' + userId + ':' + (hashedUserId ?? ''));
};
90 changes: 26 additions & 64 deletions lib/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
DeliveryOptionsForEmail,
DeliveryOptionsForInappWeb,
PostUserRequest,
SlackChannel,
SlackUser,
User,
UserAccountMetadata,
WS_REGION
Expand Down Expand Up @@ -36,9 +34,6 @@

// Debug mode:
debug: boolean;

// SDK Dev Mode:
sdkDevMode: boolean;
};

const defaultConfig: NotificationAPIClientSDKConfig = {
Expand All @@ -53,10 +48,15 @@
).toISOString(),
onNewInAppNotifications: undefined,
keepWebSocketAliveForSeconds: 24 * 60 * 60, // 24 hours
debug: false,
sdkDevMode: false
debug: false
};

const userResourcePath = () =>
`/users/${encodeURIComponent(NotificationAPIClientSDK.config.userId)}`;

const endUserResourcePath = () =>
`/enduser/${encodeURIComponent(NotificationAPIClientSDK.config.userId)}`;

type NotificationAPIClientSDK = {
config: NotificationAPIClientSDKConfig;
logger: Logger;
Expand All @@ -70,10 +70,10 @@
generic(
method: 'GET' | 'POST' | 'PATCH' | 'DELETE',
resource: string,
data?: any

Check warning on line 73 in lib/client.ts

View workflow job for this annotation

GitHub Actions / pull_request_pipeline

Unexpected any. Specify a different type
): Promise<any>;

Check warning on line 74 in lib/client.ts

View workflow job for this annotation

GitHub Actions / pull_request_pipeline

Unexpected any. Specify a different type
getNotifications(before: string, count: number): Promise<any>;

Check warning on line 75 in lib/client.ts

View workflow job for this annotation

GitHub Actions / pull_request_pipeline

Unexpected any. Specify a different type
patchNotifications(params: any): Promise<any>;

Check warning on line 76 in lib/client.ts

View workflow job for this annotation

GitHub Actions / pull_request_pipeline

Unexpected any. Specify a different type

Check warning on line 76 in lib/client.ts

View workflow job for this annotation

GitHub Actions / pull_request_pipeline

Unexpected any. Specify a different type
getPreferences(): Promise<GetPreferencesResponse>;
postPreferences(
params: Array<{
Expand All @@ -85,7 +85,7 @@
| DeliveryOptionsForInappWeb
| BaseDeliveryOptions;
}>
): Promise<any>;

Check warning on line 88 in lib/client.ts

View workflow job for this annotation

GitHub Actions / pull_request_pipeline

Unexpected any. Specify a different type
postUser(params: PostUserRequest): Promise<any>;
getUserAccountMetadata(): Promise<{
userAccountMetadata: UserAccountMetadata;
Expand Down Expand Up @@ -129,17 +129,6 @@
user: {
get: () => Promise<User>;
};
slack: {
getOAuthUrl: (props?: { destinationUrl?: string }) => string;
getChannels: () => Promise<{
channels: SlackChannel[];
users: SlackUser[];
me: SlackUser;
hasMoreChannels?: boolean;
hasMoreUsers?: boolean;
}>;
setChannel: (channelId: string) => Promise<void>;
};
};

export const NotificationAPIClientSDK: NotificationAPIClientSDK = {
Expand Down Expand Up @@ -185,31 +174,41 @@
getNotifications: function (before, count) {
return NotificationAPIClientSDK.rest.generic(
'GET',
`notifications/INAPP_WEB?count=${count}&before=${before}`
`/enduser/inapp?count=${count}&before=${encodeURIComponent(before)}`
);
},
patchNotifications: function (params) {
return NotificationAPIClientSDK.rest.generic(
'PATCH',
'notifications/INAPP_WEB',
'/enduser/inapp',
params
);
},
getPreferences: function () {
return NotificationAPIClientSDK.rest.generic('GET', 'preferences');
return NotificationAPIClientSDK.rest.generic(
'GET',
'/enduser/preferences'
);
},
postPreferences: function (params) {
return NotificationAPIClientSDK.rest.generic(
'POST',
'preferences',
'/enduser/preferences',
params
);
},
postUser: function (params: PostUserRequest) {
return NotificationAPIClientSDK.rest.generic('POST', '', params);
return NotificationAPIClientSDK.rest.generic(
'POST',
endUserResourcePath(),
params
);
},
getUserAccountMetadata: function () {
return NotificationAPIClientSDK.rest.generic('GET', 'account_metadata');
return NotificationAPIClientSDK.rest.generic(
'GET',
'/enduser/account-metadata'
);
}
},
websocket: {
Expand Down Expand Up @@ -420,47 +419,10 @@

user: {
get: async () => {
return NotificationAPIClientSDK.rest.generic('GET', '') as Promise<User>;
}
},

slack: {
getOAuthUrl: (props?: { destinationUrl?: string }) => {
const sdkDevMode = NotificationAPIClientSDK.config.sdkDevMode;
const domain = sdkDevMode
? 'localhost:3001'
: NotificationAPIClientSDK.config.host.replace('api.', 'app.');
// if no redirectUri is provided, use the current page's URL
const destination = props?.destinationUrl || window.location.href;

const state = encodeURIComponent(
JSON.stringify({
destination,
userId: NotificationAPIClientSDK.config.userId,
clientId: NotificationAPIClientSDK.config.clientId,
hashedUserId: NotificationAPIClientSDK.config.hashedUserId
})
);

const url =
'https://slack.com/oauth/v2/authorize?' +
'client_id=1146598856352.8825220259395' +
'&scope=chat:write,channels:read,channels:join,chat:write.customize,chat:write.public,groups:read,im:read,users:read' +
`&redirect_uri=https://${domain}/slack/oauth/callback` +
`&state=${state}`;
return url;
},
getChannels: async () => {
const response = await NotificationAPIClientSDK.rest.generic(
return NotificationAPIClientSDK.rest.generic(
'GET',
'slack/channels'
);
return response;
},
setChannel: async (channelId: string) => {
return NotificationAPIClientSDK.identify({
slackChannel: channelId
});
userResourcePath()
) as Promise<User>;
}
}
};
141 changes: 0 additions & 141 deletions lib/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,68 +174,11 @@ export interface User {
email?: string;
number?: string;
pushTokens?: PushToken[];
webPushTokens?: WebPushToken[];
lastSeenTime?: string;
createdAt?: string;
updatedAt?: string;
slackChannel?: string;
slackToken?: OauthV2AccessResponse;
}

interface WebAPICallResult {
ok: boolean;
error?: string;
response_metadata?: {
warnings?: string[];
next_cursor?: string;
scopes?: string[];
acceptedScopes?: string[];
retryAfter?: number;
messages?: string[];
};
}

interface AuthedUser {
access_token?: string;
expires_in?: number;
id?: string;
refresh_token?: string;
scope?: string;
token_type?: string;
}

interface Enterprise {
id?: string;
name?: string;
}

export interface IncomingWebhook {
channel?: string;
channel_id?: string;
configuration_url?: string;
url?: string;
}

type OauthV2AccessResponse = WebAPICallResult & {
access_token?: string;
app_id?: string;
authed_user?: AuthedUser;
bot_user_id?: string;
enterprise?: Enterprise;
error?: string;
expires_in?: number;
incoming_webhook?: IncomingWebhook;
is_enterprise_install?: boolean;
needed?: string;
ok?: boolean;
provided?: string;
refresh_token?: string;
scope?: string;
team?: Enterprise;
token_type?: string;
warning?: string;
};

export type PostUserRequest = Omit<
Partial<User>,
'lastSeenTime' | 'createdAt' | 'updatedAt'
Expand All @@ -261,90 +204,6 @@ export interface Device {
model?: string;
}

export interface PushSubscription {
endpoint: string;
keys: {
p256dh: string;
auth: string;
};
}

export interface WebPushToken {
sub: PushSubscription;
}
export interface UserAccountMetadata {
logo: string;
environmentVapidPublicKey: string;
hasWebPushEnabled: boolean;
}

/* Slack Types Start */
export interface SlackChannel {
context_team_id?: string;
conversation_host_id?: string;
created?: number;
creator?: string;
id?: string;
internal_team_ids?: string[];
is_archived?: boolean;
is_channel?: boolean;
is_ext_shared?: boolean;
is_general?: boolean;
is_global_shared?: boolean;
is_group?: boolean;
is_im?: boolean;
is_member?: boolean;
is_moved?: number;
is_mpim?: boolean;
is_org_default?: boolean;
is_org_mandatory?: boolean;
is_org_shared?: boolean;
is_pending_ext_shared?: boolean;
is_private?: boolean;
is_shared?: boolean;
is_user_deleted?: boolean;
name?: string;
name_normalized?: string;
num_members?: number;
pending_connected_team_ids?: string[];
pending_shared?: string[];
previous_names?: string[];
priority?: number;
properties?: unknown;
purpose?: unknown;
shared_team_ids?: string[];
topic?: unknown;
unlinked?: number;
updated?: number;
user?: string;
}

export interface SlackUser {
color?: string;
deleted?: boolean;
enterprise_user?: unknown;
has_2fa?: boolean;
id?: string;
is_admin?: boolean;
is_app_user?: boolean;
is_bot?: boolean;
is_connector_bot?: boolean;
is_email_confirmed?: boolean;
is_invited_user?: boolean;
is_owner?: boolean;
is_primary_owner?: boolean;
is_restricted?: boolean;
is_ultra_restricted?: boolean;
is_workflow_bot?: boolean;
locale?: string;
name?: string;
profile?: unknown;
real_name?: string;
team_id?: string;
two_factor_type?: string;
tz?: string;
tz_label?: string;
tz_offset?: number;
updated?: number;
who_can_share_contact_card?: string;
}
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@notificationapi/core",
"version": "1.2.9",
"version": "2.0.0",
"type": "module",
"main": "dist/main.js",
"types": "dist/main.d.ts",
Expand Down
Loading
Loading