Skip to content
Open
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
80 changes: 80 additions & 0 deletions packages/cli/src/util/AssetUploader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,26 @@ import {
import { JSDOM } from 'jsdom';
import { afterEach, describe, expect, it, vi } from 'vitest';

const appClient = vi.hoisted(() => ({
CheckIfMediaExists: vi.fn(),
UploadNewMedia: vi.fn(),
}));

vi.mock('./clientGenerators.js', () => ({
createAppClient: () => appClient,
}));

vi.mock('@oclif/core', () => ({
ux: {
action: {
start: vi.fn(),
stop: vi.fn(),
},
error: vi.fn(),
info: vi.fn(),
},
}));

import { AssetUploader, queryAssets, transformHTML } from './AssetUploader.js';
import type { DevvitCommand } from './commands/DevvitCommand.js';

Expand Down Expand Up @@ -165,6 +185,66 @@ describe('assertAssetCanBeAnIcon', () => {
}
});

describe('syncAssets()', () => {
let tmpDir: string;

beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'devvit-assets-test-'));
fs.writeFileSync(path.join(tmpDir, 'header-logo.svg'), '<svg></svg>');
fs.writeFileSync(path.join(tmpDir, 'footer-logo.svg'), '<svg></svg>');

appClient.CheckIfMediaExists.mockImplementation(
async ({ signatures }: { signatures: { filePath: string }[] }) => ({
statuses: signatures.map((signature, index) => ({
...signature,
isNew: true,
uploadUrl: `https://uploads.example.com/assets/${index}?signature=test`,
uploadHeaders: {},
})),
})
);
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok: true,
})
);
});

afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
vi.clearAllMocks();
vi.unstubAllGlobals();
});

it('maps duplicate WebView asset paths to the same uploaded URL', async () => {
const cmd = {
project: {
root: tmpDir,
mediaDir: undefined,
clientDir: '.',
appConfig: undefined,
},
error: vi.fn((message: string) => {
throw new Error(message);
}),
log: vi.fn(),
warn: vi.fn(),
};
const assetUploader = new AssetUploader(cmd as unknown as DevvitCommand, 'some-slug', {
verbose: false,
});

const result = await assetUploader.syncAssets();

expect(fetch).toHaveBeenCalledTimes(1);
expect(result.webViewAssetMap).toEqual({
'footer-logo.svg': 'https://uploads.example.com/assets/0',
'header-logo.svg': 'https://uploads.example.com/assets/0',
});
});
});

describe('queryAssets()', () => {
let tmpDir: string;

Expand Down
24 changes: 22 additions & 2 deletions packages/cli/src/util/AssetUploader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ type MediaSignatureWithContentsAndUploadInfo = MediaSignatureWithContents & {
uploadHeaders: { [key: string]: string };
};

function getAssetSignature(asset: Pick<MediaSignature, 'hash' | 'size'>): string {
return `${asset.hash}:${asset.size}`;
}

type SyncAssetsResult = {
assetMap: AssetMap | undefined;
webViewAssetMap: AssetMap | undefined;
Expand Down Expand Up @@ -457,6 +461,7 @@ export class AssetUploader {
ux.action.start(
`Uploading new WebView assets, ${assetsRemaining} remaining (${prettyPrintSize(sizeRemaining)})`
);
const uploadedUrlsBySignature = new Map<string, string>();

await mapAsyncWithMaxConcurrency(
newAssets,
Expand Down Expand Up @@ -487,12 +492,24 @@ export class AssetUploader {
}

const uploadUrl = new URL(newAsset.uploadUrl);
assetMap[newAsset.filePath] = uploadUrl.origin + uploadUrl.pathname;
const publicUploadUrl = uploadUrl.origin + uploadUrl.pathname;
assetMap[newAsset.filePath] = publicUploadUrl;
uploadedUrlsBySignature.set(getAssetSignature(newAsset), publicUploadUrl);
updateUploadMsg(newAsset.size);
},
PARALLEL_UPLOADS
);

for (const duplicateAsset of duplicateAssets) {
const uploadedUrl = uploadedUrlsBySignature.get(getAssetSignature(duplicateAsset));
if (!uploadedUrl) {
throw new Error(
`Could not find the uploaded WebView asset matching duplicate ${duplicateAsset.filePath}.`
);
}
assetMap[duplicateAsset.filePath] = uploadedUrl;
}

ux.action.stop(`${newAssets.length} new WebView assets uploaded.`);
ux.action.start(`Finishing upload`);

Expand Down Expand Up @@ -536,6 +553,7 @@ export class AssetUploader {

const newAssets: (MediaSignatureWithContents | MediaSignatureWithContentsAndUploadInfo)[] = [];
const duplicateAssets: MediaSignatureWithContents[] = [];
const newAssetSignatures = new Set<string>();
const existingAssets: AssetMap = {};
statuses.forEach((status) => {
const asset = assetsByFilePath[status.filePath];
Expand All @@ -547,9 +565,11 @@ export class AssetUploader {
if (status.isNew) {
// The user may have the same asset in multiple places, but we need to
// only upload it once
if (newAssets.find((a) => a.hash === asset.hash && a.size === asset.size)) {
const signature = getAssetSignature(asset);
if (newAssetSignatures.has(signature)) {
duplicateAssets.push(asset);
} else {
newAssetSignatures.add(signature);
if (!areWebviewAssets) {
newAssets.push(asset);
return;
Expand Down