Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
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
68 changes: 68 additions & 0 deletions .claude/rules/karpathy-guidelines.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# CLAUDE.md

Behavioral guidelines to reduce common LLM coding mistakes. Merge with project-specific instructions as needed.

**Tradeoff:** These guidelines bias toward caution over speed. For trivial tasks, use judgment.

## 1. Think Before Coding

**Don't assume. Don't hide confusion. Surface tradeoffs.**

Before implementing:
- State your assumptions explicitly. If uncertain, ask.
- If multiple interpretations exist, present them - don't pick silently.
- If a simpler approach exists, say so. Push back when warranted.
- If something is unclear, stop. Name what's confusing. Ask.
- **Blast radius.** List what depends on this — callers, consumers, migrations, contracts, flags, cached state. What you can't enumerate, you can't reason about.
- **Guardrails inventory.** Know what already exists: validation, auth, rate limits, error handling. Don't duplicate. Don't silently bypass. If one needs to change, change it explicitly.

## 2. Simplicity First

**Minimum code that solves the problem. Nothing speculative.**

- Write the code carefully. All code will be reviewed by Codex.
- No features beyond what was asked.
- No abstractions for single-use code.
- No "flexibility" or "configurability" that wasn't requested.
- No error handling for impossible scenarios.
- If you write 200 lines and it could be 50, rewrite it.

Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, simplify.

## 3. Surgical Changes

**Touch only what you must. Clean up only your own mess.**

When editing existing code:
- Don't "improve" adjacent code, comments, or formatting.
- Don't refactor things that aren't broken.
- Match existing style, even if you'd do it differently.
- If you notice unrelated dead code, mention it - don't delete it.

When your changes create orphans:
- Remove imports/variables/functions that YOUR changes made unused.
- Don't remove pre-existing dead code unless asked.

The test: Every changed line should trace directly to the user's request.

## 4. Goal-Driven Execution

**Define success criteria. Loop until verified.**

Transform tasks into verifiable goals:
- "Add validation" → "Write tests for invalid inputs, then make them pass"
- "Fix the bug" → "Write a test that reproduces it, then make it pass"
- "Refactor X" → "Ensure tests pass before and after"

For multi-step tasks, state a brief plan:
```
1. [Step] → verify: [check]
2. [Step] → verify: [check]
3. [Step] → verify: [check]
```

Strong success criteria let you loop independently. Weak criteria ("make it work") require constant clarification.

---

**These guidelines are working if:** fewer unnecessary changes in diffs, fewer rewrites due to overcomplication, and clarifying questions come before implementation rather than after mistakes.
2 changes: 1 addition & 1 deletion .nvmrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
v18
22.22.2
176 changes: 97 additions & 79 deletions CLAUDE.md

Large diffs are not rendered by default.

114 changes: 37 additions & 77 deletions __tests__/compressor.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
const mockListeners: Record<string, Array<(event: unknown) => void>> = {};
const mockSubscriptions: Array<{ remove: jest.Mock }> = [];

// These unit tests validate the JavaScript wrapper contract. The native
// Compressor module is mocked, so real media decoding must be smoke-tested
// in an example app on a simulator or device.
Expand All @@ -27,41 +24,26 @@ const localVideoUri = 'file:///tmp/react-native-compressor/input-video.mp4';
const localImageUri = 'file:///tmp/react-native-compressor/input-image.jpg';
const localAudioUri = 'file:///tmp/react-native-compressor/input-audio.wav';

