gt 2.28.5 → 2.28.7

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.
Files changed (46) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/dist/api/collectUserEditDiffs.js.map +1 -1
  3. package/dist/formats/files/aggregateFiles.js +25 -3
  4. package/dist/formats/files/aggregateFiles.js.map +1 -1
  5. package/dist/formats/files/supportedFiles.d.ts +10 -1
  6. package/dist/formats/files/supportedFiles.js +27 -3
  7. package/dist/formats/files/supportedFiles.js.map +1 -1
  8. package/dist/formats/files/transformFormat.d.ts +14 -0
  9. package/dist/formats/files/transformFormat.js +24 -3
  10. package/dist/formats/files/transformFormat.js.map +1 -1
  11. package/dist/fs/findFilepath.d.ts +1 -1
  12. package/dist/fs/findFilepath.js +1 -1
  13. package/dist/fs/findFilepath.js.map +1 -1
  14. package/dist/generated/version.d.ts +1 -1
  15. package/dist/generated/version.js +1 -1
  16. package/dist/generated/version.js.map +1 -1
  17. package/dist/next/parse/wrapContent.js +1 -1
  18. package/dist/react/jsx/utils/getPathsAndAliases.d.ts +11 -0
  19. package/dist/react/jsx/utils/getPathsAndAliases.js +62 -21
  20. package/dist/react/jsx/utils/getPathsAndAliases.js.map +1 -1
  21. package/dist/react/jsx/utils/parseStringFunction.js +16 -2
  22. package/dist/react/jsx/utils/parseStringFunction.js.map +1 -1
  23. package/dist/react/parse/createInlineUpdates.d.ts +15 -0
  24. package/dist/react/parse/createInlineUpdates.js +31 -111
  25. package/dist/react/parse/createInlineUpdates.js.map +1 -1
  26. package/dist/react/parse/scanFiles.d.ts +22 -0
  27. package/dist/react/parse/scanFiles.js +125 -0
  28. package/dist/react/parse/scanFiles.js.map +1 -0
  29. package/dist/react/parse/scanPool.d.ts +28 -0
  30. package/dist/react/parse/scanPool.js +122 -0
  31. package/dist/react/parse/scanPool.js.map +1 -0
  32. package/dist/react/parse/scanWorker.d.ts +1 -0
  33. package/dist/react/parse/scanWorker.js +19 -0
  34. package/dist/react/parse/scanWorker.js.map +1 -0
  35. package/dist/react/parse/wrapContent.js +1 -1
  36. package/dist/translation/stage.js +2 -2
  37. package/dist/translation/stage.js.map +1 -1
  38. package/dist/types/index.d.ts +1 -0
  39. package/dist/types/index.js.map +1 -1
  40. package/dist/utils/hash.d.ts +2 -0
  41. package/dist/utils/hash.js +5 -1
  42. package/dist/utils/hash.js.map +1 -1
  43. package/dist/utils/localizeStaticUrls.js +1 -1
  44. package/dist/utils/sharedStaticAssets.js +22 -4
  45. package/dist/utils/sharedStaticAssets.js.map +1 -1
  46. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"createInlineUpdates.js","names":[],"sources":["../../../src/react/parse/createInlineUpdates.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { Updates } from '../../types/index.js';\n\nimport { parse } from '@babel/parser';\nimport { parseTranslationComponent } from '../jsx/utils/jsxParsing/parseJsx.js';\nimport { parseStrings } from '../jsx/utils/parseStringFunction.js';\nimport { logger } from '../../console/logger.js';\nimport { matchFiles } from '../../fs/matchFiles.js';\nimport { DEFAULT_SRC_PATTERNS } from '../../config/generateSettings.js';\nimport type {\n ParsingConfigOptions,\n GTParsingFlags,\n} from '../../types/parsing.js';\nimport { resolveAutoderive } from '../../types/parsing.js';\nimport { getPathsAndAliases } from '../jsx/utils/getPathsAndAliases.js';\nimport {\n GTLibrary,\n GT_LIBRARIES_UPSTREAM,\n REACT_LIBRARIES,\n ReactLibrary,\n} from '../../types/libraries.js';\nimport {\n calculateHashes,\n dedupeUpdates,\n linkDeriveUpdates,\n} from '../../extraction/postProcess.js';\nimport { warnDeprecatedTSugarPropsSync } from '../../console/index.js';\nimport {\n ensureTAndVarImported,\n autoInsertJsxComponents,\n} from '../jsx/utils/jsxParsing/autoInsertion.js';\nimport { INTERNAL_TRANSLATION_COMPONENT } from '../jsx/utils/constants.js';\nimport traverseModule from '@babel/traverse';\nconst traverse = traverseModule.default || traverseModule;\n\nexport async function createInlineUpdates(\n pkg: GTLibrary,\n validate: boolean,\n filePatterns: string[] | undefined,\n parsingFlags: GTParsingFlags,\n parsingOptions: ParsingConfigOptions\n): Promise<{ updates: Updates; errors: string[]; warnings: string[] }> {\n const updates: Updates = [];\n\n const errors: string[] = [];\n const warnings: Set<string> = new Set();\n // Deprecated $-prefixed <T> prop occurrences, consolidated into one warning\n const sugarPropLocations: string[] = [];\n\n const pkgs = getUpstreamPackages(pkg);\n\n const autoderive = resolveAutoderive(parsingFlags.autoderive);\n\n // Use the provided app directory or default to the current directory\n const files = matchFiles(process.cwd(), filePatterns || DEFAULT_SRC_PATTERNS);\n\n for (const file of files) {\n const code = await fs.promises.readFile(file, 'utf8');\n let ast;\n try {\n ast = parse(code, {\n sourceType: 'module',\n plugins: ['jsx', 'typescript'],\n });\n } catch (error) {\n logger.error(`Error parsing file ${file}: ${error}`);\n continue;\n }\n\n // First pass: collect imports and process translation functions\n const { importAliases, inlineTranslationPaths, translationComponentPaths } =\n getPathsAndAliases(ast, pkgs);\n\n // Process translation functions asynchronously\n for (const {\n localName: name,\n originalName,\n path,\n } of inlineTranslationPaths) {\n parseStrings(\n name,\n originalName,\n path,\n {\n parsingOptions,\n file,\n ignoreInlineMetadata: false,\n ignoreDynamicContent: false,\n ignoreInvalidIcu: false,\n ignoreInlineListContent: false,\n includeSourceCodeContext: parsingFlags.includeSourceCodeContext,\n ignoreTaggedTemplates: false,\n ignoreGlobalTaggedTemplates: false,\n // User configurable, otherwise default to AUTO\n autoderiveMethod: autoderive.strings ? 'AUTO' : 'DISABLED',\n },\n { updates, errors, warnings }\n );\n }\n\n // Parse <T> components — PASS 1: user-written T\n if (REACT_LIBRARIES.includes(pkg as ReactLibrary)) {\n for (const { localName, path } of translationComponentPaths) {\n parseTranslationComponent({\n originalName: localName,\n localName,\n path,\n updates,\n config: {\n importAliases,\n parsingOptions,\n pkgs,\n file,\n includeSourceCodeContext: parsingFlags.includeSourceCodeContext,\n autoderive: autoderive.jsx,\n },\n output: {\n errors,\n warnings,\n unwrappedExpressions: [],\n sugarPropLocations,\n },\n });\n }\n\n // PASS 2: Auto-inject GtInternalTranslateJsx and GtInternalVar and extract (flag-gated)\n if (parsingFlags.enableAutoJsxInjection) {\n // Add translation component names to importAliases so autoInsertJsxComponents\n // recognizes user T as hands-off (getPathsAndAliases separates them out)\n for (const { localName, originalName } of translationComponentPaths) {\n importAliases[localName] = originalName;\n }\n\n // Ensure GtInternalTranslateJsx and GtInternalVar are imported in the AST\n ensureTAndVarImported(\n ast,\n importAliases,\n parsingFlags.legacyGtReactImportSource\n );\n\n // Insert T/Var into the AST\n autoInsertJsxComponents(ast, importAliases);\n\n // Refresh scope to pick up new T references\n traverse(ast, {\n Program(programPath) {\n programPath.scope.crawl();\n },\n });\n\n // Re-collect with updated AST\n const refreshed = getPathsAndAliases(ast, pkgs);\n\n // Add translation component names to refreshed aliases so parseJsx\n // can recognize GtInternalTranslateJsx inside Derive for transparent unwrap\n for (const {\n localName: tLocalName,\n originalName: tOrigName,\n } of refreshed.translationComponentPaths) {\n refreshed.importAliases[tLocalName] = tOrigName;\n }\n\n // Extract only from auto-injected GtInternalTranslateJsx — never re-extract user T\n for (const {\n localName,\n path,\n originalName,\n } of refreshed.translationComponentPaths) {\n if (originalName !== INTERNAL_TRANSLATION_COMPONENT) continue;\n parseTranslationComponent({\n originalName: localName,\n localName,\n path,\n updates,\n config: {\n importAliases: refreshed.importAliases,\n parsingOptions,\n pkgs,\n file,\n includeSourceCodeContext: parsingFlags.includeSourceCodeContext,\n enableAutoJsxInjection: true,\n autoderive: autoderive.jsx,\n },\n output: {\n errors,\n warnings,\n unwrappedExpressions: [],\n },\n });\n }\n }\n }\n }\n\n // Warn once per scan about deprecated $-prefixed <T> props\n if (sugarPropLocations.length > 0) {\n warnings.add(warnDeprecatedTSugarPropsSync(sugarPropLocations));\n }\n\n // Post processing steps:\n await calculateHashes(updates);\n dedupeUpdates(updates);\n linkDeriveUpdates(updates);\n\n return { updates, errors, warnings: [...warnings] };\n}\n\n/**\n * Given a package name, return the upstream packages that it depends on\n * @param pkg - The package name\n * @returns The upstream packages that the package depends on\n */\nfunction getUpstreamPackages(pkg: GTLibrary): GTLibrary[] {\n return GT_LIBRARIES_UPSTREAM[pkg];\n}\n\nexport { dedupeUpdates as _test_dedupeUpdates };\n"],"mappings":";;;;;;;;;;;;;;;;AAiCA,MAAM,WAAW,eAAe,WAAW;AAE3C,eAAsB,oBACpB,KACA,UACA,cACA,cACA,gBACqE;CACrE,MAAM,UAAmB,EAAE;CAE3B,MAAM,SAAmB,EAAE;CAC3B,MAAM,2BAAwB,IAAI,KAAK;CAEvC,MAAM,qBAA+B,EAAE;CAEvC,MAAM,OAAO,oBAAoB,IAAI;CAErC,MAAM,aAAa,kBAAkB,aAAa,WAAW;CAG7D,MAAM,QAAQ,WAAW,QAAQ,KAAK,EAAE,gBAAgB,qBAAqB;AAE7E,MAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,OAAO,MAAM,GAAG,SAAS,SAAS,MAAM,OAAO;EACrD,IAAI;AACJ,MAAI;AACF,SAAM,MAAM,MAAM;IAChB,YAAY;IACZ,SAAS,CAAC,OAAO,aAAa;IAC/B,CAAC;WACK,OAAO;AACd,UAAO,MAAM,sBAAsB,KAAK,IAAI,QAAQ;AACpD;;EAIF,MAAM,EAAE,eAAe,wBAAwB,8BAC7C,mBAAmB,KAAK,KAAK;AAG/B,OAAK,MAAM,EACT,WAAW,MACX,cACA,UACG,uBACH,cACE,MACA,cACA,MACA;GACE;GACA;GACA,sBAAsB;GACtB,sBAAsB;GACtB,kBAAkB;GAClB,yBAAyB;GACzB,0BAA0B,aAAa;GACvC,uBAAuB;GACvB,6BAA6B;GAE7B,kBAAkB,WAAW,UAAU,SAAS;GACjD,EACD;GAAE;GAAS;GAAQ;GAAU,CAC9B;AAIH,MAAI,gBAAgB,SAAS,IAAoB,EAAE;AACjD,QAAK,MAAM,EAAE,WAAW,UAAU,0BAChC,2BAA0B;IACxB,cAAc;IACd;IACA;IACA;IACA,QAAQ;KACN;KACA;KACA;KACA;KACA,0BAA0B,aAAa;KACvC,YAAY,WAAW;KACxB;IACD,QAAQ;KACN;KACA;KACA,sBAAsB,EAAE;KACxB;KACD;IACF,CAAC;AAIJ,OAAI,aAAa,wBAAwB;AAGvC,SAAK,MAAM,EAAE,WAAW,kBAAkB,0BACxC,eAAc,aAAa;AAI7B,0BACE,KACA,eACA,aAAa,0BACd;AAGD,4BAAwB,KAAK,cAAc;AAG3C,aAAS,KAAK,EACZ,QAAQ,aAAa;AACnB,iBAAY,MAAM,OAAO;OAE5B,CAAC;IAGF,MAAM,YAAY,mBAAmB,KAAK,KAAK;AAI/C,SAAK,MAAM,EACT,WAAW,YACX,cAAc,eACX,UAAU,0BACb,WAAU,cAAc,cAAc;AAIxC,SAAK,MAAM,EACT,WACA,MACA,kBACG,UAAU,2BAA2B;AACxC,SAAI,iBAAA,yBAAiD;AACrD,+BAA0B;MACxB,cAAc;MACd;MACA;MACA;MACA,QAAQ;OACN,eAAe,UAAU;OACzB;OACA;OACA;OACA,0BAA0B,aAAa;OACvC,wBAAwB;OACxB,YAAY,WAAW;OACxB;MACD,QAAQ;OACN;OACA;OACA,sBAAsB,EAAE;OACzB;MACF,CAAC;;;;;AAOV,KAAI,mBAAmB,SAAS,EAC9B,UAAS,IAAI,8BAA8B,mBAAmB,CAAC;AAIjE,OAAM,gBAAgB,QAAQ;AAC9B,eAAc,QAAQ;AACtB,mBAAkB,QAAQ;AAE1B,QAAO;EAAE;EAAS;EAAQ,UAAU,CAAC,GAAG,SAAS;EAAE;;;;;;;AAQrD,SAAS,oBAAoB,KAA6B;AACxD,QAAO,sBAAsB"}
