diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml index 02cce13..00551ff 100644 --- a/.github/workflows/publish.yaml +++ b/.github/workflows/publish.yaml @@ -17,6 +17,8 @@ jobs: registry-url: https://registry.npmjs.org cache: npm - run: npm ci + - name: Set version in src/version.js + run: echo "export const version = '${GITHUB_REF_NAME#v}';" > src/version.js - run: | npm version --no-git-tag-version ${GITHUB_REF_NAME#v} npm publish diff --git a/src/utils.ts b/src/utils.ts index f67bf41..d082440 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,3 +1,4 @@ +import { version } from './version' import type { Fetch, ErrorResponse } from './interfaces.js' class ResponseError extends Error { @@ -40,8 +41,40 @@ const checkOk = async (response: Response): Promise => { } } +function getPlatform() { + if (typeof window !== 'undefined' && window.navigator) { + return `${window.navigator.platform.toLowerCase()} Browser/${navigator.userAgent};` + } else if (typeof process !== 'undefined') { + return `${process.arch} ${process.platform} Node.js/${process.version}` + } + return '' // unknown +} + +const fetchWithHeaders = async ( + fetch: Fetch, + url: string, + options: RequestInit = {}, +): Promise => { + const defaultHeaders = { + 'Content-Type': 'application/json', + Accept: 'application/json', + 'User-Agent': `ollama-js/${version} (${getPlatform()})`, + } + + if (!options.headers) { + options.headers = {} + } + + options.headers = { + ...defaultHeaders, + ...options.headers, + } + + return fetch(url, options) +} + export const get = async (fetch: Fetch, host: string): Promise => { - const response = await fetch(host) + const response = await fetchWithHeaders(fetch, host) await checkOk(response) @@ -49,7 +82,7 @@ export const get = async (fetch: Fetch, host: string): Promise => { } export const head = async (fetch: Fetch, host: string): Promise => { - const response = await fetch(host, { + const response = await fetchWithHeaders(fetch, host, { method: 'HEAD', }) @@ -70,7 +103,7 @@ export const post = async ( const formattedData = isRecord(data) ? JSON.stringify(data) : data - const response = await fetch(host, { + const response = await fetchWithHeaders(fetch, host, { method: 'POST', body: formattedData, signal: options?.signal, @@ -86,7 +119,7 @@ export const del = async ( host: string, data?: Record, ): Promise => { - const response = await fetch(host, { + const response = await fetchWithHeaders(fetch, host, { method: 'DELETE', body: JSON.stringify(data), }) diff --git a/src/version.ts b/src/version.ts new file mode 100644 index 0000000..d5a5614 --- /dev/null +++ b/src/version.ts @@ -0,0 +1 @@ +export const version = '0.0.0'