-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathextractJson.ts
More file actions
186 lines (164 loc) · 5.76 KB
/
extractJson.ts
File metadata and controls
186 lines (164 loc) · 5.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import { AdditionalOptions } from '../../types/index.js';
import { logger } from '../../console/logger.js';
import {
findMatchingItemArray,
findMatchingItemObject,
generateSourceObjectPointers,
validateJsonSchema,
} from './utils.js';
import { flattenJsonWithStringFilter } from './flattenJson.js';
import { gt } from '../../utils/gt.js';
import { applyStructuralTransforms } from './transformJson.js';
/**
* Extracts translated values from a full JSON file back into composite JSON format.
* This is the inverse of mergeJson - it takes a merged/reconstructed JSON file
* and extracts the values for a specific locale into the composite structure
* that the server expects.
*
* @param localContent - The full JSON content from the user's local file
* @param inputPath - The path to the file (used for matching jsonSchema)
* @param options - Additional options containing jsonSchema config
* @param targetLocale - The locale to extract values for
* @param defaultLocale - The default/source locale
* @returns The composite JSON string, or null if no extraction needed
*/
export function extractJson(
localContent: string,
inputPath: string,
options: AdditionalOptions,
targetLocale: string,
defaultLocale: string
): string | null {
const jsonSchema = validateJsonSchema(options, inputPath);
if (!jsonSchema) {
// No schema
return null;
}
let localJson: any;
try {
localJson = JSON.parse(localContent);
} catch {
logger.error(`Invalid JSON file: ${inputPath}`);
return null;
}
const useCanonicalLocaleKeys =
options?.experimentalCanonicalLocaleKeys ?? false;
const canonicalTargetLocale = useCanonicalLocaleKeys
? gt.resolveCanonicalLocale(targetLocale)
: targetLocale;
const canonicalDefaultLocale = useCanonicalLocaleKeys
? gt.resolveCanonicalLocale(defaultLocale)
: defaultLocale;
if (jsonSchema.structuralTransform && jsonSchema.composite) {
applyStructuralTransforms(
localJson,
jsonSchema.structuralTransform,
jsonSchema.composite
);
}
// Handle include-style schemas (simple path-based extraction)
if (jsonSchema.include) {
const extracted = flattenJsonWithStringFilter(
localJson,
jsonSchema.include
);
return JSON.stringify(extracted, null, 2);
}
if (!jsonSchema.composite) {
logger.error('No include or composite property found in JSON schema');
return null;
}
// Handle composite schemas
const compositeResult: Record<string, any> = {};
// Generate source object pointers from the local JSON
const sourceObjectPointers = generateSourceObjectPointers(
jsonSchema.composite,
localJson
);
for (const [
sourceObjectPointer,
{ sourceObjectValue, sourceObjectOptions },
] of Object.entries(sourceObjectPointers)) {
if (sourceObjectOptions.type === 'array') {
if (!Array.isArray(sourceObjectValue)) {
logger.warn(
`Source object value is not an array at path: ${sourceObjectPointer}`
);
continue;
}
// Find the matching items for the target locale
const matchingTargetLocaleItems = findMatchingItemArray(
canonicalTargetLocale,
sourceObjectOptions,
sourceObjectPointer,
sourceObjectValue
);
if (!Object.keys(matchingTargetLocaleItems).length) {
logger.warn(
`No matching items found for locale ${targetLocale} at path: ${sourceObjectPointer}`
);
continue;
}
// Also find default locale items
const matchingDefaultLocaleItems = findMatchingItemArray(
canonicalDefaultLocale,
sourceObjectOptions,
sourceObjectPointer,
sourceObjectValue
);
const defaultKeys = Object.keys(matchingDefaultLocaleItems);
const targetEntries = Object.entries(matchingTargetLocaleItems);
// Initialize the nested structure for this source object pointer
if (!compositeResult[sourceObjectPointer]) {
compositeResult[sourceObjectPointer] = {};
}
// For each target item, use the default locale's key position
for (let i = 0; i < targetEntries.length; i++) {
const [, { sourceItem }] = targetEntries[i];
// Extract values at the include paths
const extractedValues = flattenJsonWithStringFilter(
sourceItem,
sourceObjectOptions.include
);
// Use default locale key
const outputKey =
i < defaultKeys.length ? defaultKeys[i] : targetEntries[i][0];
compositeResult[sourceObjectPointer][outputKey] = extractedValues;
}
} else {
// Object type
if (typeof sourceObjectValue !== 'object' || sourceObjectValue === null) {
logger.warn(
`Source object value is not an object at path: ${sourceObjectPointer}`
);
continue;
}
// Find the matching item for the target locale
const matchingTargetItem = findMatchingItemObject(
canonicalTargetLocale,
sourceObjectPointer,
sourceObjectOptions,
sourceObjectValue
);
if (!matchingTargetItem.sourceItem) {
logger.warn(
`No matching item found for locale ${targetLocale} at path: ${sourceObjectPointer}`
);
continue;
}
// If the source item is a string, use it directly
if (typeof matchingTargetItem.sourceItem === 'string') {
compositeResult[sourceObjectPointer] = matchingTargetItem.sourceItem;
continue;
}
// Extract values at the include paths
const extractedValues = flattenJsonWithStringFilter(
matchingTargetItem.sourceItem,
sourceObjectOptions.include
);
// Store the extracted values
compositeResult[sourceObjectPointer] = extractedValues;
}
}
return JSON.stringify(compositeResult, null, 2);
}