1
+ {"version":3,"file":"createInlineUpdates.js","names":[],"sources":["../../../src/react/parse/createInlineUpdates.ts"],"sourcesContent":["import { Updates } from '../../types/index.js';\n\nimport { logger } from '../../console/logger.js';\nimport { matchFiles } from '../../fs/matchFiles.js';\nimport { DEFAULT_SRC_PATTERNS } from '../../config/generateSettings.js';\nimport type {\n ParsingConfigOptions,\n GTParsingFlags,\n} from '../../types/parsing.js';\nimport { GTLibrary } from '../../types/libraries.js';\nimport {\n calculateHashes,\n dedupeUpdates,\n linkDeriveUpdates,\n} from '../../extraction/postProcess.js';\nimport { warnDeprecatedTSugarPropsSync } from '../../console/index.js';\nimport { type ScanContext, type ScanResult } from './scanFiles.js';\nimport {\n scanFilesInMainThread,\n scanFilesInThreads,\n scanThreads,\n} from './scanPool.js';\n\nexport async function createInlineUpdates(\n pkg: GTLibrary,\n validate: boolean,\n filePatterns: string[] | undefined,\n parsingFlags: GTParsingFlags,\n parsingOptions: ParsingConfigOptions\n): Promise<{ updates: Updates; errors: string[]; warnings: string[] }> {\n // Use the provided app directory or default to the current directory\n const files = matchFiles(process.cwd(), filePatterns || DEFAULT_SRC_PATTERNS);\n\n const context: ScanContext = { pkg, parsingFlags, parsingOptions };\n // In these modes what a file reached through an import yields depends on which caller reaches it first.\n const needsOneThread =\n parsingFlags.enableAutoJsxInjection ||\n parsingFlags.includeSourceCodeContext;\n const threads = needsOneThread ? 0 : scanThreads(files.length);\n const results =\n threads > 0\n ? await scanFilesInThreads(files, context, threads)\n : await scanFilesInMainThread(files, context);\n\n return collectScanResults(results);\n}\n\n/**\n * Joins the results of a scan, given in file order, into what one pass over\n * every file gives.\n *\n * A thread remembers the functions it resolved in other files, so it reports\n * what such a function yields once, at its first caller. Several threads each\n * report it. Everything is therefore kept once, at its first place in file\n * order: errors, warnings and locations here, updates by hash below.\n */\nexport async function collectScanResults(\n results: readonly ScanResult[]\n): Promise<{ updates: Updates; errors: string[]; warnings: string[] }> {\n const updates: Updates = [];\n const errors: Set<string> = new Set();\n const warnings: Set<string> = new Set();\n const sugarPropLocations: Set<string> = new Set();\n\n for (const result of results) {\n for (const message of result.parseErrors) logger.error(message);\n for (const update of result.updates) updates.push(update);\n for (const error of result.errors) errors.add(error);\n for (const warning of result.warnings) warnings.add(warning);\n for (const location of result.sugarPropLocations) {\n sugarPropLocations.add(location);\n }\n }\n\n // Warn once per scan about deprecated $-prefixed <T> props\n if (sugarPropLocations.size > 0) {\n warnings.add(warnDeprecatedTSugarPropsSync([...sugarPropLocations]));\n }\n\n // Post processing steps:\n await calculateHashes(updates);\n dedupeUpdates(updates);\n linkDeriveUpdates(updates);\n\n return { updates, errors: [...errors], warnings: [...warnings] };\n}\n\nexport { dedupeUpdates as _test_dedupeUpdates };\n"],"mappings":";;;;;;;AAuBA,eAAsB,oBACpB,KACA,UACA,cACA,cACA,gBACqE;CAErE,MAAM,QAAQ,WAAW,QAAQ,KAAK,EAAE,gBAAgB,qBAAqB;CAE7E,MAAM,UAAuB;EAAE;EAAK;EAAc;EAAgB;CAKlE,MAAM,UAFJ,aAAa,0BACb,aAAa,2BACkB,IAAI,YAAY,MAAM,OAAO;AAM9D,QAAO,mBAJL,UAAU,IACN,MAAM,mBAAmB,OAAO,SAAS,QAAQ,GACjD,MAAM,sBAAsB,OAAO,QAAQ,CAEf;;;;;;;;;;;AAYpC,eAAsB,mBACpB,SACqE;CACrE,MAAM,UAAmB,EAAE;CAC3B,MAAM,yBAAsB,IAAI,KAAK;CACrC,MAAM,2BAAwB,IAAI,KAAK;CACvC,MAAM,qCAAkC,IAAI,KAAK;AAEjD,MAAK,MAAM,UAAU,SAAS;AAC5B,OAAK,MAAM,WAAW,OAAO,YAAa,QAAO,MAAM,QAAQ;AAC/D,OAAK,MAAM,UAAU,OAAO,QAAS,SAAQ,KAAK,OAAO;AACzD,OAAK,MAAM,SAAS,OAAO,OAAQ,QAAO,IAAI,MAAM;AACpD,OAAK,MAAM,WAAW,OAAO,SAAU,UAAS,IAAI,QAAQ;AAC5D,OAAK,MAAM,YAAY,OAAO,mBAC5B,oBAAmB,IAAI,SAAS;;AAKpC,KAAI,mBAAmB,OAAO,EAC5B,UAAS,IAAI,8BAA8B,CAAC,GAAG,mBAAmB,CAAC,CAAC;AAItE,OAAM,gBAAgB,QAAQ;AAC9B,eAAc,QAAQ;AACtB,mBAAkB,QAAQ;AAE1B,QAAO;EAAE;EAAS,QAAQ,CAAC,GAAG,OAAO;EAAE,UAAU,CAAC,GAAG,SAAS;EAAE"}
@@ -0,0 +1,22 @@
1
+ import { Updates } from '../../types/index.js';
2
+ import type { ParsingConfigOptions, GTParsingFlags } from '../../types/parsing.js';
3
+ import { GTLibrary } from '../../types/libraries.js';
4
+ export type ScanContext = {
5
+ pkg: GTLibrary;
6
+ parsingFlags: GTParsingFlags;
7
+ parsingOptions: ParsingConfigOptions;
8
+ };
9
+ export type ScanResult = {
10
+ updates: Updates;
11
+ errors: string[];
12
+ warnings: string[];
13
+ /** Deprecated $-prefixed <T> prop occurrences, consolidated into one warning by the caller. */
14
+ sugarPropLocations: string[];
15
+ /** Messages for files that could not be parsed, logged by the caller. */
16
+ parseErrors: string[];
17
+ };
18
+ /**
19
+ * Extracts inline translatable content from `files`, in order. It holds no
20
+ * state between calls besides caches, so it runs the same in a worker thread.
21
+ */
22
+ export declare function scanFiles(files: readonly string[], { pkg, parsingFlags, parsingOptions }: ScanContext): ScanResult;
@@ -0,0 +1,125 @@
1
+ import { GT_LIBRARIES_UPSTREAM, REACT_LIBRARIES } from "../../types/libraries.js";
2
+ import "../jsx/utils/constants.js";
3
+ import { getPathsAndAliases, hasTranslationEntryPoints, mayHaveTranslationEntryPoints } from "../jsx/utils/getPathsAndAliases.js";
4
+ import { autoInsertJsxComponents, ensureTAndVarImported } from "../jsx/utils/jsxParsing/autoInsertion.js";
5
+ import { parseTranslationComponent } from "../jsx/utils/jsxParsing/parseJsx.js";
6
+ import { parseStrings } from "../jsx/utils/parseStringFunction.js";
7
+ import { resolveAutoderive } from "../../types/parsing.js";
8
+ import fs from "node:fs";
9
+ import { parse } from "@babel/parser";
10
+ import traverseModule from "@babel/traverse";
11
+ //#region src/react/parse/scanFiles.ts
12
+ const traverse = traverseModule.default || traverseModule;
13
+ /**
14
+ * Extracts inline translatable content from `files`, in order. It holds no
15
+ * state between calls besides caches, so it runs the same in a worker thread.
16
+ */
17
+ function scanFiles(files, { pkg, parsingFlags, parsingOptions }) {
18
+ const updates = [];
19
+ const errors = [];
20
+ const warnings = /* @__PURE__ */ new Set();
21
+ const sugarPropLocations = [];
22
+ const parseErrors = [];
23
+ const pkgs = GT_LIBRARIES_UPSTREAM[pkg];
24
+ const autoderive = resolveAutoderive(parsingFlags.autoderive);
25
+ const ignoreGlobalTaggedTemplates = false;
26
+ const skipUnrelatedFiles = !parsingFlags.enableAutoJsxInjection;
27
+ for (const file of files) {
28
+ const code = fs.readFileSync(file, "utf8");
29
+ if (skipUnrelatedFiles && !mayHaveTranslationEntryPoints(code, pkgs, true)) continue;
30
+ let ast;
31
+ try {
32
+ ast = parse(code, {
33
+ sourceType: "module",
34
+ plugins: ["jsx", "typescript"]
35
+ });
36
+ } catch (error) {
37
+ parseErrors.push(`Error parsing file ${file}: ${error}`);
38
+ continue;
39
+ }
40
+ if (skipUnrelatedFiles && !hasTranslationEntryPoints(ast, pkgs)) continue;
41
+ const { importAliases, inlineTranslationPaths, translationComponentPaths } = getPathsAndAliases(ast, pkgs);
42
+ for (const { localName: name, originalName, path } of inlineTranslationPaths) parseStrings(name, originalName, path, {
43
+ parsingOptions,
44
+ file,
45
+ ignoreInlineMetadata: false,
46
+ ignoreDynamicContent: false,
47
+ ignoreInvalidIcu: false,
48
+ ignoreInlineListContent: false,
49
+ includeSourceCodeContext: parsingFlags.includeSourceCodeContext,
50
+ ignoreTaggedTemplates: false,
51
+ ignoreGlobalTaggedTemplates,
52
+ autoderiveMethod: autoderive.strings ? "AUTO" : "DISABLED"
53
+ }, {
54
+ updates,
55
+ errors,
56
+ warnings
57
+ });
58
+ if (REACT_LIBRARIES.includes(pkg)) {
59
+ for (const { localName, path } of translationComponentPaths) parseTranslationComponent({
60
+ originalName: localName,
61
+ localName,
62
+ path,
63
+ updates,
64
+ config: {
65
+ importAliases,
66
+ parsingOptions,
67
+ pkgs,
68
+ file,
69
+ includeSourceCodeContext: parsingFlags.includeSourceCodeContext,
70
+ autoderive: autoderive.jsx
71
+ },
72
+ output: {
73
+ errors,
74
+ warnings,
75
+ unwrappedExpressions: [],
76
+ sugarPropLocations
77
+ }
78
+ });
79
+ if (parsingFlags.enableAutoJsxInjection) {
80
+ for (const { localName, originalName } of translationComponentPaths) importAliases[localName] = originalName;
81
+ ensureTAndVarImported(ast, importAliases, parsingFlags.legacyGtReactImportSource);
82
+ autoInsertJsxComponents(ast, importAliases);
83
+ traverse(ast, { Program(programPath) {
84
+ programPath.scope.crawl();
85
+ } });
86
+ const refreshed = getPathsAndAliases(ast, pkgs);
87
+ for (const { localName: tLocalName, originalName: tOrigName } of refreshed.translationComponentPaths) refreshed.importAliases[tLocalName] = tOrigName;
88
+ for (const { localName, path, originalName } of refreshed.translationComponentPaths) {
89
+ if (originalName !== "GtInternalTranslateJsx") continue;
90
+ parseTranslationComponent({
91
+ originalName: localName,
92
+ localName,
93
+ path,
94
+ updates,
95
+ config: {
96
+ importAliases: refreshed.importAliases,
97
+ parsingOptions,
98
+ pkgs,
99
+ file,
100
+ includeSourceCodeContext: parsingFlags.includeSourceCodeContext,
101
+ enableAutoJsxInjection: true,
102
+ autoderive: autoderive.jsx
103
+ },
104
+ output: {
105
+ errors,
106
+ warnings,
107
+ unwrappedExpressions: []
108
+ }
109
+ });
110
+ }
111
+ }
112
+ }
113
+ }
114
+ return {
115
+ updates,
116
+ errors,
117
+ warnings: [...warnings],
118
+ sugarPropLocations,
119
+ parseErrors
120
+ };
121
+ }
122
+ //#endregion
123
+ export { scanFiles };
124
+
125
+ //# sourceMappingURL=scanFiles.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scanFiles.js","names":[],"sources":["../../../src/react/parse/scanFiles.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { Updates } from '../../types/index.js';\n\nimport { parse } from '@babel/parser';\nimport { parseTranslationComponent } from '../jsx/utils/jsxParsing/parseJsx.js';\nimport { parseStrings } from '../jsx/utils/parseStringFunction.js';\nimport type {\n ParsingConfigOptions,\n GTParsingFlags,\n} from '../../types/parsing.js';\nimport { resolveAutoderive } from '../../types/parsing.js';\nimport {\n getPathsAndAliases,\n hasTranslationEntryPoints,\n mayHaveTranslationEntryPoints,\n} from '../jsx/utils/getPathsAndAliases.js';\nimport {\n GTLibrary,\n GT_LIBRARIES_UPSTREAM,\n REACT_LIBRARIES,\n ReactLibrary,\n} from '../../types/libraries.js';\nimport {\n ensureTAndVarImported,\n autoInsertJsxComponents,\n} from '../jsx/utils/jsxParsing/autoInsertion.js';\nimport { INTERNAL_TRANSLATION_COMPONENT } from '../jsx/utils/constants.js';\nimport traverseModule from '@babel/traverse';\nconst traverse = traverseModule.default || traverseModule;\n\nexport type ScanContext = {\n pkg: GTLibrary;\n parsingFlags: GTParsingFlags;\n parsingOptions: ParsingConfigOptions;\n};\n\nexport type ScanResult = {\n updates: Updates;\n errors: string[];\n warnings: string[];\n /** Deprecated $-prefixed <T> prop occurrences, consolidated into one warning by the caller. */\n sugarPropLocations: string[];\n /** Messages for files that could not be parsed, logged by the caller. */\n parseErrors: string[];\n};\n\n/**\n * Extracts inline translatable content from `files`, in order. It holds no\n * state between calls besides caches, so it runs the same in a worker thread.\n */\nexport function scanFiles(\n files: readonly string[],\n { pkg, parsingFlags, parsingOptions }: ScanContext\n): ScanResult {\n const updates: Updates = [];\n const errors: string[] = [];\n const warnings: Set<string> = new Set();\n const sugarPropLocations: string[] = [];\n const parseErrors: string[] = [];\n\n const pkgs = GT_LIBRARIES_UPSTREAM[pkg];\n\n const autoderive = resolveAutoderive(parsingFlags.autoderive);\n\n const ignoreGlobalTaggedTemplates = false;\n\n // Auto JSX injection extracts from files that reference no GT package.\n const skipUnrelatedFiles = !parsingFlags.enableAutoJsxInjection;\n\n for (const file of files) {\n const code = fs.readFileSync(file, 'utf8');\n if (\n skipUnrelatedFiles &&\n !mayHaveTranslationEntryPoints(code, pkgs, !ignoreGlobalTaggedTemplates)\n ) {\n continue;\n }\n let ast;\n try {\n ast = parse(code, {\n sourceType: 'module',\n plugins: ['jsx', 'typescript'],\n });\n } catch (error) {\n parseErrors.push(`Error parsing file ${file}: ${error}`);\n continue;\n }\n\n if (skipUnrelatedFiles && !hasTranslationEntryPoints(ast, pkgs)) continue;\n\n // First pass: collect imports and process translation functions\n const { importAliases, inlineTranslationPaths, translationComponentPaths } =\n getPathsAndAliases(ast, pkgs);\n\n // Process translation functions asynchronously\n for (const {\n localName: name,\n originalName,\n path,\n } of inlineTranslationPaths) {\n parseStrings(\n name,\n originalName,\n path,\n {\n parsingOptions,\n file,\n ignoreInlineMetadata: false,\n ignoreDynamicContent: false,\n ignoreInvalidIcu: false,\n ignoreInlineListContent: false,\n includeSourceCodeContext: parsingFlags.includeSourceCodeContext,\n ignoreTaggedTemplates: false,\n ignoreGlobalTaggedTemplates,\n // User configurable, otherwise default to AUTO\n autoderiveMethod: autoderive.strings ? 'AUTO' : 'DISABLED',\n },\n { updates, errors, warnings }\n );\n }\n\n // Parse <T> components — PASS 1: user-written T\n if (REACT_LIBRARIES.includes(pkg as ReactLibrary)) {\n for (const { localName, path } of translationComponentPaths) {\n parseTranslationComponent({\n originalName: localName,\n localName,\n path,\n updates,\n config: {\n importAliases,\n parsingOptions,\n pkgs,\n file,\n includeSourceCodeContext: parsingFlags.includeSourceCodeContext,\n autoderive: autoderive.jsx,\n },\n output: {\n errors,\n warnings,\n unwrappedExpressions: [],\n sugarPropLocations,\n },\n });\n }\n\n // PASS 2: Auto-inject GtInternalTranslateJsx and GtInternalVar and extract (flag-gated)\n if (parsingFlags.enableAutoJsxInjection) {\n // Add translation component names to importAliases so autoInsertJsxComponents\n // recognizes user T as hands-off (getPathsAndAliases separates them out)\n for (const { localName, originalName } of translationComponentPaths) {\n importAliases[localName] = originalName;\n }\n\n // Ensure GtInternalTranslateJsx and GtInternalVar are imported in the AST\n ensureTAndVarImported(\n ast,\n importAliases,\n parsingFlags.legacyGtReactImportSource\n );\n\n // Insert T/Var into the AST\n autoInsertJsxComponents(ast, importAliases);\n\n // Refresh scope to pick up new T references\n traverse(ast, {\n Program(programPath) {\n programPath.scope.crawl();\n },\n });\n\n // Re-collect with updated AST\n const refreshed = getPathsAndAliases(ast, pkgs);\n\n // Add translation component names to refreshed aliases so parseJsx\n // can recognize GtInternalTranslateJsx inside Derive for transparent unwrap\n for (const {\n localName: tLocalName,\n originalName: tOrigName,\n } of refreshed.translationComponentPaths) {\n refreshed.importAliases[tLocalName] = tOrigName;\n }\n\n // Extract only from auto-injected GtInternalTranslateJsx — never re-extract user T\n for (const {\n localName,\n path,\n originalName,\n } of refreshed.translationComponentPaths) {\n if (originalName !== INTERNAL_TRANSLATION_COMPONENT) continue;\n parseTranslationComponent({\n originalName: localName,\n localName,\n path,\n updates,\n config: {\n importAliases: refreshed.importAliases,\n parsingOptions,\n pkgs,\n file,\n includeSourceCodeContext: parsingFlags.includeSourceCodeContext,\n enableAutoJsxInjection: true,\n autoderive: autoderive.jsx,\n },\n output: {\n errors,\n warnings,\n unwrappedExpressions: [],\n },\n });\n }\n }\n }\n }\n\n return {\n updates,\n errors,\n warnings: [...warnings],\n sugarPropLocations,\n parseErrors,\n };\n}\n"],"mappings":";;;;;;;;;;;AA4BA,MAAM,WAAW,eAAe,WAAW;;;;;AAsB3C,SAAgB,UACd,OACA,EAAE,KAAK,cAAc,kBACT;CACZ,MAAM,UAAmB,EAAE;CAC3B,MAAM,SAAmB,EAAE;CAC3B,MAAM,2BAAwB,IAAI,KAAK;CACvC,MAAM,qBAA+B,EAAE;CACvC,MAAM,cAAwB,EAAE;CAEhC,MAAM,OAAO,sBAAsB;CAEnC,MAAM,aAAa,kBAAkB,aAAa,WAAW;CAE7D,MAAM,8BAA8B;CAGpC,MAAM,qBAAqB,CAAC,aAAa;AAEzC,MAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,OAAO,GAAG,aAAa,MAAM,OAAO;AAC1C,MACE,sBACA,CAAC,8BAA8B,MAAM,MAAM,KAA6B,CAExE;EAEF,IAAI;AACJ,MAAI;AACF,SAAM,MAAM,MAAM;IAChB,YAAY;IACZ,SAAS,CAAC,OAAO,aAAa;IAC/B,CAAC;WACK,OAAO;AACd,eAAY,KAAK,sBAAsB,KAAK,IAAI,QAAQ;AACxD;;AAGF,MAAI,sBAAsB,CAAC,0BAA0B,KAAK,KAAK,CAAE;EAGjE,MAAM,EAAE,eAAe,wBAAwB,8BAC7C,mBAAmB,KAAK,KAAK;AAG/B,OAAK,MAAM,EACT,WAAW,MACX,cACA,UACG,uBACH,cACE,MACA,cACA,MACA;GACE;GACA;GACA,sBAAsB;GACtB,sBAAsB;GACtB,kBAAkB;GAClB,yBAAyB;GACzB,0BAA0B,aAAa;GACvC,uBAAuB;GACvB;GAEA,kBAAkB,WAAW,UAAU,SAAS;GACjD,EACD;GAAE;GAAS;GAAQ;GAAU,CAC9B;AAIH,MAAI,gBAAgB,SAAS,IAAoB,EAAE;AACjD,QAAK,MAAM,EAAE,WAAW,UAAU,0BAChC,2BAA0B;IACxB,cAAc;IACd;IACA;IACA;IACA,QAAQ;KACN;KACA;KACA;KACA;KACA,0BAA0B,aAAa;KACvC,YAAY,WAAW;KACxB;IACD,QAAQ;KACN;KACA;KACA,sBAAsB,EAAE;KACxB;KACD;IACF,CAAC;AAIJ,OAAI,aAAa,wBAAwB;AAGvC,SAAK,MAAM,EAAE,WAAW,kBAAkB,0BACxC,eAAc,aAAa;AAI7B,0BACE,KACA,eACA,aAAa,0BACd;AAGD,4BAAwB,KAAK,cAAc;AAG3C,aAAS,KAAK,EACZ,QAAQ,aAAa;AACnB,iBAAY,MAAM,OAAO;OAE5B,CAAC;IAGF,MAAM,YAAY,mBAAmB,KAAK,KAAK;AAI/C,SAAK,MAAM,EACT,WAAW,YACX,cAAc,eACX,UAAU,0BACb,WAAU,cAAc,cAAc;AAIxC,SAAK,MAAM,EACT,WACA,MACA,kBACG,UAAU,2BAA2B;AACxC,SAAI,iBAAA,yBAAiD;AACrD,+BAA0B;MACxB,cAAc;MACd;MACA;MACA;MACA,QAAQ;OACN,eAAe,UAAU;OACzB;OACA;OACA;OACA,0BAA0B,aAAa;OACvC,wBAAwB;OACxB,YAAY,WAAW;OACxB;MACD,QAAQ;OACN;OACA;OACA,sBAAsB,EAAE;OACzB;MACF,CAAC;;;;;AAMV,QAAO;EACL;EACA;EACA,UAAU,CAAC,GAAG,SAAS;EACvB;EACA;EACD"}
@@ -0,0 +1,28 @@
1
+ import chalk from 'chalk';
2
+ import { type ScanContext, type ScanResult } from './scanFiles.js';
3
+ export type ScanWorkerData = {
4
+ context: ScanContext;
5
+ colorLevel: typeof chalk.level;
6
+ };
7
+ export type ScanWorkerResponse = {
8
+ result: ScanResult;
9
+ } | {
10
+ failed: true;
11
+ };
12
+ /**
13
+ * How many threads scan `fileCount` files: none for a small project, else up
14
+ * to `MAX_THREADS`, as many as the spare cores and half the memory hold.
15
+ * `GT_SCAN_THREADS` sets it, e.g. to 0 to scan in the main thread.
16
+ */
17
+ export declare function scanThreads(fileCount: number, workerUrl?: URL): number;
18
+ /**
19
+ * Scans `files` in the main thread and gives the results in file order, one
20
+ * per chunk, yielding to the event loop between chunks.
21
+ */
22
+ export declare function scanFilesInMainThread(files: readonly string[], context: ScanContext): Promise<ScanResult[]>;
23
+ /**
24
+ * Scans `files` in `threads` worker threads and gives the results in file
25
+ * order, one per chunk. A chunk whose thread fails, e.g. for want of memory,
26
+ * is scanned again in the main thread.
27
+ */
28
+ export declare function scanFilesInThreads(files: readonly string[], context: ScanContext, threads: number, workerUrl?: URL, heapMb?: number): Promise<ScanResult[]>;
@@ -0,0 +1,122 @@
1
+ import { scanFiles } from "./scanFiles.js";
2
+ import chalk from "chalk";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import { fileURLToPath } from "node:url";
6
+ import { Worker } from "node:worker_threads";
7
+ //#region src/react/parse/scanPool.ts
8
+ const WORKER_URL = new URL("./scanWorker.js", import.meta.url);
9
+ /** Files are scanned in chunks of this many. */
10
+ const CHUNK = 64;
11
+ /** A thread is worth starting for this many files: it takes longer to start than to scan fewer. */
12
+ const FILES_PER_THREAD = 1e3;
13
+ /** More threads than this add memory faster than they save time. */
14
+ const MAX_THREADS = 4;
15
+ const MB = 1024 * 1024;
16
+ /**
17
+ * The heap a scan thread may grow to, in MB. Without a limit a thread grows
18
+ * its heap toward the process default, mostly with garbage it has not
19
+ * collected yet.
20
+ */
21
+ const THREAD_HEAP_MB = 512;
22
+ /** What a thread is planned to take in all, about: its heap, the parser's buffers, native memory. */
23
+ const THREAD_MEMORY = (THREAD_HEAP_MB + 256) * MB;
24
+ /**
25
+ * How many threads scan `fileCount` files: none for a small project, else up
26
+ * to `MAX_THREADS`, as many as the spare cores and half the memory hold.
27
+ * `GT_SCAN_THREADS` sets it, e.g. to 0 to scan in the main thread.
28
+ */
29
+ function scanThreads(fileCount, workerUrl = WORKER_URL) {
30
+ if (!fs.existsSync(fileURLToPath(workerUrl))) return 0;
31
+ const configured = process.env.GT_SCAN_THREADS;
32
+ if (configured !== void 0 && configured !== "") {
33
+ const threads = Number(configured);
34
+ if (Number.isInteger(threads) && threads >= 0) return threads;
35
+ }
36
+ const threads = Math.min(MAX_THREADS, os.availableParallelism() - 1, Math.floor(availableMemory() / 2 / THREAD_MEMORY), Math.floor(fileCount / FILES_PER_THREAD));
37
+ return threads >= 2 ? threads : 0;
38
+ }
39
+ /** The memory the process may take, in bytes: the host's, or less in a container. */
40
+ function availableMemory() {
41
+ const total = os.totalmem();
42
+ const constrained = process.constrainedMemory();
43
+ return constrained ? Math.min(constrained, total) : total;
44
+ }
45
+ function chunksOf(files) {
46
+ const chunks = [];
47
+ for (let start = 0; start < files.length; start += CHUNK) chunks.push(files.slice(start, start + CHUNK));
48
+ return chunks;
49
+ }
50
+ /** Lets timers and I/O of the caller run: a scan is synchronous. */
51
+ const yieldToEventLoop = () => new Promise((resolve) => setImmediate(resolve));
52
+ /**
53
+ * Scans `files` in the main thread and gives the results in file order, one
54
+ * per chunk, yielding to the event loop between chunks.
55
+ */
56
+ async function scanFilesInMainThread(files, context) {
57
+ const results = [];
58
+ for (const chunk of chunksOf(files)) {
59
+ results.push(scanFiles(chunk, context));
60
+ await yieldToEventLoop();
61
+ }
62
+ return results;
63
+ }
64
+ /**
65
+ * Scans `files` in `threads` worker threads and gives the results in file
66
+ * order, one per chunk. A chunk whose thread fails, e.g. for want of memory,
67
+ * is scanned again in the main thread.
68
+ */
69
+ async function scanFilesInThreads(files, context, threads, workerUrl = WORKER_URL, heapMb = THREAD_HEAP_MB) {
70
+ const chunks = chunksOf(files);
71
+ const results = [];
72
+ const workerData = {
73
+ context,
74
+ colorLevel: chalk.level
75
+ };
76
+ let next = 0;
77
+ const runThread = () => new Promise((resolve) => {
78
+ let worker;
79
+ try {
80
+ worker = new Worker(workerUrl, {
81
+ workerData,
82
+ resourceLimits: { maxOldGenerationSizeMb: heapMb }
83
+ });
84
+ } catch {
85
+ resolve();
86
+ return;
87
+ }
88
+ let current;
89
+ const sendNext = () => {
90
+ if (next >= chunks.length) {
91
+ current = void 0;
92
+ worker.terminate();
93
+ return;
94
+ }
95
+ current = next++;
96
+ worker.postMessage(chunks[current]);
97
+ };
98
+ worker.on("message", (response) => {
99
+ if ("result" in response) results[current] = response.result;
100
+ sendNext();
101
+ });
102
+ worker.on("error", () => void 0);
103
+ worker.on("exit", () => resolve());
104
+ sendNext();
105
+ });
106
+ await Promise.all(Array.from({ length: threads }, runThread));
107
+ const scanned = [];
108
+ for (const [index, chunk] of chunks.entries()) {
109
+ const result = results[index];
110
+ if (result) {
111
+ scanned.push(result);
112
+ continue;
113
+ }
114
+ scanned.push(scanFiles(chunk, context));
115
+ await yieldToEventLoop();
116
+ }
117
+ return scanned;
118
+ }
119
+ //#endregion
120
+ export { scanFilesInMainThread, scanFilesInThreads, scanThreads };
121
+
122
+ //# sourceMappingURL=scanPool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scanPool.js","names":[],"sources":["../../../src/react/parse/scanPool.ts"],"sourcesContent":["import fs from 'node:fs';\nimport os from 'node:os';\nimport { fileURLToPath } from 'node:url';\nimport { Worker } from 'node:worker_threads';\nimport chalk from 'chalk';\nimport { scanFiles, type ScanContext, type ScanResult } from './scanFiles.js';\n\nexport type ScanWorkerData = {\n context: ScanContext;\n colorLevel: typeof chalk.level;\n};\n\nexport type ScanWorkerResponse = { result: ScanResult } | { failed: true };\n\nconst WORKER_URL = new URL('./scanWorker.js', import.meta.url);\n\n/** Files are scanned in chunks of this many. */\nconst CHUNK = 64;\n\n/** A thread is worth starting for this many files: it takes longer to start than to scan fewer. */\nconst FILES_PER_THREAD = 1000;\n\n/** More threads than this add memory faster than they save time. */\nconst MAX_THREADS = 4;\n\nconst MB = 1024 * 1024;\n\n/**\n * The heap a scan thread may grow to, in MB. Without a limit a thread grows\n * its heap toward the process default, mostly with garbage it has not\n * collected yet.\n */\nconst THREAD_HEAP_MB = 512;\n\n/** What a thread is planned to take in all, about: its heap, the parser's buffers, native memory. */\nconst THREAD_MEMORY = (THREAD_HEAP_MB + 256) * MB;\n\n/**\n * How many threads scan `fileCount` files: none for a small project, else up\n * to `MAX_THREADS`, as many as the spare cores and half the memory hold.\n * `GT_SCAN_THREADS` sets it, e.g. to 0 to scan in the main thread.\n */\nexport function scanThreads(\n fileCount: number,\n workerUrl: URL = WORKER_URL\n): number {\n // Run from the TypeScript sources or a standalone binary, there is no worker file to start.\n if (!fs.existsSync(fileURLToPath(workerUrl))) return 0;\n\n const configured = process.env.GT_SCAN_THREADS;\n if (configured !== undefined && configured !== '') {\n const threads = Number(configured);\n if (Number.isInteger(threads) && threads >= 0) return threads;\n }\n\n const threads = Math.min(\n MAX_THREADS,\n os.availableParallelism() - 1,\n Math.floor(availableMemory() / 2 / THREAD_MEMORY),\n Math.floor(fileCount / FILES_PER_THREAD)\n );\n\n return threads >= 2 ? threads : 0;\n}\n\n/** The memory the process may take, in bytes: the host's, or less in a container. */\nfunction availableMemory(): number {\n const total = os.totalmem();\n // 0 or undefined when there is no limit, or more than the host has.\n const constrained = process.constrainedMemory() as number | undefined;\n\n return constrained ? Math.min(constrained, total) : total;\n}\n\nfunction chunksOf(files: readonly string[]): string[][] {\n const chunks: string[][] = [];\n for (let start = 0; start < files.length; start += CHUNK) {\n chunks.push(files.slice(start, start + CHUNK));\n }\n\n return chunks;\n}\n\n/** Lets timers and I/O of the caller run: a scan is synchronous. */\nconst yieldToEventLoop = () =>\n new Promise<void>((resolve) => setImmediate(resolve));\n\n/**\n * Scans `files` in the main thread and gives the results in file order, one\n * per chunk, yielding to the event loop between chunks.\n */\nexport async function scanFilesInMainThread(\n files: readonly string[],\n context: ScanContext\n): Promise<ScanResult[]> {\n const results: ScanResult[] = [];\n for (const chunk of chunksOf(files)) {\n results.push(scanFiles(chunk, context));\n await yieldToEventLoop();\n }\n\n return results;\n}\n\n/**\n * Scans `files` in `threads` worker threads and gives the results in file\n * order, one per chunk. A chunk whose thread fails, e.g. for want of memory,\n * is scanned again in the main thread.\n */\nexport async function scanFilesInThreads(\n files: readonly string[],\n context: ScanContext,\n threads: number,\n workerUrl: URL = WORKER_URL,\n heapMb: number = THREAD_HEAP_MB\n): Promise<ScanResult[]> {\n const chunks = chunksOf(files);\n const results: (ScanResult | undefined)[] = [];\n const workerData: ScanWorkerData = { context, colorLevel: chalk.level };\n let next = 0;\n\n const runThread = () =>\n new Promise<void>((resolve) => {\n let worker: Worker;\n try {\n worker = new Worker(workerUrl, {\n workerData,\n resourceLimits: { maxOldGenerationSizeMb: heapMb },\n });\n } catch {\n // Threads cannot start here, e.g. under Node's permission model.\n resolve();\n return;\n }\n let current: number | undefined;\n\n const sendNext = () => {\n if (next >= chunks.length) {\n current = undefined;\n void worker.terminate();\n return;\n }\n current = next++;\n worker.postMessage(chunks[current]);\n };\n\n worker.on('message', (response: ScanWorkerResponse) => {\n if ('result' in response) results[current!] = response.result;\n sendNext();\n });\n // Its unfinished chunk stays without a result.\n worker.on('error', () => undefined);\n worker.on('exit', () => resolve());\n\n sendNext();\n });\n\n await Promise.all(Array.from({ length: threads }, runThread));\n\n const scanned: ScanResult[] = [];\n for (const [index, chunk] of chunks.entries()) {\n const result = results[index];\n if (result) {\n scanned.push(result);\n continue;\n }\n scanned.push(scanFiles(chunk, context));\n await yieldToEventLoop();\n }\n\n return scanned;\n}\n"],"mappings":";;;;;;;AAcA,MAAM,aAAa,IAAI,IAAI,mBAAmB,OAAO,KAAK,IAAI;;AAG9D,MAAM,QAAQ;;AAGd,MAAM,mBAAmB;;AAGzB,MAAM,cAAc;AAEpB,MAAM,KAAK,OAAO;;;;;;AAOlB,MAAM,iBAAiB;;AAGvB,MAAM,iBAAiB,iBAAiB,OAAO;;;;;;AAO/C,SAAgB,YACd,WACA,YAAiB,YACT;AAER,KAAI,CAAC,GAAG,WAAW,cAAc,UAAU,CAAC,CAAE,QAAO;CAErD,MAAM,aAAa,QAAQ,IAAI;AAC/B,KAAI,eAAe,KAAA,KAAa,eAAe,IAAI;EACjD,MAAM,UAAU,OAAO,WAAW;AAClC,MAAI,OAAO,UAAU,QAAQ,IAAI,WAAW,EAAG,QAAO;;CAGxD,MAAM,UAAU,KAAK,IACnB,aACA,GAAG,sBAAsB,GAAG,GAC5B,KAAK,MAAM,iBAAiB,GAAG,IAAI,cAAc,EACjD,KAAK,MAAM,YAAY,iBAAiB,CACzC;AAED,QAAO,WAAW,IAAI,UAAU;;;AAIlC,SAAS,kBAA0B;CACjC,MAAM,QAAQ,GAAG,UAAU;CAE3B,MAAM,cAAc,QAAQ,mBAAmB;AAE/C,QAAO,cAAc,KAAK,IAAI,aAAa,MAAM,GAAG;;AAGtD,SAAS,SAAS,OAAsC;CACtD,MAAM,SAAqB,EAAE;AAC7B,MAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS,MACjD,QAAO,KAAK,MAAM,MAAM,OAAO,QAAQ,MAAM,CAAC;AAGhD,QAAO;;;AAIT,MAAM,yBACJ,IAAI,SAAe,YAAY,aAAa,QAAQ,CAAC;;;;;AAMvD,eAAsB,sBACpB,OACA,SACuB;CACvB,MAAM,UAAwB,EAAE;AAChC,MAAK,MAAM,SAAS,SAAS,MAAM,EAAE;AACnC,UAAQ,KAAK,UAAU,OAAO,QAAQ,CAAC;AACvC,QAAM,kBAAkB;;AAG1B,QAAO;;;;;;;AAQT,eAAsB,mBACpB,OACA,SACA,SACA,YAAiB,YACjB,SAAiB,gBACM;CACvB,MAAM,SAAS,SAAS,MAAM;CAC9B,MAAM,UAAsC,EAAE;CAC9C,MAAM,aAA6B;EAAE;EAAS,YAAY,MAAM;EAAO;CACvE,IAAI,OAAO;CAEX,MAAM,kBACJ,IAAI,SAAe,YAAY;EAC7B,IAAI;AACJ,MAAI;AACF,YAAS,IAAI,OAAO,WAAW;IAC7B;IACA,gBAAgB,EAAE,wBAAwB,QAAQ;IACnD,CAAC;UACI;AAEN,YAAS;AACT;;EAEF,IAAI;EAEJ,MAAM,iBAAiB;AACrB,OAAI,QAAQ,OAAO,QAAQ;AACzB,cAAU,KAAA;AACL,WAAO,WAAW;AACvB;;AAEF,aAAU;AACV,UAAO,YAAY,OAAO,SAAS;;AAGrC,SAAO,GAAG,YAAY,aAAiC;AACrD,OAAI,YAAY,SAAU,SAAQ,WAAY,SAAS;AACvD,aAAU;IACV;AAEF,SAAO,GAAG,eAAe,KAAA,EAAU;AACnC,SAAO,GAAG,cAAc,SAAS,CAAC;AAElC,YAAU;GACV;AAEJ,OAAM,QAAQ,IAAI,MAAM,KAAK,EAAE,QAAQ,SAAS,EAAE,UAAU,CAAC;CAE7D,MAAM,UAAwB,EAAE;AAChC,MAAK,MAAM,CAAC,OAAO,UAAU,OAAO,SAAS,EAAE;EAC7C,MAAM,SAAS,QAAQ;AACvB,MAAI,QAAQ;AACV,WAAQ,KAAK,OAAO;AACpB;;AAEF,UAAQ,KAAK,UAAU,OAAO,QAAQ,CAAC;AACvC,QAAM,kBAAkB;;AAG1B,QAAO"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,19 @@
1
+ import { scanFiles } from "./scanFiles.js";
2
+ import chalk from "chalk";
3
+ import { parentPort, workerData } from "node:worker_threads";
4
+ //#region src/react/parse/scanWorker.ts
5
+ const { context, colorLevel } = workerData;
6
+ chalk.level = colorLevel;
7
+ parentPort.on("message", (files) => {
8
+ let response;
9
+ try {
10
+ response = { result: scanFiles(files, context) };
11
+ } catch {
12
+ response = { failed: true };
13
+ }
14
+ parentPort.postMessage(response);
15
+ });
16
+ //#endregion
17
+ export {};
18
+
19
+ //# sourceMappingURL=scanWorker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scanWorker.js","names":[],"sources":["../../../src/react/parse/scanWorker.ts"],"sourcesContent":["import { parentPort, workerData } from 'node:worker_threads';\nimport chalk from 'chalk';\nimport { scanFiles } from './scanFiles.js';\nimport type { ScanWorkerData, ScanWorkerResponse } from './scanPool.js';\n\nconst { context, colorLevel } = workerData as ScanWorkerData;\n\n// A thread has no terminal to detect colors from, and messages are compared with the main thread's.\nchalk.level = colorLevel;\n\nparentPort!.on('message', (files: string[]) => {\n let response: ScanWorkerResponse;\n try {\n response = { result: scanFiles(files, context) };\n } catch {\n response = { failed: true };\n }\n parentPort!.postMessage(response);\n});\n"],"mappings":";;;;AAKA,MAAM,EAAE,SAAS,eAAe;AAGhC,MAAM,QAAQ;AAEd,WAAY,GAAG,YAAY,UAAoB;CAC7C,IAAI;AACJ,KAAI;AACF,aAAW,EAAE,QAAQ,UAAU,OAAO,QAAQ,EAAE;SAC1C;AACN,aAAW,EAAE,QAAQ,MAAM;;AAE7B,YAAY,YAAY,SAAS;EACjC"}
@@ -1,9 +1,9 @@
1
1
  import "../../types/libraries.js";
