Skip to content

Commit

Permalink
feat(javascript): add worker build (generated)
Browse files Browse the repository at this point in the history
algolia/api-clients-automation#4249

Co-authored-by: algolia-bot <[email protected]>
Co-authored-by: Clément Vannicatte <[email protected]>
Co-authored-by: Torbjørn Holtmon <[email protected]>
  • Loading branch information
3 people committed Dec 16, 2024
1 parent 9a18e62 commit 4f59d81
Show file tree
Hide file tree
Showing 47 changed files with 929 additions and 41 deletions.
2 changes: 2 additions & 0 deletions base.tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ type PKG = {

const requesters = {
fetch: '@algolia/requester-fetch',
worker: '@algolia/requester-fetch',
http: '@algolia/requester-node-http',
xhr: '@algolia/requester-browser-xhr',
};
Expand Down Expand Up @@ -36,6 +37,7 @@ export function getDependencies(pkg: PKG, requester: Requester): string[] {
case 'xhr':
return deps.filter((dep) => dep !== requesters.fetch && dep !== requesters.http);
case 'fetch':
case 'worker':
return deps.filter((dep) => dep !== requesters.xhr && dep !== requesters.http);
default:
throw new Error('unknown requester', requester);
Expand Down
55 changes: 55 additions & 0 deletions packages/algoliasearch/__tests__/algoliasearch.worker.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { expect, test, vi } from 'vitest';

import { LogLevelEnum } from '../../client-common/src/types';
import { createConsoleLogger } from '../../logger-console/src/logger';
import { algoliasearch as node_algoliasearch } from '../builds/node';
import { algoliasearch, apiClientVersion } from '../builds/worker';

test('sets the ua', () => {
const client = algoliasearch('APP_ID', 'API_KEY');
expect(client.transporter.algoliaAgent).toEqual({
add: expect.any(Function),
value: expect.stringContaining(
`Algolia for JavaScript (${apiClientVersion}); Search (${apiClientVersion}); Worker`,
),
});
});

test('forwards node search helpers', () => {
const client = algoliasearch('APP_ID', 'API_KEY');
expect(client.generateSecuredApiKey).not.toBeUndefined();
expect(client.getSecuredApiKeyRemainingValidity).not.toBeUndefined();
expect(async () => {
const resp = await client.generateSecuredApiKey({ parentApiKey: 'foo', restrictions: { validUntil: 200 } });
client.getSecuredApiKeyRemainingValidity({ securedApiKey: resp });
}).not.toThrow();
});

test('web crypto implementation gives the same result as node crypto', async () => {
const client = algoliasearch('APP_ID', 'API_KEY');
const nodeClient = node_algoliasearch('APP_ID', 'API_KEY');
const resp = await client.generateSecuredApiKey({ parentApiKey: 'foo-bar', restrictions: { validUntil: 200 } });
const nodeResp = await nodeClient.generateSecuredApiKey({
parentApiKey: 'foo-bar',
restrictions: { validUntil: 200 },
});

expect(resp).toEqual(nodeResp);
});

test('with logger', () => {
vi.spyOn(console, 'debug');
vi.spyOn(console, 'info');
vi.spyOn(console, 'error');

const client = algoliasearch('APP_ID', 'API_KEY', {
logger: createConsoleLogger(LogLevelEnum.Debug),
});

expect(async () => {
await client.setSettings({ indexName: 'foo', indexSettings: {} });
expect(console.debug).toHaveBeenCalledTimes(1);
expect(console.info).toHaveBeenCalledTimes(1);
expect(console.error).toHaveBeenCalledTimes(1);
}).not.toThrow();
});
130 changes: 130 additions & 0 deletions packages/algoliasearch/builds/worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
// Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT.

import type { ClientOptions } from '@algolia/client-common';

import type { AbtestingClient } from '@algolia/client-abtesting';
import { abtestingClient } from '@algolia/client-abtesting';
import type { AnalyticsClient } from '@algolia/client-analytics';
import { analyticsClient } from '@algolia/client-analytics';
import type { InsightsClient } from '@algolia/client-insights';
import { insightsClient } from '@algolia/client-insights';
import type { PersonalizationClient } from '@algolia/client-personalization';
import { personalizationClient } from '@algolia/client-personalization';
import type { QuerySuggestionsClient } from '@algolia/client-query-suggestions';
import { querySuggestionsClient } from '@algolia/client-query-suggestions';
import type { SearchClient } from '@algolia/client-search';
import { searchClient } from '@algolia/client-search';
import type { IngestionClient } from '@algolia/ingestion';
import { ingestionClient } from '@algolia/ingestion';
import type { MonitoringClient } from '@algolia/monitoring';
import { monitoringClient } from '@algolia/monitoring';
import type { RecommendClient } from '@algolia/recommend';
import { recommendClient } from '@algolia/recommend';

import type {
AbtestingRegionOptions,
AnalyticsRegionOptions,
IngestionRegionOptions,
InitClientOptions,
InsightsRegionOptions,
PersonalizationRegionOptions,
QuerySuggestionsRegionOptions,
} from './models';

export * from './models';

export type Algoliasearch = SearchClient & {
initAbtesting: (initOptions: InitClientOptions & AbtestingRegionOptions) => AbtestingClient;
initAnalytics: (initOptions: InitClientOptions & AnalyticsRegionOptions) => AnalyticsClient;
initIngestion: (initOptions: InitClientOptions & IngestionRegionOptions) => IngestionClient;
initInsights: (initOptions: InitClientOptions & InsightsRegionOptions) => InsightsClient;
initMonitoring: (initOptions?: InitClientOptions) => MonitoringClient;
initPersonalization: (initOptions: InitClientOptions & PersonalizationRegionOptions) => PersonalizationClient;
initQuerySuggestions: (initOptions: InitClientOptions & QuerySuggestionsRegionOptions) => QuerySuggestionsClient;
initRecommend: (initOptions?: InitClientOptions) => RecommendClient;
};

export function algoliasearch(appId: string, apiKey: string, options?: ClientOptions): Algoliasearch {
if (!appId || typeof appId !== 'string') {
throw new Error('`appId` is missing.');
}

if (!apiKey || typeof apiKey !== 'string') {
throw new Error('`apiKey` is missing.');
}

const client = searchClient(appId, apiKey, options);

return {
...client,

/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
get _ua(): string {
return client.transporter.algoliaAgent.value;
},

initAbtesting: (initOptions: InitClientOptions & AbtestingRegionOptions): AbtestingClient => {
return abtestingClient(
initOptions.appId || appId,
initOptions.apiKey || apiKey,
initOptions.region,
initOptions.options,
);
},

initAnalytics: (initOptions: InitClientOptions & AnalyticsRegionOptions): AnalyticsClient => {
return analyticsClient(
initOptions.appId || appId,
initOptions.apiKey || apiKey,
initOptions.region,
initOptions.options,
);
},

initIngestion: (initOptions: InitClientOptions & IngestionRegionOptions): IngestionClient => {
return ingestionClient(
initOptions.appId || appId,
initOptions.apiKey || apiKey,
initOptions.region,
initOptions.options,
);
},

initInsights: (initOptions: InitClientOptions & InsightsRegionOptions): InsightsClient => {
return insightsClient(
initOptions.appId || appId,
initOptions.apiKey || apiKey,
initOptions.region,
initOptions.options,
);
},

initMonitoring: (initOptions: InitClientOptions = {}): MonitoringClient => {
return monitoringClient(initOptions.appId || appId, initOptions.apiKey || apiKey, initOptions.options);
},

initPersonalization: (initOptions: InitClientOptions & PersonalizationRegionOptions): PersonalizationClient => {
return personalizationClient(
initOptions.appId || appId,
initOptions.apiKey || apiKey,
initOptions.region,
initOptions.options,
);
},

initQuerySuggestions: (initOptions: InitClientOptions & QuerySuggestionsRegionOptions): QuerySuggestionsClient => {
return querySuggestionsClient(
initOptions.appId || appId,
initOptions.apiKey || apiKey,
initOptions.region,
initOptions.options,
);
},

initRecommend: (initOptions: InitClientOptions = {}): RecommendClient => {
return recommendClient(initOptions.appId || appId, initOptions.apiKey || apiKey, initOptions.options);
},
};
}
4 changes: 2 additions & 2 deletions packages/algoliasearch/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@
"require": "./dist/node.cjs"
},
"worker": {
"types": "./dist/fetch.d.ts",
"default": "./dist/fetch.js"
"types": "./dist/worker.d.ts",
"default": "./dist/worker.js"
},
"default": {
"types": "./dist/browser.d.ts",
Expand Down
9 changes: 9 additions & 0 deletions packages/algoliasearch/tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,15 @@ const nodeConfigs: Options[] = [
outDir: 'dist',
external: getDependencies(pkg, 'fetch'),
},
{
...nodeOptions,
format: 'esm',
name: 'worker algoliasearch esm',
dts: { entry: { worker: 'builds/worker.ts' } },
entry: ['builds/worker.ts'],
outDir: 'dist',
external: getDependencies(pkg, 'worker'),
},
];

const browserOptions: Options = {
Expand Down
14 changes: 13 additions & 1 deletion packages/algoliasearch/vitest.workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,19 @@ export default defineWorkspace([
},
test: {
include: ['__tests__/algoliasearch.fetch.test.ts'],
name: 'miniflare',
name: 'miniflare fetch',
environment: 'miniflare',
},
},
{
resolve: {
alias: {
'@algolia/client-search': '../../client-search/builds/worker',
},
},
test: {
include: ['__tests__/algoliasearch.worker.test.ts'],
name: 'miniflare worker',
environment: 'miniflare',
},
},
Expand Down
2 changes: 1 addition & 1 deletion packages/client-abtesting/builds/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ export function abtestingClient(
write: 30000,
},
logger: createNullLogger(),
algoliaAgents: [{ segment: 'Fetch' }],
requester: createFetchRequester(),
algoliaAgents: [{ segment: 'Fetch' }],
responsesCache: createNullCache(),
requestsCache: createNullCache(),
hostsCache: createMemoryCache(),
Expand Down
58 changes: 58 additions & 0 deletions packages/client-abtesting/builds/worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT.

export type AbtestingClient = ReturnType<typeof createAbtestingClient>;

import { createMemoryCache, createNullCache, createNullLogger } from '@algolia/client-common';
import { createFetchRequester } from '@algolia/requester-fetch';

import type { ClientOptions } from '@algolia/client-common';

import { createAbtestingClient } from '../src/abtestingClient';

import type { Region } from '../src/abtestingClient';
import { REGIONS } from '../src/abtestingClient';

export type { Region, RegionOptions } from '../src/abtestingClient';

export { apiClientVersion } from '../src/abtestingClient';

export * from '../model';

export function abtestingClient(
appId: string,
apiKey: string,
region?: Region,
options?: ClientOptions,
): AbtestingClient {
if (!appId || typeof appId !== 'string') {
throw new Error('`appId` is missing.');
}

if (!apiKey || typeof apiKey !== 'string') {
throw new Error('`apiKey` is missing.');
}

if (region && (typeof region !== 'string' || !REGIONS.includes(region))) {
throw new Error(`\`region\` must be one of the following: ${REGIONS.join(', ')}`);
}

return {
...createAbtestingClient({
appId,
apiKey,
region,
timeouts: {
connect: 2000,
read: 5000,
write: 30000,
},
logger: createNullLogger(),
requester: createFetchRequester(),
algoliaAgents: [{ segment: 'Worker' }],
responsesCache: createNullCache(),
requestsCache: createNullCache(),
hostsCache: createMemoryCache(),
...options,
}),
};
}
4 changes: 2 additions & 2 deletions packages/client-abtesting/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@
"require": "./dist/builds/node.cjs"
},
"worker": {
"types": "./dist/fetch.d.ts",
"default": "./dist/builds/fetch.js"
"types": "./dist/worker.d.ts",
"default": "./dist/builds/worker.js"
},
"default": {
"types": "./dist/browser.d.ts",
Expand Down
8 changes: 8 additions & 0 deletions packages/client-abtesting/tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ const nodeConfigs: Options[] = [
external: getDependencies(pkg, 'fetch'),
entry: ['builds/fetch.ts', 'src/*.ts'],
},
{
...nodeOptions,
format: 'esm',
name: `worker ${pkg.name} esm`,
dts: { entry: { worker: 'builds/worker.ts' } },
external: getDependencies(pkg, 'worker'),
entry: ['builds/worker.ts', 'src/*.ts'],
},
];

const browserOptions: Options = {
Expand Down
2 changes: 1 addition & 1 deletion packages/client-analytics/builds/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ export function analyticsClient(
write: 30000,
},
logger: createNullLogger(),
algoliaAgents: [{ segment: 'Fetch' }],
requester: createFetchRequester(),
algoliaAgents: [{ segment: 'Fetch' }],
responsesCache: createNullCache(),
requestsCache: createNullCache(),
hostsCache: createMemoryCache(),
Expand Down
Loading

0 comments on commit 4f59d81

Please sign in to comment.