@intlayer/engine 9.5.6 → 9.5.8

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 (63) hide show
  1. package/dist/assets/installSkills/skills/angular.md +19 -68
  2. package/dist/assets/installSkills/skills/astro.md +38 -4
  3. package/dist/assets/installSkills/skills/backend.md +113 -0
  4. package/dist/assets/installSkills/skills/cli.md +29 -25
  5. package/dist/assets/installSkills/skills/compat.md +87 -0
  6. package/dist/assets/installSkills/skills/compiler.md +14 -4
  7. package/dist/assets/installSkills/skills/config.md +15 -5
  8. package/dist/assets/installSkills/skills/content.md +80 -6
  9. package/dist/assets/installSkills/skills/dev-tools.md +82 -0
  10. package/dist/assets/installSkills/skills/lit.md +115 -0
  11. package/dist/assets/installSkills/skills/markdown.md +96 -0
  12. package/dist/assets/installSkills/skills/next-js.md +21 -38
  13. package/dist/assets/installSkills/skills/preact.md +18 -0
  14. package/dist/assets/installSkills/skills/react.md +21 -4
  15. package/dist/assets/installSkills/skills/remix.md +95 -0
  16. package/dist/assets/installSkills/skills/remote-content.md +1 -1
  17. package/dist/assets/installSkills/skills/solid.md +21 -1
  18. package/dist/assets/installSkills/skills/svelte.md +22 -1
  19. package/dist/assets/installSkills/skills/usage.md +28 -0
  20. package/dist/assets/installSkills/skills/vanilla.md +108 -0
  21. package/dist/assets/installSkills/skills/vue.md +22 -0
  22. package/dist/cjs/cli.cjs +2 -0
  23. package/dist/cjs/init/index.cjs +305 -300
  24. package/dist/cjs/init/index.cjs.map +1 -1
  25. package/dist/cjs/init/upgradeIntlayerPackages.cjs +60 -0
  26. package/dist/cjs/init/upgradeIntlayerPackages.cjs.map +1 -0
  27. package/dist/cjs/init/utils/index.cjs +13 -4
  28. package/dist/cjs/init/utils/intlayerDependencies.cjs +119 -0
  29. package/dist/cjs/init/utils/intlayerDependencies.cjs.map +1 -0
  30. package/dist/cjs/init/utils/packageManager.cjs +145 -94
  31. package/dist/cjs/init/utils/packageManager.cjs.map +1 -1
  32. package/dist/cjs/installSkills/index.cjs +110 -19
  33. package/dist/cjs/installSkills/index.cjs.map +1 -1
  34. package/dist/cjs/utils/runOnce.cjs +66 -15
  35. package/dist/cjs/utils/runOnce.cjs.map +1 -1
  36. package/dist/esm/cli.mjs +2 -1
  37. package/dist/esm/init/index.mjs +306 -301
  38. package/dist/esm/init/index.mjs.map +1 -1
  39. package/dist/esm/init/upgradeIntlayerPackages.mjs +57 -0
  40. package/dist/esm/init/upgradeIntlayerPackages.mjs.map +1 -0
  41. package/dist/esm/init/utils/index.mjs +3 -2
  42. package/dist/esm/init/utils/intlayerDependencies.mjs +110 -0
  43. package/dist/esm/init/utils/intlayerDependencies.mjs.map +1 -0
  44. package/dist/esm/init/utils/packageManager.mjs +143 -93
  45. package/dist/esm/init/utils/packageManager.mjs.map +1 -1
  46. package/dist/esm/installSkills/index.mjs +110 -19
  47. package/dist/esm/installSkills/index.mjs.map +1 -1
  48. package/dist/esm/utils/runOnce.mjs +67 -16
  49. package/dist/esm/utils/runOnce.mjs.map +1 -1
  50. package/dist/types/cli.d.ts +2 -1
  51. package/dist/types/init/index.d.ts +9 -6
  52. package/dist/types/init/index.d.ts.map +1 -1
  53. package/dist/types/init/upgradeIntlayerPackages.d.ts +26 -0
  54. package/dist/types/init/upgradeIntlayerPackages.d.ts.map +1 -0
  55. package/dist/types/init/utils/index.d.ts +3 -2
  56. package/dist/types/init/utils/intlayerDependencies.d.ts +66 -0
  57. package/dist/types/init/utils/intlayerDependencies.d.ts.map +1 -0
  58. package/dist/types/init/utils/packageManager.d.ts +44 -19
  59. package/dist/types/init/utils/packageManager.d.ts.map +1 -1
  60. package/dist/types/installSkills/index.d.ts +16 -3
  61. package/dist/types/installSkills/index.d.ts.map +1 -1
  62. package/dist/types/utils/runOnce.d.ts.map +1 -1
  63. package/package.json +7 -7
@@ -11,36 +11,127 @@ import { getMarkdownMetadata } from "@intlayer/core/markdown";
11
11
  const SKILLS_METADATA = {
12
12
  Config: "Intlayer configuration documentation",
13
13
  Content: "Reference for all Intlayer content node types (t, enu, etc.)",
14
+ Markdown: "Markdown / rich text content: md(), MDX components, MarkdownProvider, SSR",
14
15
  Usage: "How to use Intlayer in your project",
15
16
  CLI: "Intlayer CLI commands and usage",
16
17
  Compiler: "Intlayer Compiler setup and usage for automatic content extraction without .content files",
17
18
  RemoteContent: "How to use Intlayer with Remote/CMS/Server-side content",
19
+ DevTools: "ESLint, LSP, VS Code & Chrome extensions, MCP server and CI/CD",
20
+ Compat: "Migrate from i18next, next-intl, react-intl, vue-i18n, Lingui… keeping their API",
18
21
  NextJS: "Next.js-specific usage (Server & Client components)",
19
22
  React: "React-specific syntax and hooks usage",
20
23
  Vue: "Vue-specific composables and syntax",
21
24
  Svelte: "Svelte-specific stores and syntax",
22
25
  Angular: "Angular-specific syntax and Injectable Function usage",
23
26
  Preact: "Preact-specific syntax and hooks usage",
24
- Solid: "Integrates Intlayer internationalization with SolidJS components. Use when the user asks to \"setup SolidJS i18n\", use the \"useIntlayer\" hook in Solid, or manage locales in a SolidJS application.",
25
- Astro: "Astro-specific usage and getIntlayer"
27
+ Solid: "Solid-specific syntax and hooks usage",
28
+ Astro: "Astro-specific usage, middleware and islands",
29
+ Lit: "Lit-specific ReactiveController usage (useIntlayer, useLocale)",
30
+ Vanilla: "Framework-less JavaScript usage (vanilla-intlayer)",
31
+ Remix: "Remix 3 router middleware and request-scoped hooks",
32
+ Backend: "Server-side usage for Express, Fastify, Hono, NestJS, AdonisJS and Elysia"
26
33
  };
27
34
  const SKILLS = Object.keys(SKILLS_METADATA);
