fimo 0.8.0 → 0.9.0-experimental.10

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 (218) hide show
  1. package/assets/agent-templates/content-translator/scripts/write-locale-files.ts +66 -0
  2. package/assets/agents-starter/claude/settings.json +19 -0
  3. package/assets/content-templates/hooks-template.eta +4 -2
  4. package/assets/content-templates/types-template.eta +67 -1
  5. package/assets/skills/fimo/SKILL.md +1 -1
  6. package/assets/skills/fimo/references/content.md +86 -15
  7. package/assets/skills/fimo/references/translations.md +75 -0
  8. package/assets/skills/fimo-cli/SKILL.md +6 -2
  9. package/assets/skills/fimo-cli/references/content.md +61 -2
  10. package/assets/skills/fimo-cli/references/integrations/firecrawl.md +20 -4
  11. package/assets/skills/fimo-cli/references/integrations.md +5 -1
  12. package/assets/skills/fimo-cli/references/webhooks.md +162 -0
  13. package/assets/skills/fimo-migration/SKILL.md +24 -2
  14. package/assets/skills/fimo-migration/references/content.md +24 -0
  15. package/assets/skills/fimo-migration/references/manifest.md +46 -0
  16. package/assets/skills/fimo-migration/references/pages.md +234 -0
  17. package/assets/skills/fimo-migration/references/qa.md +24 -2
  18. package/assets/skills/fimo-migration/references/workflow.md +12 -1
  19. package/assets/skills/fimo-migration/references/wrap.md +662 -0
  20. package/assets/skills/fimo-studio/SKILL.md +5 -3
  21. package/assets/skills/fimo-studio/references/cms.md +9 -1
  22. package/assets/skills/fimo-studio/references/visual-editing.md +5 -3
  23. package/assets/skills/fimo-studio/references/webhooks.md +42 -0
  24. package/dist/build/vite/plugins/translations.d.ts +2 -8
  25. package/dist/build/vite/plugins/translations.js +31 -131
  26. package/dist/cli/bundle.json +1 -1
  27. package/dist/cli/index.js +1337 -189
  28. package/dist/runtime/app/FimoProviders.d.ts +1 -11
  29. package/dist/runtime/app/FimoProviders.js +31 -30
  30. package/dist/runtime/astro/index.d.ts +2 -0
  31. package/dist/runtime/astro/index.js +3 -0
  32. package/dist/runtime/astro/server.d.ts +3 -0
  33. package/dist/runtime/astro/server.js +6 -0
  34. package/dist/runtime/content/client/internal.js +1 -0
  35. package/dist/runtime/content/client/types.d.ts +16 -0
  36. package/dist/runtime/core/BuiltWithBadge.d.ts +2 -0
  37. package/dist/runtime/core/BuiltWithBadge.js +68 -0
  38. package/dist/runtime/i18n/FimoLocaleContext.js +1 -0
  39. package/dist/runtime/next/FimoNextProviders.d.ts +24 -0
  40. package/dist/runtime/next/FimoNextProviders.js +20 -0
  41. package/dist/runtime/next/FimoNextScripts.d.ts +10 -0
  42. package/dist/runtime/next/FimoNextScripts.js +19 -0
  43. package/dist/runtime/next/index.d.ts +14 -0
  44. package/dist/runtime/next/index.js +14 -0
  45. package/dist/runtime/next/server.d.ts +2 -0
  46. package/dist/runtime/next/server.js +4 -0
  47. package/dist/runtime/nuxt/composables.d.ts +9 -0
  48. package/dist/runtime/nuxt/composables.js +57 -0
  49. package/dist/runtime/nuxt/index.d.ts +3 -0
  50. package/dist/runtime/nuxt/index.js +6 -0
  51. package/dist/runtime/nuxt/server.d.ts +3 -0
  52. package/dist/runtime/nuxt/server.js +6 -0
  53. package/dist/runtime/primitives/components/RichText.d.ts +5 -1
  54. package/dist/runtime/primitives/components/RichText.js +2 -2
  55. package/dist/runtime/primitives/labels-hook.d.ts +33 -0
  56. package/dist/runtime/primitives/labels-hook.js +41 -0
  57. package/dist/runtime/primitives/labels-store.d.ts +12 -0
  58. package/dist/runtime/primitives/labels-store.js +60 -0
  59. package/dist/runtime/primitives/lib/useFimoLiveValue.d.ts +5 -3
  60. package/dist/runtime/primitives/lib/useFimoLiveValue.js +11 -4
  61. package/dist/runtime/primitives/translations.d.ts +1 -27
  62. package/dist/runtime/primitives/translations.js +7 -85
  63. package/dist/runtime/react/FimoSpaProviders.d.ts +36 -0
  64. package/dist/runtime/react/FimoSpaProviders.js +122 -0
  65. package/dist/runtime/react/index.d.ts +35 -0
  66. package/dist/runtime/react/index.js +40 -0
  67. package/dist/runtime/react/spa-content-cache.d.ts +38 -0
  68. package/dist/runtime/react/spa-content-cache.js +64 -0
  69. package/dist/runtime/remix/FimoRemixProviders.d.ts +16 -0
  70. package/dist/runtime/remix/FimoRemixProviders.js +12 -0
  71. package/dist/runtime/remix/FimoRemixScripts.d.ts +10 -0
  72. package/dist/runtime/remix/FimoRemixScripts.js +19 -0
  73. package/dist/runtime/remix/index.d.ts +12 -0
  74. package/dist/runtime/remix/index.js +11 -0
  75. package/dist/runtime/remix/server.d.ts +2 -0
  76. package/dist/runtime/remix/server.js +2 -0
  77. package/dist/runtime/seo/neutral.d.ts +22 -0
  78. package/dist/runtime/seo/neutral.js +17 -0
  79. package/dist/runtime/shared/display-routes.d.ts +14 -0
  80. package/dist/runtime/shared/display-routes.js +25 -0
  81. package/dist/runtime/shared/fimo-config.server.d.ts +0 -1
  82. package/dist/runtime/shared/fimo-config.server.js +1 -13
  83. package/dist/runtime/shared/fimo-config.types.d.ts +2 -0
  84. package/dist/runtime/shared/i18n-messages.d.ts +29 -0
  85. package/dist/runtime/shared/i18n-messages.js +79 -0
  86. package/dist/runtime/shared/labels-fetch.pure.d.ts +17 -0
  87. package/dist/runtime/shared/labels-fetch.pure.js +71 -0
  88. package/dist/runtime/shared/labels-fetch.server.d.ts +7 -0
  89. package/dist/runtime/shared/labels-fetch.server.js +97 -0
  90. package/dist/runtime/shared/labels-t.pure.d.ts +2 -0
  91. package/dist/runtime/shared/labels-t.pure.js +10 -0
  92. package/dist/runtime/strapi/client.d.ts +30 -0
  93. package/dist/runtime/strapi/client.js +132 -0
  94. package/dist/runtime/strapi/index.d.ts +5 -0
  95. package/dist/runtime/strapi/index.js +6 -0
  96. package/dist/runtime/strapi/reshape.d.ts +50 -0
  97. package/dist/runtime/strapi/reshape.js +121 -0
  98. package/dist/runtime/svelte/index.d.ts +3 -0
  99. package/dist/runtime/svelte/index.js +7 -0
  100. package/dist/runtime/svelte/server.d.ts +3 -0
  101. package/dist/runtime/svelte/server.js +6 -0
  102. package/dist/runtime/vue/index.d.ts +3 -0
  103. package/dist/runtime/vue/index.js +5 -0
  104. package/dist/runtime/vue/server.d.ts +3 -0
  105. package/dist/runtime/vue/server.js +6 -0
  106. package/dist/runtime/wrapped/FimoFileLink.d.ts +17 -0
  107. package/dist/runtime/wrapped/FimoFileLink.js +19 -0
  108. package/dist/runtime/wrapped/FimoMediaImage.d.ts +14 -0
  109. package/dist/runtime/wrapped/FimoMediaImage.js +20 -0
  110. package/dist/runtime/wrapped/FimoMediaVideo.d.ts +14 -0
  111. package/dist/runtime/wrapped/FimoMediaVideo.js +20 -0
  112. package/dist/runtime/wrapped/FimoRichTextBlock.d.ts +26 -0
  113. package/dist/runtime/wrapped/FimoRichTextBlock.js +22 -0
  114. package/dist/runtime/wrapped/FimoText.d.ts +22 -0
  115. package/dist/runtime/wrapped/FimoText.js +20 -0
  116. package/dist/runtime/wrapped/WrappedContentContext.d.ts +28 -0
  117. package/dist/runtime/wrapped/WrappedContentContext.js +30 -0
  118. package/dist/runtime/wrapped/WrappedProviders.d.ts +33 -0
  119. package/dist/runtime/wrapped/WrappedProviders.js +101 -0
  120. package/dist/runtime/wrapped/content-fetch.pure.d.ts +20 -0
  121. package/dist/runtime/wrapped/content-fetch.pure.js +106 -0
  122. package/dist/runtime/wrapped/dom.d.ts +4 -0
  123. package/dist/runtime/wrapped/dom.js +23 -0
  124. package/dist/runtime/wrapped/server.d.ts +80 -0
  125. package/dist/runtime/wrapped/server.js +207 -0
  126. package/dist/scripts/apply-wrap-templates.d.ts +61 -0
  127. package/dist/scripts/apply-wrap-templates.js +137 -0
  128. package/dist/scripts/apply-wrap.d.ts +73 -0
  129. package/dist/scripts/apply-wrap.js +340 -0
  130. package/dist/scripts/cms/discover.d.ts +2 -0
  131. package/dist/scripts/cms/discover.js +17 -0
  132. package/dist/scripts/cms/example-content.d.ts +33 -0
  133. package/dist/scripts/cms/example-content.js +165 -0
  134. package/dist/scripts/cms/strapi/detect.d.ts +2 -0
  135. package/dist/scripts/cms/strapi/detect.js +186 -0
  136. package/dist/scripts/cms/strapi/index.d.ts +3 -0
  137. package/dist/scripts/cms/strapi/index.js +25 -0
  138. package/dist/scripts/cms/strapi/list-source.d.ts +17 -0
  139. package/dist/scripts/cms/strapi/list-source.js +90 -0
  140. package/dist/scripts/cms/strapi/schema-map.d.ts +9 -0
  141. package/dist/scripts/cms/strapi/schema-map.js +289 -0
  142. package/dist/scripts/cms/strapi/shapes.d.ts +25 -0
  143. package/dist/scripts/cms/strapi/shapes.js +48 -0
  144. package/dist/scripts/cms/strapi/touchpoints.d.ts +31 -0
  145. package/dist/scripts/cms/strapi/touchpoints.js +145 -0
  146. package/dist/scripts/cms/strapi/wire-client.d.ts +15 -0
  147. package/dist/scripts/cms/strapi/wire-client.js +107 -0
  148. package/dist/scripts/cms/strapi/wiring.d.ts +17 -0
  149. package/dist/scripts/cms/strapi/wiring.js +46 -0
  150. package/dist/scripts/cms/types.d.ts +145 -0
  151. package/dist/scripts/cms/types.js +11 -0
  152. package/dist/scripts/detect-framework.d.ts +39 -0
  153. package/dist/scripts/detect-framework.js +139 -0
  154. package/dist/scripts/draft-rows.d.ts +19 -0
  155. package/dist/scripts/draft-rows.js +178 -0
  156. package/dist/scripts/draft-schemas.d.ts +27 -0
  157. package/dist/scripts/draft-schemas.js +247 -0
  158. package/dist/scripts/extract-translations.js +16 -11
  159. package/dist/scripts/frameworks/astro/routes.d.ts +3 -0
  160. package/dist/scripts/frameworks/astro/routes.js +44 -0
  161. package/dist/scripts/frameworks/astro/template-style.d.ts +7 -0
  162. package/dist/scripts/frameworks/astro/template-style.js +19 -0
  163. package/dist/scripts/frameworks/discover.d.ts +83 -0
  164. package/dist/scripts/frameworks/discover.js +288 -0
  165. package/dist/scripts/frameworks/discovered-route.d.ts +9 -0
  166. package/dist/scripts/frameworks/discovered-route.js +17 -0
  167. package/dist/scripts/frameworks/next/rewire.d.ts +43 -0
  168. package/dist/scripts/frameworks/next/rewire.js +282 -0
  169. package/dist/scripts/frameworks/next/routes.d.ts +30 -0
  170. package/dist/scripts/frameworks/next/routes.js +176 -0
  171. package/dist/scripts/frameworks/next/wiring.d.ts +33 -0
  172. package/dist/scripts/frameworks/next/wiring.js +186 -0
  173. package/dist/scripts/frameworks/nuxt/routes.d.ts +3 -0
  174. package/dist/scripts/frameworks/nuxt/routes.js +38 -0
  175. package/dist/scripts/frameworks/nuxt/template-style.d.ts +9 -0
  176. package/dist/scripts/frameworks/nuxt/template-style.js +27 -0
  177. package/dist/scripts/frameworks/remix/routes.d.ts +3 -0
  178. package/dist/scripts/frameworks/remix/routes.js +36 -0
  179. package/dist/scripts/frameworks/support.d.ts +75 -0
  180. package/dist/scripts/frameworks/support.js +165 -0
  181. package/dist/scripts/frameworks/sveltekit/routes.d.ts +3 -0
  182. package/dist/scripts/frameworks/sveltekit/routes.js +35 -0
  183. package/dist/scripts/frameworks/sveltekit/template-style.d.ts +9 -0
  184. package/dist/scripts/frameworks/sveltekit/template-style.js +54 -0
  185. package/dist/scripts/frameworks/vite/routes.d.ts +20 -0
  186. package/dist/scripts/frameworks/vite/routes.js +143 -0
  187. package/dist/scripts/frameworks/vite/wiring.d.ts +22 -0
  188. package/dist/scripts/frameworks/vite/wiring.js +144 -0
  189. package/dist/scripts/i18n-namespace.d.ts +27 -0
  190. package/dist/scripts/i18n-namespace.js +155 -0
  191. package/dist/scripts/lib/humanize.d.ts +14 -0
  192. package/dist/scripts/lib/humanize.js +54 -0
  193. package/dist/scripts/lib/validation-report.d.ts +1 -3
  194. package/dist/scripts/lib/validation-report.js +3 -9
  195. package/dist/scripts/render-parity/capture.d.ts +64 -0
  196. package/dist/scripts/render-parity/capture.js +436 -0
  197. package/dist/scripts/render-parity/compare.d.ts +59 -0
  198. package/dist/scripts/render-parity/compare.js +0 -0
  199. package/dist/scripts/render-parity/normalize-html.d.ts +13 -0
  200. package/dist/scripts/render-parity/normalize-html.js +223 -0
  201. package/dist/scripts/render-parity/types.d.ts +41 -0
  202. package/dist/scripts/render-parity/types.js +1 -0
  203. package/dist/scripts/routes/bindings.d.ts +93 -0
  204. package/dist/scripts/routes/bindings.js +117 -0
  205. package/dist/scripts/routes/label-prefixes.d.ts +49 -0
  206. package/dist/scripts/routes/label-prefixes.js +136 -0
  207. package/dist/scripts/routes/module-resolve.d.ts +20 -0
  208. package/dist/scripts/routes/module-resolve.js +78 -0
  209. package/dist/scripts/routes/page-structure.d.ts +72 -0
  210. package/dist/scripts/routes/page-structure.js +234 -0
  211. package/dist/scripts/scan-wrappable.d.ts +200 -0
  212. package/dist/scripts/scan-wrappable.js +1355 -0
  213. package/dist/scripts/validate-route-metadata.js +11 -0
  214. package/dist/scripts/validate-schemas.js +42 -1
  215. package/package.json +88 -4
  216. package/release.json +2 -2
  217. package/templates/react-router/package.json +1 -1
  218. package/templates/react-router/translations/en.json +1 -0
