@slicemachine/manager 0.24.4-alpha.xru-slice-generation-ai-poc.1 → 0.24.4-alpha.xru-slice-generation-ai-poc.2

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.
@@ -1,11 +1,9 @@
1
- import fs from "node:fs";
2
1
  import * as t from "io-ts";
3
2
  import OpenAI from "openai";
4
3
  import * as prismicCustomTypesClient from "@prismicio/custom-types-client";
5
4
  import { SharedSliceContent } from "@prismicio/types-internal/lib/content";
6
5
  import { SliceComparator } from "@prismicio/types-internal/lib/customtypes/diff";
7
6
  import { SharedSlice } from "@prismicio/types-internal/lib/customtypes";
8
- import path__default from "node:path";
9
7
  import { assertPluginsInitialized } from "../../lib/assertPluginsInitialized.js";
10
8
  import { bufferCodec } from "../../lib/bufferCodec.js";
11
9
  import { decodeHookResult } from "../../lib/decodeHookResult.js";
@@ -1237,38 +1235,117 @@ type GroupField = {
1237
1235
  }
1238
1236
  async generateSlicesFromUrl(args) {
1239
1237
  assertPluginsInitialized(this.sliceMachinePluginRunner);
1240
- const { OPENAI_API_KEY } = process.env;
1238
+ const { OPENAI_API_KEY, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY } = process.env;
1239
+ if (!AWS_ACCESS_KEY_ID || !AWS_SECRET_ACCESS_KEY) {
1240
+ throw new Error("AWS credentials are not set.");
1241
+ }
1242
+ const AWS_REGION = "us-east-1";
1243
+ const bedrockClient = new BedrockRuntimeClient({
1244
+ region: AWS_REGION,
1245
+ credentials: {
1246
+ accessKeyId: AWS_ACCESS_KEY_ID,
1247
+ secretAccessKey: AWS_SECRET_ACCESS_KEY
1248
+ }
1249
+ });
1241
1250
  if (!OPENAI_API_KEY) {
1242
1251
  throw new Error("OPENAI_API_KEY is not set.");
1243
1252
  }
1244
- const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
1253
+ const openai = new OpenAI({ apiKey: OPENAI_API_KEY });
1245
1254
  const sliceMachineConfig = await this.project.getSliceMachineConfig();
1246
1255
  const libraryIDs = sliceMachineConfig.libraries || [];
1247
1256
  const DEFAULT_LIBRARY_ID = libraryIDs[0];
1248
- const KNOWNED_WEBSITE_URLS = {
1249
- "https://www.criteo.com/": "./resources/criteo/homepage",
1250
- "https://www.brevo.com/landing/email-marketing-service/": "./resources/brevo/mail"
1251
- };
1252
- async function readImagesFromFolder(folderPath) {
1253
- console.log(process.cwd());
1254
- const files = await fs.promises.readdir(folderPath);
1255
- const images = await Promise.all(files.map(async (file) => {
1256
- const buffer = await fs.promises.readFile(path__default.join(folderPath, file));
1257
- return new Uint8Array(buffer);
1258
- }));
1259
- return images;
1260
- }
1261
- async function readCodeFromFolder(folderPath) {
1262
- const files = await fs.promises.readdir(folderPath);
1263
- const codes = await Promise.all(files.map(async (file) => {
1264
- const buffer = await fs.promises.readFile(path__default.join(folderPath, file), "utf-8");
1265
- return buffer.toString();
1266
- }));
1267
- return codes;
1268
- }
1269
- async function getGlobalStyle(filePath) {
1270
- const buffer = await fs.promises.readFile(filePath).catch(() => Buffer.from(""));
1271
- return buffer.toString();
1257
+ let retry = args.sliceImages.map((_) => ({
1258
+ MODEL: 0,
1259
+ MOCKS: 0,
1260
+ CODE: 0,
1261
+ APPEARANCE: 0
1262
+ }));
1263
+ async function callAI({ ai, sliceIndex, stepName, systemPrompt, imageFile, textContent }) {
1264
+ var _a, _b, _c, _d, _e, _f, _g, _h;
1265
+ let resultText;
1266
+ if (ai === "OPENAI") {
1267
+ const messages = [
1268
+ { role: "system", content: systemPrompt }
1269
+ ];
1270
+ const userContent = [];
1271
+ if (imageFile) {
1272
+ userContent.push({
1273
+ type: "image_url",
1274
+ image_url: {
1275
+ url: "data:image/png;base64," + Buffer.from(imageFile).toString("base64")
1276
+ }
1277
+ });
1278
+ }
1279
+ if (textContent) {
1280
+ userContent.push({ type: "text", text: textContent });
1281
+ }
1282
+ if (userContent.length > 0) {
1283
+ messages.push({
1284
+ role: "user",
1285
+ content: userContent
1286
+ });
1287
+ }
1288
+ const response = await openai.chat.completions.create({
1289
+ model: "gpt-4o",
1290
+ messages,
1291
+ response_format: { type: "json_object" }
1292
+ });
1293
+ console.log(`Generated response for ${stepName} - ${sliceIndex}:`, JSON.stringify(response));
1294
+ resultText = (_c = (_b = (_a = response.choices[0]) == null ? void 0 : _a.message) == null ? void 0 : _b.content) == null ? void 0 : _c.trim();
1295
+ } else if (ai === "AWS") {
1296
+ const messages = [];
1297
+ if (imageFile) {
1298
+ messages.push({
1299
+ role: "user",
1300
+ content: [
1301
+ {
1302
+ image: { format: "png", source: { bytes: imageFile } }
1303
+ }
1304
+ ]
1305
+ });
1306
+ }
1307
+ if (textContent) {
1308
+ messages.push({
1309
+ role: "user",
1310
+ content: [
1311
+ {
1312
+ text: textContent
1313
+ }
1314
+ ]
1315
+ });
1316
+ }
1317
+ const command = new ConverseCommand({
1318
+ modelId: "us.anthropic.claude-3-7-sonnet-20250219-v1:0",
1319
+ system: [{ text: systemPrompt }],
1320
+ messages
1321
+ });
1322
+ const response = await bedrockClient.send(command);
1323
+ console.log(`Generated response for ${stepName} - ${sliceIndex}:`, JSON.stringify(response));
1324
+ resultText = (_h = (_g = (_f = (_e = (_d = response.output) == null ? void 0 : _d.message) == null ? void 0 : _e.content) == null ? void 0 : _f[0]) == null ? void 0 : _g.text) == null ? void 0 : _h.trim();
1325
+ }
1326
+ async function retryCall(error) {
1327
+ if (retry[sliceIndex][stepName] < 3) {
1328
+ retry[sliceIndex][stepName]++;
1329
+ console.log(`Retrying ${retry[sliceIndex][stepName]} ${stepName} for slice ${sliceIndex}.`, error);
1330
+ return await callAI({
1331
+ ai,
1332
+ sliceIndex,
1333
+ stepName,
1334
+ systemPrompt,
1335
+ imageFile,
1336
+ textContent
1337
+ });
1338
+ }
1339
+ throw new Error(error);
1340
+ }
1341
+ if (!resultText) {
1342
+ return await retryCall(`No valid response was generated for ${stepName}.`);
1343
+ }
1344
+ try {
1345
+ return JSON.parse(resultText);
1346
+ } catch (error) {
1347
+ return await retryCall(`Failed to parse AI response for ${stepName}: ` + error);
1348
+ }
1272
1349
  }
1273
1350
  const SHARED_SLICE_SCHEMA = `
1274
1351
  /**
@@ -1586,355 +1663,289 @@ type GroupField = {
1586
1663
  }
1587
1664
  ]
1588
1665
  };
1589
- async function generateSliceModel(imageFile, codeFile) {
1590
- var _a, _b, _c;
1666
+ async function generateSliceModel(sliceIndex, imageFile) {
1591
1667
  const systemPrompt = `
1592
- You are an expert in Prismic content modeling. Using the image and the code provided, generate a valid Prismic JSON model for the slice described below. Follow these rules precisely:
1593
- - Use the TypeScript schema provided as your reference.
1594
- - Place all main content fields under the "primary" object.
1595
- - Do not create any collections or groups for single-image content (background images should be a single image field).
1596
- - Ensure that each field has appropriate placeholders, labels, and configurations.
1597
- - Never generate a Link / Button text field, only the Link / Button field itself is enough. Just enable "allowText" when doing that.
1598
- - Do not forget any field visible from the image provide in the user prompt.
1599
- - Ensure to differentiate Prismic fields from just an image with visual inside the image. When that's the case, just add a Prismic image field.
1600
- - Use the code to know exactly what is a real field and not an image. If in the code it's an image, then the field should also be an image, do a 1-1 mapping thanks to the code.
1601
- - Do not include any decorative fields. When an element is purely visual, decorative, don't include it att all in the slice model.
1602
- - Do not include any extra commentary or formatting.
1603
- - When you see a repetition of an image, a text, a link, etc, NEVER create one field per repeated item, you HAVE to use a group for that.
1604
- - When you see multiple fields repeated, you MUST use a group for that.
1605
- - NEVER put a group inside another group field, this is not allowed. In the final JSON a group CANNOT be within another group field. YOU CANNOT NEST GROUP FIELDS! Not for any reason you are allowed to do that! Even for navigation, in header or footer you cannot nest group fields.
1606
- - The "items" field must not be used under any circumstances. All repeatable fields should be defined using a Group field inside the primary object. If a field represents a collection of items, it must be part of a Group field, and items must never appear in the JSON output.
1607
- - Don't forget to replace the temporary text in the "Existing Slice to update", like <ID_TO_CHANGE>, <NAME_TO_CHANGE>, <DESCRIPTION_TO_CHANGE>, <VARIATION_ID_TO_CHANGE>, etc.
1608
- - Field placeholder should be super short, do not put the content from the image inside the placeholder.
1609
- - Field label and id should define the field's purpose, not its content.
1610
- - Slice name and id should define the slice's purpose, not its content.
1611
- - Slice description should be a brief explanation of the slice's purpose not its content.
1612
-
1613
- !IMPORTANT!:
1614
- - Only return a valid JSON object representing the full slice model, nothing else before. JSON.parse on your response should not throw an error.
1615
- - All your response should fit in a single return response.
1616
- - Never stop the response until you totally finish the full JSON response you wanted.
1668
+ You are an **expert in Prismic content modeling**. Using the **image and code provided**, generate a **valid Prismic JSON model** for the slice described below.
1617
1669
 
1618
- Reference Schema:
1670
+ **STRICT MODELING RULES (NO EXCEPTIONS):**
1671
+ - **Use the TypeScript schema provided as your reference**.
1672
+ - **Absolutely all fields must be placed under the "primary" object**.
1673
+ - **Do not create groups or collections for single-image content** (background images must be a single image field).
1674
+ - **Ensure each field has appropriate placeholders, labels, and configurations**.
1675
+ - **Never generate a Link/Button text field—only the Link/Button field itself** with \`"allowText": true\`.
1676
+ - **Include all fields visible in the provided image**, do not forget any field and everything should be covered.
1677
+ - **Repeated fields must always be grouped**:
1678
+ - **Identify when field are part of a group**, when there is a repetition of a field or multiple fields together use a Group field.
1679
+ - **DO NOT** create individually numbered fields like \`feature1\`, \`feature2\`, \`feature3\`. Instead, define a single **Group field** (e.g., \`features\`) and move all repeated items inside it.
1680
+ - **Differentiate Prismic fields from decorative elements:**
1681
+ - If an element in the image is purely visual/decorative, **do not include it in the model**.
1682
+ - Use the **code as the source of truth** to determine what should be a field.
1683
+ - If an element is an image in the code, it **must also be an image field in Prismic** (strict 1:1 mapping).
1684
+ - **Handle repeated content correctly:**
1685
+ - **If an image, text, or link is repeated, always use a Group field**—do not create individual fields.
1686
+ - **If multiple fields are repeated together, they must be inside a single Group field**.
1687
+ - **Strictly forbid nesting of groups:**
1688
+ - **NEVER put a Group inside another Group field**.
1689
+ - **Group fields CANNOT be nested for any reason**—this is **strictly prohibited** even for navigation structures like headers or footers.
1690
+ - **Do not use the "items" field**:
1691
+ - **All repeatable fields must be defined as Group fields under "primary"**.
1692
+ - **"items" must never appear in the final JSON output**.
1693
+ - **Do not create more than one SliceVariation**, only one variation is enough to create the model.
1694
+
1695
+ **STRICT FIELD NAMING & CONTENT RULES:**
1696
+ - **Replace placeholders in the existing slice template** (\`<ID_TO_CHANGE>\`, \`<NAME_TO_CHANGE>\`, etc.).
1697
+ - **Field placeholders must be very short**—do **not** put actual image content inside placeholders.
1698
+ - **Field labels and IDs must define the field's purpose, not its content**.
1699
+ - **Slice name, ID, and description must describe the slice's function, not its content**.
1700
+ - The slice name and ID must be **generic and reusable**, defining what the slice **does**, not what it is used for.
1701
+ - **DO NOT name the slice after a specific topic, content type, or industry. Instead, name it based on its structure and function.
1702
+
1703
+ **STRICT JSON OUTPUT FORMAT (NO MARKDOWN OR EXTRA TEXT):**
1704
+ - **Return ONLY a valid JSON object**—no extra text, comments, or formatting.
1705
+ - **The response must be directly parseable** using \`JSON.parse(output)\`.
1706
+ - **Do not wrap the output in markdown (\`\`\`\`json\`) or any other formatting.**
1707
+
1708
+ **VALIDATION REQUIREMENT:**
1709
+ - Before returning, **validate that \`JSON.parse(output)\` runs without errors**.
1710
+ - If there is **any extra text, markdown, or incorrect structure**, **rewrite the response before returning**.
1711
+
1712
+ **REFERENCE SCHEMA (Follow this exactly):**
1619
1713
  ${SHARED_SLICE_SCHEMA}
1620
1714
 
1621
- Existing Slice to update:
1715
+ **EXISTING SLICE TO UPDATE (Modify strictly according to the rules above):**
1622
1716
  ${JSON.stringify(DEFAULT_SLICE_MODEL)}
1623
1717
  `.trim();
1624
- const messages = [
1625
- { role: "system", content: systemPrompt },
1626
- {
1627
- role: "user",
1628
- content: [
1629
- {
1630
- type: "image_url",
1631
- image_url: {
1632
- url: "data:image/png;base64," + Buffer.from(imageFile).toString("base64")
1633
- }
1634
- },
1635
- { type: "text", text: codeFile }
1636
- ]
1637
- }
1638
- ];
1639
- const response = await openai.chat.completions.create({
1640
- model: "gpt-4o",
1641
- messages,
1642
- response_format: {
1643
- type: "json_object"
1644
- }
1718
+ const generatedModel = await callAI({
1719
+ ai: "OPENAI",
1720
+ sliceIndex,
1721
+ stepName: "MODEL",
1722
+ systemPrompt,
1723
+ imageFile
1645
1724
  });
1646
- console.log("Generated model response:", JSON.stringify(response));
1647
- const resultText = (_c = (_b = (_a = response.choices[0]) == null ? void 0 : _a.message) == null ? void 0 : _b.content) == null ? void 0 : _c.trim();
1648
- if (!resultText) {
1649
- throw new Error("No valid slice model was generated.");
1650
- }
1651
- try {
1652
- const generatedModel = JSON.parse(resultText);
1653
- return generatedModel;
1654
- } catch (error) {
1655
- throw new Error("Failed to parse AI response for model: " + error);
1656
- }
1725
+ return generatedModel;
1657
1726
  }
1658
- async function generateSliceMocks(imageFile, existingMocks) {
1659
- var _a, _b, _c;
1727
+ async function generateSliceMocks(sliceIndex, imageFile, existingMocks) {
1660
1728
  const systemPrompt = `
1661
- You are a seasoned frontend engineer with deep expertise in Prismic slices.
1662
- Your task is to update the provided mocks template based solely on the visible content in the image.
1663
- Follow these guidelines strictly:
1664
- - Do not modify the overall structure of the mocks template.
1665
- - Strictly only update text content.
1666
- - Do not touch images.
1667
- - If you see a repetition with a group, you must create the same number of group items that are visible on the image.
1668
- - Absolutely do not touch what is not necessary to be changed, like link "key" property, or the StructureText "direction", spans", etc or the structure, this is really important that you just do a replace of the text.
1669
- - For structure text content you must alway keep the same structure and properties, even if empty, ONLY replace text content.
1670
- - Only and strictly update the text content of the fields, nothing else. You should only and strictly update the text that is visible in the image.
1671
- - Never touch the image fields, nothing should be changed for image fields.
1729
+ You are a **seasoned frontend engineer** with **deep expertise in Prismic slices**.
1730
+ Your task is to **update the provided mocks template** based **only** on the visible text content in the provided image.
1672
1731
 
1673
- !IMPORTANT!:
1674
- - Only return a valid JSON object for mocks, nothing else before. JSON.parse on your response should not throw an error.
1675
- - All your response should fit in a single return response.
1676
- - Never stop the response until you totally finish the full JSON response you wanted.
1732
+ **STRICT UPDATE GUIDELINES:**
1733
+ - **Do no create content, only take visible text from the image.**
1734
+ - **Do not modify the overall structure of the mocks template.**
1735
+ - **Strictly update text content only.**
1736
+ - **Do not touch images or image-related fields.**
1737
+ - **If a repeated item appears in a group, match the exact number of group items seen in the image.**
1738
+ - **Do not modify metadata, field properties, or structure.** This includes:
1739
+ - Do **not** change the \`"key"\` property of links.
1740
+ - Do **not** modify \`StructuredText\` properties such as \`"direction"\`, \`"spans"\`, or \`"type"\`.
1741
+ - Do **not** alter field nesting or object structure.
1742
+ - **For StructuredText fields, maintain all existing structure and properties**—**only replace text content**.
1743
+ - **Ensure that only visible text in the image is updated**—do not generate or assume content.
1744
+ - **Never modify image fields**—image references and properties must remain unchanged.
1677
1745
 
1678
- Existing Mocks Template:
1746
+ **STRICT JSON OUTPUT FORMAT:**
1747
+ - **Return ONLY a valid JSON object**—no extra text, explanations, or formatting.
1748
+ - **The response must be directly parseable** using \`JSON.parse(output)\`.
1749
+ - **Do not wrap the output in markdown (\`\`\`\`json\`) or any other formatting.**
1750
+
1751
+ **VALIDATION REQUIREMENT:**
1752
+ - Before returning, **validate that \`JSON.parse(output)\` runs without errors**.
1753
+ - If there is **any extra text, markdown, or incorrect structure**, **rewrite the response before returning**.
1754
+
1755
+ **EXISTING MOCKS TEMPLATE (To be updated with the visible text from the image only):**
1679
1756
  ${JSON.stringify(existingMocks)}
1680
1757
  `.trim();
1681
- const messages = [
1682
- { role: "system", content: systemPrompt },
1683
- {
1684
- role: "user",
1685
- content: [
1686
- {
1687
- type: "image_url",
1688
- image_url: {
1689
- url: "data:image/png;base64," + Buffer.from(imageFile).toString("base64")
1690
- }
1691
- }
1692
- ]
1693
- }
1694
- ];
1695
- const response = await openai.chat.completions.create({
1696
- model: "gpt-4o",
1697
- messages,
1698
- response_format: {
1699
- type: "json_object"
1700
- }
1758
+ const updatedMock = await callAI({
1759
+ ai: "OPENAI",
1760
+ sliceIndex,
1761
+ stepName: "MOCKS",
1762
+ systemPrompt,
1763
+ imageFile
1701
1764
  });
1702
- console.log("Generated mocks response:", JSON.stringify(response));
1703
- const resultText = (_c = (_b = (_a = response.choices[0]) == null ? void 0 : _a.message) == null ? void 0 : _b.content) == null ? void 0 : _c.trim();
1704
- if (!resultText) {
1705
- throw new Error("No valid mocks were generated.");
1706
- }
1707
- try {
1708
- const updatedMock = JSON.parse(resultText);
1709
- return [updatedMock];
1710
- } catch (error) {
1711
- throw new Error("Failed to parse AI response for mocks: " + error);
1712
- }
1765
+ return [updatedMock];
1713
1766
  }
1714
- async function generateSliceComponentCode(imageFile, codeFile, updatedSlice) {
1715
- var _a, _b, _c;
1716
- const systemPrompt = `
1717
- You are a seasoned frontend engineer with deep expertise in Prismic slices.
1718
- Your task is to generate a fully isolated React component code for a slice based on the provided image and code input.
1719
- The goal is to create the React (HTML) structure of the slice, NO STYLING! Concentrate 100% on the perfect structure of each component.
1720
-
1721
- Follow these guidelines strictly:
1722
- - Be self-contained.
1723
- - For links, you must use PrismicNextLink and you must just pass the field, PrismicNextLink will handle the display of the link text, don't do it manually.
1724
- - PrismicNextLink should never be open, just passing the field is enough like in the code example below. You can use className or inline style directly on the PrismicNextLink component.
1725
- - Ensure to strictly respect what is defined on the model for each fields ID, do not invent or use something not in the model.
1726
- - Ensure to use all fields provided in the model.
1727
- - Follow the structure provided in the code example below.
1728
- - Use the provided code to help yourself to create the structure.
1729
- - As you can see in the example of the code you MUST never access the data with "<field>.value".
1730
- - You need to really inspire yourself from the code example bellow in order to understand how to access field, write field etc. Do not try to invent something that you didn't see.
1731
- - You cannot add a style prop to "PrismicRichText" component, it's not allowed.
1732
- - It's important to respect the same imports as done in the code example bellow, import exactly from the same package.
1733
- - Never do wrong W3C HTML structure, always respect a correct HTML structure, for example you cannot put a PrismicRichText component inside a <h1>, or a <p>, etc.
1734
- - Ensure to map the field type to the correct Prismic component, for example, a StructuredText field should be mapped to PrismicRichText, an image field should be mapped to PrismicNextImage, a Text field should just be map to a classic <p> component
1735
-
1736
- !IMPORTANT!:
1737
- - Return a valid JSON object containing only one key: "componentCode". No additional keys, text, or formatting are allowed before, after, or within the JSON object.
1738
- - Return a valid JSON, meaning you should NEVER start with a sentence, directly the JSON so that I can JSON.parse your response.
1739
- - All strings must be enclosed in double quotes ("). Do not use single quotes or template literals.
1740
- - Within the string value for "componentCode", every embedded double quote must be escaped as ". Similarly, every backslash must be escaped as \\.
1741
- - Ensure that the string value does not contain any raw control characters (such as literal newline, tab, or carriage return characters). Instead, use their escape sequences.
1742
- - Before finalizing the output, validate that JSON.parse(output) works without throwing an error. No unescaped characters should cause the parser to crash.
1743
- - The output must not include any markdown formatting, code block fences, or extra text. It should be a single, clean JSON object.
1744
-
1745
- ## Example of a Fully Isolated Slice Component:
1746
- -----------------------------------------------------------
1747
- import { FC } from "react";
1748
- import { Content } from "@prismicio/client";
1749
- import { SliceComponentProps, PrismicRichText } from "@prismicio/react";
1750
- import { PrismicNextImage, PrismicNextLink } from "@prismicio/next";
1767
+ const SLICE_CODE_EXAMPLE = `
1768
+ -----------------------------------------------------------
1769
+ import { FC } from "react";
1770
+ import { Content } from "@prismicio/client";
1771
+ import { SliceComponentProps, PrismicRichText } from "@prismicio/react";
1772
+ import { PrismicNextImage, PrismicNextLink } from "@prismicio/next";
1751
1773
 
1752
- export type PascalNameToReplaceProps =
1753
- SliceComponentProps<Content.PascalNameToReplaceSlice>;
1774
+ export type PascalNameToReplaceProps =
1775
+ SliceComponentProps<Content.PascalNameToReplaceSlice>;
1754
1776
 
1755
- const PascalNameToReplace: FC<PascalNameToReplaceProps> = ({ slice }) => {
1756
- return (
1757
- <section
1758
- data-slice-type={slice.slice_type}
1759
- data-slice-variation={slice.variation}
1760
- className="es-bounded es-alternate-grid"
1761
- >
1762
- <PrismicNextLink
1763
- className="es-alternate-grid__button"
1764
- field={slice.primary.buttonLink}
1765
- />
1766
- <div className="es-alternate-grid__content">
1767
- <PrismicNextImage
1768
- field={slice.primary.image}
1769
- className="es-alternate-grid__image"
1770
- />
1771
- <div className="es-alternate-grid__primary-content">
1772
- <div className="es-alternate-grid__primary-content__intro">
1773
- <p className="es-alternate-grid__primary-content__intro__eyebrow">
1774
- {slice.primary.eyebrowHeadline}
1775
- </p>
1776
- <div className="es-alternate-grid__primary-content__intro__headline">
1777
- <PrismicRichText field={slice.primary.title} />
1778
- </div>
1779
- <div className="es-alternate-grid__primary-content__intro__description">
1780
- <PrismicRichText field={slice.primary.description} />
1781
- </div>
1782
- </div>
1777
+ const PascalNameToReplace: FC<PascalNameToReplaceProps> = ({ slice }) => {
1778
+ return (
1779
+ <section
1780
+ data-slice-type={slice.slice_type}
1781
+ data-slice-variation={slice.variation}
1782
+ className="es-bounded es-alternate-grid"
1783
+ >
1784
+ <PrismicNextLink
1785
+ className="es-alternate-grid__button"
1786
+ field={slice.primary.buttonLink}
1787
+ />
1788
+ <div className="es-alternate-grid__content">
1789
+ <PrismicNextImage
1790
+ field={slice.primary.image}
1791
+ className="es-alternate-grid__image"
1792
+ />
1793
+ <div className="es-alternate-grid__primary-content">
1794
+ <div className="es-alternate-grid__primary-content__intro">
1795
+ <p className="es-alternate-grid__primary-content__intro__eyebrow">
1796
+ {slice.primary.eyebrowHeadline}
1797
+ </p>
1798
+ <div className="es-alternate-grid__primary-content__intro__headline">
1799
+ <PrismicRichText field={slice.primary.title} />
1800
+ </div>
1801
+ <div className="es-alternate-grid__primary-content__intro__description">
1802
+ <PrismicRichText field={slice.primary.description} />
1803
+ </div>
1804
+ </div>
1783
1805
 
1784
- <div className="es-alternate-grid__primary-content__stats">
1785
- {slice.primary.stats.map((stat, i) => (
1786
- <div key={\`stat-\${i + 1}\`} className="es-alternate-grid__stat">
1787
- <div className="es-alternate-grid__stat__heading">
1788
- <PrismicRichText field={stat.title} />
1789
- </div>
1790
- <div className="es-alternate-grid__stat__description">
1791
- <PrismicRichText field={stat.description} />
1792
- </div>
1793
- </div>
1794
- ))}
1795
- </div>
1806
+ <div className="es-alternate-grid__primary-content__stats">
1807
+ {slice.primary.stats.map((stat, i) => (
1808
+ <div key={\`stat-\${i + 1}\`} className="es-alternate-grid__stat">
1809
+ <div className="es-alternate-grid__stat__heading">
1810
+ <PrismicRichText field={stat.title} />
1811
+ </div>
1812
+ <div className="es-alternate-grid__stat__description">
1813
+ <PrismicRichText field={stat.description} />
1796
1814
  </div>
1797
1815
  </div>
1798
- </section>
1799
- );
1800
- };
1816
+ ))}
1817
+ </div>
1818
+ </div>
1819
+ </div>
1820
+ </section>
1821
+ );
1822
+ };
1801
1823
 
1802
- export default PascalNameToReplace;
1803
- -----------------------------------------------------------
1824
+ export default PascalNameToReplace;
1825
+ -----------------------------------------------------------
1826
+ `.trim();
1827
+ async function generateSliceComponentCode(sliceIndex, imageFile, updatedSlice) {
1828
+ const systemPrompt = `
1829
+ You are a **seasoned frontend engineer** with **deep expertise in Prismic slices**.
1830
+ Your task is to generate a **fully isolated React component** for a Prismic slice, **focusing ONLY on structure (HTML) without styling**.
1831
+
1832
+ **STRICT STRUCTURAL GUIDELINES:**
1833
+ - **Do not include styling.** Focus **100% on correct structure**.
1834
+ - **Be self-contained.** The component must work in isolation.
1835
+ - **Follow the structure provided in the example.** Do not introduce **any variations**.
1836
+ - **Use all fields provided in the model**—do not omit or invent fields.
1837
+ - **Never access a field using** \`<field>.value\`. Always follow the example pattern with just \`<field>\`.
1838
+ - **Ensure correct mapping of field types:**
1839
+ - **StructuredText** → \`PrismicRichText\`
1840
+ - **Image field** → \`PrismicNextImage\`
1841
+ - **Text field** → Standard \`<p>\` element
1842
+ - **Link field** → \`PrismicNextLink\`
1843
+ - **Group field** → Map to the correct structure based on the example.
1844
+ - **Maintain W3C-compliant HTML.** Do not place \`PrismicRichText\` inside \`<h1>\`, \`<p>\`, or other invalid elements.
1845
+
1846
+ **PRISMIC COMPONENT USAGE RULES:**
1847
+ - **Links must use \`PrismicNextLink\`**, passing only the \`field\` (no manual text extraction).
1848
+ - **\`PrismicNextLink\` must never be opened manually**—pass the field directly as in the example.
1849
+ - **\`PrismicRichText\` cannot have a \`style\` prop**.
1850
+ - **Imports must be identical to the provided example**.
1851
+
1852
+ **STRICT JSON OUTPUT FORMAT**
1853
+ - **Return ONLY a valid JSON object** with **one key**: \`"componentCode"\`.
1854
+ - **No markdown (\`\`\`\`json\`), no comments, no text before or after—ONLY pure JSON**.
1855
+ - **The response MUST start with \`{\` and end with \`}\` exactly, do not start with a sentence explaining what you will do.**
1856
+ - **Ensure the output is directly parseable** with \`JSON.parse(output)\`.
1857
+ - **All strings must use double quotes (\`"\`).** Do not use single quotes or template literals.
1858
+ - **Escape all embedded double quotes (\`"\`) and backslashes (\`\\\`).**
1859
+ - **The output must not contain raw control characters** (newline, tab, etc.); use escape sequences instead.
1860
+
1861
+ **Before returning, VALIDATE that \`JSON.parse(output)\` runs without errors.**
1804
1862
 
1805
- Model of the slice:
1863
+ **EXAMPLE OF A FULLY ISOLATED SLICE COMPONENT (Follow this strictly):**
1864
+ ${SLICE_CODE_EXAMPLE}
1865
+
1866
+ **SLICE MODEL (Use this as the exact reference):**
1806
1867
  ${JSON.stringify(updatedSlice)}
1807
1868
  `.trim();
1808
- const messages = [
1809
- { role: "system", content: systemPrompt },
1810
- {
1811
- role: "user",
1812
- content: [
1813
- {
1814
- type: "image_url",
1815
- image_url: {
1816
- url: "data:image/png;base64," + Buffer.from(imageFile).toString("base64")
1817
- }
1818
- },
1819
- { type: "text", text: codeFile }
1820
- ]
1821
- }
1822
- ];
1823
- const response = await openai.chat.completions.create({
1824
- model: "gpt-4o",
1825
- messages,
1826
- response_format: {
1827
- type: "json_object"
1828
- }
1869
+ const parsed = await callAI({
1870
+ ai: "AWS",
1871
+ sliceIndex,
1872
+ stepName: "CODE",
1873
+ systemPrompt,
1874
+ imageFile
1829
1875
  });
1830
- console.log("Generated component code response:", JSON.stringify(response));
1831
- const resultText = (_c = (_b = (_a = response.choices[0]) == null ? void 0 : _a.message) == null ? void 0 : _b.content) == null ? void 0 : _c.trim();
1832
- if (!resultText) {
1833
- throw new Error("No valid slice component code was generated.");
1834
- }
1835
- try {
1836
- const parsed = JSON.parse(resultText);
1837
- if (!parsed.componentCode) {
1838
- throw new Error("Missing key 'componentCode' in AI response.");
1839
- }
1840
- return parsed.componentCode;
1841
- } catch (error) {
1842
- throw new Error("Failed to parse AI response for component code: " + error);
1876
+ if (!parsed.componentCode) {
1877
+ throw new Error("Missing key 'componentCode' in AI response.");
1843
1878
  }
1879
+ return parsed.componentCode;
1844
1880
  }
1845
- async function generateSliceComponentCodeAppearance(imageFile, codeFile, globalStyle, componentCode) {
1846
- var _a, _b, _c;
1881
+ async function generateSliceComponentCodeAppearance(sliceIndex, imageFile, componentCode) {
1847
1882
  const systemPrompt = `
1848
- You are a seasoned frontend engineer with deep expertise in Prismic slices.
1849
- Your task is to apply the branding (appearance) based on the provided image and code input.
1850
- The branding is SUPER important, and the slice you create should PERFECTLY match the branding (appearance) of the provided slice image and code.
1851
-
1852
- Follow these guidelines strictly:
1853
- - Don't change anything related to the structure of the code, ONLY apply styling, PURELY styling is your ONLY task.
1854
- - Be self-contained, no dependency should be use to do the styling, do inline style.
1855
- - Your goal is to make the code visually looks as close as possible to the image from the user input.
1856
- - Ensure that the color used for the background is the same as the image provide in the user prompt! It's better no background color than a wrong one.
1857
- - Strictly respect the padding and margin visible in the image provide in the user prompt.
1858
- - Strictly respect the fonts size, color, type visible in the image provide in the user prompt.
1859
- - Strictly respect the colors visible in the image provide in the user prompt.
1860
- - Strictly respect the position of elements visible in the image provide in the user prompt.
1861
- - Strictly respect the size of each elements visible in the image provide in the user prompt.
1862
- - Strictly respect the overall proportions of the slice from the image provide in the user prompt.
1863
- - Ensure image are always displayed with the same aspect ratio as the image provide in the user prompt, put constraints on the image with / height to make sure it's the same.
1864
- - Handle animations, but never make them too long, it should be fast enough to be nice to read.
1865
- - Use inline <style> (do not use <style jsx>).
1866
- - Items repetitions should be styled in the same way as the image provided, the direction of the flex should be the same so that the items are vertical or horizontal as in the image.
1867
-
1868
- !IMPORTANT!:
1869
- - DO NOT CHANGE anything else than the style BUT return everything as before for the rest, like from the import to the last export line, everything should stay the same BUT you add the styling on top.
1870
- - Return a valid JSON object containing only one key: "componentCode". No additional keys, text, or formatting are allowed before, after, or within the JSON object.
1871
- - Return a valid JSON, meaning you should NEVER start with a sentence, directly the JSON so that I can JSON.parse your response.
1872
- - All strings must be enclosed in double quotes ("). Do not use single quotes or template literals.
1873
- - Within the string value for "componentCode", every embedded double quote must be escaped as ". Similarly, every backslash must be escaped as \\.
1874
- - Ensure that the string value does not contain any raw control characters (such as literal newline, tab, or carriage return characters). Instead, use their escape sequences.
1875
- - Before finalizing the output, validate that JSON.parse(output) works without throwing an error. No unescaped characters should cause the parser to crash.
1876
- - The output must not include any markdown formatting, code block fences, or extra text. It should be a single, clean JSON object.
1877
-
1878
- Existing code to apply branding on it:
1883
+ You are a **seasoned frontend engineer** with **deep expertise in Prismic slices**.
1884
+ Your task is to **apply branding (appearance) strictly based on the provided image and code input**.
1885
+ The **branding is CRITICAL**—the slice you create **must perfectly match the visual appearance** of the provided slice image.
1886
+
1887
+ **STRICT GUIDELINES TO FOLLOW (NO EXCEPTIONS):**
1888
+ - **DO NOT** modify the structure of the code—**ONLY apply styling**. Your role is **purely styling-related**.
1889
+ - **NO external dependencies**—use **only inline** styling.
1890
+ - **VISUAL ACCURACY IS MANDATORY**—your goal is to make the output **visually identical** to the provided image.
1891
+
1892
+ **MUST strictly respect the following:**
1893
+ - **Background color** Must **exactly match** the image. If unsure, **do not apply** any background color.
1894
+ - **Padding & margin** Must be **pixel-perfect** per the provided image.
1895
+ - **Font size, color, and type** Must match exactly. If the exact font is unavailable, choose the **closest possible match**.
1896
+ - **Typography precision** If the font-family does not match, **the output is incorrect**.
1897
+ - **Color accuracy** Use **ONLY the colors visible** in the provided image.
1898
+ - **Element positioning** Elements **must be placed exactly** as seen in the provided image.
1899
+ - **Element sizes** Every element **must match** the provided image in width, height, and proportions.
1900
+ - **Overall proportions** The slice must maintain **identical proportions** to the provided image.
1901
+ - **Image constraints** Images **must** maintain their **original aspect ratio**. Use explicit \`width\` and \`height\` constraints with an explicit pixels value. Avoid \`width: auto\`, \`height: auto\`, \`width: 100%\` or \`height: 100%\`.
1902
+ - **Repetitions & layout** → Ensure **consistent styling** across repeated items. The **layout direction (horizontal/vertical)** must match the image.
1903
+ - **Animations** → Handle animations as seen in the image, but **keep them fast and subtle** (avoid long animations).
1904
+
1905
+ **IMPORTANT RULES:**
1906
+ 1. **DO NOT modify any non-styling code**.
1907
+ - **Everything from the first import to the last export must remain unchanged**.
1908
+ - **Only add styling** on top of the existing structure.
1909
+
1910
+ 2. **STRICT JSON OUTPUT FORMAT**
1911
+ - Return a **valid JSON object** with **one key only**: \`"componentCode"\`.
1912
+ - **NO markdown, NO code blocks, NO text before or after**—only **pure JSON**.
1913
+ - The response **must start and end directly with \`{ "componentCode": ... }\`**.
1914
+ - Ensure the output is **directly parseable** using \`JSON.parse(output)\`.
1915
+
1916
+ 3. **INLINE \`<style>\` RULES**
1917
+ - Use **only inline** \`<style>\` tags (not \`<style jsx>\`).
1918
+ - Ensure **all CSS is valid** and matches the image precisely.
1919
+ - **Use backtick inside the \`<style>\` tag like this: <style>{\`...\`}</style>**.
1920
+ - **Do NOT escape the backtick (\`\`\`) inside the \`<style>\` tag**.
1921
+
1922
+ **Before returning, VALIDATE that \`JSON.parse(output)\` runs without errors.**
1923
+
1924
+ **EXISTING CODE (to apply branding on):**
1879
1925
  ${componentCode}
1880
- `.trim();
1881
- const messages = [
1882
- { role: "system", content: systemPrompt },
1883
- {
1884
- role: "user",
1885
- content: [
1886
- {
1887
- type: "image_url",
1888
- image_url: {
1889
- url: "data:image/png;base64," + Buffer.from(imageFile).toString("base64")
1890
- }
1891
- },
1892
- { type: "text", text: codeFile }
1893
- ]
1894
- }
1895
- ];
1896
- const response = await openai.chat.completions.create({
1897
- model: "gpt-4o",
1898
- messages,
1899
- response_format: {
1900
- type: "json_object"
1901
- }
1926
+ `.trim();
1927
+ const parsed = await callAI({
1928
+ ai: "AWS",
1929
+ sliceIndex,
1930
+ stepName: "APPEARANCE",
1931
+ systemPrompt,
1932
+ imageFile
1902
1933
  });
1903
- console.log("Generated component code appearance response:", JSON.stringify(response));
1904
- const resultText = (_c = (_b = (_a = response.choices[0]) == null ? void 0 : _a.message) == null ? void 0 : _b.content) == null ? void 0 : _c.trim();
1905
- if (!resultText) {
1906
- throw new Error("No valid slice component code was generated.");
1907
- }
1908
- try {
1909
- const parsed = JSON.parse(resultText);
1910
- if (!parsed.componentCode) {
1911
- throw new Error("Missing key 'componentCode' in AI response.");
1912
- }
1913
- return parsed.componentCode;
1914
- } catch (error) {
1915
- throw new Error("Failed to parse AI response for component code appearance: " + error);
1934
+ if (!parsed.componentCode) {
1935
+ throw new Error("Missing key 'componentCode' in AI response.");
1916
1936
  }
1937
+ return parsed.componentCode;
1917
1938
  }
1918
1939
  try {
1919
- let slices = [];
1920
- const folderPath = KNOWNED_WEBSITE_URLS[args.websiteUrl];
1921
- console.log("STEP 1: Get the slices images from the folder.");
1922
- const sliceImages = await readImagesFromFolder(`${folderPath}/images`);
1923
- console.log("STEP 2: Get the slices codes from the folder.");
1924
- const sliceCodes = await readCodeFromFolder(`${folderPath}/code`);
1925
- slices = sliceImages.map((sliceImage, index) => ({
1926
- sliceImage,
1927
- codeFile: sliceCodes[index]
1928
- }));
1929
- const updatedSlices = await Promise.all(slices.map(async ({ sliceImage, codeFile }, index) => {
1930
- console.log("STEP 3: Generate the slice model using the image for slice:", index);
1931
- const updatedSlice = await generateSliceModel(sliceImage, codeFile);
1932
- console.log("STEP 4: Persist the updated slice model for:", `${index} - ${updatedSlice.name}`);
1940
+ const updatedSlices = await Promise.all(args.sliceImages.map(async (sliceImage, index) => {
1941
+ console.log("STEP 1: Generate the slice model using the image for slice:", index);
1942
+ const updatedSlice = await generateSliceModel(index, sliceImage);
1943
+ console.log("STEP 2: Persist the updated slice model for:", `${index} - ${updatedSlice.name}`);
1933
1944
  await this.updateSlice({
1934
1945
  libraryID: DEFAULT_LIBRARY_ID,
1935
1946
  model: updatedSlice
1936
1947
  });
1937
- console.log("STEP 5: Update the slice screenshot for:", `${index} - ${updatedSlice.name}`);
1948
+ console.log("STEP 3: Update the slice screenshot for:", `${index} - ${updatedSlice.name}`);
1938
1949
  await this.updateSliceScreenshot({
1939
1950
  libraryID: DEFAULT_LIBRARY_ID,
1940
1951
  sliceID: updatedSlice.id,
@@ -1943,47 +1954,53 @@ type GroupField = {
1943
1954
  });
1944
1955
  let updatedMock;
1945
1956
  try {
1946
- console.log("STEP 6: Generate updated mocks for:", `${index} - ${updatedSlice.name}`);
1957
+ console.log("STEP 4: Generate updated mocks for:", `${index} - ${updatedSlice.name}`);
1947
1958
  const existingMocks = mockSlice({ model: updatedSlice });
1948
- updatedMock = await generateSliceMocks(sliceImage, existingMocks);
1959
+ updatedMock = await generateSliceMocks(index, sliceImage, existingMocks);
1949
1960
  } catch (error) {
1950
1961
  console.error(`Failed to generate mocks for ${index} - ${updatedSlice.name}:`, error);
1951
1962
  updatedMock = mockSlice({ model: updatedSlice });
1952
1963
  }
1953
1964
  let componentCode;
1954
1965
  try {
1955
- console.log("STEP 7: Generate the isolated slice component code for:", `${index} - ${updatedSlice.name}`);
1956
- const globalStyle = await getGlobalStyle(`${folderPath}/globalStyle.css`);
1957
- const initialCode = await generateSliceComponentCode(sliceImage, codeFile, updatedSlice);
1958
- console.log("STEP 8: Generate the branding on the code:", `${index} - ${updatedSlice.name}`);
1959
- componentCode = await generateSliceComponentCodeAppearance(sliceImage, codeFile, globalStyle, initialCode);
1966
+ console.log("STEP 5: Generate the isolated slice component code for:", `${index} - ${updatedSlice.name}`);
1967
+ const initialCode = await generateSliceComponentCode(index, sliceImage, updatedSlice);
1968
+ console.log("STEP 6: Generate the branding on the code:", `${index} - ${updatedSlice.name}`);
1969
+ componentCode = await generateSliceComponentCodeAppearance(index, sliceImage, initialCode);
1960
1970
  } catch (error) {
1961
1971
  console.error(`Failed to generate code for ${index} - ${updatedSlice.name}:`, error);
1962
1972
  }
1963
1973
  return { updatedSlice, componentCode, updatedMock };
1964
1974
  }));
1965
- await Promise.all(updatedSlices.map(async ({ updatedSlice, componentCode, updatedMock }, index) => {
1966
- console.log("STEP 9: Update the slice code for:", `${index} - ${updatedSlice.name}`);
1975
+ await updatedSlices.forEach(async ({ updatedSlice, componentCode, updatedMock }, index) => {
1976
+ console.log("STEP 7: Update the slice code for:", `${index} - ${updatedSlice.name}`);
1967
1977
  if (componentCode) {
1968
- await this.createSlice({
1978
+ const { errors } = await this.createSlice({
1969
1979
  libraryID: DEFAULT_LIBRARY_ID,
1970
1980
  model: updatedSlice,
1971
1981
  componentContents: componentCode
1972
1982
  });
1983
+ if (errors.length > 0) {
1984
+ console.log(`Errors while updating the slice code for ${index} - ${updatedSlice.name}:`, errors);
1985
+ await this.createSlice({
1986
+ libraryID: DEFAULT_LIBRARY_ID,
1987
+ model: updatedSlice
1988
+ });
1989
+ }
1973
1990
  } else {
1974
1991
  await this.createSlice({
1975
1992
  libraryID: DEFAULT_LIBRARY_ID,
1976
1993
  model: updatedSlice
1977
1994
  });
1978
1995
  }
1979
- console.log("STEP 10: Persist the generated mocks for:", `${index} - ${updatedSlice.name}`);
1996
+ console.log("STEP 8: Persist the generated mocks for:", `${index} - ${updatedSlice.name}`);
1980
1997
  await this.updateSliceMocks({
1981
1998
  libraryID: DEFAULT_LIBRARY_ID,
1982
1999
  sliceID: updatedSlice.id,
1983
2000
  mocks: updatedMock
1984
2001
  });
1985
- }));
1986
- console.log("STEP 11: THE END");
2002
+ });
2003
+ console.log("STEP 9: THE END");
1987
2004
  return {
1988
2005
  slices: updatedSlices.map(({ updatedSlice }) => updatedSlice)
1989
2006
  };