28
- const getInitialSkills = (deps) => {
29
- const skills = [
30
- "Usage",
31
- "Content",
32
- "Config",
33
- "CLI",
34
- "Compiler"
35
- ];
36
- if (deps.next) skills.push("NextJS");
37
- if (deps.react || !deps.next) skills.push("React");
38
- if (deps.preact) skills.push("Preact");
39
- if (deps["solid-js"]) skills.push("Solid");
40
- if (deps.vue || deps.nuxt) skills.push("Vue");
41
- if (deps.svelte || deps["@sveltejs/kit"]) skills.push("Svelte");
42
- if (deps.astro) skills.push("Astro");
43
- return skills;
35
+ /** Skills preselected for every project, whatever its stack. */
36
+ const BASE_SKILLS = [
37
+ "Usage",
38
+ "Content",
39
+ "Config",
40
+ "CLI",
41
+ "Compiler",
42
+ "DevTools"
43
+ ];
44
+ /**
45
+ * Packages whose presence in `package.json` preselects a framework skill.
46
+ * Both the framework itself and its Intlayer adapter are listed, so a skill is
47
+ * suggested before and after the adapter is installed.
48
+ */
49
+ const SKILL_TRIGGER_PACKAGES = {
50
+ NextJS: ["next", "next-intlayer"],
51
+ React: [
52
+ "react",
53
+ "react-intlayer",
54
+ "react-native-intlayer",
55
+ "react-scripts-intlayer",
56
+ "lynx-intlayer"
57
+ ],
58
+ Preact: ["preact", "preact-intlayer"],
59
+ Solid: [
60
+ "solid-js",
61
+ "@solidjs/start",
62
+ "solid-intlayer"
63
+ ],
64
+ Vue: [
65
+ "vue",
66
+ "nuxt",
67
+ "vue-intlayer",
68
+ "nuxt-intlayer"
69
+ ],
70
+ Svelte: [
71
+ "svelte",
72
+ "@sveltejs/kit",
73
+ "svelte-intlayer"
74
+ ],
75
+ Angular: [
76
+ "@angular/core",
77
+ "@analogjs/platform",
78
+ "angular-intlayer"
79
+ ],
80
+ Astro: ["astro", "astro-intlayer"],
81
+ Lit: ["lit", "lit-intlayer"],
82
+ Vanilla: ["vanilla-intlayer"],
83
+ Remix: ["remix", "remix-intlayer"],
84
+ Compat: [
85
+ "i18next",
86
+ "react-i18next",
87
+ "next-i18next",
88
+ "next-intl",
89
+ "use-intl",
90
+ "react-intl",
91
+ "vue-i18n",
92
+ "@lingui/core",
93
+ "@lingui/react",
94
+ "@nuxtjs/i18n",
95
+ "@ngx-translate/core",
96
+ "@jsverse/transloco",
97
+ "svelte-i18n",
98
+ "next-translate",
99
+ "node-polyglot",
100
+ "i18n-js",
101
+ "@intlayer/i18next",
102
+ "@intlayer/react-i18next",
103
+ "@intlayer/next-i18next",
104
+ "@intlayer/next-intl",
105
+ "@intlayer/use-intl",
106
+ "@intlayer/react-intl",
107
+ "@intlayer/vue-i18n",
108
+ "@intlayer/lingui",
109
+ "@intlayer/sync-json-plugin",
110
+ "@intlayer/sync-po-plugin"
111
+ ],
112
+ Backend: [
113
+ "express",
114
+ "fastify",
115
+ "hono",
116
+ "elysia",
117
+ "@nestjs/core",
118
+ "@adonisjs/core",
119
+ "express-intlayer",
120
+ "fastify-intlayer",
121
+ "hono-intlayer",
122
+ "elysia-intlayer",
123
+ "adonis-intlayer"
124
+ ]
125
+ };
126
+ /**
127
+ * Resolves the skills to preselect from the project's installed packages.
128
+ *
129
+ * @param dependencies - Merged `dependencies` and `devDependencies` of `package.json`.
130
+ * @returns The base skills plus every framework skill whose packages are installed.
131
+ */
132
+ const getInitialSkills = (dependencies) => {
133
+ const detectedSkills = SKILLS.filter((skill) => SKILL_TRIGGER_PACKAGES[skill]?.some((packageName) => packageName in dependencies));
134
+ return [...BASE_SKILLS, ...detectedSkills];
44
135
  };
45
136
  /**
46
137
  * Metadata and configuration for each supported platform.
@@ -294,7 +385,7 @@ const installSkills = async (projectRoot, platform, skills) => {
294
385
  const content = await fetchUrlContent(url);
295
386
  const metadata = getMarkdownMetadata(content);
296
387
  let fileName = "";
297
- if (Array.isArray(metadata.slugs)) fileName = metadata.slugs.filter((slug) => slug !== "doc").join("_");
388
+ if (Array.isArray(metadata.slugs)) fileName = metadata.slugs.filter((slug) => slug !== "doc").join("_").replaceAll("/", "_");
298
389
  else fileName = new URL(url).pathname.split("/").filter((part) => part && part !== "doc").map((part) => part.replace(".md", "")).join("_");
299
390
  fileName = fileName ? `${fileName}.md` : "index.md";
300
391
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["fs"],"sources":["../../../src/installSkills/index.ts"],"sourcesContent":["import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { readAsset } from 'utils:asset';\nimport { v } from '@intlayer/config/logger';\nimport { getMarkdownMetadata } from '@intlayer/core/markdown';\n\n/**\n * Metadata for each available documentation skill.\n */\nexport const SKILLS_METADATA = {\n Config: 'Intlayer configuration documentation',\n Content: 'Reference for all Intlayer content node types (t, enu, etc.)',\n Usage: 'How to use Intlayer in your project',\n CLI: 'Intlayer CLI commands and usage',\n Compiler:\n 'Intlayer Compiler setup and usage for automatic content extraction without .content files',\n RemoteContent: 'How to use Intlayer with Remote/CMS/Server-side content',\n NextJS: 'Next.js-specific usage (Server & Client components)',\n React: 'React-specific syntax and hooks usage',\n Vue: 'Vue-specific composables and syntax',\n Svelte: 'Svelte-specific stores and syntax',\n Angular: 'Angular-specific syntax and Injectable Function usage',\n Preact: 'Preact-specific syntax and hooks usage',\n Solid:\n 'Integrates Intlayer internationalization with SolidJS components. Use when the user asks to \"setup SolidJS i18n\", use the \"useIntlayer\" hook in Solid, or manage locales in a SolidJS application.',\n Astro: 'Astro-specific usage and getIntlayer',\n} as const;\n\nexport type Skill = keyof typeof SKILLS_METADATA;\n\nexport const SKILLS = Object.keys(SKILLS_METADATA) as Skill[];\n\nexport const getInitialSkills = (\n deps: Record<string, string>\n): (keyof typeof SKILLS_METADATA)[] => {\n const skills: (keyof typeof SKILLS_METADATA)[] = [\n 'Usage',\n 'Content',\n 'Config',\n 'CLI',\n 'Compiler',\n ];\n\n if (deps.next) skills.push('NextJS');\n if (deps.react || !deps.next) skills.push('React');\n if (deps.preact) skills.push('Preact');\n if (deps['solid-js']) skills.push('Solid');\n if (deps.vue || deps.nuxt) skills.push('Vue');\n if (deps.svelte || deps['@sveltejs/kit']) skills.push('Svelte');\n if (deps.astro) skills.push('Astro');\n\n return skills;\n};\n\nexport interface PlatformMetadata {\n label: string;\n dir: string;\n check?: () => boolean;\n}\n\n/**\n * Metadata and configuration for each supported platform.\n */\nexport const PLATFORMS_METADATA: Record<string, PlatformMetadata> = {\n Cursor: {\n label: 'Cursor',\n dir: '.cursor/skills',\n check: () =>\n process.env.CURSOR === 'true' || process.env.TERM_PROGRAM === 'cursor',\n },\n Windsurf: {\n label: 'Windsurf',\n dir: '.windsurf/skills',\n check: () =>\n process.env.WINDSURF === 'true' ||\n process.env.TERM_PROGRAM === 'windsurf',\n },\n Trae: {\n label: 'Trae',\n dir: '.trae/skills',\n check: () =>\n process.env.TRAE === 'true' || process.env.TERM_PROGRAM === 'trae',\n },\n TraeCN: {\n label: 'Trae CN',\n dir: '.trae/skills',\n check: () => process.env.TRAE_CN === 'true',\n },\n VSCode: {\n label: 'VS Code',\n dir: '.vscode/skills',\n check: () =>\n process.env.VSCODE === 'true' || process.env.TERM_PROGRAM === 'vscode',\n },\n OpenCode: {\n label: 'OpenCode',\n dir: '.opencode/skills',\n check: () => process.env.OPENCODE === 'true',\n },\n Claude: {\n label: 'Claude Code',\n dir: '.claude/skills',\n check: () => process.env.CLAUDE === 'true',\n },\n GitHub: {\n label: 'GitHub Copilot Workspace',\n dir: '.github/skills',\n check: () =>\n process.env.GITHUB_ACTIONS === 'true' || !!process.env.GITHUB_WORKSPACE,\n },\n Antigravity: {\n label: 'Antigravity',\n dir: '.agent/skills',\n },\n Augment: {\n label: 'Augment',\n dir: '.augment/skills',\n },\n OpenClaw: {\n label: 'OpenClaw',\n dir: 'skills',\n },\n Cline: {\n label: 'Cline',\n dir: '.cline/skills',\n },\n CodeBuddy: {\n label: 'CodeBuddy',\n dir: '.codebuddy/skills',\n },\n CommandCode: {\n label: 'Command Code',\n dir: '.commandcode/skills',\n },\n Continue: {\n label: 'Continue',\n dir: '.continue/skills',\n },\n Crush: {\n label: 'Crush',\n dir: '.crush/skills',\n },\n Droid: {\n label: 'Droid',\n dir: '.factory/skills',\n },\n Goose: {\n label: 'Goose',\n dir: '.goose/skills',\n },\n IFlow: {\n label: 'iFlow CLI',\n dir: '.iflow/skills',\n },\n Junie: {\n label: 'Junie',\n dir: '.junie/skills',\n },\n KiloCode: {\n label: 'Kilo Code',\n dir: '.kilocode/skills',\n },\n Kiro: {\n label: 'Kiro CLI',\n dir: '.kiro/skills',\n },\n Kode: {\n label: 'Kode',\n dir: '.kode/skills',\n },\n MCPJam: {\n label: 'MCPJam',\n dir: '.mcpjam/skills',\n },\n MistralVibe: {\n label: 'Mistral Vibe',\n dir: '.vibe/skills',\n },\n Mux: {\n label: 'Mux',\n dir: '.mux/skills',\n },\n OpenHands: {\n label: 'OpenHands',\n dir: '.openhands/skills',\n },\n Pi: {\n label: 'Pi',\n dir: '.pi/skills',\n },\n Qoder: {\n label: 'Qoder',\n dir: '.qoder/skills',\n },\n Qwen: {\n label: 'Qwen Code',\n dir: '.qwen/skills',\n },\n RooCode: {\n label: 'Roo Code',\n dir: '.roo/skills',\n },\n Zencoder: {\n label: 'Zencoder',\n dir: '.zencoder/skills',\n },\n Neovate: {\n label: 'Neovate',\n dir: '.neovate/skills',\n },\n Pochi: {\n label: 'Pochi',\n dir: '.pochi/skills',\n },\n Other: {\n label: 'Other',\n dir: 'skills',\n },\n} as const;\n\nexport type Platform = keyof typeof PLATFORMS_METADATA;\n\nexport const PLATFORMS = Object.keys(PLATFORMS_METADATA) as Platform[];\n\n/**\n * Maps specific skill keys to special filenames if they differ from standard snake_case.\n */\nconst SKILL_FILENAME_MAP: Partial<Record<Skill, string>> = {};\n\n/**\n * Helper to convert CamelCase to kebab-case for directory naming\n */\nconst camelToKebabCase = (str: string) =>\n str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();\n\n/**\n * Reads the raw markdown content for a specific skill from the assets folder.\n */\nconst getSkillContent = (skill: Skill): string => {\n const baseName = SKILL_FILENAME_MAP[skill] ?? camelToKebabCase(skill);\n const fileName = `./skills/${baseName}.md`;\n\n try {\n return readAsset(fileName);\n } catch {\n console.warn(\n `Warning: Could not read asset for skill: ${skill} at ${fileName}`\n );\n return '';\n }\n};\n\n/**\n * Reads the licence content from the assets folder.\n */\nconst getLicenceContent = (): string => {\n try {\n return readAsset('./LICENCE.md');\n } catch {\n console.warn('Warning: Could not read LICENCE.md asset');\n return '';\n }\n};\n\nconst ALLOWED_FETCH_HOSTS = new Set(['intlayer.org']);\n\n/** Upper bound on the redirect chain a reference URL may take. */\nconst MAX_FETCH_REDIRECTS = 5;\n\n/**\n * Parses a URL and rejects it unless it is an HTTPS address on an allowed host.\n *\n * @param url - Absolute URL to validate.\n * @returns The parsed URL.\n * @throws When the protocol or host is not allowed.\n */\nconst parseAllowedUrl = (url: string | URL): URL => {\n const parsed = new URL(url);\n\n if (\n parsed.protocol !== 'https:' ||\n !ALLOWED_FETCH_HOSTS.has(parsed.hostname)\n ) {\n throw new Error(`Blocked fetch to disallowed host: ${parsed.hostname}`);\n }\n\n return parsed;\n};\n\n/**\n * Fetches the content of a URL using native fetch.\n *\n * Redirects are followed manually so every hop is re-checked against the host\n * allowlist — a redirect off `intlayer.org` is refused rather than silently\n * followed. Letting `fetch` refuse them outright (`redirect: 'error'`) instead\n * reported an unhelpful `TypeError: fetch failed` for a documentation URL that\n * merely moved.\n *\n * @param url - Absolute URL to read.\n * @returns The response body as text.\n */\nconst fetchUrlContent = async (url: string): Promise<string> => {\n let target = parseAllowedUrl(url);\n\n for (let hop = 0; hop <= MAX_FETCH_REDIRECTS; hop++) {\n const response = await fetch(target, { redirect: 'manual' });\n\n if (response.status >= 300 && response.status < 400) {\n const location = response.headers.get('location');\n\n if (!location) {\n throw new Error(`Failed to fetch ${url}: redirect without a location`);\n }\n\n target = parseAllowedUrl(new URL(location, target));\n continue;\n }\n\n if (!response.ok) {\n throw new Error(`Failed to fetch ${url}: ${response.statusText}`);\n }\n\n return response.text();\n }\n\n throw new Error(`Failed to fetch ${url}: too many redirects`);\n};\n\n/**\n * Installs skills using the \"Agent Skills\" directory standard.\n * Standard: <PROJECT_ROOT>/<CONFIG_DIR>/skills/<SKILL_NAME>/SKILL.md\n */\nexport const installSkills = async (\n projectRoot: string,\n platform: Platform,\n skills: Skill[]\n): Promise<string> => {\n // Determine destination directory\n const relativeDir = PLATFORMS_METADATA[platform]?.dir ?? 'skills';\n const skillsBaseDir = path.join(projectRoot, relativeDir);\n\n // Ensure the base directory exists\n await fs.mkdir(skillsBaseDir, { recursive: true });\n\n const createdSkills: string[] = [];\n const licenceContent = getLicenceContent();\n\n for (const skill of skills) {\n const baseName = SKILL_FILENAME_MAP[skill] ?? camelToKebabCase(skill);\n const skillName = `intlayer-${baseName}`;\n const skillContent = getSkillContent(skill);\n\n if (!skillContent) continue;\n\n // Extract unique URLs\n const urls = Array.from(\n new Set(skillContent.match(/https:\\/\\/intlayer\\.org\\/[^\\s)]+\\.md/g) || [])\n );\n\n // Agent Standard: .../skills/<skill-name>/SKILL.md\n const skillDir = path.join(skillsBaseDir, skillName);\n const referenceDir = path.join(skillDir, 'references');\n\n // Ensure directories exist\n await fs.mkdir(referenceDir, { recursive: true });\n\n // Write License\n if (licenceContent) {\n await fs.writeFile(\n path.join(skillDir, 'LICENCE.md'),\n licenceContent,\n 'utf-8'\n );\n }\n\n let updatedSkillContent = skillContent;\n\n // Parallel download of references\n const downloadPromises = urls.map(async (url) => {\n try {\n const content = await fetchUrlContent(url);\n const metadata = getMarkdownMetadata<{ slugs?: string[] }>(content);\n\n let fileName = '';\n\n // Determine filename from slugs or URL path\n if (Array.isArray(metadata.slugs)) {\n fileName = metadata.slugs.filter((slug) => slug !== 'doc').join('_');\n } else {\n const urlPath = new URL(url).pathname;\n fileName = urlPath\n .split('/')\n .filter((part) => part && part !== 'doc')\n .map((part) => part.replace('.md', '')) // Clean extension for joining\n .join('_');\n }\n\n // Ensure it ends with .md\n fileName = fileName ? `${fileName}.md` : 'index.md';\n const localRefPath = `references/${fileName}`;\n\n return {\n url,\n localRefPath,\n fileName,\n content,\n success: true,\n };\n } catch (error) {\n console.warn(\n `Warning: Failed to download ref ${url} for skill ${skill}`,\n error\n );\n return { url, success: false };\n }\n });\n\n const results = await Promise.all(downloadPromises);\n\n // Process results: Write files and update content string\n for (const res of results) {\n if (res.success && res.fileName && res.content && res.localRefPath) {\n // Write the reference file\n await fs.writeFile(\n path.join(referenceDir, res.fileName),\n res.content,\n 'utf-8'\n );\n\n // Update the main content to point to local file\n updatedSkillContent = updatedSkillContent.replaceAll(\n res.url,\n res.localRefPath\n );\n }\n }\n\n // Write the main SKILL.md\n const filePath = path.join(skillDir, 'SKILL.md');\n await fs.writeFile(filePath, updatedSkillContent, 'utf-8');\n createdSkills.push(`${skillName}/SKILL.md`);\n }\n\n if (createdSkills.length === 0) {\n return `No skill files were created. Check your asset paths.`;\n }\n\n return `${v} Created ${createdSkills.length} skills in ${skillsBaseDir}`;\n};\n"],"mappings":";;;;;;;;;;AASA,MAAa,kBAAkB;CAC7B,QAAQ;CACR,SAAS;CACT,OAAO;CACP,KAAK;CACL,UACE;CACF,eAAe;CACf,QAAQ;CACR,OAAO;CACP,KAAK;CACL,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,OACE;CACF,OAAO;AACT;AAIA,MAAa,SAAS,OAAO,KAAK,eAAe;AAEjD,MAAa,oBACX,SACqC;CACrC,MAAM,SAA2C;EAC/C;EACA;EACA;EACA;EACA;CACF;CAEA,IAAI,KAAK,MAAM,OAAO,KAAK,QAAQ;CACnC,IAAI,KAAK,SAAS,CAAC,KAAK,MAAM,OAAO,KAAK,OAAO;CACjD,IAAI,KAAK,QAAQ,OAAO,KAAK,QAAQ;CACrC,IAAI,KAAK,aAAa,OAAO,KAAK,OAAO;CACzC,IAAI,KAAK,OAAO,KAAK,MAAM,OAAO,KAAK,KAAK;CAC5C,IAAI,KAAK,UAAU,KAAK,kBAAkB,OAAO,KAAK,QAAQ;CAC9D,IAAI,KAAK,OAAO,OAAO,KAAK,OAAO;CAEnC,OAAO;AACT;;;;AAWA,MAAa,qBAAuD;CAClE,QAAQ;EACN,OAAO;EACP,KAAK;EACL,aACE,QAAQ,IAAI,WAAW,UAAU,QAAQ,IAAI,iBAAiB;CAClE;CACA,UAAU;EACR,OAAO;EACP,KAAK;EACL,aACE,QAAQ,IAAI,aAAa,UACzB,QAAQ,IAAI,iBAAiB;CACjC;CACA,MAAM;EACJ,OAAO;EACP,KAAK;EACL,aACE,Q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,QAAQ,SAAS,KAAK,GAC9B,WAAW,SAAS,MAAM,QAAQ,SAAS,SAAS,KAAK,CAAC,CAAC,KAAK,GAAG;SAGnE,WADgB,IAAI,IAAI,GAAG,CAAC,CAAC,SAE1B,MAAM,GAAG,CAAC,CACV,QAAQ,SAAS,QAAQ,SAAS,KAAK,CAAC,CACxC,KAAK,SAAS,KAAK,QAAQ,OAAO,EAAE,CAAC,CAAC,CACtC,KAAK,GAAG;IAIb,WAAW,WAAW,GAAG,SAAS,OAAO;IAGzC,OAAO;KACL;KACA,4BAJiC;KAKjC;KACA;KACA,SAAS;IACX;GACF,SAAS,OAAO;IACd,QAAQ,KACN,mCAAmC,IAAI,aAAa,SACpD,KACF;IACA,OAAO;KAAE;KAAK,SAAS;IAAM;GAC/B;EACF,CAAC;EAED,MAAM,UAAU,MAAM,QAAQ,IAAI,gBAAgB;EAGlD,KAAK,MAAM,OAAO,SAChB,IAAI,IAAI,WAAW,IAAI,YAAY,IAAI,WAAW,IAAI,cAAc;GAElE,MAAMA,SAAG,UACP,KAAK,KAAK,cAAc,IAAI,QAAQ,GACpC,IAAI,SACJ,OACF;GAGA,sBAAsB,oBAAoB,WACxC,IAAI,KACJ,IAAI,YACN;EACF;EAIF,MAAM,WAAW,KAAK,KAAK,UAAU,UAAU;EAC/C,MAAMA,SAAG,UAAU,UAAU,qBAAqB,OAAO;EACzD,cAAc,KAAK,GAAG,UAAU,UAAU;CAC5C;CAEA,IAAI,cAAc,WAAW,GAC3B,OAAO;CAGT,OAAO,GAAG,EAAE,WAAW,cAAc,OAAO,aAAa;AAC3D"}
1
+ {"version":3,"file":"index.mjs","names":["fs"],"sources":["../../../src/installSkills/index.ts"],"sourcesContent":["import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { readAsset } from 'utils:asset';\nimport { v } from '@intlayer/config/logger';\nimport { getMarkdownMetadata } from '@intlayer/core/markdown';\n\n/**\n * Metadata for each available documentation skill.\n */\nexport const SKILLS_METADATA = {\n Config: 'Intlayer configuration documentation',\n Content: 'Reference for all Intlayer content node types (t, enu, etc.)',\n Markdown:\n 'Markdown / rich text content: md(), MDX components, MarkdownProvider, SSR',\n Usage: 'How to use Intlayer in your project',\n CLI: 'Intlayer CLI commands and usage',\n Compiler:\n 'Intlayer Compiler setup and usage for automatic content extraction without .content files',\n RemoteContent: 'How to use Intlayer with Remote/CMS/Server-side content',\n DevTools: 'ESLint, LSP, VS Code & Chrome extensions, MCP server and CI/CD',\n Compat:\n 'Migrate from i18next, next-intl, react-intl, vue-i18n, Lingui… keeping their API',\n NextJS: 'Next.js-specific usage (Server & Client components)',\n React: 'React-specific syntax and hooks usage',\n Vue: 'Vue-specific composables and syntax',\n Svelte: 'Svelte-specific stores and syntax',\n Angular: 'Angular-specific syntax and Injectable Function usage',\n Preact: 'Preact-specific syntax and hooks usage',\n Solid: 'Solid-specific syntax and hooks usage',\n Astro: 'Astro-specific usage, middleware and islands',\n Lit: 'Lit-specific ReactiveController usage (useIntlayer, useLocale)',\n Vanilla: 'Framework-less JavaScript usage (vanilla-intlayer)',\n Remix: 'Remix 3 router middleware and request-scoped hooks',\n Backend:\n 'Server-side usage for Express, Fastify, Hono, NestJS, AdonisJS and Elysia',\n} as const;\n\nexport type Skill = keyof typeof SKILLS_METADATA;\n\nexport const SKILLS = Object.keys(SKILLS_METADATA) as Skill[];\n\n/** Skills preselected for every project, whatever its stack. */\nconst BASE_SKILLS: Skill[] = [\n 'Usage',\n 'Content',\n 'Config',\n 'CLI',\n 'Compiler',\n 'DevTools',\n];\n\n/**\n * Packages whose presence in `package.json` preselects a framework skill.\n * Both the framework itself and its Intlayer adapter are listed, so a skill is\n * suggested before and after the adapter is installed.\n */\nconst SKILL_TRIGGER_PACKAGES: Partial<Record<Skill, string[]>> = {\n NextJS: ['next', 'next-intlayer'],\n React: [\n 'react',\n 'react-intlayer',\n 'react-native-intlayer',\n 'react-scripts-intlayer',\n 'lynx-intlayer',\n ],\n Preact: ['preact', 'preact-intlayer'],\n Solid: ['solid-js', '@solidjs/start', 'solid-intlayer'],\n Vue: ['vue', 'nuxt', 'vue-intlayer', 'nuxt-intlayer'],\n Svelte: ['svelte', '@sveltejs/kit', 'svelte-intlayer'],\n Angular: ['@angular/core', '@analogjs/platform', 'angular-intlayer'],\n Astro: ['astro', 'astro-intlayer'],\n Lit: ['lit', 'lit-intlayer'],\n Vanilla: ['vanilla-intlayer'],\n Remix: ['remix', 'remix-intlayer'],\n Compat: [\n 'i18next',\n 'react-i18next',\n 'next-i18next',\n 'next-intl',\n 'use-intl',\n 'react-intl',\n 'vue-i18n',\n '@lingui/core',\n '@lingui/react',\n '@nuxtjs/i18n',\n '@ngx-translate/core',\n '@jsverse/transloco',\n 'svelte-i18n',\n 'next-translate',\n 'node-polyglot',\n 'i18n-js',\n '@intlayer/i18next',\n '@intlayer/react-i18next',\n '@intlayer/next-i18next',\n '@intlayer/next-intl',\n '@intlayer/use-intl',\n '@intlayer/react-intl',\n '@intlayer/vue-i18n',\n '@intlayer/lingui',\n '@intlayer/sync-json-plugin',\n '@intlayer/sync-po-plugin',\n ],\n Backend: [\n 'express',\n 'fastify',\n 'hono',\n 'elysia',\n '@nestjs/core',\n '@adonisjs/core',\n 'express-intlayer',\n 'fastify-intlayer',\n 'hono-intlayer',\n 'elysia-intlayer',\n 'adonis-intlayer',\n ],\n};\n\n/**\n * Resolves the skills to preselect from the project's installed packages.\n *\n * @param dependencies - Merged `dependencies` and `devDependencies` of `package.json`.\n * @returns The base skills plus every framework skill whose packages are installed.\n */\nexport const getInitialSkills = (\n dependencies: Record<string, string>\n): Skill[] => {\n const detectedSkills = SKILLS.filter((skill) =>\n SKILL_TRIGGER_PACKAGES[skill]?.some(\n (packageName) => packageName in dependencies\n )\n );\n\n return [...BASE_SKILLS, ...detectedSkills];\n};\n\nexport interface PlatformMetadata {\n label: string;\n dir: string;\n check?: () => boolean;\n}\n\n/**\n * Metadata and configuration for each supported platform.\n */\nexport const PLATFORMS_METADATA: Record<string, PlatformMetadata> = {\n Cursor: {\n label: 'Cursor',\n dir: '.cursor/skills',\n check: () =>\n process.env.CURSOR === 'true' || process.env.TERM_PROGRAM === 'cursor',\n },\n Windsurf: {\n label: 'Windsurf',\n dir: '.windsurf/skills',\n check: () =>\n process.env.WINDSURF === 'true' ||\n process.env.TERM_PROGRAM === 'windsurf',\n },\n Trae: {\n label: 'Trae',\n dir: '.trae/skills',\n check: () =>\n process.env.TRAE === 'true' || process.env.TERM_PROGRAM === 'trae',\n },\n TraeCN: {\n label: 'Trae CN',\n dir: '.trae/skills',\n check: () => process.env.TRAE_CN === 'true',\n },\n VSCode: {\n label: 'VS Code',\n dir: '.vscode/skills',\n check: () =>\n process.env.VSCODE === 'true' || process.env.TERM_PROGRAM === 'vscode',\n },\n OpenCode: {\n label: 'OpenCode',\n dir: '.opencode/skills',\n check: () => process.env.OPENCODE === 'true',\n },\n Claude: {\n label: 'Claude Code',\n dir: '.claude/skills',\n check: () => process.env.CLAUDE === 'true',\n },\n GitHub: {\n label: 'GitHub Copilot Workspace',\n dir: '.github/skills',\n check: () =>\n process.env.GITHUB_ACTIONS === 'true' || !!process.env.GITHUB_WORKSPACE,\n },\n Antigravity: {\n label: 'Antigravity',\n dir: '.agent/skills',\n },\n Augment: {\n label: 'Augment',\n dir: '.augment/skills',\n },\n OpenClaw: {\n label: 'OpenClaw',\n dir: 'skills',\n },\n Cline: {\n label: 'Cline',\n dir: '.cline/skills',\n },\n CodeBuddy: {\n label: 'CodeBuddy',\n dir: '.codebuddy/skills',\n },\n CommandCode: {\n label: 'Command Code',\n dir: '.commandcode/skills',\n },\n Continue: {\n label: 'Continue',\n dir: '.continue/skills',\n },\n Crush: {\n label: 'Crush',\n dir: '.crush/skills',\n },\n Droid: {\n label: 'Droid',\n dir: '.factory/skills',\n },\n Goose: {\n label: 'Goose',\n dir: '.goose/skills',\n },\n IFlow: {\n label: 'iFlow CLI',\n dir: '.iflow/skills',\n },\n Junie: {\n label: 'Junie',\n dir: '.junie/skills',\n },\n KiloCode: {\n label: 'Kilo Code',\n dir: '.kilocode/skills',\n },\n Kiro: {\n label: 'Kiro CLI',\n dir: '.kiro/skills',\n },\n Kode: {\n label: 'Kode',\n dir: '.kode/skills',\n },\n MCPJam: {\n label: 'MCPJam',\n dir: '.mcpjam/skills',\n },\n MistralVibe: {\n label: 'Mistral Vibe',\n dir: '.vibe/skills',\n },\n Mux: {\n label: 'Mux',\n dir: '.mux/skills',\n },\n OpenHands: {\n label: 'OpenHands',\n dir: '.openhands/skills',\n },\n Pi: {\n label: 'Pi',\n dir: '.pi/skills',\n },\n Qoder: {\n label: 'Qoder',\n dir: '.qoder/skills',\n },\n Qwen: {\n label: 'Qwen Code',\n dir: '.qwen/skills',\n },\n RooCode: {\n label: 'Roo Code',\n dir: '.roo/skills',\n },\n Zencoder: {\n label: 'Zencoder',\n dir: '.zencoder/skills',\n },\n Neovate: {\n label: 'Neovate',\n dir: '.neovate/skills',\n },\n Pochi: {\n label: 'Pochi',\n dir: '.pochi/skills',\n },\n Other: {\n label: 'Other',\n dir: 'skills',\n },\n} as const;\n\nexport type Platform = keyof typeof PLATFORMS_METADATA;\n\nexport const PLATFORMS = Object.keys(PLATFORMS_METADATA) as Platform[];\n\n/**\n * Maps specific skill keys to special filenames if they differ from standard snake_case.\n */\nconst SKILL_FILENAME_MAP: Partial<Record<Skill, string>> = {};\n\n/**\n * Helper to convert CamelCase to kebab-case for directory naming\n */\nconst camelToKebabCase = (str: string) =>\n str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();\n\n/**\n * Reads the raw markdown content for a specific skill from the assets folder.\n */\nconst getSkillContent = (skill: Skill): string => {\n const baseName = SKILL_FILENAME_MAP[skill] ?? camelToKebabCase(skill);\n const fileName = `./skills/${baseName}.md`;\n\n try {\n return readAsset(fileName);\n } catch {\n console.warn(\n `Warning: Could not read asset for skill: ${skill} at ${fileName}`\n );\n return '';\n }\n};\n\n/**\n * Reads the licence content from the assets folder.\n */\nconst getLicenceContent = (): string => {\n try {\n return readAsset('./LICENCE.md');\n } catch {\n console.warn('Warning: Could not read LICENCE.md asset');\n return '';\n }\n};\n\nconst ALLOWED_FETCH_HOSTS = new Set(['intlayer.org']);\n\n/** Upper bound on the redirect chain a reference URL may take. */\nconst MAX_FETCH_REDIRECTS = 5;\n\n/**\n * Parses a URL and rejects it unless it is an HTTPS address on an allowed host.\n *\n * @param url - Absolute URL to validate.\n * @returns The parsed URL.\n * @throws When the protocol or host is not allowed.\n */\nconst parseAllowedUrl = (url: string | URL): URL => {\n const parsed = new URL(url);\n\n if (\n parsed.protocol !== 'https:' ||\n !ALLOWED_FETCH_HOSTS.has(parsed.hostname)\n ) {\n throw new Error(`Blocked fetch to disallowed host: ${parsed.hostname}`);\n }\n\n return parsed;\n};\n\n/**\n * Fetches the content of a URL using native fetch.\n *\n * Redirects are followed manually so every hop is re-checked against the host\n * allowlist — a redirect off `intlayer.org` is refused rather than silently\n * followed. Letting `fetch` refuse them outright (`redirect: 'error'`) instead\n * reported an unhelpful `TypeError: fetch failed` for a documentation URL that\n * merely moved.\n *\n * @param url - Absolute URL to read.\n * @returns The response body as text.\n */\nconst fetchUrlContent = async (url: string): Promise<string> => {\n let target = parseAllowedUrl(url);\n\n for (let hop = 0; hop <= MAX_FETCH_REDIRECTS; hop++) {\n const response = await fetch(target, { redirect: 'manual' });\n\n if (response.status >= 300 && response.status < 400) {\n const location = response.headers.get('location');\n\n if (!location) {\n throw new Error(`Failed to fetch ${url}: redirect without a location`);\n }\n\n target = parseAllowedUrl(new URL(location, target));\n continue;\n }\n\n if (!response.ok) {\n throw new Error(`Failed to fetch ${url}: ${response.statusText}`);\n }\n\n return response.text();\n }\n\n throw new Error(`Failed to fetch ${url}: too many redirects`);\n};\n\n/**\n * Installs skills using the \"Agent Skills\" directory standard.\n * Standard: <PROJECT_ROOT>/<CONFIG_DIR>/skills/<SKILL_NAME>/SKILL.md\n */\nexport const installSkills = async (\n projectRoot: string,\n platform: Platform,\n skills: Skill[]\n): Promise<string> => {\n // Determine destination directory\n const relativeDir = PLATFORMS_METADATA[platform]?.dir ?? 'skills';\n const skillsBaseDir = path.join(projectRoot, relativeDir);\n\n // Ensure the base directory exists\n await fs.mkdir(skillsBaseDir, { recursive: true });\n\n const createdSkills: string[] = [];\n const licenceContent = getLicenceContent();\n\n for (const skill of skills) {\n const baseName = SKILL_FILENAME_MAP[skill] ?? camelToKebabCase(skill);\n const skillName = `intlayer-${baseName}`;\n const skillContent = getSkillContent(skill);\n\n if (!skillContent) continue;\n\n // Extract unique URLs\n const urls = Array.from(\n new Set(skillContent.match(/https:\\/\\/intlayer\\.org\\/[^\\s)]+\\.md/g) || [])\n );\n\n // Agent Standard: .../skills/<skill-name>/SKILL.md\n const skillDir = path.join(skillsBaseDir, skillName);\n const referenceDir = path.join(skillDir, 'references');\n\n // Ensure directories exist\n await fs.mkdir(referenceDir, { recursive: true });\n\n // Write License\n if (licenceContent) {\n await fs.writeFile(\n path.join(skillDir, 'LICENCE.md'),\n licenceContent,\n 'utf-8'\n );\n }\n\n let updatedSkillContent = skillContent;\n\n // Parallel download of references\n const downloadPromises = urls.map(async (url) => {\n try {\n const content = await fetchUrlContent(url);\n const metadata = getMarkdownMetadata<{ slugs?: string[] }>(content);\n\n let fileName = '';\n\n // Determine filename from slugs or URL path\n if (Array.isArray(metadata.slugs)) {\n fileName = metadata.slugs\n .filter((slug) => slug !== 'doc')\n .join('_')\n // Scoped package slugs (`@intlayer/babel`) must not create subfolders\n .replaceAll('/', '_');\n } else {\n const urlPath = new URL(url).pathname;\n fileName = urlPath\n .split('/')\n .filter((part) => part && part !== 'doc')\n .map((part) => part.replace('.md', '')) // Clean extension for joining\n .join('_');\n }\n\n // Ensure it ends with .md\n fileName = fileName ? `${fileName}.md` : 'index.md';\n const localRefPath = `references/${fileName}`;\n\n return {\n url,\n localRefPath,\n fileName,\n content,\n success: true,\n };\n } catch (error) {\n console.warn(\n `Warning: Failed to download ref ${url} for skill ${skill}`,\n error\n );\n return { url, success: false };\n }\n });\n\n const results = await Promise.all(downloadPromises);\n\n // Process results: Write files and update content string\n for (const res of results) {\n if (res.success && res.fileName && res.content && res.localRefPath) {\n // Write the reference file\n await fs.writeFile(\n path.join(referenceDir, res.fileName),\n res.content,\n 'utf-8'\n );\n\n // Update the main content to point to local file\n updatedSkillContent = updatedSkillContent.replaceAll(\n res.url,\n res.localRefPath\n );\n }\n }\n\n // Write the main SKILL.md\n const filePath = path.join(skillDir, 'SKILL.md');\n await fs.writeFile(filePath, updatedSkillContent, 'utf-8');\n createdSkills.push(`${skillName}/SKILL.md`);\n }\n\n if (createdSkills.length === 0) {\n return `No skill files were created. Check your asset paths.`;\n }\n\n return `${v} Created ${createdSkills.length} skills in ${skillsBaseDir}`;\n};\n"],"mappings":";;;;;;;;;;AASA,MAAa,kBAAkB;CAC7B,QAAQ;CACR,SAAS;CACT,UACE;CACF,OAAO;CACP,KAAK;CACL,UACE;CACF,eAAe;CACf,UAAU;CACV,QACE;CACF,QAAQ;CACR,OAAO;CACP,KAAK;CACL,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,OAAO;CACP,OAAO;CACP,KAAK;CACL,SAAS;CACT,OAAO;CACP,SACE;AACJ;AAIA,MAAa,SAAS,OAAO,KAAK,eAAe;;AAGjD,MAAM,cAAuB;CAC3B;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;AAOA,MAAM,yBAA2D;CAC/D,QAAQ,CAAC,QAAQ,eAAe;CAChC,OAAO;EACL;EACA;EACA;EACA;EACA;CACF;CACA,QAAQ,CAAC,UAAU,iBAAiB;CACpC,OAAO;EAAC;EAAY;EAAkB;CAAgB;CACtD,KAAK;EAAC;EAAO;EAAQ;EAAgB;CAAe;CACpD,QAAQ;EAAC;EAAU;EAAiB;CAAiB;CACrD,SAAS;EAAC;EAAiB;EAAsB;CAAkB;CACnE,OAAO,CAAC,SAAS,gBAAgB;CACjC,KAAK,CAAC,OAAO,cAAc;CAC3B,SAAS,CAAC,kBAAkB;CAC5B,OAAO,CAAC,S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AGlD,KAAK,MAAM,OAAO,SAChB,IAAI,IAAI,WAAW,IAAI,YAAY,IAAI,WAAW,IAAI,cAAc;GAElE,MAAMA,SAAG,UACP,KAAK,KAAK,cAAc,IAAI,QAAQ,GACpC,IAAI,SACJ,OACF;GAGA,sBAAsB,oBAAoB,WACxC,IAAI,KACJ,IAAI,YACN;EACF;EAIF,MAAM,WAAW,KAAK,KAAK,UAAU,UAAU;EAC/C,MAAMA,SAAG,UAAU,UAAU,qBAAqB,OAAO;EACzD,cAAc,KAAK,GAAG,UAAU,UAAU;CAC5C;CAEA,IAAI,cAAc,WAAW,GAC3B,OAAO;CAGT,OAAO,GAAG,EAAE,WAAW,cAAc,OAAO,aAAa;AAC3D"}
@@ -1,5 +1,5 @@
1
1
  import { rmSync } from "node:fs";
2
- import { mkdir, readFile, stat, unlink, writeFile } from "node:fs/promises";
2
+ import { mkdir, readFile, rmdir, stat, unlink, writeFile } from "node:fs/promises";
3
3
  import { dirname } from "node:path";
4
4
  import packageJson from "@intlayer/core/package.json" with { type: "json" };
5
5
 
@@ -20,6 +20,12 @@ process.on("exit", () => {
20
20
  for (const sentinelFilePath of ownedSentinelFilePaths) try {
21
21
  rmSync(sentinelFilePath, { force: true });
22
22
  } catch {}
23
+ for (const mutexDirPath of ownedMutexDirPaths) try {
24
+ rmSync(mutexDirPath, {
25
+ recursive: true,
26
+ force: true
27
+ });
28
+ } catch {}
23
29
  });
24
30
  /**
25
31
  * Reads the sentinel file, returning `undefined` when it does not exist or
@@ -100,6 +106,53 @@ const removeSentinel = async (sentinelFilePath) => {
100
106
  await unlink(sentinelFilePath);
101
107
  } catch {}
102
108
  };
109
+ /** Delay between two attempts to enter the sentinel critical section. */
110
+ const MUTEX_POLL_INTERVAL_MS = 10;
111
+ /**
112
+ * A critical-section mutex older than this was left behind by a process that
113
+ * died while holding it, and can be taken over.
114
+ */
115
+ const MUTEX_STALE_MS = 1e4;
116
+ /** Mutex directories owned by this process, released on exit like sentinels. */
117
+ const ownedMutexDirPaths = /* @__PURE__ */ new Set();
118
+ /**
119
+ * Serializes the "read the sentinel, decide, replace it" sequence across
120
+ * processes so it behaves as a compare-and-swap.
121
+ *
122
+ * Without it, two contenders reading the same stale sentinel could both remove
123
+ * it, and the slower one would delete the `running` sentinel the faster one
124
+ * had just created — letting two callbacks run at once. A directory is used
125
+ * because `mkdir` is atomic on every platform.
126
+ */
127
+ const withSentinelMutex = async (sentinelFilePath, criticalSection) => {
128
+ const mutexDirPath = `${sentinelFilePath}.mutex`;
129
+ while (true) try {
130
+ await mkdir(dirname(sentinelFilePath), { recursive: true });
131
+ await mkdir(mutexDirPath);
132
+ break;
133
+ } catch (error) {
134
+ const code = error.code;
135
+ if (code === "ENOENT") continue;
136
+ if (code !== "EEXIST") throw error;
137
+ try {
138
+ const mutexStats = await stat(mutexDirPath);
139
+ if (Date.now() - mutexStats.mtime.getTime() > MUTEX_STALE_MS) {
140
+ await rmdir(mutexDirPath).catch(() => {});
141
+ continue;
142
+ }
143
+ } catch {
144
+ continue;
145
+ }
146
+ await delay(MUTEX_POLL_INTERVAL_MS);
147
+ }
148
+ ownedMutexDirPaths.add(mutexDirPath);
149
+ try {
150
+ return await criticalSection();
151
+ } finally {
152
+ ownedMutexDirPaths.delete(mutexDirPath);
153
+ await rmdir(mutexDirPath).catch(() => {});
154
+ }
155
+ };
103
156
  /**
104
157
  * Ensures a callback function runs only once within a specified time window across multiple processes.
105
158
  * Uses a sentinel file to coordinate execution and prevent duplicate work.
@@ -135,24 +188,22 @@ const runOnce = async (sentinelFilePath, callback, options) => {
135
188
  const currentTimestamp = Date.now();
136
189
  const waitDeadline = currentTimestamp + lockWaitTimeoutMs;
137
190
  while (true) {
138
- const sentinelState = await readSentinelState(sentinelFilePath);
139
- if (sentinelState) {
140
- const sentinelAge = Date.now() - sentinelState.mtimeMs;
141
- if (sentinelState.status === "running") {
142
- if (!(sentinelAge > lockWaitTimeoutMs || !isOwnerProcessAlive(sentinelState.pid)) && Date.now() < waitDeadline) {
143
- await delay(LOCK_POLL_INTERVAL_MS);
144
- continue;
145
- }
191
+ const outcome = await withSentinelMutex(sentinelFilePath, async () => {
192
+ const sentinelState = await readSentinelState(sentinelFilePath);
193
+ if (sentinelState) {
194
+ const sentinelAge = Date.now() - sentinelState.mtimeMs;
195
+ if (sentinelState.status === "running") {
196
+ if (!(sentinelAge > lockWaitTimeoutMs || !isOwnerProcessAlive(sentinelState.pid)) && Date.now() < waitDeadline) return "wait";
197
+ } else if (!forceRun && sentinelAge <= cacheTimeoutMs && sentinelState.version === packageJson.version) return "cached";
146
198
  await removeSentinel(sentinelFilePath);
147
- continue;
148
- }
149
- if (!forceRun && sentinelAge <= cacheTimeoutMs && sentinelState.version === packageJson.version) {
150
- await onIsCached?.();
151
- return;
152
199
  }
153
- await removeSentinel(sentinelFilePath);
200
+ return await acquireSentinel(sentinelFilePath, currentTimestamp) ? "acquired" : "wait";
201
+ });
202
+ if (outcome === "cached") {
203
+ await onIsCached?.();
204
+ return;
154
205
  }
155
- if (await acquireSentinel(sentinelFilePath, currentTimestamp)) break;
206
+ if (outcome === "acquired") break;
156
207
  await delay(LOCK_POLL_INTERVAL_MS);
157
208
  }
158
209
  ownedSentinelFilePaths.add(sentinelFilePath);
@@ -1 +1 @@
1
- {"version":3,"file":"runOnce.mjs","names":[],"sources":["../../../src/utils/runOnce.ts"],"sourcesContent":["import { rmSync } from 'node:fs';\nimport { mkdir, readFile, stat, unlink, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport packageJson from '@intlayer/core/package.json' with { type: 'json' };\n\n/**\n * Lifecycle of the run described by a sentinel file.\n *\n * - `running` — a process owns the sentinel and its callback is still in flight.\n * Other processes must wait instead of starting a concurrent run.\n * - `done` — the callback completed; the sentinel is now a plain cache marker.\n */\ntype SentinelStatus = 'running' | 'done';\n\ntype SentinelData = {\n version: string;\n timestamp: number;\n status: SentinelStatus;\n /** PID of the process that owns the sentinel, used to detect abandoned locks. */\n pid: number;\n};\n\n/** Sentinel state as read from disk, enriched with the file's modification time. */\ntype SentinelState = SentinelData & { mtimeMs: number };\n\n/**\n * Context handed to the callback so it can interact with the lock it runs under.\n */\nexport type RunOnceContext = {\n /**\n * Re-create the sentinel file after an operation that may have deleted it —\n * typically cleaning the output directory, which wipes the cache directory the\n * sentinel lives in. Without this, concurrent processes would see no lock and\n * start a competing run while this one is still writing.\n */\n renewLock: () => Promise<void>;\n};\n\ntype RunOnceOptions = {\n /**\n * The function to execute when the sentinel is not found or is older than the cache timeout.\n */\n onIsCached?: () => void | Promise<void>;\n /**\n * The time window in milliseconds during which the sentinel is considered valid.\n *\n * @default 60000 = 1 minute\n */\n cacheTimeoutMs?: number;\n /**\n * If true, the callback will always run. If undefined, the callback will run only if the sentinel is older than the cache timeout.\n *\n * @default false\n */\n forceRun?: boolean;\n /**\n * How long to wait for another process to release the sentinel before\n * considering its run abandoned and taking the lock over.\n *\n * @default 300000 = 5 minutes\n */\n lockWaitTimeoutMs?: number;\n};\n\nconst DEFAULT_RUN_ONCE_OPTIONS = {\n cacheTimeoutMs: 60 * 1000, // 1 minute in milliseconds,\n lockWaitTimeoutMs: 5 * 60 * 1000, // 5 minutes in milliseconds\n} satisfies RunOnceOptions;\n\n/** Delay between two reads of a sentinel owned by another process. */\nconst LOCK_POLL_INTERVAL_MS = 50;\n\nconst delay = (durationMs: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, durationMs));\n\n/**\n * Sentinels owned by this process, released synchronously on exit so a crash or\n * a Ctrl-C never leaves a `running` lock that would stall the next run.\n */\nconst ownedSentinelFilePaths = new Set<string>();\n\nprocess.on('exit', () => {\n for (const sentinelFilePath of ownedSentinelFilePaths) {\n try {\n rmSync(sentinelFilePath, { force: true });\n } catch {}\n }\n});\n\n/**\n * Reads the sentinel file, returning `undefined` when it does not exist or\n * cannot be parsed.\n *\n * Sentinels written by older versions carry no `status`; they always describe a\n * finished run, so they are reported as `done`.\n */\nconst readSentinelState = async (\n sentinelFilePath: string\n): Promise<SentinelState | undefined> => {\n try {\n const [sentinelStats, raw] = await Promise.all([\n stat(sentinelFilePath),\n readFile(sentinelFilePath, 'utf8'),\n ]);\n\n const parsed = JSON.parse(raw) as Partial<SentinelData>;\n\n return {\n version: parsed.version ?? '',\n timestamp: parsed.timestamp ?? 0,\n status: parsed.status ?? 'done',\n pid: parsed.pid ?? 0,\n mtimeMs: sentinelStats.mtime.getTime(),\n };\n } catch {\n return undefined;\n }\n};\n\n/**\n * Whether the process that wrote the sentinel is still alive. An unknown PID\n * (legacy sentinel) is assumed alive so the staleness timeout stays the only\n * way to reclaim it.\n */\nconst isOwnerProcessAlive = (pid: number): boolean => {\n if (!pid || pid === process.pid) return true;\n\n try {\n // Signal 0 performs an existence check without delivering a signal.\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // EPERM means the process exists but belongs to another user.\n return (error as NodeJS.ErrnoException).code === 'EPERM';\n }\n};\n\nconst serializeSentinel = (timestamp: number, status: SentinelStatus): string =>\n JSON.stringify({\n version: packageJson.version,\n timestamp,\n status,\n pid: process.pid,\n } satisfies SentinelData);\n\n/**\n * Attempts to take ownership of the sentinel.\n *\n * `wx` makes the creation atomic, so exactly one process can win even when\n * several start at the same moment.\n *\n * @returns `true` when this process now owns the sentinel, `false` when another\n * process created it first.\n */\nconst acquireSentinel = async (\n sentinelFilePath: string,\n timestamp: number\n): Promise<boolean> => {\n const data = serializeSentinel(timestamp, 'running');\n\n for (let attempt = 0; attempt < 2; attempt++) {\n try {\n // Ensure the directory exists before writing the file\n await mkdir(dirname(sentinelFilePath), { recursive: true });\n\n await writeFile(sentinelFilePath, data, { flag: 'wx' });\n return true;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n\n if (code === 'EEXIST') return false;\n // The directory was removed between the mkdir and the write (e.g. a\n // concurrent output-directory clean); retry once.\n if (code === 'ENOENT' && attempt === 0) continue;\n\n throw error;\n }\n }\n\n return false;\n};\n\n/**\n * Rewrites the sentinel owned by this process, overwriting any existing file.\n */\nconst writeOwnedSentinel = async (\n sentinelFilePath: string,\n timestamp: number,\n status: SentinelStatus\n): Promise<void> => {\n try {\n await mkdir(dirname(sentinelFilePath), { recursive: true });\n await writeFile(sentinelFilePath, serializeSentinel(timestamp, status));\n } catch {}\n};\n\nconst removeSentinel = async (sentinelFilePath: string): Promise<void> => {\n try {\n await unlink(sentinelFilePath);\n } catch {}\n};\n\n/**\n * Ensures a callback function runs only once within a specified time window across multiple processes.\n * Uses a sentinel file to coordinate execution and prevent duplicate work.\n *\n * Processes that lose the race for the sentinel wait for the owner to finish\n * rather than running a competing copy of the callback — concurrent runs would\n * otherwise write to (and clean) the same output directory at the same time.\n *\n * @param sentinelFilePath - Path to the sentinel file used for coordination\n * @param callback - The function to execute (should be async)\n * @param options - The options for the runOnce function\n *\n * @example\n * ```typescript\n * await runOnce(\n * '/tmp/intlayer-sentinel',\n * async ({ renewLock }) => {\n * await cleanOutputDir(configuration); // may delete the sentinel\n * await renewLock();\n * await prepareIntlayer();\n * },\n * { cacheTimeoutMs: 30 * 1000 } // 30 seconds cache\n * );\n * ```\n *\n * @throws {Error} When there are unexpected filesystem errors\n */\nexport const runOnce = async (\n sentinelFilePath: string,\n callback: (context: RunOnceContext) => void | Promise<void>,\n options?: RunOnceOptions\n) => {\n const { onIsCached, cacheTimeoutMs, forceRun, lockWaitTimeoutMs } = {\n ...DEFAULT_RUN_ONCE_OPTIONS,\n ...(options ?? {}),\n };\n const currentTimestamp = Date.now();\n const waitDeadline = currentTimestamp + lockWaitTimeoutMs;\n\n // Acquisition loop: read the sentinel, then either return early (fresh cache),\n // wait for the current owner, or take the lock. Every branch either returns or\n // makes progress, so the loop always terminates.\n while (true) {\n const sentinelState = await readSentinelState(sentinelFilePath);\n\n if (sentinelState) {\n const sentinelAge = Date.now() - sentinelState.mtimeMs;\n\n if (sentinelState.status === 'running') {\n const isAbandoned =\n sentinelAge > lockWaitTimeoutMs ||\n !isOwnerProcessAlive(sentinelState.pid);\n\n if (!isAbandoned && Date.now() < waitDeadline) {\n await delay(LOCK_POLL_INTERVAL_MS);\n continue;\n }\n\n // The owner died or overran the timeout: reclaim the sentinel.\n await removeSentinel(sentinelFilePath);\n continue;\n }\n\n const isCacheValid =\n !forceRun &&\n sentinelAge <= cacheTimeoutMs &&\n sentinelState.version === packageJson.version;\n\n if (isCacheValid) {\n await onIsCached?.();\n return;\n }\n\n await removeSentinel(sentinelFilePath);\n }\n\n const hasAcquiredSentinel = await acquireSentinel(\n sentinelFilePath,\n currentTimestamp\n );\n\n if (hasAcquiredSentinel) break;\n\n // Another process won the race in the meantime: loop back and wait for it.\n // The delay also guarantees the loop yields, so a sentinel being repeatedly\n // created and removed can never turn into a busy wait.\n await delay(LOCK_POLL_INTERVAL_MS);\n }\n\n ownedSentinelFilePaths.add(sentinelFilePath);\n\n const renewLock = () =>\n writeOwnedSentinel(sentinelFilePath, currentTimestamp, 'running');\n\n try {\n await callback({ renewLock });\n\n // Mark the run as finished, re-creating the sentinel if the callback\n // deleted it (e.g. by cleaning the output directory).\n await writeOwnedSentinel(sentinelFilePath, currentTimestamp, 'done');\n } catch {\n await removeSentinel(sentinelFilePath); // Remove sentinel file if an error occurs\n } finally {\n ownedSentinelFilePaths.delete(sentinelFilePath);\n }\n};\n"],"mappings":";;;;;;AAgEA,MAAM,2BAA2B;CAC/B,gBAAgB;CAChB,mBAAmB;AACrB;;AAGA,MAAM,wBAAwB;AAE9B,MAAM,SAAS,eACb,IAAI,SAAS,YAAY,WAAW,SAAS,UAAU,CAAC;;;;;AAM1D,MAAM,yCAAyB,IAAI,IAAY;AAE/C,QAAQ,GAAG,cAAc;CACvB,KAAK,MAAM,oBAAoB,wBAC7B,IAAI;EACF,OAAO,kBAAkB,EAAE,OAAO,KAAK,CAAC;CAC1C,QAAQ,CAAC;AAEb,CAAC;;;;;;;;AASD,MAAM,oBAAoB,OACxB,qBACuC;CACvC,IAAI;EACF,MAAM,CAAC,eAAe,OAAO,MAAM,QAAQ,IAAI,CAC7C,KAAK,gBAAgB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O,gBAAgB;CAC/B,QAAQ,CAAC;AACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAa,UAAU,OACrB,kBACA,UACA,YACG;CACH,MAAM,EAAE,YAAY,gBAAgB,UAAU,sBAAsB;EAClE,GAAG;EACH,GAAI,WAAW,CAAC;CAClB;CACA,MAAM,mBAAmB,KAAK,IAAI;CAClC,MAAM,eAAe,mBAAmB;CAKxC,OAAO,MAAM;EACX,MAAM,gBAAgB,MAAM,kBAAkB,gBAAgB;EAE9D,IAAI,eAAe;GACjB,MAAM,cAAc,KAAK,IAAI,IAAI,cAAc;GAE/C,IAAI,cAAc,WAAW,WAAW;IAKtC,IAAI,EAHF,cAAc,qBACd,CAAC,oBAAoB,cAAc,GAAG,MAEpB,KAAK,IAAI,IAAI,cAAc;KAC7C,MAAM,MAAM,qBAAqB;KACjC;IACF;IAGA,MAAM,eAAe,gBAAgB;IACrC;GACF;GAOA,IAJE,CAAC,YACD,eAAe,kBACf,cAAc,YAAY,YAAY,SAEtB;IAChB,MAAM,aAAa;IACnB;GACF;GAEA,MAAM,eAAe,gBAAgB;EACvC;EAOA,IAAI,MAL8B,gBAChC,kBACA,gBACF,GAEyB;EAKzB,MAAM,MAAM,qBAAqB;CACnC;CAEA,uBAAuB,IAAI,gBAAgB;CAE3C,MAAM,kBACJ,mBAAmB,kBAAkB,kBAAkB,SAAS;CAElE,IAAI;EACF,MAAM,SAAS,EAAE,UAAU,CAAC;EAI5B,MAAM,mBAAmB,kBAAkB,kBAAkB,MAAM;CACrE,QAAQ;EACN,MAAM,eAAe,gBAAgB;CACvC,UAAU;EACR,uBAAuB,OAAO,gBAAgB;CAChD;AACF"}
1
+ {"version":3,"file":"runOnce.mjs","names":[],"sources":["../../../src/utils/runOnce.ts"],"sourcesContent":["import { rmSync } from 'node:fs';\nimport {\n mkdir,\n readFile,\n rmdir,\n stat,\n unlink,\n writeFile,\n} from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport packageJson from '@intlayer/core/package.json' with { type: 'json' };\n\n/**\n * Lifecycle of the run described by a sentinel file.\n *\n * - `running` — a process owns the sentinel and its callback is still in flight.\n * Other processes must wait instead of starting a concurrent run.\n * - `done` — the callback completed; the sentinel is now a plain cache marker.\n */\ntype SentinelStatus = 'running' | 'done';\n\ntype SentinelData = {\n version: string;\n timestamp: number;\n status: SentinelStatus;\n /** PID of the process that owns the sentinel, used to detect abandoned locks. */\n pid: number;\n};\n\n/** Sentinel state as read from disk, enriched with the file's modification time. */\ntype SentinelState = SentinelData & { mtimeMs: number };\n\n/**\n * Context handed to the callback so it can interact with the lock it runs under.\n */\nexport type RunOnceContext = {\n /**\n * Re-create the sentinel file after an operation that may have deleted it —\n * typically cleaning the output directory, which wipes the cache directory the\n * sentinel lives in. Without this, concurrent processes would see no lock and\n * start a competing run while this one is still writing.\n */\n renewLock: () => Promise<void>;\n};\n\ntype RunOnceOptions = {\n /**\n * The function to execute when the sentinel is not found or is older than the cache timeout.\n */\n onIsCached?: () => void | Promise<void>;\n /**\n * The time window in milliseconds during which the sentinel is considered valid.\n *\n * @default 60000 = 1 minute\n */\n cacheTimeoutMs?: number;\n /**\n * If true, the callback will always run. If undefined, the callback will run only if the sentinel is older than the cache timeout.\n *\n * @default false\n */\n forceRun?: boolean;\n /**\n * How long to wait for another process to release the sentinel before\n * considering its run abandoned and taking the lock over.\n *\n * @default 300000 = 5 minutes\n */\n lockWaitTimeoutMs?: number;\n};\n\nconst DEFAULT_RUN_ONCE_OPTIONS = {\n cacheTimeoutMs: 60 * 1000, // 1 minute in milliseconds,\n lockWaitTimeoutMs: 5 * 60 * 1000, // 5 minutes in milliseconds\n} satisfies RunOnceOptions;\n\n/** Delay between two reads of a sentinel owned by another process. */\nconst LOCK_POLL_INTERVAL_MS = 50;\n\nconst delay = (durationMs: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, durationMs));\n\n/**\n * Sentinels owned by this process, released synchronously on exit so a crash or\n * a Ctrl-C never leaves a `running` lock that would stall the next run.\n */\nconst ownedSentinelFilePaths = new Set<string>();\n\nprocess.on('exit', () => {\n for (const sentinelFilePath of ownedSentinelFilePaths) {\n try {\n rmSync(sentinelFilePath, { force: true });\n } catch {}\n }\n for (const mutexDirPath of ownedMutexDirPaths) {\n try {\n rmSync(mutexDirPath, { recursive: true, force: true });\n } catch {}\n }\n});\n\n/**\n * Reads the sentinel file, returning `undefined` when it does not exist or\n * cannot be parsed.\n *\n * Sentinels written by older versions carry no `status`; they always describe a\n * finished run, so they are reported as `done`.\n */\nconst readSentinelState = async (\n sentinelFilePath: string\n): Promise<SentinelState | undefined> => {\n try {\n const [sentinelStats, raw] = await Promise.all([\n stat(sentinelFilePath),\n readFile(sentinelFilePath, 'utf8'),\n ]);\n\n const parsed = JSON.parse(raw) as Partial<SentinelData>;\n\n return {\n version: parsed.version ?? '',\n timestamp: parsed.timestamp ?? 0,\n status: parsed.status ?? 'done',\n pid: parsed.pid ?? 0,\n mtimeMs: sentinelStats.mtime.getTime(),\n };\n } catch {\n return undefined;\n }\n};\n\n/**\n * Whether the process that wrote the sentinel is still alive. An unknown PID\n * (legacy sentinel) is assumed alive so the staleness timeout stays the only\n * way to reclaim it.\n */\nconst isOwnerProcessAlive = (pid: number): boolean => {\n if (!pid || pid === process.pid) return true;\n\n try {\n // Signal 0 performs an existence check without delivering a signal.\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // EPERM means the process exists but belongs to another user.\n return (error as NodeJS.ErrnoException).code === 'EPERM';\n }\n};\n\nconst serializeSentinel = (timestamp: number, status: SentinelStatus): string =>\n JSON.stringify({\n version: packageJson.version,\n timestamp,\n status,\n pid: process.pid,\n } satisfies SentinelData);\n\n/**\n * Attempts to take ownership of the sentinel.\n *\n * `wx` makes the creation atomic, so exactly one process can win even when\n * several start at the same moment.\n *\n * @returns `true` when this process now owns the sentinel, `false` when another\n * process created it first.\n */\nconst acquireSentinel = async (\n sentinelFilePath: string,\n timestamp: number\n): Promise<boolean> => {\n const data = serializeSentinel(timestamp, 'running');\n\n for (let attempt = 0; attempt < 2; attempt++) {\n try {\n // Ensure the directory exists before writing the file\n await mkdir(dirname(sentinelFilePath), { recursive: true });\n\n await writeFile(sentinelFilePath, data, { flag: 'wx' });\n return true;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n\n if (code === 'EEXIST') return false;\n // The directory was removed between the mkdir and the write (e.g. a\n // concurrent output-directory clean); retry once.\n if (code === 'ENOENT' && attempt === 0) continue;\n\n throw error;\n }\n }\n\n return false;\n};\n\n/**\n * Rewrites the sentinel owned by this process, overwriting any existing file.\n */\nconst writeOwnedSentinel = async (\n sentinelFilePath: string,\n timestamp: number,\n status: SentinelStatus\n): Promise<void> => {\n try {\n await mkdir(dirname(sentinelFilePath), { recursive: true });\n await writeFile(sentinelFilePath, serializeSentinel(timestamp, status));\n } catch {}\n};\n\nconst removeSentinel = async (sentinelFilePath: string): Promise<void> => {\n try {\n await unlink(sentinelFilePath);\n } catch {}\n};\n\n/** Delay between two attempts to enter the sentinel critical section. */\nconst MUTEX_POLL_INTERVAL_MS = 10;\n\n/**\n * A critical-section mutex older than this was left behind by a process that\n * died while holding it, and can be taken over.\n */\nconst MUTEX_STALE_MS = 10 * 1000;\n\n/** Mutex directories owned by this process, released on exit like sentinels. */\nconst ownedMutexDirPaths = new Set<string>();\n\n/**\n * Serializes the \"read the sentinel, decide, replace it\" sequence across\n * processes so it behaves as a compare-and-swap.\n *\n * Without it, two contenders reading the same stale sentinel could both remove\n * it, and the slower one would delete the `running` sentinel the faster one\n * had just created — letting two callbacks run at once. A directory is used\n * because `mkdir` is atomic on every platform.\n */\nconst withSentinelMutex = async <TResult>(\n sentinelFilePath: string,\n criticalSection: () => Promise<TResult>\n): Promise<TResult> => {\n const mutexDirPath = `${sentinelFilePath}.mutex`;\n\n while (true) {\n try {\n await mkdir(dirname(sentinelFilePath), { recursive: true });\n // Non-recursive on purpose: `recursive` swallows EEXIST\n await mkdir(mutexDirPath);\n break;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n\n // The parent directory was removed between the two `mkdir` calls (e.g. a\n // concurrent output-directory clean): recreate it and retry.\n if (code === 'ENOENT') continue;\n if (code !== 'EEXIST') throw error;\n\n try {\n const mutexStats = await stat(mutexDirPath);\n\n if (Date.now() - mutexStats.mtime.getTime() > MUTEX_STALE_MS) {\n await rmdir(mutexDirPath).catch(() => {});\n continue;\n }\n } catch {\n // The holder released it in the meantime: retry right away\n continue;\n }\n\n await delay(MUTEX_POLL_INTERVAL_MS);\n }\n }\n\n ownedMutexDirPaths.add(mutexDirPath);\n\n try {\n return await criticalSection();\n } finally {\n ownedMutexDirPaths.delete(mutexDirPath);\n await rmdir(mutexDirPath).catch(() => {});\n }\n};\n\n/** Outcome of one pass through the sentinel critical section. */\ntype AcquisitionOutcome = 'acquired' | 'cached' | 'wait';\n\n/**\n * Ensures a callback function runs only once within a specified time window across multiple processes.\n * Uses a sentinel file to coordinate execution and prevent duplicate work.\n *\n * Processes that lose the race for the sentinel wait for the owner to finish\n * rather than running a competing copy of the callback — concurrent runs would\n * otherwise write to (and clean) the same output directory at the same time.\n *\n * @param sentinelFilePath - Path to the sentinel file used for coordination\n * @param callback - The function to execute (should be async)\n * @param options - The options for the runOnce function\n *\n * @example\n * ```typescript\n * await runOnce(\n * '/tmp/intlayer-sentinel',\n * async ({ renewLock }) => {\n * await cleanOutputDir(configuration); // may delete the sentinel\n * await renewLock();\n * await prepareIntlayer();\n * },\n * { cacheTimeoutMs: 30 * 1000 } // 30 seconds cache\n * );\n * ```\n *\n * @throws {Error} When there are unexpected filesystem errors\n */\nexport const runOnce = async (\n sentinelFilePath: string,\n callback: (context: RunOnceContext) => void | Promise<void>,\n options?: RunOnceOptions\n) => {\n const { onIsCached, cacheTimeoutMs, forceRun, lockWaitTimeoutMs } = {\n ...DEFAULT_RUN_ONCE_OPTIONS,\n ...(options ?? {}),\n };\n const currentTimestamp = Date.now();\n const waitDeadline = currentTimestamp + lockWaitTimeoutMs;\n\n // Acquisition loop: read the sentinel, then either return early (fresh cache),\n // wait for the current owner, or take the lock. Every branch either returns or\n // makes progress, so the loop always terminates.\n while (true) {\n const outcome = await withSentinelMutex(\n sentinelFilePath,\n async (): Promise<AcquisitionOutcome> => {\n const sentinelState = await readSentinelState(sentinelFilePath);\n\n if (sentinelState) {\n const sentinelAge = Date.now() - sentinelState.mtimeMs;\n\n if (sentinelState.status === 'running') {\n const isAbandoned =\n sentinelAge > lockWaitTimeoutMs ||\n !isOwnerProcessAlive(sentinelState.pid);\n\n if (!isAbandoned && Date.now() < waitDeadline) return 'wait';\n // The owner died or overran the timeout: reclaim the sentinel below.\n } else {\n const isCacheValid =\n !forceRun &&\n sentinelAge <= cacheTimeoutMs &&\n sentinelState.version === packageJson.version;\n\n if (isCacheValid) return 'cached';\n }\n\n await removeSentinel(sentinelFilePath);\n }\n\n const hasAcquiredSentinel = await acquireSentinel(\n sentinelFilePath,\n currentTimestamp\n );\n\n return hasAcquiredSentinel ? 'acquired' : 'wait';\n }\n );\n\n if (outcome === 'cached') {\n await onIsCached?.();\n return;\n }\n\n if (outcome === 'acquired') break;\n\n // Another process owns the sentinel: wait for it, then look again. The\n // delay also guarantees the loop yields, so it can never turn into a busy\n // wait.\n await delay(LOCK_POLL_INTERVAL_MS);\n }\n\n ownedSentinelFilePaths.add(sentinelFilePath);\n\n const renewLock = () =>\n writeOwnedSentinel(sentinelFilePath, currentTimestamp, 'running');\n\n try {\n await callback({ renewLock });\n\n // Mark the run as finished, re-creating the sentinel if the callback\n // deleted it (e.g. by cleaning the output directory).\n await writeOwnedSentinel(sentinelFilePath, currentTimestamp, 'done');\n } catch {\n await removeSentinel(sentinelFilePath); // Remove sentinel file if an error occurs\n } finally {\n ownedSentinelFilePaths.delete(sentinelFilePath);\n }\n};\n"],"mappings":";;;;;;AAuEA,MAAM,2BAA2B;CAC/B,gBAAgB;CAChB,mBAAmB;AACrB;;AAGA,MAAM,wBAAwB;AAE9B,MAAM,SAAS,eACb,IAAI,SAAS,YA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AC,YAAY,CAAC,CAAC;CAC1C;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAa,UAAU,OACrB,kBACA,UACA,YACG;CACH,MAAM,EAAE,YAAY,gBAAgB,UAAU,sBAAsB;EAClE,GAAG;EACH,GAAI,WAAW,CAAC;CAClB;CACA,MAAM,mBAAmB,KAAK,IAAI;CAClC,MAAM,eAAe,mBAAmB;CAKxC,OAAO,MAAM;EACX,MAAM,UAAU,MAAM,kBACpB,kBACA,YAAyC;GACvC,MAAM,gBAAgB,MAAM,kBAAkB,gBAAgB;GAE9D,IAAI,eAAe;IACjB,MAAM,cAAc,KAAK,IAAI,IAAI,cAAc;IAE/C,IAAI,cAAc,WAAW,WAK3B;SAAI,EAHF,cAAc,qBACd,CAAC,oBAAoB,cAAc,GAAG,MAEpB,KAAK,IAAI,IAAI,cAAc,OAAO;IAAM,OAQ5D,IAJE,CAAC,YACD,eAAe,kBACf,cAAc,YAAY,YAAY,SAEtB,OAAO;IAG3B,MAAM,eAAe,gBAAgB;GACvC;GAOA,OAAO,MAL2B,gBAChC,kBACA,gBACF,IAE6B,aAAa;EAC5C,CACF;EAEA,IAAI,YAAY,UAAU;GACxB,MAAM,aAAa;GACnB;EACF;EAEA,IAAI,YAAY,YAAY;EAK5B,MAAM,MAAM,qBAAqB;CACnC;CAEA,uBAAuB,IAAI,gBAAgB;CAE3C,MAAM,kBACJ,mBAAmB,kBAAkB,kBAAkB,SAAS;CAElE,IAAI;EACF,MAAM,SAAS,EAAE,UAAU,CAAC;EAI5B,MAAM,mBAAmB,kBAAkB,kBAAkB,MAAM;CACrE,QAAQ;EACN,MAAM,eAAe,gBAAgB;CACvC,UAAU;EACR,uBAAuB,OAAO,gBAAgB;CAChD;AACF"}
@@ -13,6 +13,7 @@ import { CmsCredentials, enableEditorInConfig, setupCmsCredentials, writeCmsCred
13
13
  import { NEXT_INTLAYER_BABEL_CONFIG_CONTENT } from "./init/utils/nextCompilerBabel.js";
14
14
  import "./init/utils/index.js";
15
15
  import { ContentStrategy, InitOptions, getDefaultApplicationURL, initIntlayer } from "./init/index.js";
16
+ import { UpgradeIntlayerPackagesOptions, UpgradeIntlayerPackagesResult, upgradeIntlayerPackages } from "./init/upgradeIntlayerPackages.js";
16
17
  import { installLSP } from "./installLSP.js";
17
18
  import { PLATFORMS, PLATFORMS_METADATA, Platform, PlatformMetadata, SKILLS, SKILLS_METADATA, Skill, getInitialSkills, installSkills } from "./installSkills/index.js";
18
19
  import { MCPTransport, installMCP } from "./installMCP/installMCP.js";
@@ -20,4 +21,4 @@ import { listDictionaries, listDictionariesWithStats } from "./listDictionariesP
20
21
  import { DiffMode, ListGitFilesOptions, ListGitLinesOptions, listGitFiles, listGitLines } from "./listGitFiles.js";
21
22
  import { ListProjectsOptions, getGitRootDir, listProjects } from "./listProjects.js";
22
23
  import { logConfigDetails } from "./logConfigDetails.js";
23
- export { COMPAT_I18N_LIBRARIES, type CmsCredentials, type CompatI18nLibrary, ContentStrategy, DictionaryStatus, DiffMode, InitOptions, ListGitFilesOptions, ListGitLinesOptions, ListProjectsOptions, MCPTransport, NEXT_INTLAYER_BABEL_CONFIG_CONTENT, PLATFORMS, PLATFORMS_METADATA, type PackageManager, Platform, PlatformMetadata, type RoutingMode, SKILLS, SKILLS_METADATA, Skill, detectCompatI18nLibraries, detectExportedComponentName, detectFormatCommand, detectPackageManager, enableEditorInConfig, getContentDeclarationFileTemplate, getDefaultApplicationURL, getGitRootDir, getInitialSkills, initIntlayer, installLSP, installMCP, installPackages, installSkills, listDictionaries, listDictionariesWithStats, listGitFiles, listGitLines, listProjects, logConfigDetails, prepareIntlayer, setupCmsCredentials, transformJSFile, writeCmsCredentialsToEnv, writeContentDeclaration, writeJSFile };
24
+ export { COMPAT_I18N_LIBRARIES, type CmsCredentials, type CompatI18nLibrary, ContentStrategy, DictionaryStatus, DiffMode, InitOptions, ListGitFilesOptions, ListGitLinesOptions, ListProjectsOptions, MCPTransport, NEXT_INTLAYER_BABEL_CONFIG_CONTENT, PLATFORMS, PLATFORMS_METADATA, type PackageManager, Platform, PlatformMetadata, type RoutingMode, SKILLS, SKILLS_METADATA, Skill, UpgradeIntlayerPackagesOptions, UpgradeIntlayerPackagesResult, detectCompatI18nLibraries, detectExportedComponentName, detectFormatCommand, detectPackageManager, enableEditorInConfig, getContentDeclarationFileTemplate, getDefaultApplicationURL, getGitRootDir, getInitialSkills, initIntlayer, installLSP, installMCP, installPackages, installSkills, listDictionaries, listDictionariesWithStats, listGitFiles, listGitLines, listProjects, logConfigDetails, prepareIntlayer, setupCmsCredentials, transformJSFile, upgradeIntlayerPackages, writeCmsCredentialsToEnv, writeContentDeclaration, writeJSFile };
@@ -26,7 +26,8 @@ export type InitOptions = {
26
26
  /** Skip scaffolding the `fill` and `test` GitHub Actions workflows. */
27
27
  noGithubActions?: boolean;
28
28
  /**
29
- * Skip installing missing Intlayer dependencies and upgrading outdated ones.
29
+ * Skip installing missing Intlayer dependencies and upgrading the Intlayer
30
+ * packages of every `package.json` to their latest version.
30
31
  */
31
32
  noInstallPackages?: boolean;
32
33
  /** Skip adding the Intlayer extension to `.vscode/extensions.json`. */
@@ -36,14 +37,16 @@ export type InitOptions = {
36
37
  /** Skip enabling the Intlayer lint rules (ESLint / oxlint). */
37
38
  noEslint?: boolean;
38
39
  /**
39
- * Skip framework-specific scaffolding (middleware/proxy, providers in
40
- * layout/page, example content). Defaults to enabled.
40
+ * Skip the project setup: tsconfig types/aliases, the Intlayer config file,
41
+ * bundler/framework configs, the dev script and framework-specific
42
+ * scaffolding (middleware/proxy, providers in layout/page). Defaults to
43
+ * enabled.
41
44
  */
42
45
  noFrameworkSetup?: boolean;
43
46
  /**
44
- * Version that outdated Intlayer packages should be upgraded to (typically the
45
- * running CLI version). When omitted, installed packages are left untouched and
46
- * only missing ones are installed.
47
+ * Version to install the missing Intlayer packages at (typically the running
48
+ * CLI version). Already declared Intlayer packages are upgraded to the latest
49
+ * published version instead.
47
50
  */
48
51
  upgradeToVersion?: string;
49
52
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/init/index.ts"],"mappings":";;;;;;;;;qBAiOa,2BAAwB,cACrB;;;;;;;;;;YAsBJ;;;;YAQA;EACV;;EAEA;;;;EAIA;;EAEA;;EAEA;;EAEA;;;;;EAKA;;;;;;EAMA;;;;;;EAMA,cAAc;;;;;;;EAOd,kBAAkB;;;;;qBAMP,eAAY,iBAAyB,UAAY,gBAAW"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/init/index.ts"],"mappings":";;;;;;;;;qBA6Oa,2BAAwB,cACrB;;;;;;;;;;YAsBJ;;;;YAQA;EACV;;EAEA;;;;;EAKA;;EAEA;;EAEA;;EAEA;;;;;;;EAOA;;;;;;EAMA;;;;;;EAMA,cAAc;;;;;;;EAOd,kBAAkB;;;;;qBAMP,eAAY,iBAAyB,UAAY,gBAAW"}
@@ -0,0 +1,26 @@
1
+ import { IntlayerDependencyUpgrade, PackageJsonIntlayerDependencies } from "./utils/intlayerDependencies.js";
2
+ import "./utils/index.js";
3
+ //#region src/init/upgradeIntlayerPackages.d.ts
4
+ export type UpgradeIntlayerPackagesOptions = {
5
+ /** List the Intlayer packages and their target version without upgrading. */
6
+ dryRun?: boolean;
7
+ /**
8
+ * npm dist-tag to upgrade to (e.g. `canary`).
9
+ * @default 'latest'
10
+ */
11
+ distTag?: string;
12
+ };
13
+ export type UpgradeIntlayerPackagesResult = {
14
+ /** Intlayer dependencies found in every `package.json` of the project. */
15
+ packageJsonDependencies: PackageJsonIntlayerDependencies[];
16
+ /** Upgrades written (or that would be written, in dry-run mode). */
17
+ upgrades: IntlayerDependencyUpgrade[];
18
+ };
19
+ /**
20
+ * Lists the Intlayer packages of every `package.json` of the project
21
+ * (monorepo workspaces included), rewrites their ranges to the version of the
22
+ * given dist-tag, then runs a single install from the root.
23
+ */
24
+ export declare const upgradeIntlayerPackages: (rootDir: string, options?: UpgradeIntlayerPackagesOptions) => Promise<UpgradeIntlayerPackagesResult>;
25
+ //#endregion
26
+ //# sourceMappingURL=upgradeIntlayerPackages.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upgradeIntlayerPackages.d.ts","names":[],"sources":["../../../src/init/upgradeIntlayerPackages.ts"],"mappings":";;;YAcY;;EAEV;;;;;EAKA;;YAGU;;EAEV,yBAAyB;;EAEzB,UAAU;;;;;;;qBAQC,0BAAuB,iBACnB,UACL,mCACT,QAAQ"}
@@ -1,11 +1,12 @@
1
- import { COMPAT_I18N_LIBRARIES, CompatI18nLibrary, CompatSyncConfig, CompatVitePluginConfig, DetectMissingPackagesOptions, IntlayerPackageAnalysis, PackageManager, detectCompatI18nLibraries, detectMissingIntlayerPackages, detectOutdatedIntlayerPackages, detectPackageManager, getInstalledPackageVersion, hasLintTooling, installPackages, isIntlayerPackageName, normalizeVersion, upgradePackages } from "./packageManager.js";
1
+ import { COMPAT_I18N_LIBRARIES, COMPAT_PACKAGE_REPLACEMENTS, CompatI18nLibrary, CompatSyncConfig, CompatVitePluginConfig, DetectMissingPackagesOptions, IntlayerPackageAnalysis, PackageManager, detectCompatI18nLibraries, detectMissingIntlayerPackages, detectPackageManager, findLockFileDir, hasLintTooling, installPackages, isIntlayerPackageName, moveCompatPackagesToDevDependencies, normalizeVersion, runPackageInstall } from "./packageManager.js";
2
2
  import { RoutingMode, enableIntlayerEditorConfig, getMetroConfigTemplate, hasIntlayerVitePlugin, replaceViteConfigPluginImportSource, setIntlayerConfigCompilerOutput, setIntlayerConfigRoutingMode, updateAstroConfig, updateIntlayerConfigWithSyncPlugin, updateMetroConfig, updateNextConfig, updateNextConfigForNextI18next, updateNextConfigForNextIntl, updateNextConfigForNextTranslate, updateNuxtConfig, updateNuxtConfigForNuxtjsI18n, updateViteConfig, updateViteConfigForCompatPlugin, updateViteConfigForVueI18n } from "./configManipulation.js";
3
3
  import { ensureNamedImport, firstInsertIndex, isModuleScopeBinding } from "./astImports.js";
4
4
  import { BACKEND_INTLAYER_PACKAGES, ResolveDevScriptParams, resolveDevScript } from "./devScript.js";
5
5
  import { JsonLocalePattern, JsonLocalePatternType, LinguiCatalogPattern, NextIntlMessagesPattern, detectJsonLocalePattern, detectLinguiCatalogPattern, detectNextIntlMessagesPattern, ensureDirectory, exists, readFileFromRoot, writeFileToRoot } from "./fileSystem.js";
6
6
  import { GITHUB_FILL_WORKFLOW_PATH, GITHUB_TEST_WORKFLOW_PATH, GithubWorkflowFile, GithubWorkflowsContext, GithubWorkflowsOptions, getGithubWorkflows, resolveGithubWorkflowsContext } from "./githubActions.js";
7
+ import { IntlayerDependency, IntlayerDependencyUpgrade, PackageJsonIntlayerDependencies, fetchLatestPackageVersion, findPackageJsonFiles, getIntlayerDependencies, getIntlayerDependencyUpgrades, listIntlayerDependencies, toRange, writeIntlayerDependencyUpgrades } from "./intlayerDependencies.js";
7
8
  import { parseJSONWithComments } from "./jsonParser.js";
8
9
  import { NEXT_INTLAYER_BABEL_CONFIG_CONTENT, setupNextCompilerBabelConfig } from "./nextCompilerBabel.js";
9
10
  import { findTsConfigFiles } from "./tsConfig.js";
10
11
  import { isVersionAtLeast } from "./version.js";
11
- export { BACKEND_INTLAYER_PACKAGES, COMPAT_I18N_LIBRARIES, CompatI18nLibrary, CompatSyncConfig, CompatVitePluginConfig, DetectMissingPackagesOptions, GITHUB_FILL_WORKFLOW_PATH, GITHUB_TEST_WORKFLOW_PATH, GithubWorkflowFile, GithubWorkflowsContext, GithubWorkflowsOptions, IntlayerPackageAnalysis, JsonLocalePattern, JsonLocalePatternType, LinguiCatalogPattern, NEXT_INTLAYER_BABEL_CONFIG_CONTENT, NextIntlMessagesPattern, PackageManager, ResolveDevScriptParams, RoutingMode, detectCompatI18nLibraries, detectJsonLocalePattern, detectLinguiCatalogPattern, detectMissingIntlayerPackages, detectNextIntlMessagesPattern, detectOutdatedIntlayerPackages, detectPackageManager, enableIntlayerEditorConfig, ensureDirectory, ensureNamedImport, exists, findTsConfigFiles, firstInsertIndex, getGithubWorkflows, getInstalledPackageVersion, getMetroConfigTemplate, hasIntlayerVitePlugin, hasLintTooling, installPackages, isIntlayerPackageName, isModuleScopeBinding, isVersionAtLeast, normalizeVersion, parseJSONWithComments, readFileFromRoot, replaceViteConfigPluginImportSource, resolveDevScript, resolveGithubWorkflowsContext, setIntlayerConfigCompilerOutput, setIntlayerConfigRoutingMode, setupNextCompilerBabelConfig, updateAstroConfig, updateIntlayerConfigWithSyncPlugin, updateMetroConfig, updateNextConfig, updateNextConfigForNextI18next, updateNextConfigForNextIntl, updateNextConfigForNextTranslate, updateNuxtConfig, updateNuxtConfigForNuxtjsI18n, updateViteConfig, updateViteConfigForCompatPlugin, updateViteConfigForVueI18n, upgradePackages, writeFileToRoot };
12
+ export { BACKEND_INTLAYER_PACKAGES, COMPAT_I18N_LIBRARIES, COMPAT_PACKAGE_REPLACEMENTS, CompatI18nLibrary, CompatSyncConfig, CompatVitePluginConfig, DetectMissingPackagesOptions, GITHUB_FILL_WORKFLOW_PATH, GITHUB_TEST_WORKFLOW_PATH, GithubWorkflowFile, GithubWorkflowsContext, GithubWorkflowsOptions, IntlayerDependency, IntlayerDependencyUpgrade, IntlayerPackageAnalysis, JsonLocalePattern, JsonLocalePatternType, LinguiCatalogPattern, NEXT_INTLAYER_BABEL_CONFIG_CONTENT, NextIntlMessagesPattern, PackageJsonIntlayerDependencies, PackageManager, ResolveDevScriptParams, RoutingMode, detectCompatI18nLibraries, detectJsonLocalePattern, detectLinguiCatalogPattern, detectMissingIntlayerPackages, detectNextIntlMessagesPattern, detectPackageManager, enableIntlayerEditorConfig, ensureDirectory, ensureNamedImport, exists, fetchLatestPackageVersion, findLockFileDir, findPackageJsonFiles, findTsConfigFiles, firstInsertIndex, getGithubWorkflows, getIntlayerDependencies, getIntlayerDependencyUpgrades, getMetroConfigTemplate, hasIntlayerVitePlugin, hasLintTooling, installPackages, isIntlayerPackageName, isModuleScopeBinding, isVersionAtLeast, listIntlayerDependencies, moveCompatPackagesToDevDependencies, normalizeVersion, parseJSONWithComments, readFileFromRoot, replaceViteConfigPluginImportSource, resolveDevScript, resolveGithubWorkflowsContext, runPackageInstall, setIntlayerConfigCompilerOutput, setIntlayerConfigRoutingMode, setupNextCompilerBabelConfig, toRange, updateAstroConfig, updateIntlayerConfigWithSyncPlugin, updateMetroConfig, updateNextConfig, updateNextConfigForNextI18next, updateNextConfigForNextIntl, updateNextConfigForNextTranslate, updateNuxtConfig, updateNuxtConfigForNuxtjsI18n, updateViteConfig, updateViteConfigForCompatPlugin, updateViteConfigForVueI18n, writeFileToRoot, writeIntlayerDependencyUpgrades };
@@ -0,0 +1,66 @@
1
+ //#region src/init/utils/intlayerDependencies.d.ts
2
+ /** Dependency fields of a `package.json` scanned for Intlayer packages. */
3
+ declare const DEPENDENCY_FIELDS: readonly ['dependencies', 'devDependencies'];
4
+ type DependencyField = (typeof DEPENDENCY_FIELDS)[number];
5
+ /** An Intlayer dependency declared in one of the project's `package.json`. */
6
+ export type IntlayerDependency = {
7
+ /** Package name, e.g. `next-intlayer`. */
8
+ packageName: string;
9
+ /** Field the dependency is declared in. */
10
+ dependencyField: DependencyField;
11
+ /** Declared version range, e.g. `^9.5.0`. */
12
+ currentRange: string;
13
+ };
14
+ /** Intlayer dependencies of one `package.json`. */
15
+ export type PackageJsonIntlayerDependencies = {
16
+ /** Path of the `package.json`, relative to the project root. */
17
+ packageJsonPath: string;
18
+ dependencies: IntlayerDependency[];
19
+ };
20
+ /** A dependency range rewritten to the latest published version. */
21
+ export type IntlayerDependencyUpgrade = IntlayerDependency & {
22
+ packageJsonPath: string;
23
+ /** Range written back to the `package.json`, e.g. `^9.5.7`. */
24
+ nextRange: string;
25
+ };
26
+ /**
27
+ * Lists every `package.json` of the project (root first), skipping
28
+ * `node_modules` and build outputs.
29
+ */
30
+ export declare const findPackageJsonFiles: (rootDir: string) => Promise<string[]>;
31
+ /**
32
+ * Lists the Intlayer packages (`intlayer`, `@intlayer/*`, `*-intlayer`,
33
+ * `intlayer-*`) declared with a registry range in a parsed `package.json`.
34
+ */
35
+ export declare const getIntlayerDependencies: (packageJson: Partial<Record<DependencyField, Record<string, string>>>) => IntlayerDependency[];
36
+ /** Lists the Intlayer dependencies of every `package.json` of the project. */
37
+ export declare const listIntlayerDependencies: (rootDir: string) => Promise<PackageJsonIntlayerDependencies[]>;
38
+ /**
39
+ * Fetches the version a dist-tag (`latest` by default) of a package points to
40
+ * on the npm registry. Resolves to `null` when the registry cannot be reached,
41
+ * the package is not published or the dist-tag does not exist.
42
+ */
43
+ export declare const fetchLatestPackageVersion: (packageName: string, { distTag, registryUrl }?: {
44
+ distTag?: string;
45
+ registryUrl?: string;
46
+ }) => Promise<string | null>;
47
+ /**
48
+ * Keeps the range operator (`^`, `~` or none) of `currentRange` and points it
49
+ * to `version`.
50
+ *
51
+ * @example toRange('^9.0.0', '9.5.7') // '^9.5.7'
52
+ */
53
+ export declare const toRange: (currentRange: string, version: string) => string;
54
+ /**
55
+ * Computes the upgrades bringing every listed dependency to its latest version.
56
+ * Dependencies already on the latest version, or whose latest version could not
57
+ * be fetched, are left out.
58
+ */
59
+ export declare const getIntlayerDependencyUpgrades: (packageJsonDependencies: PackageJsonIntlayerDependencies[], latestVersions: Map<string, string | null>) => IntlayerDependencyUpgrade[];
60
+ /**
61
+ * Writes the upgraded ranges back to their `package.json`, keeping the file's
62
+ * indentation and trailing newline.
63
+ */
64
+ export declare const writeIntlayerDependencyUpgrades: (rootDir: string, upgrades: IntlayerDependencyUpgrade[]) => Promise<void>;
65
+ //#endregion
66
+ //# sourceMappingURL=intlayerDependencies.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"intlayerDependencies.d.ts","names":[],"sources":["../../../../src/init/utils/intlayerDependencies.ts"],"mappings":";;cAOM;KAED,0BAA0B;;YAGnB;;EAEV;;EAEA,iBAAiB;;EAEjB;;;YAIU;;EAEV;EACA,cAAc;;;YAIJ,4BAA4B;EACtC;;EAEA;;;;;;qBAcW,uBAAoB,oBAE9B;;;;;qBAmBU,0BAAuB,aACrB,QAAQ,OAAO,iBAAiB,6BAC5C;;qBAeU,2BAAwB,oBAElC,QAAQ;;;;;;qBA2BE,4BAAyB,uBACjB,SAAA;EAId;EAAkB;MACtB;;;;;;;qBAqBU,UAAO,sBAAwB;;;;;;qBAQ/B,gCAA6B,yBACf,mCAAiC,gBAC1C,+BACf;;;;;qBA2BU,kCAA+B,iBAC3B,UACL,gCACT"}