jest.mock('react-native', () => ({
NativeModules: {
Compressor: mockCompressor,
// The wrapper resolves the native module through Nitro instead of NativeModules.
jest.mock('react-native-nitro-modules', () => ({
NitroModules: {
createHybridObject: jest.fn(() => mockCompressor),
},
NativeEventEmitter: jest.fn().mockImplementation(() => ({
addListener: jest.fn((eventName: string, callback: (event: unknown) => void) => {
const subscription = { remove: jest.fn() };
mockListeners[eventName] = [...(mockListeners[eventName] ?? []), callback];
mockSubscriptions.push(subscription);
return subscription;
}),
removeAllListeners: jest.fn((eventName: string) => {
mockListeners[eventName] = [];
}),
})),
}));

jest.mock('react-native', () => ({
Platform: {
OS: 'ios',
select: jest.fn((options: Record<string, string>) => options.ios ?? options.default),
},
}));

const emitNativeEvent = (eventName: string, event: unknown) => {
(mockListeners[eventName] ?? []).forEach((callback) => callback(event));
};

describe('react-native-compressor JS wrapper API', () => {
let api: typeof import('../src');
let reactNative: typeof import('react-native');

beforeEach(() => {
jest.clearAllMocks();
Object.keys(mockListeners).forEach((eventName) => {
mockListeners[eventName] = [];
});
mockSubscriptions.length = 0;
reactNative = require('react-native');
reactNative.Platform.OS = 'ios';
api = require('../src');
Expand Down Expand Up @@ -96,16 +78,9 @@ describe('react-native-compressor JS wrapper API', () => {
expect(api.UploaderHttpMethod.PATCH).toBe('PATCH');
});

it('compresses images, strips base64 headers, forwards progress, and removes listeners', async () => {
mockCompressor.image_compress.mockImplementation(async (_value, options) => {
emitNativeEvent('downloadProgress', {
uuid: options.uuid,
data: { progress: 55 },
});
emitNativeEvent('downloadProgress', {
uuid: 'other-id',
data: { progress: 99 },
});
it('compresses images, strips base64 headers, and forwards download progress', async () => {
mockCompressor.image_compress.mockImplementation(async (_value, _options, onDownloadProgress) => {
onDownloadProgress?.(55);
return 'file://compressed-image.jpg';
});
const downloadProgress = jest.fn();
Expand All @@ -117,33 +92,20 @@ describe('react-native-compressor JS wrapper API', () => {
}),
).resolves.toBe('file://compressed-image.jpg');

expect(mockCompressor.image_compress).toHaveBeenCalledWith(
'abc123',
expect.objectContaining({
quality: 0.7,
uuid: expect.any(String),
}),
);
expect(mockCompressor.image_compress).toHaveBeenCalledWith('abc123', expect.objectContaining({ quality: 0.7 }), expect.any(Function));
expect(downloadProgress).toHaveBeenCalledWith(55);
expect(downloadProgress).toHaveBeenCalledTimes(1);
expect(mockSubscriptions.at(-1)?.remove).toHaveBeenCalledTimes(1);
});

it('rejects empty image compression input before calling native code', async () => {
await expect(api.Image.compress('')).rejects.toThrow('Compression value is empty');
expect(mockCompressor.image_compress).not.toHaveBeenCalled();
});

it('compresses videos with defaults, cancellation id, progress callbacks, and listener cleanup', async () => {
mockCompressor.compress.mockImplementation(async (_fileUrl, options) => {
emitNativeEvent('videoCompressProgress', {
uuid: options.uuid,
data: { progress: 22 },
});
emitNativeEvent('downloadProgress', {
uuid: options.uuid,
data: { progress: 33 },
});
it('compresses videos with defaults, cancellation id, and progress callbacks', async () => {
mockCompressor.compress.mockImplementation(async (_fileUrl, _options, onProgress, onDownloadProgress) => {
onProgress?.(22);
onDownloadProgress?.(33);
return 'file://compressed-video.mp4';
});
const onProgress = jest.fn();
Expand Down Expand Up @@ -172,13 +134,12 @@ describe('react-native-compressor JS wrapper API', () => {
maxSize: 640,
stripAudio: true,
}),
expect.any(Function),
expect.any(Function),
);
expect(getCancellationId).toHaveBeenCalledWith(expect.any(String));
expect(onProgress).toHaveBeenCalledWith(22);
expect(downloadProgress).toHaveBeenCalledWith(33);
mockSubscriptions.slice(-2).forEach((subscription) => {
expect(subscription.remove).toHaveBeenCalledTimes(1);
});
});

it('forwards manual video compression options and minimum file size', async () => {
Expand All @@ -199,12 +160,14 @@ describe('react-native-compressor JS wrapper API', () => {
minimumFileSizeForCompress: 10,
progressDivider: 5,
}),
undefined,
undefined,
);
});

it('proxies video cancellation and background task lifecycle', async () => {
mockCompressor.activateBackgroundTask.mockImplementation(async () => {
emitNativeEvent('backgroundTaskExpired', { expired: true });
mockCompressor.activateBackgroundTask.mockImplementation(async (_options, onExpired) => {
onExpired?.();
return 'activated';
});
mockCompressor.deactivateBackgroundTask.mockResolvedValue('deactivated');
Expand All @@ -215,9 +178,9 @@ describe('react-native-compressor JS wrapper API', () => {
await expect(api.Video.deactivateBackgroundTask()).resolves.toBe('deactivated');

expect(mockCompressor.cancelCompression).toHaveBeenCalledWith('video-id');
expect(mockCompressor.activateBackgroundTask).toHaveBeenCalledWith({});
expect(mockCompressor.activateBackgroundTask).toHaveBeenCalledWith({}, expect.any(Function));
expect(mockCompressor.deactivateBackgroundTask).toHaveBeenCalledWith({});
expect(onExpired).toHaveBeenCalledWith({ expired: true });
expect(onExpired).toHaveBeenCalledWith(undefined);
});

it('compresses audio with defaults and custom options', async () => {
Expand Down Expand Up @@ -291,34 +254,31 @@ describe('react-native-compressor JS wrapper API', () => {
});
});

it('downloads files, strips Android file prefixes, reports progress, and removes listeners', async () => {
it('downloads files, strips Android file prefixes, and reports progress', async () => {
reactNative.Platform.OS = 'android';
mockCompressor.download.mockImplementation(async (_fileUrl, options) => {
emitNativeEvent('downloadProgress', {
uuid: options.uuid,
data: { progress: 88 },
});
mockCompressor.download.mockImplementation(async (_fileUrl, _options, onProgress) => {
onProgress?.(88);
return '/downloads/file.mp4';
});
const downloadProgress = jest.fn();

await expect(api.download('file:///storage/input.mp4', downloadProgress, 10)).resolves.toBe('/downloads/file.mp4');

expect(mockCompressor.download).toHaveBeenCalledWith('/storage/input.mp4', {
uuid: expect.any(String),
progressDivider: 10,
});
expect(mockCompressor.download).toHaveBeenCalledWith(
'/storage/input.mp4',
{
uuid: expect.any(String),
progressDivider: 10,
},
expect.any(Function),
);
expect(downloadProgress).toHaveBeenCalledWith(88);
expect(mockSubscriptions.at(-1)?.remove).toHaveBeenCalledTimes(1);
});

it('uploads files with options, progress, cancellation id, abort handling, and Android path normalization', async () => {
reactNative.Platform.OS = 'android';
mockCompressor.upload.mockImplementation(async (_fileUrl, options) => {
emitNativeEvent('uploadProgress', {
uuid: options.uuid,
data: { written: 4, total: 10 },
});
mockCompressor.upload.mockImplementation(async (_fileUrl, _options, onProgress) => {
onProgress?.(4, 10);
return { status: 200 };
});
const onProgress = jest.fn();
Expand Down Expand Up @@ -356,11 +316,11 @@ describe('react-native-compressor JS wrapper API', () => {
headers: { Authorization: 'token' },
parameters: { album: 'demo' },
}),
expect.any(Function),
);
expect(getCancellationId).toHaveBeenCalledWith(uploadOptions.uuid);
expect(onProgress).toHaveBeenCalledWith(4, 10);
expect(mockCompressor.cancelUpload).toHaveBeenCalledWith(uploadOptions.uuid, false);
expect(mockSubscriptions.at(-1)?.remove).toHaveBeenCalledTimes(1);
});

it('cancels one upload or all uploads through the native module', () => {
Expand Down
27 changes: 27 additions & 0 deletions android/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
project(NitroCompressor)
cmake_minimum_required(VERSION 3.9.0)

set(PACKAGE_NAME NitroCompressor)
set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_CXX_STANDARD 20)

# Define the C++ library and add all of our own sources.
add_library(${PACKAGE_NAME} SHARED
src/main/cpp/cpp-adapter.cpp
)

# Add all files generated by Nitrogen (sources, headers, prefab links).
include(${CMAKE_SOURCE_DIR}/../nitrogen/generated/android/NitroCompressor+autolinking.cmake)

# Local includes
include_directories(
"src/main/cpp"
)

find_library(LOG_LIB log)

target_link_libraries(
${PACKAGE_NAME}
${LOG_LIB}
android
)
Loading
Loading