Skip to content

Commit f0f0899

Browse files
committed
Remove all unnecessary ts eslint settings, adapt code
1 parent faef3e7 commit f0f0899

17 files changed

+253
-265
lines changed

eslint.config.js

-18
Original file line numberDiff line numberDiff line change
@@ -29,30 +29,12 @@ export default tseslint.config([
2929
},
3030
},
3131
rules: {
32-
// TODO: Remove the ones between "~~", adapt code
33-
// ~~
34-
"@typescript-eslint/prefer-as-const": "off",
35-
"@typescript-eslint/ban-ts-comment": "off",
36-
"@typescript-eslint/no-unsafe-call": "off",
37-
"@typescript-eslint/no-unsafe-member-access": "off",
38-
"@typescript-eslint/no-unsafe-return": "off",
39-
"@typescript-eslint/no-unsafe-assignment": "off",
40-
"@typescript-eslint/no-unsafe-argument": "off",
41-
"@typescript-eslint/no-floating-promises": "off",
42-
// ~~
43-
"@typescript-eslint/array-type": ["warn", { default: "array-simple" }],
44-
// TODO: Should be careful with this rule, should leave it be and disable
45-
// it within files where necessary with explanations
46-
"@typescript-eslint/no-explicit-any": "off",
4732
"@typescript-eslint/no-unused-vars": [
4833
"error",
4934
// argsIgnorePattern: https://eslint.org/docs/latest/rules/no-unused-vars#argsignorepattern
5035
// varsIgnorePattern: https://eslint.org/docs/latest/rules/no-unused-vars#varsignorepattern
5136
{ args: "all", argsIgnorePattern: "^_", varsIgnorePattern: "^_" },
5237
],
53-
// TODO: Not recommended to disable rule, should instead disable locally
54-
// with explanation
55-
"@typescript-eslint/ban-ts-ignore": "off",
5638
},
5739
},
5840
// Vitest

src/errors/meilisearch-api-error.ts

+3-6
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,15 @@ import { MeiliSearchError } from "./meilisearch-error.js";
33

