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
25 changes: 25 additions & 0 deletions apps/automated/src/fetch/fetch-tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,3 +202,28 @@ export var test_fetch_post_json = function (done) {
const failOnError = function (done: (err: Error, res?: string) => void) {
return (e) => done(e);
};

function paddedJsonBytes(): Uint8Array<ArrayBuffer> {
const json = JSON.stringify({ MyVariableOne: 'ValueOne', MyVariableTwo: 'ValueTwo' });
const padded = new Uint8Array(json.length + 8).fill('x'.charCodeAt(0));
for (let i = 0; i < json.length; i++) {
padded[i + 4] = json.charCodeAt(i);
}

return padded.subarray(4, 4 + json.length);
}

export var test_fetch_post_typed_array = function (done) {
fetch('https://http-echo.nativescript.org/post', {
method: 'POST',
headers: new Headers({ 'Content-Type': 'application/json' }),
body: paddedJsonBytes(),
})
.then((r) => r.json())
.then(function (r) {
TKUnit.assertEqual(r.json?.['MyVariableOne'], 'ValueOne', 'Content not sent properly!');
TKUnit.assertEqual(r.json?.['MyVariableTwo'], 'ValueTwo', 'Content not sent properly!');
done(null);
})
.catch((e) => done(e));
};
35 changes: 35 additions & 0 deletions apps/automated/src/http/http-tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -784,3 +784,38 @@ export var test_getString_WorksProperlyInWorker = function (done) {
done(e);
};
};

function paddedJsonBytes(): Uint8Array<ArrayBuffer> {
const json = JSON.stringify({ MyVariableOne: 'ValueOne', MyVariableTwo: 'ValueTwo' });
const padded = new Uint8Array(json.length + 8).fill('x'.charCodeAt(0));
for (let i = 0; i < json.length; i++) {
padded[i + 4] = json.charCodeAt(i);
}

return padded.subarray(4, 4 + json.length);
}

export var test_request_typedArrayContentSentProperly = function (done) {
http
.request({
url: 'https://http-echo.nativescript.org/post',
method: 'POST',
headers: { 'Content-Type': 'application/json' },
content: paddedJsonBytes(),
})
.then(
function (response) {
try {
const result = response.content.toJSON();
TKUnit.assertEqual(result['json']?.['MyVariableOne'], 'ValueOne', 'Content not sent properly!');
TKUnit.assertEqual(result['json']?.['MyVariableTwo'], 'ValueTwo', 'Content not sent properly!');
done(null);
} catch (err) {
done(err);
}
},
function (e) {
done(e);
},
);
};
44 changes: 44 additions & 0 deletions apps/automated/src/xhr/xhr-tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -452,3 +452,47 @@ export var test_XMLHttpRequest_contentReceivedBlobProperly = function (done) {
// ```
// </snippet>
};

function paddedJsonBytes(): Uint8Array<ArrayBuffer> {
const json = JSON.stringify({ MyVariableOne: 'ValueOne', MyVariableTwo: 'ValueTwo' });
const padded = new Uint8Array(json.length + 8).fill('x'.charCodeAt(0));
for (let i = 0; i < json.length; i++) {
padded[i + 4] = json.charCodeAt(i);
}

return padded.subarray(4, 4 + json.length);
}

function postBinaryWithXhr(body: any, done) {
const request = new XMLHttpRequest();
request.open('POST', 'https://http-echo.nativescript.org/post');
if (!(body instanceof Blob)) {
request.setRequestHeader('Content-Type', 'application/json');
}
request.onreadystatechange = function () {
if (request.readyState > 3) {
try {
const result = JSON.parse(request.responseText);
TKUnit.assertEqual(result['json']?.['MyVariableOne'], 'ValueOne', 'Content not sent properly!');
TKUnit.assertEqual(result['json']?.['MyVariableTwo'], 'ValueTwo', 'Content not sent properly!');
done(null);
} catch (err) {
done(err);
}
}
};
request.send(body);
}

export function test_XMLHttpRequest_typedArrayContentSentProperly(done) {
postBinaryWithXhr(paddedJsonBytes(), done);
}

export function test_XMLHttpRequest_dataViewContentSentProperly(done) {
const bytes = paddedJsonBytes();
postBinaryWithXhr(new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength), done);
}

