Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
23 changes: 12 additions & 11 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,29 +12,30 @@
"test": "jest"
},
"dependencies": {
"url-join": "4.0.1",
"crypto-browserify": "^3.12.1",
"form-data": "^4.0.0",
"formdata-node": "^6.0.3",
"js-base64": "3.7.2",
"node-fetch": "2.7.0",
"qs": "6.11.2",
"readable-stream": "^4.5.2",
"js-base64": "3.7.2",
"crypto-browserify": "^3.12.1"
"url-join": "4.0.1"
},
"devDependencies": {
"@types/url-join": "4.0.1",
"@types/qs": "6.9.8",
"@types/jest": "29.5.5",
"@types/node": "17.0.33",
"@types/node-fetch": "2.6.9",
"@types/qs": "6.9.8",
"@types/readable-stream": "^4.0.15",
"webpack": "^5.94.0",
"ts-loader": "^9.3.1",
"@types/url-join": "4.0.1",
"jest": "29.7.0",
"@types/jest": "29.5.5",
"ts-jest": "29.1.1",
"jest-environment-jsdom": "29.7.0",
"@types/node": "17.0.33",
"jest-fetch-mock": "^3.0.3",
"prettier": "2.7.1",
"typescript": "4.6.4"
"ts-jest": "29.1.1",
"ts-loader": "^9.3.1",
"typescript": "4.6.4",
"webpack": "^5.94.0"
},
"browser": {
"fs": false,
Expand Down
4 changes: 4 additions & 0 deletions src/api/resources/assets/client/Client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ import * as Webflow from "../../../index";
import urlJoin from "url-join";
import * as serializers from "../../../../serialization/index";
import * as errors from "../../../../errors/index";
import crypto from "crypto";
import fetch from "node-fetch";
import FormData from 'form-data';
import { Readable } from 'stream';

export declare namespace Assets {
interface Options {
Expand Down
28 changes: 28 additions & 0 deletions src/wrapper/AssetsClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Assets } from "../api/resources/assets/client/Client";
import { Client as Utilities } from "./AssetsUtilitiesClient";

// Extends the namespace declared in the Fern generated client
declare module "../api/resources/assets/client/Client" {
export namespace Assets {
// interface RequestSignatureDetails {
// /** The headers of the incoming webhook request as a record-like object */
// headers: Record<string, string>;
// /** The body of the incoming webhook request as a string */
// body: string;
// /** The secret key generated when creating the webhook or the OAuth client secret */
// secret: string;
// }
}
}

export class Client extends Assets {
constructor(protected readonly _options: Assets.Options) {
super(_options);
}

protected _utilities: Utilities | undefined;

public get utilities(): Utilities {
return (this._utilities ??= new Utilities(this._options));
}
}
156 changes: 156 additions & 0 deletions src/wrapper/AssetsUtilitiesClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import * as Webflow from "../api";
import { Assets } from "../api/resources/assets/client/Client";
import * as core from "../core";
import * as environments from "../environments";
import crypto from "crypto";
import fetch from "node-fetch";
import FormDataConstructor from 'form-data';

export declare namespace AssetsUtilities {
interface Options {
environment?: core.Supplier<environments.WebflowEnvironment | string>;
accessToken: core.Supplier<core.BearerToken>;
}

interface RequestOptions {
/** The maximum time to wait for a response in seconds. */
timeoutInSeconds?: number;
/** The number of times to retry the request. Defaults to 2. */
maxRetries?: number;
/** A hook to abort the request. */
abortSignal?: AbortSignal;
/** Additional headers to include in the request. */
headers?: Record<string, string>;
}
}

interface TestAssetUploadRequest {
/**
* File to upload via URL where the asset is hosted, or by ArrayBuffer
*/
file: ArrayBuffer | string;

/**
* Name of the file to upload, including the extension
*/
fileName: string;

/**
* Name of the parent folder to upload to
*/
parentFolder?: string;
}

// Utilities class for Assets to add custom helper methods to assist in managing Webflow Assets
export class Client extends Assets {
constructor(protected readonly _options: AssetsUtilities.Options) {
super(_options);
}

private async _getBufferFromUrl(url: string): Promise<ArrayBuffer> {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch asset from URL: ${url}. Status: ${response.status} ${response.statusText}`);
}
return await response.arrayBuffer();
} catch (error) {
throw new Error(`Error occurred while fetching asset from URL: ${url}. ${(error as Error).message}`);
}
}

/**
* Create the Asset metadata in Webflow, and immediately upload it to the S3 bucket on behalf of the user to simplify the 2-step process
*
* @param siteId
* @param request
* @param requestOptions
* @returns
*/
public async createAndUpload(
siteId: string,
request: TestAssetUploadRequest,
requestOptions?: Assets.RequestOptions
): Promise<Webflow.AssetUpload> {
/** 1. Generate the hash */
const {file, fileName, parentFolder} = request;
let tempBuffer: Buffer | null = null;
if (typeof file === 'string') {
const arrBuffer = await this._getBufferFromUrl(file);
tempBuffer = Buffer.from(arrBuffer);
} else if (file instanceof ArrayBuffer) {
tempBuffer = Buffer.from(file);
}
if (tempBuffer === null) {
throw new Error('Invalid file');
}
const hash = crypto.createHash("md5").update(Buffer.from(tempBuffer)).digest("hex");

const wfUploadRequest = {
fileName,
fileHash: hash,
} as Webflow.AssetsCreateRequest;
if (parentFolder) {
wfUploadRequest["parentFolder"] = parentFolder;
}


/** 2. Create the Asset Metadata in Webflow */
let wfUploadedAsset: Webflow.AssetUpload;
try {
wfUploadedAsset = await this.create(siteId, wfUploadRequest, requestOptions);
} catch (error) {
throw new Error(`Failed to create Asset metadata in Webflow: ${(error as Error).message}`);
}

/** 3. Create FormData with S3 bucket signature */
const wfUploadDetails = wfUploadedAsset.uploadDetails!;
const uploadUrl = wfUploadedAsset.uploadUrl as string;
// Temp workaround since headers from response are being camelCased and we need them to be exact when sending to S3
const headerMappings = {
'xAmzAlgorithm': 'X-Amz-Algorithm',
'xAmzDate': 'X-Amz-Date',
'xAmzCredential': 'X-Amz-Credential',
'xAmzSignature': 'X-Amz-Signature',
'successActionStatus': 'success_action_status',
'contentType': 'Content-Type',
'cacheControl': 'Cache-Control',
};
const transformedUploadHeaders = Object.keys(wfUploadDetails).reduce((acc: Record<string, any>, key) => {
const mappedKey = headerMappings[key as keyof typeof headerMappings] || key;
acc[mappedKey] = wfUploadDetails[key as keyof typeof headerMappings ];
return acc;
}, {});
const formDataToUpload = new FormDataConstructor();
Object.keys(transformedUploadHeaders).forEach((key) => {
formDataToUpload.append(key, transformedUploadHeaders[key]);
});

if (!Buffer.isBuffer(tempBuffer)) {
throw new Error("Invalid Buffer: Expected a Buffer instance from file");
}

formDataToUpload.append("file", tempBuffer, {
filename: fileName,
contentType: wfUploadedAsset.contentType || "application/octet-stream",
});

/** 4. Upload to S3 */
try {
const response = await fetch(uploadUrl, {
method: 'POST',
body: formDataToUpload,
headers: { ...formDataToUpload.getHeaders() },
});

if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to upload to S3. Status: ${response.status}, Response: ${errorText}`);
}
} catch (error) {
throw new Error(`Error occurred during S3 upload: ${(error as Error).message}`);
}

return wfUploadedAsset;
}
}
7 changes: 7 additions & 0 deletions src/wrapper/WebflowClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import * as core from "../core";
import * as errors from "../errors";
import { SDK_VERSION } from "../version";
import { Client as Webhooks } from "./WebhooksClient";
import { Client as Assets } from "./AssetsClient";

export class WebflowClient extends FernClient {
constructor(protected readonly _options: FernClient.Options) {
Expand All @@ -13,10 +14,16 @@ export class WebflowClient extends FernClient {

protected _webhooks: Webhooks | undefined;

protected _assets: Assets | undefined;

public get webhooks(): Webhooks {
return (this._webhooks ??= new Webhooks(this._options));
}

public get assets(): Assets {
return (this._assets ??= new Assets(this._options));
}


/**
* @param clientId The OAuth client ID
Expand Down
Loading