@lokalise/api-contracts 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,13 @@
1
+ Copyright 2024 Lokalise, Inc.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,63 @@
1
+ # api-contracts
2
+
3
+ Key idea behind API contracts: backend owns entire definition for the route, including its path, HTTP method used and
4
+ response structure expectations, and exposes it as a part of its API schemas. Then frontend consumes that definition
5
+ instead of forming full request configuration manually on the client side.
6
+
7
+ This reduces amount of assumptions FE needs to make about the behaviour of BE, reduces amount of code that needs to be
8
+ written on FE, and makes the code more type-safe (as path parameter setting is handled by logic exposed by BE, in a
9
+ type-safe way).
10
+
11
+ Usage examples:
12
+
13
+ ```ts
14
+ import { buildGetRoute, buildDeleteRoute, buildPayloadRoute } from '@lokalise/api-contracts'
15
+
16
+ const getContract = buildGetRoute({
17
+ successResponseBodySchema: RESPONSE_BODY_SCHEMA,
18
+ requestPathParamsSchema: REQUEST_PATH_PARAMS_SCHEMA,
19
+ requestQuerySchema: REQUEST_QUERY_SCHEMA,
20
+ requestHeaderSchema: REQUEST_HEADER_SCHEMA,
21
+ pathResolver: (pathParams) => `/users/${pathParams.userId}`,
22
+ metadata: { allowedRoles: ['admin'] },
23
+ })
24
+
25
+ const postContract = buildPayloadRoute({
26
+ method: 'post', // can also be 'patch' or 'post'
27
+ successResponseBodySchema: RESPONSE_BODY_SCHEMA,
28
+ requestBodySchema: REQUEST_BODY_SCHEMA,
29
+ pathResolver: () => '/',
30
+ metadata: { allowedPermission: ['edit'] },
31
+ })
32
+
33
+ const deleteContract = buildDeleteRoute({
34
+ successResponseBodySchema: RESPONSE_BODY_SCHEMA,
35
+ requestPathParamsSchema: REQUEST_PATH_PARAMS_SCHEMA,
36
+ pathResolver: (pathParams) => `/users/${pathParams.userId}`,
37
+ })
38
+ ```
39
+
40
+ In the previous example, the `metadata` property is an optional, free-form field that allows you to store any additional
41
+ information related to the route. If you require more precise type definitions for the `metadata` field, you can utilize
42
+ TypeScript's module augmentation mechanism to enforce stricter typing. This allows for more controlled and type-safe
43
+ usage in your route definitions.
44
+
45
+ Here is how you can apply strict typing to the `metadata` property using TypeScript module augmentation:
46
+ ```typescript
47
+ // file -> apiContracts.d.ts
48
+ // Import the existing module to ensure TypeScript recognizes the original definitions
49
+ import '@lokalise/api-contracts/apiContracts';
50
+
51
+ // Augment the module to extend the interface with specific properties
52
+ declare module '@lokalise/api-contracts/apiContracts' {
53
+ interface CommonRouteDefinitionMetadata {
54
+ myTestProp?: string[];
55
+ mySecondTestProp?: number;
56
+ }
57
+ }
58
+ ```
59
+
60
+ Note that in order to make contract-based requests, you need to use a compatible HTTP client
61
+ (`@lokalise/frontend-http-client` or `@lokalise/backend-http-client`)
62
+
63
+ In case you are using fastify on the backend, you can also use `@lokalise/fastify-api-contracts` in order to simplify definition of your fastify routes, utilizing contracts as the single source of truth.
@@ -0,0 +1 @@
1
+ export type HttpStatusCode = 100 | 101 | 102 | 103 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 226 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511;
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=HttpStatusCodes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"HttpStatusCodes.js","sourceRoot":"","sources":["../src/HttpStatusCodes.ts"],"names":[],"mappings":""}
@@ -0,0 +1,36 @@
1
+ import type { ZodSchema, z } from 'zod';
2
+ import type { HttpStatusCode } from './HttpStatusCodes.js';
3
+ export type InferSchemaInput<T extends ZodSchema | undefined> = T extends ZodSchema ? z.input<T> : T extends undefined ? undefined : never;
4
+ export type InferSchemaOutput<T extends ZodSchema | undefined> = T extends ZodSchema ? z.infer<T> : T extends undefined ? undefined : never;
5
+ export type RoutePathResolver<PathParams> = (pathParams: PathParams) => string;
6
+ export interface CommonRouteDefinitionMetadata extends Record<string, unknown> {
7
+ }
8
+ export type CommonRouteDefinition<PathParams, ResponseBodySchema extends z.Schema | undefined = undefined, PathParamsSchema extends z.Schema<PathParams> | undefined = undefined, RequestQuerySchema extends z.Schema | undefined = undefined, RequestHeaderSchema extends z.Schema | undefined = undefined, IsNonJSONResponseExpected extends boolean = false, IsEmptyResponseExpected extends boolean = false> = {
9
+ isNonJSONResponseExpected?: IsNonJSONResponseExpected;
10
+ isEmptyResponseExpected?: IsEmptyResponseExpected;
11
+ successResponseBodySchema: ResponseBodySchema;
12
+ requestPathParamsSchema?: PathParamsSchema;
13
+ requestQuerySchema?: RequestQuerySchema;
14
+ requestHeaderSchema?: RequestHeaderSchema;
15
+ pathResolver: RoutePathResolver<InferSchemaOutput<PathParamsSchema>>;
16
+ responseSchemasByStatusCode?: Partial<Record<HttpStatusCode, z.Schema>>;
17
+ description?: string;
18
+ metadata?: CommonRouteDefinitionMetadata;
19
+ };
20
+ export type PayloadRouteDefinition<PathParams, RequestBodySchema extends z.Schema | undefined = undefined, SuccessResponseBodySchema extends z.Schema | undefined = undefined, PathParamsSchema extends z.Schema<PathParams> | undefined = undefined, RequestQuerySchema extends z.Schema | undefined = undefined, RequestHeaderSchema extends z.Schema | undefined = undefined, IsNonJSONResponseExpected extends boolean = false, IsEmptyResponseExpected extends boolean = false> = CommonRouteDefinition<PathParams, SuccessResponseBodySchema, PathParamsSchema, RequestQuerySchema, RequestHeaderSchema, IsNonJSONResponseExpected, IsEmptyResponseExpected> & {
21
+ method: 'post' | 'put' | 'patch';
22
+ requestBodySchema: RequestBodySchema;
23
+ };
24
+ export type GetRouteDefinition<PathParams, SuccessResponseBodySchema extends z.Schema | undefined = undefined, PathParamsSchema extends z.Schema<PathParams> | undefined = undefined, RequestQuerySchema extends z.Schema | undefined = undefined, RequestHeaderSchema extends z.Schema | undefined = undefined, IsNonJSONResponseExpected extends boolean = false, IsEmptyResponseExpected extends boolean = false> = CommonRouteDefinition<PathParams, SuccessResponseBodySchema, PathParamsSchema, RequestQuerySchema, RequestHeaderSchema, IsNonJSONResponseExpected, IsEmptyResponseExpected> & {
25
+ method: 'get';
26
+ };
27
+ export type DeleteRouteDefinition<PathParams, SuccessResponseBodySchema extends z.Schema | undefined = undefined, PathParamsSchema extends z.Schema<PathParams> | undefined = undefined, RequestQuerySchema extends z.Schema | undefined = undefined, RequestHeaderSchema extends z.Schema | undefined = undefined, IsNonJSONResponseExpected extends boolean = false, IsEmptyResponseExpected extends boolean = true> = CommonRouteDefinition<PathParams, SuccessResponseBodySchema, PathParamsSchema, RequestQuerySchema, RequestHeaderSchema, IsNonJSONResponseExpected, IsEmptyResponseExpected> & {
28
+ method: 'delete';
29
+ };
30
+ export declare function buildPayloadRoute<RequestBodySchema extends z.Schema | undefined = undefined, SuccessResponseBodySchema extends z.Schema | undefined = undefined, PathParamsSchema extends z.Schema | undefined = undefined, RequestQuerySchema extends z.Schema | undefined = undefined, RequestHeaderSchema extends z.Schema | undefined = undefined, IsNonJSONResponseExpected extends boolean = false, IsEmptyResponseExpected extends boolean = false, PathParams = PathParamsSchema extends z.Schema<infer T> ? T : never>(params: PayloadRouteDefinition<PathParams, RequestBodySchema, SuccessResponseBodySchema, PathParamsSchema, RequestQuerySchema, RequestHeaderSchema, IsNonJSONResponseExpected, IsEmptyResponseExpected>): PayloadRouteDefinition<PathParams, RequestBodySchema, SuccessResponseBodySchema, PathParamsSchema, RequestQuerySchema, RequestHeaderSchema, IsNonJSONResponseExpected, IsEmptyResponseExpected>;
31
+ export declare function buildGetRoute<SuccessResponseBodySchema extends z.Schema | undefined = undefined, PathParamsSchema extends z.Schema | undefined = undefined, RequestQuerySchema extends z.Schema | undefined = undefined, RequestHeaderSchema extends z.Schema | undefined = undefined, IsNonJSONResponseExpected extends boolean = false, IsEmptyResponseExpected extends boolean = false, PathParams = PathParamsSchema extends z.Schema<infer T> ? T : never>(params: Omit<GetRouteDefinition<PathParams, SuccessResponseBodySchema, PathParamsSchema, RequestQuerySchema, RequestHeaderSchema, IsNonJSONResponseExpected, IsEmptyResponseExpected>, 'method'>): GetRouteDefinition<PathParams, SuccessResponseBodySchema, PathParamsSchema, RequestQuerySchema, RequestHeaderSchema, IsNonJSONResponseExpected, IsEmptyResponseExpected>;
32
+ export declare function buildDeleteRoute<SuccessResponseBodySchema extends z.Schema | undefined = undefined, PathParamsSchema extends z.Schema | undefined = undefined, RequestQuerySchema extends z.Schema | undefined = undefined, RequestHeaderSchema extends z.Schema | undefined = undefined, IsNonJSONResponseExpected extends boolean = false, IsEmptyResponseExpected extends boolean = true, PathParams = PathParamsSchema extends z.Schema<infer T> ? T : never>(params: Omit<DeleteRouteDefinition<PathParams, SuccessResponseBodySchema, PathParamsSchema, RequestQuerySchema, RequestHeaderSchema, IsNonJSONResponseExpected, IsEmptyResponseExpected>, 'method'>): DeleteRouteDefinition<PathParams, SuccessResponseBodySchema, PathParamsSchema, RequestQuerySchema, RequestHeaderSchema, IsNonJSONResponseExpected, IsEmptyResponseExpected>;
33
+ /**
34
+ * This method maps given route definition to a string of the format '/static-path-part/:path-param-value'
35
+ */
36
+ export declare function mapRouteToPath(routeDefinition: CommonRouteDefinition<any, any, any, any, any, any, any>): string;
@@ -0,0 +1,64 @@
1
+ const EMPTY_PARAMS = {};
2
+ export function buildPayloadRoute(params) {
3
+ return {
4
+ isEmptyResponseExpected: params.isEmptyResponseExpected ?? false,
5
+ isNonJSONResponseExpected: params.isNonJSONResponseExpected ?? false,
6
+ method: params.method,
7
+ pathResolver: params.pathResolver,
8
+ requestBodySchema: params.requestBodySchema,
9
+ requestHeaderSchema: params.requestHeaderSchema,
10
+ requestPathParamsSchema: params.requestPathParamsSchema,
11
+ requestQuerySchema: params.requestQuerySchema,
12
+ successResponseBodySchema: params.successResponseBodySchema,
13
+ description: params.description,
14
+ responseSchemasByStatusCode: params.responseSchemasByStatusCode,
15
+ metadata: params.metadata,
16
+ };
17
+ }
18
+ export function buildGetRoute(params) {
19
+ return {
20
+ isEmptyResponseExpected: params.isEmptyResponseExpected ?? false,
21
+ isNonJSONResponseExpected: params.isNonJSONResponseExpected ?? false,
22
+ method: 'get',
23
+ pathResolver: params.pathResolver,
24
+ requestHeaderSchema: params.requestHeaderSchema,
25
+ requestPathParamsSchema: params.requestPathParamsSchema,
26
+ requestQuerySchema: params.requestQuerySchema,
27
+ successResponseBodySchema: params.successResponseBodySchema,
28
+ description: params.description,
29
+ responseSchemasByStatusCode: params.responseSchemasByStatusCode,
30
+ metadata: params.metadata,
31
+ };
32
+ }
33
+ export function buildDeleteRoute(params) {
34
+ return {
35
+ isEmptyResponseExpected: params.isEmptyResponseExpected ?? true,
36
+ isNonJSONResponseExpected: params.isNonJSONResponseExpected ?? false,
37
+ method: 'delete',
38
+ pathResolver: params.pathResolver,
39
+ requestHeaderSchema: params.requestHeaderSchema,
40
+ requestPathParamsSchema: params.requestPathParamsSchema,
41
+ requestQuerySchema: params.requestQuerySchema,
42
+ successResponseBodySchema: params.successResponseBodySchema,
43
+ description: params.description,
44
+ responseSchemasByStatusCode: params.responseSchemasByStatusCode,
45
+ metadata: params.metadata,
46
+ };
47
+ }
48
+ /**
49
+ * This method maps given route definition to a string of the format '/static-path-part/:path-param-value'
50
+ */
51
+ export function mapRouteToPath(
52
+ // biome-ignore lint/suspicious/noExplicitAny: We don't care about types here, we just need Zod schema
53
+ routeDefinition) {
54
+ if (!routeDefinition.requestPathParamsSchema) {
55
+ return routeDefinition.pathResolver(EMPTY_PARAMS);
56
+ }
57
+ const shape = routeDefinition.requestPathParamsSchema.shape;
58
+ const resolverParams = {};
59
+ for (const key of Object.keys(shape)) {
60
+ resolverParams[key] = `:${key}`;
61
+ }
62
+ return routeDefinition.pathResolver(resolverParams);
63
+ }
64
+ //# sourceMappingURL=apiContracts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apiContracts.js","sourceRoot":"","sources":["../src/apiContracts.ts"],"names":[],"mappings":"AAGA,MAAM,YAAY,GAAG,EAAE,CAAA;AAqGvB,MAAM,UAAU,iBAAiB,CAU/B,MASC;IAWD,OAAO;QACL,uBAAuB,EAAE,MAAM,CAAC,uBAAuB,IAAK,KAAiC;QAC7F,yBAAyB,EACvB,MAAM,CAAC,yBAAyB,IAAK,KAAmC;QAC1E,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,YAAY,EAAE,MAAM,CAAC,YAAY;QACjC,iBAAiB,EAAE,MAAM,CAAC,iBAAiB;QAC3C,mBAAmB,EAAE,MAAM,CAAC,mBAAmB;QAC/C,uBAAuB,EAAE,MAAM,CAAC,uBAAuB;QACvD,kBAAkB,EAAE,MAAM,CAAC,kBAAkB;QAC7C,yBAAyB,EAAE,MAAM,CAAC,yBAAyB;QAC3D,WAAW,EAAE,MAAM,CAAC,WAAW;QAC/B,2BAA2B,EAAE,MAAM,CAAC,2BAA2B;QAC/D,QAAQ,EAAE,MAAM,CAAC,QAAQ;KAC1B,CAAA;AACH,CAAC;AAED,MAAM,UAAU,aAAa,CAS3B,MAWC;IAUD,OAAO;QACL,uBAAuB,EAAE,MAAM,CAAC,uBAAuB,IAAK,KAAiC;QAC7F,yBAAyB,EACvB,MAAM,CAAC,yBAAyB,IAAK,KAAmC;QAC1E,MAAM,EAAE,KAAK;QACb,YAAY,EAAE,MAAM,CAAC,YAAY;QACjC,mBAAm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AAG,EAAE,CAAA;IACjC,CAAC;IAED,OAAO,eAAe,CAAC,YAAY,CAAC,cAAc,CAAC,CAAA;AACrD,CAAC"}
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@lokalise/api-contracts",
3
+ "version": "4.1.0",
4
+ "files": ["dist"],
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "./dist/apiContracts.js",
8
+ "enableTransparentWorkspaces": "false",
9
+ "homepage": "https://github.com/lokalise/shared-ts-libs",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git://github.com/lokalise/shared-ts-libs.git"
13
+ },
14
+ "exports": {
15
+ ".": "./dist/apiContracts.js",
16
+ "./package.json": "./package.json"
17
+ },
18
+ "private": false,
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "keywords": [
23
+ "api",
24
+ "contracts",
25
+ "contract",
26
+ "frontend",
27
+ "backend",
28
+ "single",
29
+ "source",
30
+ "truth"
31
+ ],
32
+ "scripts": {
33
+ "build": "rimraf dist && tsc --project tsconfig.build.json",
34
+ "lint": "biome check . && tsc",
35
+ "lint:fix": "biome check --write",
36
+ "test:ci": "vitest run --coverage",
37
+ "prepublishOnly": "npm run build",
38
+ "package-version": "echo $npm_package_version",
39
+ "postversion": "biome check --write package.json"
40
+ },
41
+ "peerDependencies": {
42
+ "zod": "^3.24.2"
43
+ },
44
+ "devDependencies": {
45
+ "@biomejs/biome": "^1.9.4",
46
+ "@lokalise/biome-config": "^1.5.0",
47
+ "@lokalise/tsconfig": "~1.0.2",
48
+ "@vitest/coverage-v8": "^3.0.9",
49
+ "rimraf": "^6.0.1",
50
+ "typescript": "5.8.2",
51
+ "vitest": "^3.0.9"
52
+ },
53
+ "dependencies": {}
54
+ }