diff --git a/docs/api-client-reference.md b/docs/api-client-reference.md index 6838fa3..c2d3150 100644 --- a/docs/api-client-reference.md +++ b/docs/api-client-reference.md @@ -20,6 +20,8 @@ - [keys.deprecate](#keysdeprecaterequest-config) - [keys.submitTranslation](#keyssubmittranslationrequest-config) - [keys.setTags](#keyssettagsrequest-config) + - [keys.setMetadata](#keyssetmetadatarequest-config) + - [keys.rename](#keysrenamerequest-config) - [keys.setPriority](#keyssetpriorityrequest-config) - [Suggestions](#suggestions) - [suggestions.tm](#suggestionstmrequest-config) @@ -346,6 +348,8 @@ await api.keys.update({ hidden: false, comment: 'Comment.', limit: -1, + addMetadata: { 'figma:doc': { node: '1:2' } }, // merged into the key's metadata + removeMetadata: ['figma:old'], }); ``` @@ -469,6 +473,86 @@ const { result } = await api.keys.setTags({ }); ``` +### keys.setMetadata(request[, config]) + +Add and/or remove entries of the custom metadata of [keys](../src/types/key.ts), each key with its +own change. The metadata is what `files.listKeys()` returns in `metadata` with `metadata: true`. + +Each top-level entry of `addMetadata` replaces the entry of the same name and keeps all others. +Removal is applied before addition, so a name present in both `addMetadata` and `removeMetadata` ends +up added. At most 1000 keys may be passed per call, each listed once and each adding or removing +something; a request that breaks these rules is rejected and changes nothing. + +`files.listKeys()` leaves `metadata` out for a key whose metadata was never written. Once a write has +touched it (this method, `keys.update`, an import's `@meta` or the web app, even a removal of a name +the key didn't have), it lists an object, `{}` after the last entry was removed. Check entries, not +whether `metadata` is present. + +See: [Localazy API Docs](https://localazy.com/docs/api/source-keys#update-metadata-of-multiple-keys) + +| Arguments | Type | +| ----------------- | ------------------------------------------------------------------- | +| request | [`KeySetMetadataRequest`](../src/types/key-set-metadata-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| ------------------------------------------------------------------------------ | +| [`Promise`](../src/types/key-set-metadata-response.ts) | + +Each key gets its own `state`: `updated`, `not_found` (missing, deleted or in another project) or +`not_supported` (a cluster-qualified ID or a single segment of a segmented key). A key that cannot be +changed doesn't stop the others. + +```javascript +const { keys } = await api.keys.setMetadata({ + project: 'project-id', // or Project object + keys: [ + { key: 'key-id', addMetadata: { 'figma:doc': { node: '1:2' } } }, // or Key object + { key: 'other-key-id', removeMetadata: ['figma:doc'] }, + ], +}); +``` + +### keys.rename(request[, config]) + +Rename [keys](../src/types/key.ts): each key keeps its ID, translations and their history, comments, +screenshots, tags and other settings; only its name changes. The key stays in its file and keeps its +kind. + +At most 1000 keys may be passed per call, each listed once. The whole request is checked first: if +one entry can't be applied, no key is renamed. A new name must not be used by another key of the +same file, deprecated keys included; keys may swap names within one call. Segmented keys, keys of +files that use key clustering, of filled-in document formats and of XLIFF imports can't be renamed. +The call fails while an import or another rename runs in the project; retry when it finishes. + +Downloads and the CDN get the new names with the project's next publish. Rename the keys in your +source files too: an import of the old name creates it again as a new key. + +See: [Localazy API Docs](https://localazy.com/docs/api/source-keys#rename-keys) + +| Arguments | Type | +| ----------------- | -------------------------------------------------------- | +| request | [`KeyRenameRequest`](../src/types/key-rename-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| ------------------------------------------------------------------- | +| [`Promise`](../src/types/key-rename-response.ts) | + +Each key gets its `state`: `renamed`, or `unchanged` when it already had the name, so repeating a call +is safe. `name` is a list of segments, as `key` in `files.listKeys()`: `['checkout', 'title']` is a +nested key, `['checkout.title']` a flat key that contains a dot. + +```javascript +const { keys } = await api.keys.rename({ + project: 'project-id', // or Project object + keys: [ + { key: 'key-id', name: ['checkout', 'title'] }, // or Key object + { key: 'other-key-id', name: ['checkout.subtitle'] }, + ], +}); +``` + ### keys.setPriority(request[, config]) Set the priority level on [keys](../src/types/key.ts). diff --git a/src/api/methods/api-keys.ts b/src/api/methods/api-keys.ts index 8085cbf..0f5c88a 100644 --- a/src/api/methods/api-keys.ts +++ b/src/api/methods/api-keys.ts @@ -1,6 +1,10 @@ import { ApiBase } from '@/api/methods/api-base.js'; import type { KeyDeleteRequest } from '@/types/key-delete-request.js'; import type { KeyDeprecateRequest } from '@/types/key-deprecate-request.js'; +import type { KeyRenameRequest } from '@/types/key-rename-request.js'; +import type { KeyRenameResponse } from '@/types/key-rename-response.js'; +import type { KeySetMetadataRequest } from '@/types/key-set-metadata-request.js'; +import type { KeySetMetadataResponse } from '@/types/key-set-metadata-response.js'; import type { KeySetPriorityRequest } from '@/types/key-set-priority-request.js'; import type { KeySetTagsRequest } from '@/types/key-set-tags-request.js'; import type { KeySubmitTranslationRequest } from '@/types/key-submit-translation-request.js'; @@ -144,6 +148,82 @@ export class ApiKeys extends ApiBase { )) as BooleanResult; } + /** + * Add and/or remove entries of the custom metadata of {@link Key keys}, each key with its own change. + * + * Each top-level entry of `addMetadata` replaces the entry of the same name and keeps all others. + * Removal is applied before addition, so a name present in both `addMetadata` and `removeMetadata` + * ends up added. Nothing else about the keys changes. + * + * At most 1000 keys may be passed per call, each listed once and each adding or removing something; + * a request that breaks these rules is rejected and changes nothing. Otherwise every key gets its own + * `state` in the response: a key that is missing (`not_found`) or cannot take metadata + * (`not_supported`: cluster-qualified IDs and single segments of segmented keys) does not stop the + * others. + * + * @param request Key set metadata request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/source-keys#update-metadata-of-multiple-keys Localazy API Docs} + */ + public async setMetadata( + request: KeySetMetadataRequest, + config?: RequestConfig, + ): Promise { + const { project, keys }: KeySetMetadataRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + if (!Array.isArray(keys)) { + throw new TypeError('Invalid key list: an array is required.'); + } + + return (await this.api.client.put( + `/projects/${projectId}/keys/metadata`, + { keys: keys.map(({ key, ...change }) => ({ id: ApiBase.getId(key, 'key'), ...change })) }, + config, + )) as KeySetMetadataResponse; + } + + /** + * Rename {@link Key keys}: give each key a new name, keeping its ID, translations and their + * history, comments, screenshots, tags and other settings. The key stays in its file and keeps its + * kind (a plural key stays plural). + * + * At most 1000 keys may be passed per call, each listed once. The whole request is checked before + * anything is written: if one entry can't be applied, it's rejected and no key is renamed. A new + * name must not be used by another key of the same file, deprecated keys included; keys may swap + * names within one call. Each key gets its `state` in the response: `renamed`, or `unchanged` when + * it already had that name, so repeating a call is safe. + * + * Rejected: segmented keys, keys of files that use key clustering, keys of document formats that + * Localazy exports by filling in the uploaded document, and keys imported from XLIFF. A missing or + * deleted key fails with `401`. The call also fails while an import runs in the project + * (`import_in_progress`) or another rename runs there (`409`); retry when it finishes. + * + * Downloads and the CDN get the new names with the project's next publish. Rename the keys in your + * source files too: an import of the old name creates it again as a new key. + * + * @param request Key rename request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/source-keys#rename-keys Localazy API Docs} + */ + public async rename( + request: KeyRenameRequest, + config?: RequestConfig, + ): Promise { + const { project, keys }: KeyRenameRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + if (!Array.isArray(keys)) { + throw new TypeError('Invalid key list: an array is required.'); + } + + return (await this.api.client.post( + `/projects/${projectId}/keys/rename`, + { keys: keys.map(({ key, name }) => ({ id: ApiBase.getId(key, 'key'), key: name })) }, + config, + )) as KeyRenameResponse; + } + /** * Set the priority level on {@link Key keys}. * diff --git a/src/main.ts b/src/main.ts index 92b8b26..c0cacbc 100644 --- a/src/main.ts +++ b/src/main.ts @@ -76,6 +76,10 @@ export * from '@/types/json.js'; export * from '@/types/key-delete-request.js'; export * from '@/types/key-deprecate-request.js'; export * from '@/types/key-priority.js'; +export * from '@/types/key-rename-request.js'; +export * from '@/types/key-rename-response.js'; +export * from '@/types/key-set-metadata-request.js'; +export * from '@/types/key-set-metadata-response.js'; export * from '@/types/key-set-priority-request.js'; export * from '@/types/key-set-tags-request.js'; export * from '@/types/key-submit-translation-request.js'; diff --git a/src/types/key-rename-request.ts b/src/types/key-rename-request.ts new file mode 100644 index 0000000..10f9ef6 --- /dev/null +++ b/src/types/key-rename-request.ts @@ -0,0 +1,29 @@ +import type { Key } from '@/types/key.js'; +import type { Project } from '@/types/project.js'; + +export type KeyRenameEntry = { + /** + * Key object or Key ID. + */ + key: Key | Pick | string; + + /** + * The new name of the key as a list of segments, in the same form as `key` of `files.listKeys()`: + * `['checkout', 'title']` names a nested key, `['checkout.title']` a flat key that contains a dot. + * It needs at least one segment, and no segment may be empty or blank. Segments are stored exactly + * as sent. + */ + name: string[]; +}; + +export type KeyRenameRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; + + /** + * Keys and their new names, up to 1000 per call. A key may be listed only once. + */ + keys: KeyRenameEntry[]; +}; diff --git a/src/types/key-rename-response.ts b/src/types/key-rename-response.ts new file mode 100644 index 0000000..27474bd --- /dev/null +++ b/src/types/key-rename-response.ts @@ -0,0 +1,32 @@ +/** + * What a rename did with a key: + * - `renamed`: the key now has the requested name. + * - `unchanged`: the key already had the requested name; nothing was touched. + */ +export type KeyRenameState = 'renamed' | 'unchanged'; + +export type KeyRenameResult = { + /** + * Key ID. + */ + id: string; + + /** + * The name of the key after the request, as a list of segments. + */ + key: string[]; + + state: KeyRenameState; +}; + +export type KeyRenameResponse = { + /** + * Always `true`; a request that cannot be applied is rejected instead. + */ + result: boolean; + + /** + * One entry per requested key, in the order of the request. + */ + keys: KeyRenameResult[]; +}; diff --git a/src/types/key-set-metadata-request.ts b/src/types/key-set-metadata-request.ts new file mode 100644 index 0000000..e5f7a95 --- /dev/null +++ b/src/types/key-set-metadata-request.ts @@ -0,0 +1,36 @@ +import type { Key } from '@/types/key.js'; +import type { Project } from '@/types/project.js'; + +export type KeyMetadataChange = { + /** + * Key object or Key ID. + */ + key: Key | Pick | string; + + /** + * Entries to merge into the key's custom metadata. Each top-level entry replaces the entry of the + * same name; all other entries are kept. Values may be any JSON; serialized, it may be up to 32767 + * characters. + */ + addMetadata?: Record; + + /** + * Names of top-level entries to remove from the key's custom metadata. Names the key doesn't have + * are ignored. Removal is applied before addition, so a name present in both ends up added. + * Removing the last entry leaves the metadata empty (`{}` in `files.listKeys()`), not absent. + */ + removeMetadata?: string[]; +}; + +export type KeySetMetadataRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; + + /** + * Keys and their changes, up to 1000 per call. A key may be listed only once, and each change must + * add or remove something. + */ + keys: KeyMetadataChange[]; +}; diff --git a/src/types/key-set-metadata-response.ts b/src/types/key-set-metadata-response.ts new file mode 100644 index 0000000..bd7320b --- /dev/null +++ b/src/types/key-set-metadata-response.ts @@ -0,0 +1,29 @@ +/** + * What a metadata change did with a key: + * - `updated`: the change was applied. + * - `not_found`: the key does not exist, is deleted, or does not belong to the project; nothing changed. + * - `not_supported`: the ID is cluster-qualified (`keyId:clusterKeyId`) or names a single segment of a + * segmented key; nothing changed. + */ +export type KeyMetadataState = 'updated' | 'not_found' | 'not_supported'; + +export type KeyMetadataResult = { + /** + * Key ID, as sent. + */ + id: string; + + state: KeyMetadataState; +}; + +export type KeySetMetadataResponse = { + /** + * Always `true`; a request that cannot be applied at all is rejected instead. + */ + result: boolean; + + /** + * One entry per requested key, in the order of the request. + */ + keys: KeyMetadataResult[]; +}; diff --git a/src/types/key-update-request.ts b/src/types/key-update-request.ts index e784ea5..0e12045 100644 --- a/src/types/key-update-request.ts +++ b/src/types/key-update-request.ts @@ -32,4 +32,20 @@ export type KeyUpdateRequest = { * Change the character limit or set to -1 to disable it. */ limit?: number; + + /** + * Entries to merge into the key's custom metadata (`metadata` of `files.listKeys()` with + * `metadata: true`). Each top-level entry replaces the entry of the same name; all other entries + * are kept. Values may be any JSON; serialized, it may be up to 32767 characters. + * Not accepted for a cluster-qualified key ID (`keyId:clusterKeyId`). + */ + addMetadata?: Record; + + /** + * Names of top-level entries to remove from the key's custom metadata. Names the key doesn't have + * are ignored. Removal is applied before addition, so a name present in both ends up added. + * Removing the last entry leaves the metadata empty (`{}` in `files.listKeys()`), not absent. + * Not accepted for a cluster-qualified key ID (`keyId:clusterKeyId`). + */ + removeMetadata?: string[]; }; diff --git a/src/types/key.ts b/src/types/key.ts index a5f7bb1..7bd6f6f 100644 --- a/src/types/key.ts +++ b/src/types/key.ts @@ -42,4 +42,15 @@ export type Key = { * Only available when event=true in the request. */ event?: number; + + /** + * Custom metadata of the key. Only available when `metadata: true` is requested. + * + * Absent when the key's metadata was never written. Once any write has touched it (an import's + * `@meta`, the web app, `keys.update` or `keys.setMetadata`, even one that only removed a name the + * key didn't have), it stays an object: `{}` after its last entry was removed. So `{}` tells that + * the metadata was edited at some point, though not where or when; check entries, not whether the + * field is present. + */ + metadata?: Record; }; diff --git a/tests/fixtures/full-project/index.ts b/tests/fixtures/full-project/index.ts index edca9d0..fd8f37d 100644 --- a/tests/fixtures/full-project/index.ts +++ b/tests/fixtures/full-project/index.ts @@ -53,6 +53,20 @@ export const serverResponses = { result: true, versionId: '_v000000000000000001', }, + resultRename: { + result: true, + keys: [ + { id: '_a0000000000000000001', key: ['checkout', 'title'], state: 'renamed' }, + { id: '_a0000000000000000002', key: ['checkout.subtitle'], state: 'unchanged' }, + ], + }, + resultSetMetadata: { + result: true, + keys: [ + { id: '_a0000000000000000001', state: 'updated' }, + { id: '_a0000000000000000002', state: 'not_found' }, + ], + }, resultDelete: { result: true, }, @@ -203,6 +217,14 @@ export const mockResponses = (): void => { // tags & priority fetchMock.put(`${baseUrl}/projects/_a0000000000000000001/keys/tags`, serverResponses.resultPut); + fetchMock.put( + `${baseUrl}/projects/_a0000000000000000001/keys/metadata`, + serverResponses.resultSetMetadata, + ); + fetchMock.post( + `${baseUrl}/projects/_a0000000000000000001/keys/rename`, + serverResponses.resultRename, + ); fetchMock.put( `${baseUrl}/projects/_a0000000000000000001/keys/priority`, serverResponses.resultPut, diff --git a/tests/specs/keys.spec.ts b/tests/specs/keys.spec.ts index 0f41eb5..f41bef0 100644 --- a/tests/specs/keys.spec.ts +++ b/tests/specs/keys.spec.ts @@ -3,6 +3,10 @@ import type { File, Key, KeyDeleteRequest, + KeyRenameRequest, + KeyRenameResponse, + KeySetMetadataRequest, + KeySetMetadataResponse, KeySetPriorityRequest, KeySetTagsRequest, KeySubmitTranslationRequest, @@ -55,6 +59,24 @@ describe('Keys', (): void => { ); }); + test('api.keys.update with metadata', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + await api.keys.update({ + project, + key: '_a0000000000000000001', + addMetadata: { 'figma:doc': { node: '1:2' } }, + removeMetadata: ['figma:old'], + }); + + expect(spy).toHaveBeenCalledWith( + 'https://api.localazy.com/projects/_a0000000000000000001/keys/_a0000000000000000001', + expect.objectContaining({ + body: '{"addMetadata":{"figma:doc":{"node":"1:2"}},"removeMetadata":["figma:old"]}', + method: 'PUT', + }), + ); + }); + test('api.keys.delete', async (): Promise => { const file: File = await api.files.first({ project }); const keys: Key[] = await api.files.listKeys({ project, file, lang: Locales.ENGLISH }); @@ -165,6 +187,85 @@ describe('Keys', (): void => { ); }); + test('api.keys.setMetadata', async (): Promise => { + const file: File = await api.files.first({ project }); + const keys: Key[] = await api.files.listKeys({ project, file, lang: Locales.ENGLISH }); + const firstKey = assertNotNull(keys[0]); + const request: KeySetMetadataRequest = { + project, + keys: [ + { key: firstKey, addMetadata: { 'figma:doc': { node: '1:2' } } }, + { key: '_a0000000000000000002', removeMetadata: ['figma:doc'] }, + ], + }; + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const response: KeySetMetadataResponse = await api.keys.setMetadata(request); + + expect(response.keys.map((key) => key.state)).toEqual(['updated', 'not_found']); + expect(spy).toHaveBeenCalledWith( + 'https://api.localazy.com/projects/_a0000000000000000001/keys/metadata', + { + body: '{"keys":[{"id":"_a0000000000000000001","addMetadata":{"figma:doc":{"node":"1:2"}}},{"id":"_a0000000000000000002","removeMetadata":["figma:doc"]}]}', + headers: { + Accept: 'application/json', + Authorization: `Bearer ${getToken()}`, + 'Content-Type': 'application/json', + }, + method: 'PUT', + }, + ); + }); + + test('api.keys.setMetadata rejects a missing key list', async (): Promise => { + await expect( + api.keys.setMetadata({ + project, + keys: undefined as unknown as KeySetMetadataRequest['keys'], + }), + ).rejects.toThrow(TypeError); + }); + + test('api.keys.rename', async (): Promise => { + const file: File = await api.files.first({ project }); + const keys: Key[] = await api.files.listKeys({ project, file, lang: Locales.ENGLISH }); + const firstKey = assertNotNull(keys[0]); + const request: KeyRenameRequest = { + project, + keys: [ + { key: firstKey, name: ['checkout', 'title'] }, + { key: '_a0000000000000000002', name: ['checkout.subtitle'] }, + ], + }; + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const response: KeyRenameResponse = await api.keys.rename(request); + + expect(response.keys).toEqual([ + { id: '_a0000000000000000001', key: ['checkout', 'title'], state: 'renamed' }, + { id: '_a0000000000000000002', key: ['checkout.subtitle'], state: 'unchanged' }, + ]); + expect(spy).toHaveBeenCalledWith( + 'https://api.localazy.com/projects/_a0000000000000000001/keys/rename', + { + body: '{"keys":[{"id":"_a0000000000000000001","key":["checkout","title"]},{"id":"_a0000000000000000002","key":["checkout.subtitle"]}]}', + headers: { + Accept: 'application/json', + Authorization: `Bearer ${getToken()}`, + 'Content-Type': 'application/json', + }, + method: 'POST', + }, + ); + }); + + test('api.keys.rename rejects a missing key list', async (): Promise => { + await expect( + api.keys.rename({ + project, + keys: undefined as unknown as KeyRenameRequest['keys'], + }), + ).rejects.toThrow(TypeError); + }); + test('api.keys.setPriority', async (): Promise => { const request: KeySetPriorityRequest = { project,