@@ -0,0 +1,73 @@
1
+ import { type WrappableItem } from './scan-wrappable.js';
2
+ export interface AppliedTransform {
3
+ kind: 'text' | 'image' | 'file-link';
4
+ file: string;
5
+ line: number;
6
+ id: string;
7
+ preview: string;
8
+ }
9
+ export interface ApplyWrapResult {
10
+ applied: AppliedTransform[];
11
+ skipped: Array<{
12
+ item: WrappableItem;
13
+ reason: string;
14
+ }>;
15
+ labels: Record<string, string>;
16
+ filesChanged: string[];
17
+ }
18
+ export declare function decodeJsxEntities(text: string): string;
19
+ /** Conservative markdown detection: bold pairs, inline code, links, and a
20
+ * leading heading marker — not lone `*`/`[` characters in ordinary copy. */
21
+ export declare function looksLikeMarkdown(text: string): boolean;
22
+ /** Deterministic scope from the file path: app/about/page.tsx -> about. */
23
+ export declare function keyScope(file: string): string;
24
+ export declare function slugify(text: string): string;
25
+ export declare class KeyAllocator {
26
+ private readonly used;
27
+ private readonly reusable;
28
+ /**
29
+ * `reusable` maps staged keys that no longer appear in code (a wrap the
30
+ * user reverted) to their staged value: re-applying the codemod over the
31
+ * same text reclaims the ORIGINAL key instead of minting a `-N` duplicate
32
+ * that orphans the old label (and its seeded row).
33
+ */
34
+ constructor(existing: Iterable<string>, reusable?: ReadonlyMap<string, string>);
35
+ allocate(scope: string, slug: string, value?: string): string;
36
+ }
37
+ /** Staged keys absent from the current code scan, with their staged values —
38
+ * the KeyAllocator's reuse pool. */
39
+ export declare function reusableStagedLabels(existingLabels: Record<string, string>, wrappedInCode: Iterable<string>): Map<string, string>;
40
+ /**
41
+ * Merge the fimo/next import with an existing one, or insert a new one AFTER
42
+ * the last import statement — positioned via the AST, never line matching
43
+ * (a multiline `import {\n …` opening line is not the end of the imports,
44
+ * as a real portfolio migration proved).
45
+ */
46
+ export declare function ensureFimoImport(code: string, specifiers: string[], importModule?: string): string;
47
+ export declare function applyWrapToFile(code: string, items: WrappableItem[], allocator: KeyAllocator, importModule?: string): {
48
+ code: string;
49
+ applied: AppliedTransform[];
50
+ skipped: Array<{
51
+ item: WrappableItem;
52
+ reason: string;
53
+ }>;
54
+ labels: Record<string, string>;
55
+ };
56
+ /**
57
+ * Apply the safe transforms across the project. Mutates source files and
58
+ * merges generated labels into `.fimo/migration/labels.json` (never
59
+ * overwriting existing keys).
60
+ */
61
+ /** Recorded coverage exemptions the codemod must NOT wrap — items the user
62
+ * deliberately kept out (dev-only UI, OG-image markup, …). Matched by the
63
+ * same (file, kind, preview) triple the coverage gate uses, so "record the
64
+ * exemption first, then --apply auto-wraps the rest" holds. */
65
+ export declare function readApplyExemptions(rootDir: string): Array<{
66
+ file: string;
67
+ kind: string;
68
+ preview: string;
69
+ }>;
70
+ export declare function applyWrap(rootDir: string, opts?: {
71
+ excludePrefixes?: string[];
72
+ importModule?: string;
73
+ }): ApplyWrapResult;
@@ -0,0 +1,340 @@
1
+ import { readFileSync, writeFileSync } from 'node:fs';
2
+ import { basename, join } from 'node:path';
3
+ import { parseSync } from 'oxc-parser';
4
+ import { scanWrappable } from './scan-wrappable.js';
5
+ /**
6
+ * The --apply codemod: performs the PROVABLY-SAFE wrap transforms
7
+ * deterministically, leaving every judgment call to the agent.
8
+ *
9
+ * In scope: plain JSX text -> FimoText, <img src="literal"> -> FimoMediaImage,
10
+ * <a href="/file.pdf"> -> FimoFileLink.
11
+ * Out of scope (agent work): attributes (useLabels crosses the RSC boundary),
12
+ * formatted text (marks -> FimoRichTextBlock), next/image <Image>
13
+ * (framework-specific props), collections, layout wiring.
14
+ *
15
+ * Correctness is enforced by the gates, not assumed: the render-parity
16
+ * baseline is captured BEFORE applying, and `fimo migrate wrap --check`
17
+ * verifies the result like any other actor's work.
18
+ */
19
+ /** Elements whose children cannot contain a <span> wrapper. */
20
+ const NO_ELEMENT_CHILDREN = new Set(['option', 'title', 'textarea', 'script', 'style', 'select']);
21
+ function collapse(text) {
22
+ return text.replace(/\s+/g, ' ').trim();
23
+ }
24
+ // JSX text carries HTML entities (&apos;, &amp;, …). The FALLBACK keeps the
25
+ // original source form, but the label VALUE is rendered literally by
26
+ // FimoText — seeding the raw entity re-escapes it on screen (the remix
27
+ // dogfood shipped "What&apos;s next?"). Decode when generating values.
28
+ const JSX_ENTITIES = {
29
+ '&amp;': '&',
30
+ '&lt;': '<',
31
+ '&gt;': '>',
32
+ '&quot;': '"',
33
+ '&apos;': "'",
34
+ '&nbsp;': ' ',
35
+ '&copy;': '©',
36
+ '&reg;': '®',
37
+ '&trade;': '™',
38
+ '&deg;': '°',
39
+ '&middot;': '·',
40
+ '&bull;': '•',
41
+ '&hellip;': '…',
42
+ '&mdash;': '—',
43
+ '&ndash;': '–',
44
+ '&lsquo;': '‘',
45
+ '&rsquo;': '’',
46
+ '&ldquo;': '“',
47
+ '&rdquo;': '”',
48
+ '&laquo;': '«',
49
+ '&raquo;': '»',
50
+ '&times;': '×',
51
+ '&rarr;': '→',
52
+ '&larr;': '←',
53
+ };
54
+ export function decodeJsxEntities(text) {
55
+ return text
56
+ .replace(/&(amp|lt|gt|quot|apos|nbsp|copy|reg|trade|deg|middot|bull|hellip|mdash|ndash|lsquo|rsquo|ldquo|rdquo|laquo|raquo|times|rarr|larr);/g, (entity) => JSX_ENTITIES[entity] ?? entity)
57
+ .replace(/&#(\d+);/g, (_, code) => String.fromCodePoint(Number(code)))
58
+ .replace(/&#x([0-9a-f]+);/gi, (_, code) => String.fromCodePoint(parseInt(code, 16)));
59
+ }
60
+ const MARKDOWN_SYNTAX = [/\*\*[^*]+\*\*/, /(?<!`)`[^`]+`/, /\[[^\]]+\]\([^)]+\)/, /^#{1,6}\s/];
61
+ /** Conservative markdown detection: bold pairs, inline code, links, and a
62
+ * leading heading marker — not lone `*`/`[` characters in ordinary copy. */
63
+ export function looksLikeMarkdown(text) {
64
+ return MARKDOWN_SYNTAX.some((pattern) => pattern.test(text));
65
+ }
66
+ /** Deterministic scope from the file path: app/about/page.tsx -> about. */
67
+ export function keyScope(file) {
68
+ const normalized = file.replace(/\\/g, '/');
69
+ const appMatch = normalized.match(/(?:^|\/)app\/(.*)\/?page\.[jt]sx?$/);
70
+ if (appMatch) {
71
+ const dir = appMatch[1].replace(/\/$/, '');
72
+ if (!dir) {
73
+ return 'home';
74
+ }
75
+ const segments = dir
76
+ .split('/')
77
+ .filter((segment) => !segment.startsWith('(') && !segment.startsWith('@'))
78
+ .map((segment) => segment.replace(/^\[+|\]+$/g, '').replace(/^\.\.\./, ''));
79
+ return segments.join('.') || 'home';
80
+ }
81
+ if (/(?:^|\/)app\/layout\.[jt]sx?$/.test(normalized)) {
82
+ return 'layout';
83
+ }
84
+ const stem = basename(normalized).replace(/\.[jt]sx?$/, '');
85
+ return slugify(stem) || 'shared';
86
+ }
87
+ export function slugify(text) {
88
+ // camelCase boundaries become segments BEFORE lowercasing, so component
89
+ // file names keep their word structure (AgentStrip.tsx → agent-strip.*)
90
+ // and every humanized display of the key reads like the component name.
91
+ return collapse(text)
92
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
93
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
94
+ .toLowerCase()
95
+ .normalize('NFD')
96
+ .replace(/[̀-ͯ]/g, '')
97
+ .replace(/[^a-z0-9]+/g, '-')
98
+ .replace(/^-+|-+$/g, '')
99
+ .split('-')
100
+ .slice(0, 4)
101
+ .join('-');
102
+ }
103
+ export class KeyAllocator {
104
+ used = new Set();
105
+ reusable = new Map();
106
+ /**
107
+ * `reusable` maps staged keys that no longer appear in code (a wrap the
108
+ * user reverted) to their staged value: re-applying the codemod over the
109
+ * same text reclaims the ORIGINAL key instead of minting a `-N` duplicate
110
+ * that orphans the old label (and its seeded row).
111
+ */
112
+ constructor(existing, reusable) {
113
+ for (const key of existing) {
114
+ this.used.add(key);
115
+ }
116
+ if (reusable) {
117
+ for (const [key, value] of reusable) {
118
+ this.reusable.set(key, value);
119
+ }
120
+ }
121
+ }
122
+ allocate(scope, slug, value) {
123
+ const base = `${scope}.${slug || 'item'}`;
124
+ let candidate = base;
125
+ let counter = 2;
126
+ while (this.used.has(candidate)) {
127
+ if (value !== undefined && this.reusable.get(candidate) === value) {
128
+ this.reusable.delete(candidate);
129
+ return candidate;
130
+ }
131
+ candidate = `${base}-${counter++}`;
132
+ }
133
+ this.used.add(candidate);
134
+ return candidate;
135
+ }
136
+ }
137
+ /** Staged keys absent from the current code scan, with their staged values —
138
+ * the KeyAllocator's reuse pool. */
139
+ export function reusableStagedLabels(existingLabels, wrappedInCode) {
140
+ const inCode = new Set(wrappedInCode);
141
+ return new Map(Object.entries(existingLabels).filter(([key]) => !inCode.has(key)));
142
+ }
143
+ /**
144
+ * Merge the fimo/next import with an existing one, or insert a new one AFTER
145
+ * the last import statement — positioned via the AST, never line matching
146
+ * (a multiline `import {\n …` opening line is not the end of the imports,
147
+ * as a real portfolio migration proved).
148
+ */
149
+ export function ensureFimoImport(code, specifiers, importModule = 'fimo/next') {
150
+ if (specifiers.length === 0) {
151
+ return code;
152
+ }
153
+ const moduleRe = importModule.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
154
+ const importMatch = code.match(new RegExp(`import\\s*\\{([^}]*)\\}\\s*from\\s*(['\"])${moduleRe}\\2\\s*;?`));
155
+ if (importMatch) {
156
+ const existing = importMatch[1]
157
+ .split(',')
158
+ .map((token) => token.trim())
159
+ .filter(Boolean);
160
+ const merged = [...new Set([...existing, ...specifiers])].sort();
161
+ return code.replace(importMatch[0], `import { ${merged.join(', ')} } from "${importModule}";`);
162
+ }
163
+ const statement = `import { ${[...new Set(specifiers)].sort().join(', ')} } from "${importModule}";`;
164
+ let insertAt = 0;
165
+ try {
166
+ const program = parseSync('module.tsx', code).program;
167
+ for (const node of program.body ?? []) {
168
+ if (node.type === 'ImportDeclaration') {
169
+ insertAt = node.end;
170
+ }
171
+ }
172
+ }
173
+ catch {
174
+ insertAt = 0;
175
+ }
176
+ if (insertAt === 0) {
177
+ return `${statement}\n${code}`;
178
+ }
179
+ return `${code.slice(0, insertAt)}\n${statement}${code.slice(insertAt)}`;
180
+ }
181
+ export function applyWrapToFile(code, items, allocator, importModule = 'fimo/next') {
182
+ const applied = [];
183
+ const skipped = [];
184
+ const labels = {};
185
+ const edits = [];
186
+ const specifiers = new Set();
187
+ for (const item of items) {
188
+ const span = item.span;
189
+ if (!span) {
190
+ skipped.push({ item, reason: 'no span info' });
191
+ continue;
192
+ }
193
+ const scope = keyScope(item.file);
194
+ if (item.kind === 'text') {
195
+ if (span.parentTag && NO_ELEMENT_CHILDREN.has(span.parentTag.toLowerCase())) {
196
+ skipped.push({ item, reason: `<${span.parentTag}> cannot contain a wrapper element` });
197
+ continue;
198
+ }
199
+ const raw = code.slice(span.start, span.end);
200
+ const core = raw.trim();
201
+ if (!core) {
202
+ skipped.push({ item, reason: 'whitespace only' });
203
+ continue;
204
+ }
205
+ if (looksLikeMarkdown(core)) {
206
+ // A parent that pipes its string child through a markdown renderer
207
+ // receives a React element after wrapping — the pipeline stops
208
+ // parsing and the **markers** render literally (a real parity break
209
+ // a dogfood gate caught). Text carrying markdown syntax stays agent
210
+ // work; syntax-free text renders identically either way.
211
+ skipped.push({ item, reason: 'markdown syntax in text — wrapping could break a markdown pipeline' });
212
+ continue;
213
+ }
214
+ const lead = raw.slice(0, raw.indexOf(core));
215
+ const trail = raw.slice(raw.indexOf(core) + core.length);
216
+ // Slug from the DECODED text — "&apos;" must never leak "apos" into a
217
+ // key ("today-apos-s-total" read "Today Apos S Total" in the Studio).
218
+ const value = decodeJsxEntities(collapse(core));
219
+ const id = allocator.allocate(scope, slugify(decodeJsxEntities(core)), value);
220
+ edits.push({
221
+ start: span.start,
222
+ end: span.end,
223
+ replacement: `${lead}<FimoText id="${id}">${core}</FimoText>${trail}`,
224
+ });
225
+ specifiers.add('FimoText');
226
+ labels[id] = value;
227
+ applied.push({ kind: 'text', file: item.file, line: item.line, id, preview: item.preview });
228
+ continue;
229
+ }
230
+ if (item.kind === 'image') {
231
+ if (span.openNameStart === undefined ||
232
+ span.openNameEnd === undefined ||
233
+ code.slice(span.openNameStart, span.openNameEnd) !== 'img') {
234
+ skipped.push({ item, reason: 'next/image and custom components stay agent work' });
235
+ continue;
236
+ }
237
+ const id = allocator.allocate(scope, slugify(basename(item.preview).replace(/\.[a-z0-9]+$/i, '')));
238
+ edits.push({
239
+ start: span.openNameStart,
240
+ end: span.openNameEnd,
241
+ replacement: `FimoMediaImage id="${id}"`,
242
+ });
243
+ specifiers.add('FimoMediaImage');
244
+ applied.push({ kind: 'image', file: item.file, line: item.line, id, preview: item.preview });
245
+ continue;
246
+ }
247
+ if (item.kind === 'file-link') {
248
+ if (span.openNameStart === undefined ||
249
+ span.openNameEnd === undefined ||
250
+ span.closeNameStart === undefined ||
251
+ span.closeNameEnd === undefined) {
252
+ skipped.push({ item, reason: 'self-closing or unparsable anchor' });
253
+ continue;
254
+ }
255
+ const id = allocator.allocate(scope, slugify(basename(item.preview).replace(/\.[a-z0-9]+$/i, '')));
256
+ edits.push({ start: span.openNameStart, end: span.openNameEnd, replacement: `FimoFileLink id="${id}"` });
257
+ edits.push({ start: span.closeNameStart, end: span.closeNameEnd, replacement: 'FimoFileLink' });
258
+ specifiers.add('FimoFileLink');
259
+ applied.push({ kind: 'file-link', file: item.file, line: item.line, id, preview: item.preview });
260
+ continue;
261
+ }
262
+ skipped.push({ item, reason: `${item.kind} stays agent work` });
263
+ }
264
+ let next = code;
265
+ for (const edit of edits.sort((a, b) => b.start - a.start)) {
266
+ next = next.slice(0, edit.start) + edit.replacement + next.slice(edit.end);
267
+ }
268
+ next = ensureFimoImport(next, [...specifiers], importModule);
269
+ return { code: next, applied, skipped, labels };
270
+ }
271
+ /**
272
+ * Apply the safe transforms across the project. Mutates source files and
273
+ * merges generated labels into `.fimo/migration/labels.json` (never
274
+ * overwriting existing keys).
275
+ */
276
+ /** Recorded coverage exemptions the codemod must NOT wrap — items the user
277
+ * deliberately kept out (dev-only UI, OG-image markup, …). Matched by the
278
+ * same (file, kind, preview) triple the coverage gate uses, so "record the
279
+ * exemption first, then --apply auto-wraps the rest" holds. */
280
+ export function readApplyExemptions(rootDir) {
281
+ try {
282
+ const manifest = JSON.parse(readFileSync(join(rootDir, '.fimo', 'migration', 'manifest.json'), 'utf8'));
283
+ const raw = manifest?.wrap?.exemptions;
284
+ return Array.isArray(raw)
285
+ ? raw.filter((entry) => typeof entry?.file === 'string' &&
286
+ typeof entry?.kind === 'string' &&
287
+ typeof entry?.preview === 'string')
288
+ : [];
289
+ }
290
+ catch {
291
+ return [];
292
+ }
293
+ }
294
+ export function applyWrap(rootDir, opts = {}) {
295
+ const scan = scanWrappable(rootDir, { excludePrefixes: opts.excludePrefixes });
296
+ const existingLabels = (() => {
297
+ try {
298
+ return JSON.parse(readFileSync(join(rootDir, '.fimo', 'migration', 'labels.json'), 'utf8'));
299
+ }
300
+ catch {
301
+ return {};
302
+ }
303
+ })();
304
+ // Honor recorded exemptions: the codemod skips them so the coverage gate's
305
+ // exemption and the codemod stay consistent — otherwise --apply would wrap
306
+ // an item the user just exempted and the gate would flag the drift.
307
+ const exemptions = readApplyExemptions(rootDir);
308
+ const isExempt = (item) => exemptions.some((exemption) => exemption.file === item.file && exemption.kind === item.kind && exemption.preview === item.preview);
309
+ const allocator = new KeyAllocator([...Object.keys(existingLabels), ...scan.wrappedIds.labels], reusableStagedLabels(existingLabels, scan.wrappedIds.labels));
310
+ const byFile = new Map();
311
+ for (const item of scan.items) {
312
+ if (isExempt(item)) {
313
+ continue;
314
+ }
315
+ const list = byFile.get(item.file) ?? [];
316
+ list.push(item);
317
+ byFile.set(item.file, list);
318
+ }
319
+ const result = { applied: [], skipped: [], labels: {}, filesChanged: [] };
320
+ for (const [file, items] of byFile) {
321
+ const filePath = join(rootDir, file);
322
+ let code;
323
+ try {
324
+ code = readFileSync(filePath, 'utf8');
325
+ }
326
+ catch {
327
+ result.skipped.push(...items.map((item) => ({ item, reason: 'unreadable file' })));
328
+ continue;
329
+ }
330
+ const fileResult = applyWrapToFile(code, items, allocator, opts.importModule ?? 'fimo/next');
331
+ result.applied.push(...fileResult.applied);
332
+ result.skipped.push(...fileResult.skipped);
333
+ Object.assign(result.labels, fileResult.labels);
334
+ if (fileResult.applied.length > 0) {
335
+ writeFileSync(filePath, fileResult.code);
336
+ result.filesChanged.push(file);
337
+ }
338
+ }
339
+ return result;
340
+ }
@@ -0,0 +1,2 @@
1
+ import type { CmsConnector } from './types.js';
2
+ export declare function detectCms(frontendDir: string): CmsConnector | null;
@@ -0,0 +1,17 @@
1
+ import { strapiConnector } from './strapi/index.js';
2
+ /**
3
+ * CMS-connector registry. Add a connector factory here to support a new
4
+ * headless CMS; each returns its `CmsConnector` when it recognizes the
5
+ * frontend, or null. First match wins. This is the ONLY CMS-neutral file that
6
+ * enumerates the supported CMSs (the analogue of `frameworks/discover.ts`).
7
+ */
8
+ const CONNECTORS = [strapiConnector];
9
+ export function detectCms(frontendDir) {
10
+ for (const factory of CONNECTORS) {
11
+ const connector = factory(frontendDir);
12
+ if (connector) {
13
+ return connector;
14
+ }
15
+ }
16
+ return null;
17
+ }
@@ -0,0 +1,33 @@
1
+ import type { CmsCollectionSchema } from './types.js';
2
+ /**
3
+ * Generate example content for a CMS schema WITHOUT connecting to the CMS. The
4
+ * shapes match `api.importEntries`: media fields get a self-contained
5
+ * placeholder, references point at the first example of the target type
6
+ * (`<target>-example-1`) so they resolve against the co-seeded data, blocks
7
+ * (components / dynamic zones) get a filled array so page-builder pages render
8
+ * instead of showing empty, and localized types get per-locale string variance
9
+ * so the per-language editability is visible in Fimo. This is CMS-neutral: it
10
+ * consumes the mapped Fimo schema only.
11
+ */
12
+ export interface ExampleSeed {
13
+ /** Fimo type name. */
14
+ readonly name: string;
15
+ readonly isSingleton: boolean;
16
+ readonly localized: boolean;
17
+ /** Entry data rows (slug lives inside data for collections). */
18
+ readonly rows: Array<Record<string, unknown>>;
19
+ /** Reference descriptor for `importEntries`. */
20
+ readonly references: Record<string, {
21
+ target?: string;
22
+ targets?: string[];
23
+ by: 'slug';
24
+ many?: boolean;
25
+ }>;
26
+ }
27
+ export interface ExampleOptions {
28
+ /** Rows per collection type (singletons always get exactly one). */
29
+ readonly count?: number;
30
+ /** Locale suffix on string values + the batch locale (for localized types). */
31
+ readonly locale?: string;
32
+ }
33
+ export declare function generateExampleSeed(schema: CmsCollectionSchema, options?: ExampleOptions): ExampleSeed;
@@ -0,0 +1,165 @@
1
+ import { humanizeSegment } from '../lib/humanize.js';
2
+ const DEFAULT_COUNT = 3;
3
+ /** Variants seeded per dynamic-zone (`oneOf`) field — a representative page, not
4
+ * all N components. Real content (the pull) exercises the rest. */
5
+ const EXAMPLE_BLOCK_VARIANTS = 5;
6
+ /** Items seeded for a repeatable fixed-shape block. */
7
+ const EXAMPLE_REPEATABLE_ITEMS = 2;
8
+ /** Recursion cap for nested blocks — fill to the schema's real nesting so deep
9
+ * page-builders render, matching the blocks-depth limit (7) in api-contracts.
10
+ * The schema is already depth-bounded, so generation stays finite. */
11
+ const MAX_FILL_DEPTH = 6;
12
+ function kebabCase(name) {
13
+ return name
14
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
15
+ .replace(/[^a-zA-Z0-9]+/g, '-')
16
+ .toLowerCase()
17
+ .replace(/^-+|-+$/g, '');
18
+ }
19
+ function richTextDoc(text) {
20
+ return {
21
+ type: 'doc',
22
+ content: [{ type: 'paragraph', content: [{ type: 'text', text }] }],
23
+ };
24
+ }
25
+ /** A self-contained placeholder image (inline SVG data-URI) in the media
26
+ * envelope shape the wrap runtime already understands — no external host, no
27
+ * CSP surprises, so cards/heroes render instead of showing broken images. */
28
+ function placeholderMedia(label) {
29
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630"><rect width="100%" height="100%" fill="#e5e7eb"/><text x="50%" y="50%" font-family="sans-serif" font-size="44" fill="#9ca3af" text-anchor="middle" dominant-baseline="middle">${label}</text></svg>`;
30
+ return {
31
+ source: 'local',
32
+ url: `data:image/svg+xml;utf8,${encodeURIComponent(svg)}`,
33
+ alt: `${label} placeholder`,
34
+ width: 1200,
35
+ height: 630,
36
+ mime: 'image/svg+xml',
37
+ name: 'placeholder.svg',
38
+ };
39
+ }
40
+ /** Deterministic ISO date (no wall clock): 2024-01-01 + (n-1) days. */
41
+ function exampleDate(n) {
42
+ return new Date(Date.UTC(2024, 0, n)).toISOString().slice(0, 10);
43
+ }
44
+ function exampleReferenceSlug(field) {
45
+ const targetName = field.target ?? field.targets?.[0];
46
+ if (!targetName) {
47
+ return undefined;
48
+ }
49
+ const slug = `${kebabCase(targetName)}-example-1`;
50
+ return field.many ? [slug] : slug;
51
+ }
52
+ /**
53
+ * Fill a NON-reference field value from its Fimo def (scalars, blocks, and any
54
+ * baked default such as a block variant's `__component` discriminator).
55
+ * Reference fields return `undefined` here: the top-level pass owns them, and
56
+ * server-side slug resolution does not reach references nested inside blocks.
57
+ */
58
+ function fillFieldValue(field, def, ctx) {
59
+ const baked = def.default;
60
+ if (baked !== undefined) {
61
+ return baked;
62
+ }
63
+ switch (def.type) {
64
+ case 'string':
65
+ return `${humanizeSegment(field)} example ${ctx.index}${ctx.localeSuffix}`;
66
+ case 'richtext':
67
+ return richTextDoc(`Example ${humanizeSegment(ctx.schemaName).toLowerCase()} content ${ctx.index}${ctx.localeSuffix}.`);
68
+ case 'number':
69
+ return ctx.index;
70
+ case 'boolean':
71
+ return ctx.index % 2 === 1;
72
+ case 'date':
73
+ return exampleDate(ctx.index);
74
+ case 'json':
75
+ return {};
76
+ case 'media':
77
+ return placeholderMedia(humanizeSegment(field));
78
+ case 'blocks':
79
+ return fillBlocks(def, ctx);
80
+ default:
81
+ // reference (nested) — omitted; the frontend accesses relations defensively.
82
+ return undefined;
83
+ }
84
+ }
85
+ /**
86
+ * Fill a blocks value — always an array so page builders can `.map()` it. A
87
+ * dynamic zone (`oneOf`) seeds one item per variant (representative subset,
88
+ * each tagged with its `_type` discriminator); a fixed component (`fields`)
89
+ * seeds one item (single) or a few (repeatable).
90
+ */
91
+ function fillBlocks(def, ctx) {
92
+ if (ctx.depth >= MAX_FILL_DEPTH) {
93
+ return [];
94
+ }
95
+ const childCtx = { ...ctx, depth: ctx.depth + 1 };
96
+ const schema = def.schema;
97
+ if ('oneOf' in schema) {
98
+ // Rotate the variant window by row index so example entries render
99
+ // DIFFERENT block sets (entry 1 → variants 0-4, entry 2 → 5-9, …) —
100
+ // distinct-looking pages, and collectively more of the page builder
101
+ // exercised than the first five variants over and over.
102
+ const total = schema.oneOf.length;
103
+ const take = Math.min(EXAMPLE_BLOCK_VARIANTS, total);
104
+ const offset = total > 0 ? ((ctx.index - 1) * take) % total : 0;
105
+ return Array.from({ length: take }, (_, k) => schema.oneOf[(offset + k) % total]).map((variant) => ({
106
+ _type: variant.uid,
107
+ ...fillItem(variant.fields, childCtx),
108
+ }));
109
+ }
110
+ const itemCount = def.max === 1 ? 1 : EXAMPLE_REPEATABLE_ITEMS;
111
+ return Array.from({ length: itemCount }, () => fillItem(schema.fields, childCtx));
112
+ }
113
+ /** Fill every non-reference field of a block item. */
114
+ function fillItem(fields, ctx) {
115
+ const item = {};
116
+ for (const [name, def] of Object.entries(fields)) {
117
+ const value = fillFieldValue(name, def, ctx);
118
+ if (value !== undefined) {
119
+ item[name] = value;
120
+ }
121
+ }
122
+ return item;
123
+ }
124
+ export function generateExampleSeed(schema, options = {}) {
125
+ const locale = options.locale;
126
+ const localeSuffix = locale ? ` (${locale})` : '';
127
+ const count = schema.isSingleton ? 1 : Math.max(1, options.count ?? DEFAULT_COUNT);
128
+ const references = {};
129
+ const rows = [];
130
+ for (let i = 1; i <= count; i += 1) {
131
+ const row = {};
132
+ if (!schema.isSingleton) {
133
+ row.slug = `${kebabCase(schema.name)}-example-${i}`;
134
+ }
135
+ for (const [field, def] of Object.entries(schema.fields)) {
136
+ // A connector-supplied example (dynamic zones, components) wins over the
137
+ // type-driven default — critical for dynamic zones, which must be arrays.
138
+ if (schema.examples && field in schema.examples) {
139
+ row[field] = schema.examples[field];
140
+ continue;
141
+ }
142
+ // References are top-level only: record the descriptor so the import
143
+ // endpoint resolves the slug to a documentId server-side.
144
+ if (def.type === 'reference') {
145
+ const value = exampleReferenceSlug(def);
146
+ if (value !== undefined) {
147
+ row[field] = value;
148
+ references[field] = {
149
+ ...(def.target ? { target: def.target } : {}),
150
+ ...(def.targets ? { targets: def.targets } : {}),
151
+ by: 'slug',
152
+ ...(def.many ? { many: true } : {}),
153
+ };
154
+ }
155
+ continue;
156
+ }
157
+ const value = fillFieldValue(field, def, { localeSuffix, index: i, schemaName: schema.name, depth: 0 });
158
+ if (value !== undefined) {
159
+ row[field] = value;
160
+ }
161
+ }
162
+ rows.push(row);
163
+ }
164
+ return { name: schema.name, isSingleton: schema.isSingleton, localized: schema.localized, rows, references };
165
+ }
@@ -0,0 +1,2 @@
1
+ import type { CmsDetection } from '../types.js';
2
+ export declare function detectStrapi(frontendDir: string): CmsDetection | null;