2
2
  import { getRelativePath } from "../../fs/findFilepath.js";
3
3
  import { isMeaningful } from "../jsx/evaluateJsx.js";
4
- import { createImports, generateImportMap } from "../jsx/utils/parseAst.js";
5
4
  import { matchFiles } from "../../fs/matchFiles.js";
6
5
  import { DEFAULT_SRC_PATTERNS } from "../../config/generateSettings.js";
6
+ import { createImports, generateImportMap } from "../jsx/utils/parseAst.js";
7
7
  import { handleJsxElement } from "../jsx/wrapJsx.js";
8
8
  import path from "node:path";
9
9
  import fs from "node:fs";
@@ -5,7 +5,7 @@ import { createUpdates } from "./parse.js";
5
5
  import chalk from "chalk";
6
6
  //#region src/translation/stage.ts
7
7
  async function aggregateInlineTranslations(options, settings, library) {
8
- if (!options.dictionary) options.dictionary = findFilepath([
8
+ const dictionary = options.dictionary || settings.dictionary || findFilepath([
9
9
  "./dictionary.js",
10
10
  "./src/dictionary.js",
11
11
  "./dictionary.json",
@@ -13,7 +13,7 @@ async function aggregateInlineTranslations(options, settings, library) {
13
13
  "./dictionary.ts",
14
14
  "./src/dictionary.ts"
15
15
  ]);
16
- const { updates, errors, warnings } = await createUpdates(options, settings.src, options.dictionary, library, false, settings.files.gtJson.parsingFlags, settings.parsingOptions);
16
+ const { updates, errors, warnings } = await createUpdates(options, settings.src, dictionary, library, false, settings.files.gtJson.parsingFlags, settings.parsingOptions);
17
17
  if (warnings.length > 0) logger.warn(chalk.yellow(`CLI tool encountered ${warnings.length} warnings while scanning for translatable content.\n` + warnings.map((warning) => chalk.yellow("• Warning: ") + chalk.white(warning)).join("\n")));
18
18
  if (errors.length > 0) if (options.ignoreErrors) logger.warn(chalk.yellow(`Warning: CLI tool encountered ${errors.length} syntax errors while scanning for translatable content. These components will not be translated.\n` + errors.map((error) => chalk.yellow("• ") + chalk.white(error) + "\n").join("")));
19
19
  else logErrorAndExit(chalk.red(`Error: CLI tool encountered ${errors.length} syntax errors while scanning for translatable content. ${chalk.gray("To ignore these errors, re-run with --ignore-errors")}\n` + errors.map((error) => chalk.red("• ") + chalk.white(error) + "\n").join("")));
@@ -1 +1 @@
1
- {"version":3,"file":"stage.js","names":[],"sources":["../../src/translation/stage.ts"],"sourcesContent":["import { logErrorAndExit } from '../console/logging.js';\nimport chalk from 'chalk';\n\nimport findFilepath from '../fs/findFilepath.js';\nimport { Settings, TranslateFlags, Updates } from '../types/index.js';\nimport { logger } from '../console/logger.js';\n\nimport { createUpdates } from './parse.js';\nimport { InlineLibrary } from '../types/libraries.js';\n\nexport async function aggregateInlineTranslations(\n options: TranslateFlags,\n settings: Settings,\n library: InlineLibrary\n): Promise<Updates> {\n if (!options.dictionary) {\n options.dictionary = findFilepath([\n './dictionary.js',\n './src/dictionary.js',\n './dictionary.json',\n './src/dictionary.json',\n './dictionary.ts',\n './src/dictionary.ts',\n ]);\n }\n\n // ---- CREATING UPDATES ---- //\n const { updates, errors, warnings } = await createUpdates(\n options,\n settings.src,\n options.dictionary,\n library,\n false,\n settings.files.gtJson.parsingFlags,\n settings.parsingOptions\n );\n\n if (warnings.length > 0) {\n logger.warn(\n chalk.yellow(\n `CLI tool encountered ${warnings.length} warnings while scanning for translatable content.\\n` +\n warnings\n .map(\n (warning) => chalk.yellow('• Warning: ') + chalk.white(warning)\n )\n .join('\\n')\n )\n );\n }\n\n if (errors.length > 0) {\n if (options.ignoreErrors) {\n logger.warn(\n chalk.yellow(\n `Warning: CLI tool encountered ${errors.length} syntax errors while scanning for translatable content. These components will not be translated.\\n` +\n errors\n .map((error) => chalk.yellow('• ') + chalk.white(error) + '\\n')\n .join('')\n )\n );\n } else {\n logErrorAndExit(\n chalk.red(\n `Error: CLI tool encountered ${errors.length} syntax errors while scanning for translatable content. ${chalk.gray('To ignore these errors, re-run with --ignore-errors')}\\n` +\n errors\n .map((error) => chalk.red('• ') + chalk.white(error) + '\\n')\n .join('')\n )\n );\n }\n }\n\n if (updates.length == 0) {\n logger.error(\n chalk.red(\n `No inline content or dictionaries were found for ${chalk.green(\n library\n )}. Are you sure you're running this command in the right directory?`\n )\n );\n return updates;\n }\n\n return updates;\n}\n"],"mappings":";;;;;;AAUA,eAAsB,4BACpB,SACA,UACA,SACkB;AAClB,KAAI,CAAC,QAAQ,WACX,SAAQ,aAAa,aAAa;EAChC;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;CAIJ,MAAM,EAAE,SAAS,QAAQ,aAAa,MAAM,cAC1C,SACA,SAAS,KACT,QAAQ,YACR,SACA,OACA,SAAS,MAAM,OAAO,cACtB,SAAS,eACV;AAED,KAAI,SAAS,SAAS,EACpB,QAAO,KACL,MAAM,OACJ,wBAAwB,SAAS,OAAO,wDACtC,SACG,KACE,YAAY,MAAM,OAAO,cAAc,GAAG,MAAM,MAAM,QAAQ,CAChE,CACA,KAAK,KAAK,CAChB,CACF;AAGH,KAAI,OAAO,SAAS,EAClB,KAAI,QAAQ,aACV,QAAO,KACL,MAAM,OACJ,iCAAiC,OAAO,OAAO,sGAC7C,OACG,KAAK,UAAU,MAAM,OAAO,KAAK,GAAG,MAAM,MAAM,MAAM,GAAG,KAAK,CAC9D,KAAK,GAAG,CACd,CACF;KAED,iBACE,MAAM,IACJ,+BAA+B,OAAO,OAAO,0DAA0D,MAAM,KAAK,sDAAsD,CAAC,MACvK,OACG,KAAK,UAAU,MAAM,IAAI,KAAK,GAAG,MAAM,MAAM,MAAM,GAAG,KAAK,CAC3D,KAAK,GAAG,CACd,CACF;AAIL,KAAI,QAAQ,UAAU,GAAG;AACvB,SAAO,MACL,MAAM,IACJ,oDAAoD,MAAM,MACxD,QACD,CAAC,oEACH,CACF;AACD,SAAO;;AAGT,QAAO"}
1
+ {"version":3,"file":"stage.js","names":[],"sources":["../../src/translation/stage.ts"],"sourcesContent":["import { logErrorAndExit } from '../console/logging.js';\nimport chalk from 'chalk';\n\nimport findFilepath from '../fs/findFilepath.js';\nimport { Settings, TranslateFlags, Updates } from '../types/index.js';\nimport { logger } from '../console/logger.js';\n\nimport { createUpdates } from './parse.js';\nimport { InlineLibrary } from '../types/libraries.js';\n\nexport async function aggregateInlineTranslations(\n options: TranslateFlags,\n settings: Settings,\n library: InlineLibrary\n): Promise<Updates> {\n // Resolve the dictionary path: --dictionary flag, then the `dictionary`\n // key from gt.config.json, then auto-detection (mirrors `gt validate`).\n const dictionary =\n options.dictionary ||\n settings.dictionary ||\n findFilepath([\n './dictionary.js',\n './src/dictionary.js',\n './dictionary.json',\n './src/dictionary.json',\n './dictionary.ts',\n './src/dictionary.ts',\n ]);\n\n // ---- CREATING UPDATES ---- //\n const { updates, errors, warnings } = await createUpdates(\n options,\n settings.src,\n dictionary,\n library,\n false,\n settings.files.gtJson.parsingFlags,\n settings.parsingOptions\n );\n\n if (warnings.length > 0) {\n logger.warn(\n chalk.yellow(\n `CLI tool encountered ${warnings.length} warnings while scanning for translatable content.\\n` +\n warnings\n .map(\n (warning) => chalk.yellow('• Warning: ') + chalk.white(warning)\n )\n .join('\\n')\n )\n );\n }\n\n if (errors.length > 0) {\n if (options.ignoreErrors) {\n logger.warn(\n chalk.yellow(\n `Warning: CLI tool encountered ${errors.length} syntax errors while scanning for translatable content. These components will not be translated.\\n` +\n errors\n .map((error) => chalk.yellow('• ') + chalk.white(error) + '\\n')\n .join('')\n )\n );\n } else {\n logErrorAndExit(\n chalk.red(\n `Error: CLI tool encountered ${errors.length} syntax errors while scanning for translatable content. ${chalk.gray('To ignore these errors, re-run with --ignore-errors')}\\n` +\n errors\n .map((error) => chalk.red('• ') + chalk.white(error) + '\\n')\n .join('')\n )\n );\n }\n }\n\n if (updates.length == 0) {\n logger.error(\n chalk.red(\n `No inline content or dictionaries were found for ${chalk.green(\n library\n )}. Are you sure you're running this command in the right directory?`\n )\n );\n return updates;\n }\n\n return updates;\n}\n"],"mappings":";;;;;;AAUA,eAAsB,4BACpB,SACA,UACA,SACkB;CAGlB,MAAM,aACJ,QAAQ,cACR,SAAS,cACT,aAAa;EACX;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;CAGJ,MAAM,EAAE,SAAS,QAAQ,aAAa,MAAM,cAC1C,SACA,SAAS,KACT,YACA,SACA,OACA,SAAS,MAAM,OAAO,cACtB,SAAS,eACV;AAED,KAAI,SAAS,SAAS,EACpB,QAAO,KACL,MAAM,OACJ,wBAAwB,SAAS,OAAO,wDACtC,SACG,KACE,YAAY,MAAM,OAAO,cAAc,GAAG,MAAM,MAAM,QAAQ,CAChE,CACA,KAAK,KAAK,CAChB,CACF;AAGH,KAAI,OAAO,SAAS,EAClB,KAAI,QAAQ,aACV,QAAO,KACL,MAAM,OACJ,iCAAiC,OAAO,OAAO,sGAC7C,OACG,KAAK,UAAU,MAAM,OAAO,KAAK,GAAG,MAAM,MAAM,MAAM,GAAG,KAAK,CAC9D,KAAK,GAAG,CACd,CACF;KAED,iBACE,MAAM,IACJ,+BAA+B,OAAO,OAAO,0DAA0D,MAAM,KAAK,sDAAsD,CAAC,MACvK,OACG,KAAK,UAAU,MAAM,IAAI,KAAK,GAAG,MAAM,MAAM,MAAM,GAAG,KAAK,CAC3D,KAAK,GAAG,CACd,CACF;AAIL,KAAI,QAAQ,UAAU,GAAG;AACvB,SAAO,MACL,MAAM,IACJ,oDAAoD,MAAM,MACxD,QACD,CAAC,oEACH,CACF;AACD,SAAO;;AAGT,QAAO"}
@@ -192,6 +192,7 @@ export type Settings = {
192
192
  projectId?: string;
193
193
  defaultLocale: string;
194
194
  locales: string[];
195
+ dictionary?: string;
195
196
  customMapping?: CustomMapping;
196
197
  files: {
197
198
  resolvedPaths: ResolvedFiles;
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/types/index.ts"],"sourcesContent":["import type { CustomMapping } from '@generaltranslation/format/types';\nimport type { UserTokenProvider } from 'generaltranslation/api';\nimport type { ModelProvider } from 'generaltranslation/internal';\nimport type { FileFormat } from 'generaltranslation/types';\nimport { SUPPORTED_FILE_EXTENSIONS } from '../formats/files/supportedFiles.js';\nimport {\n ParsingConfigOptions,\n GTParsingFlags,\n ParsingFlagsFor,\n ParseFlagsByFileType,\n} from './parsing.js';\nimport { Libraries, InlineLibrary } from './libraries.js';\n\nexport type { Updates } from 'generaltranslation/types';\n\nexport type Options = {\n config: string;\n apiKey?: string;\n projectId?: string;\n versionId?: string;\n jsconfig?: string;\n dictionary?: string;\n src?: string[];\n defaultLocale?: string;\n locales?: string[];\n baseUrl: string;\n inline?: boolean;\n ignoreErrors: boolean;\n suppressWarnings: boolean;\n dryRun: boolean;\n timeout: number;\n force?: boolean;\n stageTranslations?: boolean;\n experimentalLocalizeStaticUrls?: boolean;\n experimentalHideDefaultLocale?: boolean;\n experimentalFlattenJsonFiles?: boolean;\n experimentalLocalizeStaticImports?: boolean;\n experimentalLocalizeRelativeAssets?: boolean;\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default';\n docsImportRewrites?: Array<{\n match: string;\n replace: string;\n }>;\n};\n\nexport type OpenApiConfig = {\n files: string[];\n translateFields?: string[];\n};\n\nexport type MintlifyOptions = {\n openapi?: OpenApiConfig;\n inferTitleFromFilename?: boolean;\n localizeRedirects?: boolean; // add localized redirects for pages renamed or removed in a translate run\n};\n\nexport type SharedFlags = {\n config?: string;\n apiKey?: string;\n projectId?: string;\n};\n\nexport type TranslateFlags = SharedFlags & {\n versionId?: string;\n jsconfig?: string;\n dictionary?: string;\n defaultLocale?: string;\n locales?: string[];\n ignoreErrors?: boolean;\n src?: string[];\n timeout: number;\n dryRun: boolean;\n saveLocal?: boolean;\n stageTranslations?: boolean;\n setupProject?: boolean; // if true, skip enqueue step\n publish?: boolean;\n force?: boolean;\n forceDownload?: boolean;\n tag?: string;\n message?: string;\n experimentalLocalizeStaticUrls?: boolean;\n experimentalHideDefaultLocale?: boolean;\n experimentalFlattenJsonFiles?: boolean;\n experimentalLocalizeStaticImports?: boolean;\n experimentalLocalizeRelativeAssets?: boolean;\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default';\n omitConfigIds?: boolean;\n excludeStaticUrls?: string[];\n excludeStaticImports?: string[];\n docsImportRewrites?: Array<{\n match: string;\n replace: string;\n }>;\n};\n\nexport type WrapOptions = {\n src?: string[];\n config: string;\n skipTs: boolean;\n disableIds: boolean;\n disableFormatting: boolean;\n addGTProvider: boolean;\n};\n\nexport type SetupOptions = {\n src?: string[];\n config: string;\n};\n\nexport type GenerateSourceOptions = {\n src?: string[];\n config: string;\n defaultLocale: string;\n dictionary?: string;\n jsconfig?: string;\n inline?: boolean;\n ignoreErrors: boolean;\n suppressWarnings: boolean;\n};\n\nexport type Framework =\n | typeof Libraries.GT_NEXT\n | typeof Libraries.GT_REACT\n | typeof Libraries.GT_REACT_NATIVE\n | typeof Libraries.GT_TANSTACK_START;\n\nexport const SUPPORTED_REACT_FRAMEWORKS = [\n 'next-app',\n 'next-pages',\n 'vite',\n 'gatsby',\n 'react',\n 'redwood',\n 'tanstack-start',\n 'react-router',\n] as const;\n\nexport type FrameworkObject =\n | {\n name: 'mintlify';\n type?: undefined;\n }\n | {\n name: (typeof SUPPORTED_REACT_FRAMEWORKS)[number];\n type: 'react';\n };\nexport type ReactFrameworkObject = Extract<FrameworkObject, { type: 'react' }>;\n/** Detected so setup can stop; the wizard cannot set React Native up yet. */\nexport type ReactNativeFrameworkObject = {\n name: 'react-native';\n type: 'react-native';\n};\n\nexport type FrameworkType = FrameworkObject['type'];\n\nexport type SupportedFrameworks = FrameworkObject['name'];\nexport type SupportedReactFrameworks = Extract<\n FrameworkObject,\n { type: 'react' }\n>['name'];\n\nexport type SupportedLibraries =\n | InlineLibrary\n | 'next-intl'\n | 'react-i18next'\n | 'next-i18next'\n | 'i18next'\n | 'i18next-icu'\n | 'base';\n\nexport interface ContentScanner {\n scanForContent(\n options: WrapOptions,\n framework: Framework\n ): Promise<{\n errors: string[];\n filesUpdated: string[];\n warnings: string[];\n }>;\n}\n\n// Create a type based on the supported file extensions\nexport type SupportedFileExtension = (typeof SUPPORTED_FILE_EXTENSIONS)[number];\n\n// Update ResolvedFiles to use the dynamic keys\nexport type ResolvedFiles = {\n [K in SupportedFileExtension]?: string[];\n} & {\n gt?: string; // Output glob: /path/[locale].json\n};\n\nexport type TransformOption = {\n match?: string; // regex to match strings, supports capture groups\n replace: string; // string or regex pattern to replace the match with\n // Special placeholders:\n // -> if used in the match string, they will be replaced with the corresponding default locale property value\n // -> if used in the replace string, they will be replaced with the corresponding target locale property value\n // {locale} -> will be replaced with the locale code\n // And any other property from getLocaleProperties()\n};\n\nexport type TransformFiles = {\n [K in SupportedFileExtension]?: TransformOption | string | TransformOption[]; // if a string, only transform the file name\n};\n\nexport type TransformFormats = {\n [K in SupportedFileExtension]?: FileFormat;\n};\n\n// Include patterns can be plain strings or objects with a publish flag\nexport type IncludePattern = string | { pattern: string; publish?: boolean };\n\n// Review requirement for matched files: a boolean applies to all files of the\n// type; the object form opts path groups in/out with globs. exclude wins over\n// include; files matching neither inherit the top-level requiresReview default.\nexport type RequiresReviewConfig =\n | boolean\n | {\n include?: string[];\n exclude?: string[];\n };\n\n// Update FilesOptions to fix the error\nexport type FilesOptions = {\n [K in SupportedFileExtension]?: {\n include: IncludePattern[];\n exclude?: string[];\n transform?: string | TransformOption | TransformOption[];\n transformationFormat?: FileFormat;\n parsingFlags?: ParsingFlagsFor<K>; // Flags for parsing inline content\n requiresReview?: RequiresReviewConfig; // Whether translated versions of matched files require approval before use\n };\n} & {\n gt?: {\n output: string; // Output glob: /path/[locale].json\n publish?: boolean; // if true, publish gtjson translations to the CDN\n parsingFlags?: Partial<GTParsingFlags>; // Flags for parsing inline content\n /**\n * @deprecated\n * use `files.gt.parsingFlags.includeSourceCodeContext` instead\n */\n includeSourceCodeContext?: boolean; // Include surrounding source code lines as context for translations (default: false)\n };\n};\n\n// Shared settings between all API-related commands\nexport type FontsConfig = {\n include: string[]; // globs of .ttf/.otf files\n exclude?: string[];\n};\n\nexport type Settings = {\n config: string;\n configDirectory: string;\n baseUrl: string;\n dashboardUrl: string;\n apiKey?: string;\n userTokenProvider?: UserTokenProvider;\n projectId?: string;\n defaultLocale: string;\n locales: string[];\n customMapping?: CustomMapping;\n files: {\n resolvedPaths: ResolvedFiles; // Absolute resolved paths for the default locale\n placeholderPaths: ResolvedFiles; // Absolute placeholder paths for all locales containing [locale]\n transformPaths: TransformFiles; // Absolute transform paths for all locales containing [locale]\n transformFormats: TransformFormats; // Output file format transforms keyed by config file type\n publishPaths: Set<string>; // Absolute paths explicitly opted IN to publishing\n unpublishPaths: Set<string>; // Absolute paths explicitly opted OUT of publishing\n requiresReviewPaths: Set<string>; // Absolute paths whose effective requiresReview policy is true\n parsingFlags: ParseFlagsByFileType;\n gtJson: {\n publish?: boolean; // if true, publish gtjson translations to the CDN\n parsingFlags: GTParsingFlags; // Flags for parsing inline content\n /**\n * @deprecated\n * use {@link files.gt.GTParsingFlags.parsingFlags.includeSourceCodeContext} instead\n */\n includeSourceCodeContext?: boolean; // Include surrounding source code lines as context for translations (default: false)\n };\n };\n stageTranslations: boolean; // if true, always stage the project during translate command\n requiresReview?: boolean; // top-level default: translated artifacts require approval before the client uses them\n publish?: boolean; // if true, publish the translations to the CDN; undefined means no global publish intent\n omitConfigIds?: boolean; // if true, do not write _versionId or _branchId to gt.config.json\n _versionId?: string; // internal use only\n _branchId?: string; // internal use only\n version?: string; // for specifying a custom version id to use. Should be unique\n description?: string;\n src?: string[]; // list of glob patterns for source file scanning\n fonts?: FontsConfig; // fonts to sync to the API before translating\n framework?: SupportedFrameworks;\n options?: AdditionalOptions;\n modelProvider?: ModelProvider;\n tag?: string;\n tagMessage?: string;\n parsingOptions: ParsingConfigOptions;\n branchOptions: BranchOptions;\n // Optional shared static assets config\n sharedStaticAssets?: SharedStaticAssetsConfig;\n};\n\nexport type StaticLocalizationFiles = Pick<\n Settings['files'],\n 'placeholderPaths' | 'resolvedPaths'\n> &\n Partial<Pick<Settings['files'], 'transformPaths' | 'transformFormats'>>;\n\nexport type StaticLocalizationSettings = Pick<\n Settings,\n 'defaultLocale' | 'locales' | 'options'\n> & {\n files?: StaticLocalizationFiles | null;\n};\n\nexport type BranchOptions = {\n currentBranch?: string;\n autoDetectBranches?: boolean;\n remoteName: string; // default 'origin'. The name of the remote to use for auto-detection.\n enabled: boolean; // if true, branching is enabled for the project\n};\n\nexport type AdditionalOptions = {\n // Optional schema to follow while translating JSON files\n jsonSchema?: {\n [fileGlob: string]: JsonSchema;\n };\n // Optional schema to follow while translating YAML files\n yamlSchema?: {\n [fileGlob: string]: YamlSchema;\n };\n // Skip pre-parse validation checks for specific file types\n skipFileValidation?: {\n json?: boolean;\n yaml?: boolean;\n mdx?: boolean;\n };\n // Optional Mintlify-specific options container\n mintlify?: MintlifyOptions;\n docsUrlPattern?: string | string[]; // eg /docs/[locale] or /[locale] for localizing static urls in markdown files; a list localizes several URL prefixes\n docsImportPattern?: string; // eg /docs/[locale]/foo.md or /[locale]/foo.md for localizing static imports in markdown files\n excludeStaticUrls?: string[]; // A list of file globs to include for static url localization\n excludeStaticImports?: string[]; // A list of file globs to include for static import localization\n docsHideDefaultLocaleImport?: boolean; // if true, hide the default locale in the import path\n copyFiles?: string[]; // array of files to copy to the target locale\n experimentalClearLocaleDirs?: boolean; // if true, clear locale directories before writing translations (default: false)\n clearLocaleDirsExclude?: string[]; // array of glob patterns with [locale] or [locales] placeholder to exclude from clearing (e.g., \"./snippets/[locale]/preserved/**\" or \"./[locales]/static/**\")\n experimentalLocalizeStaticImports?: boolean; // Inserts locale in static import paths in md/mdx files\n // Inserts locale in static url paths in md/mdx files and adds anchor IDs to\n // preserve navigation. The object form enables it with extra behavior.\n experimentalLocalizeStaticUrls?:\n | boolean\n | {\n // Keep links to source pages that have no translation\n skipUntranslatedPages?: boolean;\n // Extra JSX attribute names or globs to localize\n attributes?: string[];\n };\n experimentalLocalizeRelativeAssets?: boolean; // Rewrites relative asset URLs in translated md/mdx files to valid paths\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default'; // Format for anchor IDs: 'mintlify' for Mintlify's native {#id} on every heading, 'default' or undefined for escaped inline \\{#id\\}. Can run independently of static url localization\n experimentalHideDefaultLocale?: boolean; // Hides the default locale in the import path\n experimentalFlattenJsonFiles?: boolean; // Flattens JSON files into a single file\n baseDomain?: string; // The base http:// url where the project is hosted\n docsImportRewrites?: Array<{\n match: string; // prefix to match, e.g. '@site/docs'\n replace: string; // replacement prefix, can include [locale] or [defaultLocale]\n }>;\n experimentalCanonicalLocaleKeys?: boolean; // For composite JSON schemas with locale keys, force canonical locale even when alias provided\n saveLocal?: boolean; // if true, detect and save local edits to translated output before enqueuing translations (default: false)\n};\n\nexport type SharedStaticAssetsConfig = {\n include: string | string[];\n outDir?: string;\n publicPath?: string;\n mirrorToLocales?: boolean;\n};\n\nexport type StructuralTransform = {\n sourcePointer: string; // e.g., \"/msg\"\n destinationPointer: string; // e.g., \"/translations/en\"\n};\n\nexport type JsonSchema = {\n preset?: 'mintlify' | 'mintlify-hide-default' | 'openapi';\n structuralTransform?: StructuralTransform[];\n\n // when true, resolve $ref entries in this file before processing\n resolveRefs?: boolean;\n\n // exactly 1 of include or composite must be provided; not both\n\n // specify include if file is not composite\n // multiple target JSONs will be created for each locale,\n // with the only differing content being the specified JSONPath values\n include?: string[]; // array of JSONPaths to include\n\n // specify composite if no new JSONs should be created\n composite?: {\n // The sourceObjectPath is a JSONPath to the array or object containing\n // content in the source and target locales\n // This value is denoted as the \"sourceObject\"\n // Array elements or object sub-elements are denoted as \"sourceItem\"\n [sourceObjectPath: string]: SourceObjectOptions;\n };\n};\n\nexport type YamlSchema = {\n preset?: 'mintlify' | 'openapi';\n include?: string[];\n transform?: TransformOptions;\n};\n\nexport type SourceObjectOptions = {\n type: 'array' | 'object'; // type of the sourceObject;\n // array if the sourceObject is an array\n // -> We will simply add duplicated sourceItems for each locale\n // object if the sourceObject is an object\n // -> We will duplicate the sourceItem for each locale and set the corresponding\n // key with the locale property\n // In both cases, we search the sourceObject for the key that matches the source locale\n\n // Below, relative JSONPaths are relative to the sourceItem root, NOT the sourceObject\n\n include: string[]; // array of relative JSONPaths to include in the translated JSON\n\n // if type is array, there must be a key property in the array element\n // corresponding value should be a locale code\n key?: string; // relative jsonPath to the key to use to distinguish between source and target locales\n // if type is object, the key is simply the JSON key for the sourceItem - this is unnecessary in this case\n\n localeProperty?: string; // specific locale property to use for the key for target locales, default 'code'\n // ex: code, name, nativeName, languageCode, languageName, etc. (values returned by getLocaleProperties)\n\n // optional config for transforming specific fields in the sourceItem\n // for example, helpful for handling urls with locale-specific paths\n transform?: TransformOptions;\n\n // optional list of top-level properties to remove from generated\n // non-default-locale entries (e.g. Mintlify's `default: true` flag on the\n // default language entry, which must not be cloned into other locales)\n omitProperties?: string[];\n\n // optional sorting behavior for array sourceObjects. When set to 'locale',\n // the array will be ordered to match the locales array provided to mergeJson\n // When set to 'localesAlphabetical', the default locale will be placed first\n // and the remaining locales will be ordered alphabetically by locale code\n experimentalSort?: 'locales' | 'localesAlphabetical';\n\n // when true, non-default keyed entries in this composite array are extracted\n // into separate files (using the key value as the directory name) and replaced\n // with $ref pointers. Keeps the source file compact.\n splitEntries?: boolean;\n};\n\nexport type TransformOptions = {\n // relative jsonPath to content to mutate\n [transformPath: string]: TransformOption;\n};\n"],"mappings":";AA8HA,MAAa,6BAA6B;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/types/index.ts"],"sourcesContent":["import type { CustomMapping } from '@generaltranslation/format/types';\nimport type { UserTokenProvider } from 'generaltranslation/api';\nimport type { ModelProvider } from 'generaltranslation/internal';\nimport type { FileFormat } from 'generaltranslation/types';\nimport { SUPPORTED_FILE_EXTENSIONS } from '../formats/files/supportedFiles.js';\nimport {\n ParsingConfigOptions,\n GTParsingFlags,\n ParsingFlagsFor,\n ParseFlagsByFileType,\n} from './parsing.js';\nimport { Libraries, InlineLibrary } from './libraries.js';\n\nexport type { Updates } from 'generaltranslation/types';\n\nexport type Options = {\n config: string;\n apiKey?: string;\n projectId?: string;\n versionId?: string;\n jsconfig?: string;\n dictionary?: string;\n src?: string[];\n defaultLocale?: string;\n locales?: string[];\n baseUrl: string;\n inline?: boolean;\n ignoreErrors: boolean;\n suppressWarnings: boolean;\n dryRun: boolean;\n timeout: number;\n force?: boolean;\n stageTranslations?: boolean;\n experimentalLocalizeStaticUrls?: boolean;\n experimentalHideDefaultLocale?: boolean;\n experimentalFlattenJsonFiles?: boolean;\n experimentalLocalizeStaticImports?: boolean;\n experimentalLocalizeRelativeAssets?: boolean;\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default';\n docsImportRewrites?: Array<{\n match: string;\n replace: string;\n }>;\n};\n\nexport type OpenApiConfig = {\n files: string[];\n translateFields?: string[];\n};\n\nexport type MintlifyOptions = {\n openapi?: OpenApiConfig;\n inferTitleFromFilename?: boolean;\n localizeRedirects?: boolean; // add localized redirects for pages renamed or removed in a translate run\n};\n\nexport type SharedFlags = {\n config?: string;\n apiKey?: string;\n projectId?: string;\n};\n\nexport type TranslateFlags = SharedFlags & {\n versionId?: string;\n jsconfig?: string;\n dictionary?: string;\n defaultLocale?: string;\n locales?: string[];\n ignoreErrors?: boolean;\n src?: string[];\n timeout: number;\n dryRun: boolean;\n saveLocal?: boolean;\n stageTranslations?: boolean;\n setupProject?: boolean; // if true, skip enqueue step\n publish?: boolean;\n force?: boolean;\n forceDownload?: boolean;\n tag?: string;\n message?: string;\n experimentalLocalizeStaticUrls?: boolean;\n experimentalHideDefaultLocale?: boolean;\n experimentalFlattenJsonFiles?: boolean;\n experimentalLocalizeStaticImports?: boolean;\n experimentalLocalizeRelativeAssets?: boolean;\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default';\n omitConfigIds?: boolean;\n excludeStaticUrls?: string[];\n excludeStaticImports?: string[];\n docsImportRewrites?: Array<{\n match: string;\n replace: string;\n }>;\n};\n\nexport type WrapOptions = {\n src?: string[];\n config: string;\n skipTs: boolean;\n disableIds: boolean;\n disableFormatting: boolean;\n addGTProvider: boolean;\n};\n\nexport type SetupOptions = {\n src?: string[];\n config: string;\n};\n\nexport type GenerateSourceOptions = {\n src?: string[];\n config: string;\n defaultLocale: string;\n dictionary?: string;\n jsconfig?: string;\n inline?: boolean;\n ignoreErrors: boolean;\n suppressWarnings: boolean;\n};\n\nexport type Framework =\n | typeof Libraries.GT_NEXT\n | typeof Libraries.GT_REACT\n | typeof Libraries.GT_REACT_NATIVE\n | typeof Libraries.GT_TANSTACK_START;\n\nexport const SUPPORTED_REACT_FRAMEWORKS = [\n 'next-app',\n 'next-pages',\n 'vite',\n 'gatsby',\n 'react',\n 'redwood',\n 'tanstack-start',\n 'react-router',\n] as const;\n\nexport type FrameworkObject =\n | {\n name: 'mintlify';\n type?: undefined;\n }\n | {\n name: (typeof SUPPORTED_REACT_FRAMEWORKS)[number];\n type: 'react';\n };\nexport type ReactFrameworkObject = Extract<FrameworkObject, { type: 'react' }>;\n/** Detected so setup can stop; the wizard cannot set React Native up yet. */\nexport type ReactNativeFrameworkObject = {\n name: 'react-native';\n type: 'react-native';\n};\n\nexport type FrameworkType = FrameworkObject['type'];\n\nexport type SupportedFrameworks = FrameworkObject['name'];\nexport type SupportedReactFrameworks = Extract<\n FrameworkObject,\n { type: 'react' }\n>['name'];\n\nexport type SupportedLibraries =\n | InlineLibrary\n | 'next-intl'\n | 'react-i18next'\n | 'next-i18next'\n | 'i18next'\n | 'i18next-icu'\n | 'base';\n\nexport interface ContentScanner {\n scanForContent(\n options: WrapOptions,\n framework: Framework\n ): Promise<{\n errors: string[];\n filesUpdated: string[];\n warnings: string[];\n }>;\n}\n\n// Create a type based on the supported file extensions\nexport type SupportedFileExtension = (typeof SUPPORTED_FILE_EXTENSIONS)[number];\n\n// Update ResolvedFiles to use the dynamic keys\nexport type ResolvedFiles = {\n [K in SupportedFileExtension]?: string[];\n} & {\n gt?: string; // Output glob: /path/[locale].json\n};\n\nexport type TransformOption = {\n match?: string; // regex to match strings, supports capture groups\n replace: string; // string or regex pattern to replace the match with\n // Special placeholders:\n // -> if used in the match string, they will be replaced with the corresponding default locale property value\n // -> if used in the replace string, they will be replaced with the corresponding target locale property value\n // {locale} -> will be replaced with the locale code\n // And any other property from getLocaleProperties()\n};\n\nexport type TransformFiles = {\n [K in SupportedFileExtension]?: TransformOption | string | TransformOption[]; // if a string, only transform the file name\n};\n\nexport type TransformFormats = {\n [K in SupportedFileExtension]?: FileFormat;\n};\n\n// Include patterns can be plain strings or objects with a publish flag\nexport type IncludePattern = string | { pattern: string; publish?: boolean };\n\n// Review requirement for matched files: a boolean applies to all files of the\n// type; the object form opts path groups in/out with globs. exclude wins over\n// include; files matching neither inherit the top-level requiresReview default.\nexport type RequiresReviewConfig =\n | boolean\n | {\n include?: string[];\n exclude?: string[];\n };\n\n// Update FilesOptions to fix the error\nexport type FilesOptions = {\n [K in SupportedFileExtension]?: {\n include: IncludePattern[];\n exclude?: string[];\n transform?: string | TransformOption | TransformOption[];\n transformationFormat?: FileFormat;\n parsingFlags?: ParsingFlagsFor<K>; // Flags for parsing inline content\n requiresReview?: RequiresReviewConfig; // Whether translated versions of matched files require approval before use\n };\n} & {\n gt?: {\n output: string; // Output glob: /path/[locale].json\n publish?: boolean; // if true, publish gtjson translations to the CDN\n parsingFlags?: Partial<GTParsingFlags>; // Flags for parsing inline content\n /**\n * @deprecated\n * use `files.gt.parsingFlags.includeSourceCodeContext` instead\n */\n includeSourceCodeContext?: boolean; // Include surrounding source code lines as context for translations (default: false)\n };\n};\n\n// Shared settings between all API-related commands\nexport type FontsConfig = {\n include: string[]; // globs of .ttf/.otf files\n exclude?: string[];\n};\n\nexport type Settings = {\n config: string;\n configDirectory: string;\n baseUrl: string;\n dashboardUrl: string;\n apiKey?: string;\n userTokenProvider?: UserTokenProvider;\n projectId?: string;\n defaultLocale: string;\n locales: string[];\n dictionary?: string; // path to the source dictionary file (gt.config.json `dictionary` key)\n customMapping?: CustomMapping;\n files: {\n resolvedPaths: ResolvedFiles; // Absolute resolved paths for the default locale\n placeholderPaths: ResolvedFiles; // Absolute placeholder paths for all locales containing [locale]\n transformPaths: TransformFiles; // Absolute transform paths for all locales containing [locale]\n transformFormats: TransformFormats; // Output file format transforms keyed by config file type\n publishPaths: Set<string>; // Absolute paths explicitly opted IN to publishing\n unpublishPaths: Set<string>; // Absolute paths explicitly opted OUT of publishing\n requiresReviewPaths: Set<string>; // Absolute paths whose effective requiresReview policy is true\n parsingFlags: ParseFlagsByFileType;\n gtJson: {\n publish?: boolean; // if true, publish gtjson translations to the CDN\n parsingFlags: GTParsingFlags; // Flags for parsing inline content\n /**\n * @deprecated\n * use {@link files.gt.GTParsingFlags.parsingFlags.includeSourceCodeContext} instead\n */\n includeSourceCodeContext?: boolean; // Include surrounding source code lines as context for translations (default: false)\n };\n };\n stageTranslations: boolean; // if true, always stage the project during translate command\n requiresReview?: boolean; // top-level default: translated artifacts require approval before the client uses them\n publish?: boolean; // if true, publish the translations to the CDN; undefined means no global publish intent\n omitConfigIds?: boolean; // if true, do not write _versionId or _branchId to gt.config.json\n _versionId?: string; // internal use only\n _branchId?: string; // internal use only\n version?: string; // for specifying a custom version id to use. Should be unique\n description?: string;\n src?: string[]; // list of glob patterns for source file scanning\n fonts?: FontsConfig; // fonts to sync to the API before translating\n framework?: SupportedFrameworks;\n options?: AdditionalOptions;\n modelProvider?: ModelProvider;\n tag?: string;\n tagMessage?: string;\n parsingOptions: ParsingConfigOptions;\n branchOptions: BranchOptions;\n // Optional shared static assets config\n sharedStaticAssets?: SharedStaticAssetsConfig;\n};\n\nexport type StaticLocalizationFiles = Pick<\n Settings['files'],\n 'placeholderPaths' | 'resolvedPaths'\n> &\n Partial<Pick<Settings['files'], 'transformPaths' | 'transformFormats'>>;\n\nexport type StaticLocalizationSettings = Pick<\n Settings,\n 'defaultLocale' | 'locales' | 'options'\n> & {\n files?: StaticLocalizationFiles | null;\n};\n\nexport type BranchOptions = {\n currentBranch?: string;\n autoDetectBranches?: boolean;\n remoteName: string; // default 'origin'. The name of the remote to use for auto-detection.\n enabled: boolean; // if true, branching is enabled for the project\n};\n\nexport type AdditionalOptions = {\n // Optional schema to follow while translating JSON files\n jsonSchema?: {\n [fileGlob: string]: JsonSchema;\n };\n // Optional schema to follow while translating YAML files\n yamlSchema?: {\n [fileGlob: string]: YamlSchema;\n };\n // Skip pre-parse validation checks for specific file types\n skipFileValidation?: {\n json?: boolean;\n yaml?: boolean;\n mdx?: boolean;\n };\n // Optional Mintlify-specific options container\n mintlify?: MintlifyOptions;\n docsUrlPattern?: string | string[]; // eg /docs/[locale] or /[locale] for localizing static urls in markdown files; a list localizes several URL prefixes\n docsImportPattern?: string; // eg /docs/[locale]/foo.md or /[locale]/foo.md for localizing static imports in markdown files\n excludeStaticUrls?: string[]; // A list of file globs to include for static url localization\n excludeStaticImports?: string[]; // A list of file globs to include for static import localization\n docsHideDefaultLocaleImport?: boolean; // if true, hide the default locale in the import path\n copyFiles?: string[]; // array of files to copy to the target locale\n experimentalClearLocaleDirs?: boolean; // if true, clear locale directories before writing translations (default: false)\n clearLocaleDirsExclude?: string[]; // array of glob patterns with [locale] or [locales] placeholder to exclude from clearing (e.g., \"./snippets/[locale]/preserved/**\" or \"./[locales]/static/**\")\n experimentalLocalizeStaticImports?: boolean; // Inserts locale in static import paths in md/mdx files\n // Inserts locale in static url paths in md/mdx files and adds anchor IDs to\n // preserve navigation. The object form enables it with extra behavior.\n experimentalLocalizeStaticUrls?:\n | boolean\n | {\n // Keep links to source pages that have no translation\n skipUntranslatedPages?: boolean;\n // Extra JSX attribute names or globs to localize\n attributes?: string[];\n };\n experimentalLocalizeRelativeAssets?: boolean; // Rewrites relative asset URLs in translated md/mdx files to valid paths\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default'; // Format for anchor IDs: 'mintlify' for Mintlify's native {#id} on every heading, 'default' or undefined for escaped inline \\{#id\\}. Can run independently of static url localization\n experimentalHideDefaultLocale?: boolean; // Hides the default locale in the import path\n experimentalFlattenJsonFiles?: boolean; // Flattens JSON files into a single file\n baseDomain?: string; // The base http:// url where the project is hosted\n docsImportRewrites?: Array<{\n match: string; // prefix to match, e.g. '@site/docs'\n replace: string; // replacement prefix, can include [locale] or [defaultLocale]\n }>;\n experimentalCanonicalLocaleKeys?: boolean; // For composite JSON schemas with locale keys, force canonical locale even when alias provided\n saveLocal?: boolean; // if true, detect and save local edits to translated output before enqueuing translations (default: false)\n};\n\nexport type SharedStaticAssetsConfig = {\n include: string | string[];\n outDir?: string;\n publicPath?: string;\n mirrorToLocales?: boolean;\n};\n\nexport type StructuralTransform = {\n sourcePointer: string; // e.g., \"/msg\"\n destinationPointer: string; // e.g., \"/translations/en\"\n};\n\nexport type JsonSchema = {\n preset?: 'mintlify' | 'mintlify-hide-default' | 'openapi';\n structuralTransform?: StructuralTransform[];\n\n // when true, resolve $ref entries in this file before processing\n resolveRefs?: boolean;\n\n // exactly 1 of include or composite must be provided; not both\n\n // specify include if file is not composite\n // multiple target JSONs will be created for each locale,\n // with the only differing content being the specified JSONPath values\n include?: string[]; // array of JSONPaths to include\n\n // specify composite if no new JSONs should be created\n composite?: {\n // The sourceObjectPath is a JSONPath to the array or object containing\n // content in the source and target locales\n // This value is denoted as the \"sourceObject\"\n // Array elements or object sub-elements are denoted as \"sourceItem\"\n [sourceObjectPath: string]: SourceObjectOptions;\n };\n};\n\nexport type YamlSchema = {\n preset?: 'mintlify' | 'openapi';\n include?: string[];\n transform?: TransformOptions;\n};\n\nexport type SourceObjectOptions = {\n type: 'array' | 'object'; // type of the sourceObject;\n // array if the sourceObject is an array\n // -> We will simply add duplicated sourceItems for each locale\n // object if the sourceObject is an object\n // -> We will duplicate the sourceItem for each locale and set the corresponding\n // key with the locale property\n // In both cases, we search the sourceObject for the key that matches the source locale\n\n // Below, relative JSONPaths are relative to the sourceItem root, NOT the sourceObject\n\n include: string[]; // array of relative JSONPaths to include in the translated JSON\n\n // if type is array, there must be a key property in the array element\n // corresponding value should be a locale code\n key?: string; // relative jsonPath to the key to use to distinguish between source and target locales\n // if type is object, the key is simply the JSON key for the sourceItem - this is unnecessary in this case\n\n localeProperty?: string; // specific locale property to use for the key for target locales, default 'code'\n // ex: code, name, nativeName, languageCode, languageName, etc. (values returned by getLocaleProperties)\n\n // optional config for transforming specific fields in the sourceItem\n // for example, helpful for handling urls with locale-specific paths\n transform?: TransformOptions;\n\n // optional list of top-level properties to remove from generated\n // non-default-locale entries (e.g. Mintlify's `default: true` flag on the\n // default language entry, which must not be cloned into other locales)\n omitProperties?: string[];\n\n // optional sorting behavior for array sourceObjects. When set to 'locale',\n // the array will be ordered to match the locales array provided to mergeJson\n // When set to 'localesAlphabetical', the default locale will be placed first\n // and the remaining locales will be ordered alphabetically by locale code\n experimentalSort?: 'locales' | 'localesAlphabetical';\n\n // when true, non-default keyed entries in this composite array are extracted\n // into separate files (using the key value as the directory name) and replaced\n // with $ref pointers. Keeps the source file compact.\n splitEntries?: boolean;\n};\n\nexport type TransformOptions = {\n // relative jsonPath to content to mutate\n [transformPath: string]: TransformOption;\n};\n"],"mappings":";AA8HA,MAAa,6BAA6B;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD"}
@@ -12,3 +12,5 @@ export declare function hashStringSync(string: string): string;
12
12
  * preserving pre-requiresReview version IDs.
13
13
  */
14
14
  export declare function hashVersionId(content: string, requiresReview: boolean): string;
15
+ /** Hashes raw bytes with SHA-256, as the API versions media files. */
16
+ export declare function hashBytesSync(bytes: Uint8Array): string;
@@ -20,7 +20,11 @@ function hashStringSync(string) {
20
20
  function hashVersionId(content, requiresReview) {
21
21
  return requiresReview ? hashStringSync(content + "\0requiresReview:true") : hashStringSync(content);
22
22
  }
23
+ /** Hashes raw bytes with SHA-256, as the API versions media files. */
24
+ function hashBytesSync(bytes) {
25
+ return crypto.createHash("sha256").update(bytes).digest("hex");
26
+ }
23
27
  //#endregion
24
- export { hashStringSync, hashVersionId };
28
+ export { hashBytesSync, hashStringSync, hashVersionId };
25
29
 
26
30
  //# sourceMappingURL=hash.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"hash.js","names":[],"sources":["../../src/utils/hash.ts"],"sourcesContent":["import crypto from 'crypto';\n\n/**\n * Hashes a string using SHA-256 algorithm.\n * @param {string} string - The string to be hashed.\n * @returns {string} The hashed string.\n */\nexport function hashStringSync(string: string): string {\n const hash = crypto.createHash('sha256');\n hash.update(string);\n return hash.digest('hex');\n}\n\n/**\n * Computes a file content version hash. When the file's effective\n * requiresReview policy is true, the policy is mixed into the hash so\n * review-policy changes produce a new version identity even for unchanged\n * content. A false policy hashes identically to the plain content hash,\n * preserving pre-requiresReview version IDs.\n */\nexport function hashVersionId(\n content: string,\n requiresReview: boolean\n): string {\n return requiresReview\n ? hashStringSync(content + '\\u0000requiresReview:true')\n : hashStringSync(content);\n}\n"],"mappings":";;;;;;;AAOA,SAAgB,eAAe,QAAwB;CACrD,MAAM,OAAO,OAAO,WAAW,SAAS;AACxC,MAAK,OAAO,OAAO;AACnB,QAAO,KAAK,OAAO,MAAM;;;;;;;;;AAU3B,SAAgB,cACd,SACA,gBACQ;AACR,QAAO,iBACH,eAAe,UAAU,wBAA4B,GACrD,eAAe,QAAQ"}
1
+ {"version":3,"file":"hash.js","names":[],"sources":["../../src/utils/hash.ts"],"sourcesContent":["import crypto from 'crypto';\n\n/**\n * Hashes a string using SHA-256 algorithm.\n * @param {string} string - The string to be hashed.\n * @returns {string} The hashed string.\n */\nexport function hashStringSync(string: string): string {\n const hash = crypto.createHash('sha256');\n hash.update(string);\n return hash.digest('hex');\n}\n\n/**\n * Computes a file content version hash. When the file's effective\n * requiresReview policy is true, the policy is mixed into the hash so\n * review-policy changes produce a new version identity even for unchanged\n * content. A false policy hashes identically to the plain content hash,\n * preserving pre-requiresReview version IDs.\n */\nexport function hashVersionId(\n content: string,\n requiresReview: boolean\n): string {\n return requiresReview\n ? hashStringSync(content + '\\u0000requiresReview:true')\n : hashStringSync(content);\n}\n\n/** Hashes raw bytes with SHA-256, as the API versions media files. */\nexport function hashBytesSync(bytes: Uint8Array): string {\n return crypto.createHash('sha256').update(bytes).digest('hex');\n}\n"],"mappings":";;;;;;;AAOA,SAAgB,eAAe,QAAwB;CACrD,MAAM,OAAO,OAAO,WAAW,SAAS;AACxC,MAAK,OAAO,OAAO;AACnB,QAAO,KAAK,OAAO,MAAM;;;;;;;;;AAU3B,SAAgB,cACd,SACA,gBACQ;AACR,QAAO,iBACH,eAAe,UAAU,wBAA4B,GACrD,eAAe,QAAQ;;;AAI7B,SAAgB,cAAc,OAA2B;AACvD,QAAO,OAAO,WAAW,SAAS,CAAC,OAAO,MAAM,CAAC,OAAO,MAAM"}
@@ -2,8 +2,8 @@ import { createFileMapping } from "../formats/files/fileMapping.js";
2
2
  import { parseMdxForRoundTrip, restoreAnchorIds } from "./mdxAnchorSyntax.js";
3
3
  import { batchProcess } from "./batchProcess.js";
4
4
  import * as fs$1 from "fs";
5
- import { parse } from "@babel/parser";
6
5
  import micromatch from "micromatch";
6
+ import { parse } from "@babel/parser";
7
7
  import * as path$1 from "path";
8
8
  import { unified } from "unified";
9
9
  import remarkMdx from "remark-mdx";