export function test_XMLHttpRequest_blobContentSentProperly(done) {
postBinaryWithXhr(new Blob([paddedJsonBytes()], { type: 'application/json' }), done);
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { getDebugRequestMethodAndBody } from './http-request-internal-common';
import { getDebugRequestMethodAndBody, getRequestBodyBytes } from './http-request-internal-common';

describe('getDebugRequestMethodAndBody', () => {
it('defaults to GET with no body', () => {
Expand All @@ -21,3 +21,30 @@ describe('getDebugRequestMethodAndBody', () => {
expect(getDebugRequestMethodAndBody({ url: 'https://example.com', method: 'POST', content: new ArrayBuffer(4) })).toEqual({ method: 'POST' });
});
});

describe('getRequestBodyBytes', () => {
it('returns the bytes of an ArrayBuffer', () => {
const buffer = new Uint8Array([1, 2, 3]).buffer;
const bytes = getRequestBodyBytes(buffer);
expect(bytes.buffer).toBe(buffer);
expect(Array.from(bytes)).toEqual([1, 2, 3]);
});

it('returns only the bytes a typed array view covers, without copying', () => {
const source = new Uint16Array([0x0101, 0x0202, 0x0303, 0x0404]);
const bytes = getRequestBodyBytes(source.subarray(1, 3));
expect(bytes.buffer).toBe(source.buffer);
expect(Array.from(bytes)).toEqual([2, 2, 3, 3]);
});

it('returns only the bytes a DataView covers', () => {
const source = new Uint8Array([9, 1, 2, 9]);
expect(Array.from(getRequestBodyBytes(new DataView(source.buffer, 1, 2)))).toEqual([1, 2]);
});

it('ignores non-binary content', () => {
expect(getRequestBodyBytes('text')).toBeUndefined();
expect(getRequestBodyBytes(undefined)).toBeUndefined();
expect(getRequestBodyBytes([1, 2])).toBeUndefined();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,14 @@ export function getDebugRequestMethodAndBody(options: HttpRequestOptions): { met

return { method };
}

export function getRequestBodyBytes(content: unknown): Uint8Array | undefined {
if (content instanceof ArrayBuffer) {
return new Uint8Array(content);
}
if (ArrayBuffer.isView(content)) {
return new Uint8Array(content.buffer, content.byteOffset, content.byteLength);
}

return undefined;
}
11 changes: 6 additions & 5 deletions packages/core/http/http-request-internal/index.android.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import * as domainDebugger from '../../debugger';
import { isObject } from '../../utils';
import { runtimeCopiesTypedArraysToByteArrays } from '../../utils/android-runtime-version';
import { HttpResponseEncoding } from '../http-interfaces';
import { addHeader, getDebugRequestMethodAndBody } from './http-request-internal-common';
import { addHeader, getDebugRequestMethodAndBody, getRequestBodyBytes } from './http-request-internal-common';
export { addHeader } from './http-request-internal-common';

export interface BaseHttpContent {
Expand Down Expand Up @@ -162,10 +162,11 @@ function buildJavaOptions(options: HttpRequestOptions) {
const nativeBytes = nativeString.getBytes('UTF-8');
const nativeBuffer = java.nio.ByteBuffer.wrap(nativeBytes);
javaOptions.content = nativeBuffer;
} else if (options.content instanceof ArrayBuffer) {
const typedArray = new Uint8Array(options.content as ArrayBuffer);
const nativeBuffer = java.nio.ByteBuffer.wrap(runtimeCopiesTypedArraysToByteArrays() ? (typedArray as any) : Array.from(typedArray));
javaOptions.content = nativeBuffer;
} else {
const bytes = getRequestBodyBytes(options.content);
if (bytes) {
javaOptions.content = java.nio.ByteBuffer.wrap(runtimeCopiesTypedArraysToByteArrays() ? (bytes as any) : Array.from(bytes));
}
}
if (typeof options.timeout === 'number') {
javaOptions.timeout = options.timeout;
Expand Down
12 changes: 8 additions & 4 deletions packages/core/http/http-request-internal/index.ios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import * as types from '../../utils/types';
import * as domainDebugger from '../../debugger';
import type { HttpRequestOptions, HttpResponse, Headers } from '../http-interfaces';
import { HttpResponseEncoding } from '../http-interfaces';
import { addHeader, getDebugRequestMethodAndBody } from './http-request-internal-common';
import { addHeader, getDebugRequestMethodAndBody, getRequestBodyBytes } from './http-request-internal-common';
export { addHeader } from './http-request-internal-common';

export interface BaseHttpContent {
Expand Down Expand Up @@ -74,9 +74,13 @@ export function requestInternal<T extends object>(options: HttpRequestOptions, c

if (types.isString(options.content) || options.content instanceof FormData) {
urlRequest.HTTPBody = NSString.stringWithString(options.content.toString()).dataUsingEncoding(4);
} else if (options.content instanceof ArrayBuffer) {
const buffer = options.content as ArrayBuffer;
urlRequest.HTTPBody = NSData.dataWithData(buffer as any);
} else {
const bytes = getRequestBodyBytes(options.content);
if (bytes) {
const { buffer, byteOffset, byteLength } = bytes;
const body = byteOffset === 0 && byteLength === buffer.byteLength ? buffer : buffer.slice(byteOffset, byteOffset + byteLength);
urlRequest.HTTPBody = NSData.dataWithData(body as any);
}
}

if (types.isNumber(options.timeout)) {
Expand Down
6 changes: 3 additions & 3 deletions packages/core/xhr/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,8 @@ export class XMLHttpRequest {
this._options.content = Blob.InternalAccessor.getBuffer(data);
} else if (data instanceof ArrayBuffer) {
this._options.content = data;
} else if (ArrayBuffer.isView(data)) {
this._options.content = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
}

this._sendFlag = true;
Expand Down Expand Up @@ -402,10 +404,8 @@ export class Blob {
} else if (typeof chunk === 'string') {
const textEncoder = new TextEncoder();
dataChunks.push(textEncoder.encode(chunk));
} else if (chunk instanceof DataView) {
dataChunks.push(new Uint8Array(chunk.buffer.slice(0)));
} else if (chunk instanceof ArrayBuffer || ArrayBuffer.isView(chunk)) {
dataChunks.push(new Uint8Array(ArrayBuffer.isView(chunk) ? chunk.buffer.slice(0) : chunk.slice(0)));
dataChunks.push(new Uint8Array(ArrayBuffer.isView(chunk) ? chunk.buffer.slice(chunk.byteOffset, chunk.byteOffset + chunk.byteLength) : chunk.slice(0)));
} else {
const textEncoder = new TextEncoder();
dataChunks.push(textEncoder.encode(String(chunk)));
Expand Down
Loading