44
export class MeiliSearchApiError extends MeiliSearchError {
55
override name = "MeiliSearchApiError";
6-
override cause?: MeiliSearchErrorResponse;
6+
override cause: MeiliSearchErrorResponse;
77
readonly response: Response;
88

9-
constructor(response: Response, responseBody?: MeiliSearchErrorResponse) {
9+
constructor(response: Response, responseBody: MeiliSearchErrorResponse) {
1010
super(
1111
responseBody?.message ?? `${response.status}: ${response.statusText}`,
1212
);
1313

1414
this.response = response;
15-
16-
if (responseBody !== undefined) {
17-
this.cause = responseBody;
18-
}
15+
this.cause = responseBody;
1916
}
2017
}

src/http-requests.ts

+6-4
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import type {
44
RequestOptions,
55
MainRequestOptions,
66
URLSearchParamsRecord,
7+
MeiliSearchErrorResponse,
78
} from "./types.js";
89
import { PACKAGE_VERSION } from "./package-version.js";
910
import {
@@ -261,14 +262,15 @@ export class HttpRequests {
261262
);
262263

263264
const responseBody = await response.text();
264-
const parsedResponse =
265-
responseBody === "" ? undefined : JSON.parse(responseBody);
266265

267266
if (!response.ok) {
268-
throw new MeiliSearchApiError(response, parsedResponse);
267+
throw new MeiliSearchApiError(
268+
response,
269+
JSON.parse(responseBody) as MeiliSearchErrorResponse,
270+
);
269271
}
270272

271-
return parsedResponse as T;
273+
return (responseBody === "" ? undefined : JSON.parse(responseBody)) as T;
272274
}
273275

274276
/** Request with GET. */

src/indexes.ts

+7-9
Original file line numberDiff line numberDiff line change
@@ -52,12 +52,13 @@ import type {
5252
EnqueuedTaskObject,
5353
ExtraRequestInit,
5454
PrefixSearch,
55+
RecordAny,
5556
} from "./types.js";
5657
import { HttpRequests } from "./http-requests.js";
5758
import { Task, TaskClient } from "./task.js";
5859
import { EnqueuedTask } from "./enqueued-task.js";
5960

60-
class Index<T extends Record<string, any> = Record<string, any>> {
61+
class Index<T extends RecordAny = RecordAny> {
6162
uid: string;
6263
primaryKey: string | undefined;
6364
createdAt: Date | undefined;
@@ -89,10 +90,7 @@ class Index<T extends Record<string, any> = Record<string, any>> {
8990
* @param config - Additional request configuration options
9091
* @returns Promise containing the search response
9192
*/
92-
async search<
93-
D extends Record<string, any> = T,
94-
S extends SearchParams = SearchParams,
95-
>(
93+
async search<D extends RecordAny = T, S extends SearchParams = SearchParams>(
9694
query?: string | null,
9795
options?: S,
9896
extraRequestInit?: ExtraRequestInit,
@@ -113,7 +111,7 @@ class Index<T extends Record<string, any> = Record<string, any>> {
113111
* @returns Promise containing the search response
114112
*/
115113
async searchGet<
116-
D extends Record<string, any> = T,
114+
D extends RecordAny = T,
117115
S extends SearchParams = SearchParams,
118116
>(
119117
query?: string | null,
@@ -175,7 +173,7 @@ class Index<T extends Record<string, any> = Record<string, any>> {
175173
* @returns Promise containing the search response
176174
*/
177175
async searchSimilarDocuments<
178-
D extends Record<string, any> = T,
176+
D extends RecordAny = T,
179177
S extends SearchParams = SearchParams,
180178
>(params: SearchSimilarDocumentsParams): Promise<SearchResponse<D, S>> {
181179
return await this.httpRequest.post<SearchResponse<D, S>>({
@@ -357,7 +355,7 @@ class Index<T extends Record<string, any> = Record<string, any>> {
357355
* the `filter` field only available in Meilisearch v1.2 and newer
358356
* @returns Promise containing the returned documents
359357
*/
360-
async getDocuments<D extends Record<string, any> = T>(
358+
async getDocuments<D extends RecordAny = T>(
361359
params?: DocumentsQuery<D>,
362360
): Promise<ResourceResults<D[]>> {
363361
const relativeBaseURL = `indexes/${this.uid}/documents`;
@@ -384,7 +382,7 @@ class Index<T extends Record<string, any> = Record<string, any>> {
384382
* @param parameters - Parameters applied on a document
385383
* @returns Promise containing Document response
386384
*/
387-
async getDocument<D extends Record<string, any> = T>(
385+
async getDocument<D extends RecordAny = T>(
388386
documentId: string | number,
389387
parameters?: DocumentQuery<T>,
390388
): Promise<D> {

src/meilisearch.ts

+11-7
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,14 @@ import type {
2929
BatchesQuery,
3030
MultiSearchResponseOrSearchResponse,
3131
Network,
32+
RecordAny,
3233
} from "./types.js";
3334
import { ErrorStatusCode } from "./types.js";
3435
import { HttpRequests } from "./http-requests.js";
3536
import { TaskClient } from "./task.js";
3637
import { EnqueuedTask } from "./enqueued-task.js";
3738
import { type Batch, BatchClient } from "./batch.js";
39+
import type { MeiliSearchApiError } from "./errors/meilisearch-api-error.js";
3840

3941
export class MeiliSearch {
4042
config: Config;
@@ -60,9 +62,7 @@ export class MeiliSearch {
6062
* @param indexUid - The index UID
6163
* @returns Instance of Index
6264
*/
63-
index<T extends Record<string, any> = Record<string, any>>(
64-
indexUid: string,
65-
): Index<T> {
65+
index<T extends RecordAny = RecordAny>(indexUid: string): Index<T> {
6666
return new Index<T>(this.config, indexUid);
6767
}
6868

@@ -73,7 +73,7 @@ export class MeiliSearch {
7373
* @param indexUid - The index UID
7474
* @returns Promise returning Index instance
7575
*/
76-
async getIndex<T extends Record<string, any> = Record<string, any>>(
76+
async getIndex<T extends RecordAny = RecordAny>(
7777
indexUid: string,
7878
): Promise<Index<T>> {
7979
return new Index<T>(this.config, indexUid).fetchInfo();
@@ -170,10 +170,14 @@ export class MeiliSearch {
170170
try {
171171
await this.deleteIndex(uid);
172172
return true;
173-
} catch (e: any) {
174-
if (e.code === ErrorStatusCode.INDEX_NOT_FOUND) {
173+
} catch (e) {
174+
if (
175+
(e as MeiliSearchApiError)?.cause?.code ===
176+
ErrorStatusCode.INDEX_NOT_FOUND
177+
) {
175178
return false;
176179
}
180+
177181
throw e;
178182
}
179183
}
@@ -244,7 +248,7 @@ export class MeiliSearch {
244248
*/
245249
async multiSearch<
246250
T1 extends MultiSearchParams | FederatedMultiSearchParams,
247-
T2 extends Record<string, any> = Record<string, any>,
251+
T2 extends RecordAny = RecordAny,
248252
>(
249253
queries: T1,
250254
extraRequestInit?: ExtraRequestInit,

src/token.ts

+8-14
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
import type { webcrypto } from "node:crypto";
2-
import type { TenantTokenGeneratorOptions, TokenSearchRules } from "./types.js";
2+
import type {
3+
TenantTokenGeneratorOptions,
4+
TenantTokenHeader,
5+
TokenClaims,
6+
} from "./types.js";
37

48
function getOptionsWithDefaults(options: TenantTokenGeneratorOptions) {
59
const {
@@ -80,20 +84,10 @@ async function sign(
8084
function getHeader({
8185
algorithm: alg,
8286
}: TenantTokenGeneratorOptionsWithDefaults): string {
83-
const header = { alg, typ: "JWT" };
87+
const header: TenantTokenHeader = { alg, typ: "JWT" };
8488
return encodeToBase64(header).replace(/=/g, "");
8589
}
8690

87-
/**
88-
* @see {@link https://www.meilisearch.com/docs/learn/security/tenant_token_reference | Tenant token payload reference}
89-
* @see {@link https://github.com/meilisearch/meilisearch/blob/b21d7aedf9096539041362d438e973a18170f3fc/crates/meilisearch/src/extractors/authentication/mod.rs#L334-L340 | GitHub source code}
90-
*/
91-
type TokenClaims = {
92-
searchRules: TokenSearchRules;
93-
exp?: number;
94-
apiKeyUid: string;
95-
};
96-
9791
/** Create the payload of the token. */
9892
function getPayload({
9993
searchRules,
@@ -124,8 +118,8 @@ function getPayload({
124118
* is the recommended way according to
125119
* {@link https://min-common-api.proposal.wintercg.org/#navigator-useragent-requirements | WinterCG specs}.
126120
* {@link https://developer.mozilla.org/en-US/docs/Web/API/Navigator/userAgent | User agent }
127-
* can be spoofed, `process` can be patched. It should prevent misuse for the
128-
* overwhelming majority of cases.
121+
* can be spoofed, `process` can be patched. Even so it should prevent misuse
122+
* for the overwhelming majority of cases.
129123
*/
130124
function tryDetectEnvironment(): void {
131125
if (typeof navigator !== "undefined" && "userAgent" in navigator) {

src/types.ts

+31-12
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77
import { Task } from "./task.js";
88
import { Batch } from "./batch.js";
99

10+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
11+
export type RecordAny = Record<string, any>;
12+
1013
/**
1114
* Shape of allowed record object that can be appended to a
1215
* {@link URLSearchParams}.
@@ -332,7 +335,7 @@ export type RankingScoreDetails = {
332335
matchType: string;
333336
score: number;
334337
};
335-
[key: string]: Record<string, any> | undefined;
338+
[key: string]: RecordAny | undefined;
336339
};
337340

338341
export type FederationDetails = {
@@ -341,15 +344,15 @@ export type FederationDetails = {
341344
weightedRankingScore: number;
342345
};
343346

344-
export type Hit<T = Record<string, any>> = T & {
347+
export type Hit<T = RecordAny> = T & {
345348
_formatted?: Partial<T>;
346349
_matchesPosition?: MatchesPosition<T>;
347350
_rankingScore?: number;
348351
_rankingScoreDetails?: RankingScoreDetails;
349352
_federation?: FederationDetails;
350353
};
351354

352-
export type Hits<T = Record<string, any>> = Array<Hit<T>>;
355+
export type Hits<T = RecordAny> = Array<Hit<T>>;
353356

354357
export type FacetStat = { min: number; max: number };
355358
export type FacetStats = Record<string, FacetStat>;
@@ -363,7 +366,7 @@ export type FacetsByIndex = Record<
363366
>;
364367

365368
export type SearchResponse<
366-
T = Record<string, any>,
369+
T = RecordAny,
367370
S extends SearchParams | undefined = undefined,
368371
> = {
369372
hits: Hits<T>;
@@ -411,13 +414,13 @@ type HasPage<S extends SearchParams> = undefined extends S["page"]
411414

412415
export type MultiSearchResult<T> = SearchResponse<T> & { indexUid: string };
413416

414-
export type MultiSearchResponse<T = Record<string, any>> = {
417+
export type MultiSearchResponse<T = RecordAny> = {
415418
results: Array<MultiSearchResult<T>>;
416419
};
417420

418421
export type MultiSearchResponseOrSearchResponse<
419422
T1 extends FederatedMultiSearchParams | MultiSearchParams,
420-
T2 extends Record<string, unknown> = Record<string, any>,
423+
T2 extends RecordAny = RecordAny,
421424
> = T1 extends FederatedMultiSearchParams
422425
? SearchResponse<T2>
423426
: MultiSearchResponse<T2>;
@@ -442,7 +445,7 @@ export type SearchSimilarDocumentsParams = {
442445
** Documents
443446
*/
444447

445-
type Fields<T = Record<string, any>> =
448+
type Fields<T = RecordAny> =
446449
| Array<Extract<keyof T, string>>
447450
| Extract<keyof T, string>;
448451

@@ -465,15 +468,15 @@ export type RawDocumentAdditionOptions = DocumentOptions & {
465468
csvDelimiter?: string;
466469
};
467470

468-
export type DocumentsQuery<T = Record<string, any>> = ResourceQuery & {
471+
export type DocumentsQuery<T = RecordAny> = ResourceQuery & {
469472
fields?: Fields<T>;
470473
filter?: Filter;
471474
limit?: number;
472475
offset?: number;
473476
retrieveVectors?: boolean;
474477
};
475478

476-
export type DocumentQuery<T = Record<string, any>> = {
479+
export type DocumentQuery<T = RecordAny> = {
477480
fields?: Fields<T>;
478481
};
479482

@@ -486,7 +489,7 @@ export type DocumentsIds = string[] | number[];
486489
export type UpdateDocumentsByFunctionOptions = {
487490
function: string;
488491
filter?: string | string[];
489-
context?: Record<string, any>;
492+
context?: RecordAny;
490493
};
491494

492495
/*
@@ -556,8 +559,8 @@ export type RestEmbedder = {
556559
dimensions?: number;
557560
documentTemplate?: string;
558561
distribution?: Distribution;
559-
request: Record<string, any>;
560-
response: Record<string, any>;
562+
request: RecordAny;
563+
response: RecordAny;
561564
headers?: Record<string, string>;
562565
documentTemplateMaxBytes?: number;
563566
binaryQuantized?: boolean;
@@ -1394,3 +1397,19 @@ export type TenantTokenGeneratorOptions = {
13941397
*/
13951398
force?: boolean;
13961399
};
1400+
1401+
/**
1402+
* @see {@link https://www.meilisearch.com/docs/learn/security/tenant_token_reference | Tenant token payload reference}
1403+
* @see {@link https://github.com/meilisearch/meilisearch/blob/b21d7aedf9096539041362d438e973a18170f3fc/crates/meilisearch/src/extractors/authentication/mod.rs#L334-L340 | GitHub source code}
1404+
*/
1405+
export type TokenClaims = {
1406+
searchRules: TokenSearchRules;
1407+
exp?: number;
1408+
apiKeyUid: string;
1409+
};
1410+
1411+
/** JSON Web Token header. */
1412+
export type TenantTokenHeader = {
1413+
alg: NonNullable<TenantTokenGeneratorOptions["algorithm"]>;
1414+
typ: "JWT";
1415+
};

0 commit comments

Comments
 (0)