@slicemachine/manager 0.25.7-alpha.xru-unskip-e2e-test-redirection.3 → 0.25.7-beta.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.
@@ -36,6 +36,20 @@ import { UnauthorizedError } from "../../errors";
36
36
 
37
37
  import { BaseManager } from "../BaseManager";
38
38
  import { CustomTypeFormat } from "./types";
39
+ import { existsSync } from "node:fs";
40
+ import { tmpdir } from "node:os";
41
+ import { randomUUID } from "node:crypto";
42
+ import { join as joinPath, relative as relativePath } from "node:path";
43
+ import {
44
+ mkdtemp,
45
+ rename,
46
+ rm,
47
+ writeFile,
48
+ readFile,
49
+ readdir,
50
+ } from "node:fs/promises";
51
+ import { query as queryClaude } from "@anthropic-ai/claude-agent-sdk";
52
+ import { APPLICATION_MODE } from "../../constants/APPLICATION_MODE";
39
53
 
40
54
  type SliceMachineManagerReadCustomTypeLibraryReturnType = {
41
55
  ids: string[];
@@ -533,37 +547,379 @@ export class CustomTypesManager extends BaseManager {
533
547
  return await client.getAllCustomTypes();
534
548
  }
535
549
 
536
- async inferSlice({
537
- imageUrl,
538
- }: {
539
- imageUrl: string;
540
- }): Promise<InferSliceResponse> {
541
- const authToken = await this.user.getAuthenticationToken();
542
- const headers = {
543
- Authorization: `Bearer ${authToken}`,
544
- };
550
+ async inferSlice(
551
+ args: { imageUrl: string } & (
552
+ | { source: "upload" }
553
+ | { source: "figma"; libraryID: string }
554
+ ),
555
+ ): Promise<InferSliceResponse> {
556
+ const { source, imageUrl } = args;
545
557
 
558
+ const authToken = await this.user.getAuthenticationToken();
546
559
  const repository = await this.project.getResolvedRepositoryName();
547
- const searchParams = new URLSearchParams({
548
- repository,
549
- });
550
560
 
551
- const url = new URL("./slices/infer", API_ENDPOINTS.CustomTypeService);
552
- url.search = searchParams.toString();
561
+ console.info(`inferSlice (${source}) started`);
562
+ const startTime = Date.now();
553
563
 
554
- const response = await fetch(url.toString(), {
555
- method: "POST",
556
- headers: headers,
557
- body: JSON.stringify({ imageUrl }),
558
- });
564
+ try {
565
+ if (source === "figma") {
566
+ const { libraryID } = args;
559
567
 
560
- if (!response.ok) {
561
- throw new Error(`Failed to infer slice: ${response.statusText}`);
562
- }
568
+ const exp =
569
+ await this.telemetry.getExperimentVariant("llm-proxy-access");
570
+ if (exp?.value !== "on") {
571
+ throw new Error("User does not have access to the LLM proxy.");
572
+ }
573
+
574
+ const { llmProxyUrl } = z
575
+ .object({ llmProxyUrl: z.string().url() })
576
+ .parse(exp.payload);
577
+
578
+ console.info({ llmProxyUrl });
579
+
580
+ let tmpDir: string | undefined;
581
+ try {
582
+ const config = await this.project.getSliceMachineConfig();
583
+
584
+ let framework:
585
+ | { type: "nextjs" | "nuxt" | "sveltekit"; label: string }
586
+ | undefined;
587
+ if (config.adapter === "@slicemachine/adapter-next") {
588
+ framework = { type: "nextjs", label: "Next.js (React)" };
589
+ } else if (
590
+ config.adapter === "@slicemachine/adapter-nuxt" ||
591
+ config.adapter === "@slicemachine/adapter-nuxt2"
592
+ ) {
593
+ framework = { type: "nuxt", label: "Nuxt (Vue)" };
594
+ } else if (config.adapter === "@slicemachine/adapter-sveltekit") {
595
+ framework = { type: "sveltekit", label: "SvelteKit (Svelte)" };
596
+ }
563
597
 
564
- const json = await response.json();
598
+ if (!framework) {
599
+ throw new Error(
600
+ "Could not determine framework from Slice Machine config.",
601
+ );
602
+ }
603
+
604
+ const projectRoot = await this.project.getRoot();
605
+ const libraryAbsPath = joinPath(projectRoot, libraryID);
606
+ const cwd = libraryAbsPath;
607
+
608
+ tmpDir = await mkdtemp(
609
+ joinPath(tmpdir(), "slice-machine-infer-slice-tmp-"),
610
+ );
611
+ const tmpImageAbsPath = joinPath(tmpDir, `${randomUUID()}.png`);
612
+ const response = await fetch(imageUrl);
613
+ if (!response.ok) {
614
+ throw new Error(
615
+ `Failed to download image: ${response.status} ${response.statusText}`,
616
+ );
617
+ }
618
+ await writeFile(
619
+ tmpImageAbsPath,
620
+ Buffer.from(await response.arrayBuffer()),
621
+ );
622
+
623
+ const otherSlices = (
624
+ await Promise.all(
625
+ (await readdir(libraryAbsPath, { withFileTypes: true })).flatMap(
626
+ async (path) => {
627
+ try {
628
+ if (!path.isDirectory()) {
629
+ throw new Error("Not a directory");
630
+ }
631
+
632
+ const absPath = joinPath(libraryAbsPath, path.name);
633
+ const modelAbsPath = joinPath(absPath, "model.json");
634
+ if (!existsSync(modelAbsPath)) {
635
+ throw new Error("Model file not found");
636
+ }
637
+
638
+ const decoded = SharedSlice.decode(
639
+ JSON.parse(await readFile(modelAbsPath, "utf-8")),
640
+ );
641
+ if (decoded._tag === "Left") {
642
+ throw new Error("Invalid model file");
643
+ }
644
+
645
+ return [
646
+ {
647
+ absPath,
648
+ relPath: relativePath(cwd, absPath),
649
+ name: decoded.right.name,
650
+ },
651
+ ];
652
+ } catch {
653
+ return [];
654
+ }
655
+ },
656
+ ),
657
+ )
658
+ ).flat();
659
+
660
+ const prompt = `CRITICAL INSTRUCTIONS - READ FIRST:
661
+ - You MUST start immediately with Step 1.1. DO NOT read, analyze, or explore any project files first.
662
+ - Work step-by-step through the numbered tasks below.
663
+ - DO NOT present any summary, explanation, or completion message after finishing.
664
+ - DO NOT create TODO lists while performing tasks.
665
+ - Keep responses minimal - only show necessary tool calls and brief progress notes.
666
+
667
+ # CONTEXT
668
+
669
+ The user wants to build a new Prismic Slice based on a design image they provided.
670
+ Your goal is to analyze the design image and generate the JSON model data and boilerplate code for the slice following Prismic requirements.
671
+
672
+ You will work under the slice library at <slice_library_directory_path>, where all the slices are stored.
673
+
674
+ # AVAILABLE RESOURCES
675
+
676
+ <framework>
677
+ ${framework.label}
678
+ </framework>
679
+
680
+ <design_image_path>
681
+ ${tmpImageAbsPath}
682
+ </design_image_path>
683
+
684
+ <slice_library_directory_path>
685
+ ${libraryAbsPath}
686
+ </slice_library_directory_path>
687
+
688
+ <disallowed_slice_names>
689
+ ${otherSlices.map((slice) => `- ${slice.name}`).join("\n")}
690
+ </disallowed_slice_names>
691
+
692
+ # AVAILABLE TOOLS
565
693
 
566
- return InferSliceResponse.parse(json);
694
+ You have access to specialized Prismic MCP tools for this task:
695
+
696
+ <tool name="mcp__prismic__how_to_model_slice">
697
+ <description>
698
+ Provides detailed guidance on creating Prismic slice models, including field types, naming conventions, and best practices.
699
+ </description>
700
+ <when_to_use>
701
+ Call this tool in Step 2.1 to learn how to structure the slice model data for the design you analysed.
702
+ </when_to_use>
703
+ </tool>
704
+
705
+ <tool name="mcp__prismic__how_to_code_slice">
706
+ <description>
707
+ Provides guidance on implementing Prismic slice components, including how to use Prismic field components, props structure, and best practices.
708
+ </description>
709
+ <when_to_use>
710
+ Call this tool in Step 2.1 to learn how to properly structure the slice component with Prismic fields.
711
+ </when_to_use>
712
+ </tool>
713
+
714
+ <tool name="mcp__prismic__save_slice_data">
715
+ <description>
716
+ Validates and saves the slice model data to model.json. This is the ONLY way to create the model file.
717
+ </description>
718
+ <when_to_use>
719
+ Call this tool in Step 2.3 after you have built the complete slice model structure in memory.
720
+ </when_to_use>
721
+ </tool>
722
+
723
+ # TASK REQUIREMENTS
724
+
725
+ ## Step 1: Gather information from the design image
726
+ 1.1. Analyse the design image at <design_image_path>.
727
+ 1.2. Identify all elements in the image that should be dynamically editable (e.g., headings, paragraphs, images, links, buttons, etc.).
728
+ 1.3. Come up with a UNIQUE name for the new slice based on the content of the image, DO NOT use any of the names in <disallowed_slice_names>.
729
+
730
+ ## Step 2: Model the Prismic slice
731
+ 2.1. Call mcp__prismic__how_to_model_slice to learn how to structure the model for this design.
732
+ 2.2. Build the complete slice JSON model data in memory based on the guidance received and the information extracted from the image.
733
+ 2.3. Call mcp__prismic__save_slice_data to save the model (DO NOT manually write model.json) in the slice library at <slice_library_directory_path>.
734
+
735
+ ## Step 3: Code a boilerplate slice component based on the model
736
+ 3.1. Call mcp__prismic__how_to_code_slice to learn how to properly structure the slice component with Prismic fields.
737
+ 3.2. Update the slice component code at <slice_library_directory_path>/index.*, replacing the placeholder code with boilerplate code with the following requirements:
738
+ - Must NOT be based on existing slices or components from the codebase.
739
+ - Must render all the Prismic components to display the fields of the slice model created at <slice_model_path>.
740
+ - Must be a valid ${framework.label} component.
741
+ - Must NOT have any styling/CSS. No inlines styles or classNames. Just the skeleton component structure.
742
+ - Must NOT use any other custom component or functions from the user's codebase.
743
+ - Avoid creating unnecessary wrapper elements, like if they only wrap a single component (e.g., <div><PrismicRichText /></div>).
744
+
745
+ ## Step 4: Present the newly created slice path
746
+ 4.1. Present the path to the newly created slice in the following format: <new_slice_path>${libraryAbsPath}/MyNewSlice</new_slice_path>.
747
+ - "MyNewSlice" must be the name of the directory of the newly created slice.
748
+
749
+ # EXAMPLE OF CORRECT EXECUTION
750
+
751
+ <example>
752
+ Assistant: Step 1.1: Analysing design image...
753
+ [reads <design_image_path>]
754
+
755
+ Step 1.2: Identifying editable content elements...
756
+ [identifies: title field, description field, buttonText field, buttonLink field, backgroundImage field]
757
+
758
+ Step 1.3: Listing slice directories under <slice_library_directory_path>...
759
+ [lists slice directories: Hero, Hero2, Hero3]
760
+
761
+ Step 1.4: Coming up with a unique name for the new slice...
762
+ [comes up with a unique name for the new slice: Hero4]
763
+
764
+ Step 2.1: Getting Prismic modeling guidance...
765
+ [calls mcp__prismic__how_to_model_slice]
766
+
767
+ Step 2.2: Building slice model based on guidance and the information extracted...
768
+ [creates model with title field, description field, buttonText field, buttonLink field, backgroundImage field]
769
+
770
+ Step 2.3: Saving slice model...
771
+ [calls mcp__prismic__save_slice_data]
772
+
773
+ Step 3.1: Learning Prismic slice coding requirements...
774
+ [calls mcp__prismic__how_to_code_slice]
775
+
776
+ Step 3.2: Coding boilerplate slice component based on the model...
777
+ [updates component with Prismic field components, no styling, no other components]
778
+
779
+ Step 4.1: Presenting the path to the newly created slice...
780
+ [presents <new_slice_path>${joinPath(
781
+ libraryAbsPath,
782
+ "MyNewSlice",
783
+ )}</new_slice_path>]
784
+
785
+ # DELIVERABLES
786
+ - Slice model saved to <slice_library_directory_path>/model.json using mcp__prismic__save_slice_data
787
+ - Slice component at <slice_library_directory_path>/index.* updated with boilerplate code
788
+ - New slice path presented in the format mentioned in Step 3.1
789
+
790
+ YOU ARE NOT FINISHED UNTIL YOU HAVE THESE DELIVERABLES.
791
+
792
+ ---
793
+
794
+ FINAL REMINDERS:
795
+ - You MUST use mcp__prismic__save_slice_data to save the model
796
+ - You MUST call mcp__prismic__how_to_code_slice in Step 3.1
797
+ - DO NOT ATTEMPT TO BUILD THE APPLICATION
798
+ - START IMMEDIATELY WITH STEP 1.1 - NO PRELIMINARY ANALYSIS`;
799
+
800
+ const queries = queryClaude({
801
+ prompt,
802
+ options: {
803
+ cwd,
804
+ stderr: (data) => {
805
+ if (!data.startsWith("Spawning Claude Code process")) {
806
+ console.error("inferSlice error:" + data);
807
+ }
808
+ },
809
+ model: "claude-haiku-4-5",
810
+ permissionMode: "acceptEdits",
811
+ allowedTools: [
812
+ `Bash(${cwd})`,
813
+ "Read",
814
+ "Grep",
815
+ "Glob",
816
+ "Write",
817
+ "Edit",
818
+ "MultiEdit",
819
+ "FileSearch",
820
+ "mcp__prismic__how_to_model_slice",
821
+ "mcp__prismic__how_to_code_slice",
822
+ "mcp__prismic__save_slice_data",
823
+ ],
824
+ disallowedTools: [
825
+ `Edit(**/model.json)`,
826
+ `Write(**/model.json)`,
827
+ "Edit(**/mocks.json)",
828
+ "Write(**/mocks.json)",
829
+ ...otherSlices.flatMap((slice) => [
830
+ `Write(${slice.relPath})`,
831
+ `Edit(${slice.relPath})`,
832
+ `MultiEdit(${slice.relPath})`,
833
+ ]),
834
+ ],
835
+ env: {
836
+ ...process.env,
837
+ ANTHROPIC_BASE_URL: llmProxyUrl,
838
+ ANTHROPIC_CUSTOM_HEADERS:
839
+ `x-prismic-token: ${authToken}\n` +
840
+ `x-prismic-repository: ${repository}\n`,
841
+ },
842
+ mcpServers: {
843
+ prismic: {
844
+ type: "stdio",
845
+ command: "npx",
846
+ args: ["-y", "@prismicio/mcp-server@0.0.20-alpha.6"],
847
+ },
848
+ },
849
+ },
850
+ });
851
+
852
+ let newSliceAbsPath: string | undefined;
853
+
854
+ for await (const query of queries) {
855
+ if (process.env.SM_ENV !== APPLICATION_MODE.Production) {
856
+ console.info(JSON.stringify(query, null, 2));
857
+ }
858
+ switch (query.type) {
859
+ case "result":
860
+ if (query.subtype === "success") {
861
+ newSliceAbsPath = query.result.match(
862
+ /<new_slice_path>(.*)<\/new_slice_path>/s,
863
+ )?.[1];
864
+ }
865
+ break;
866
+ }
867
+ }
868
+
869
+ if (!newSliceAbsPath) {
870
+ throw new Error("Could not find path for the newly created slice.");
871
+ }
872
+
873
+ const model = await readFile(
874
+ joinPath(newSliceAbsPath, "model.json"),
875
+ "utf8",
876
+ );
877
+
878
+ if (!model) {
879
+ throw new Error(
880
+ "Could not find model for the newly created slice.",
881
+ );
882
+ }
883
+
884
+ // move the screenshot image to the new slice directory
885
+ await rename(
886
+ tmpImageAbsPath,
887
+ joinPath(newSliceAbsPath, "screenshot-default.png"),
888
+ );
889
+
890
+ return InferSliceResponse.parse({ slice: JSON.parse(model) });
891
+ } finally {
892
+ if (tmpDir && existsSync(tmpDir)) {
893
+ await rm(tmpDir, { recursive: true });
894
+ }
895
+ }
896
+ } else {
897
+ const searchParams = new URLSearchParams({ repository });
898
+ const url = new URL("./slices/infer", API_ENDPOINTS.CustomTypeService);
899
+ url.search = searchParams.toString();
900
+
901
+ const response = await fetch(url.toString(), {
902
+ method: "POST",
903
+ headers: { Authorization: `Bearer ${authToken}` },
904
+ body: JSON.stringify({ imageUrl }),
905
+ });
906
+
907
+ if (!response.ok) {
908
+ throw new Error(`Failed to infer slice: ${response.statusText}`);
909
+ }
910
+
911
+ const json = await response.json();
912
+
913
+ return InferSliceResponse.parse(json);
914
+ }
915
+ } catch (error) {
916
+ console.error(`inferSlice (${source}) failed`, error);
917
+
918
+ throw error;
919
+ } finally {
920
+ const elapsedTimeSeconds = (Date.now() - startTime) / 1000;
921
+ console.info(`inferSlice (${source}) took ${elapsedTimeSeconds}s`);
922
+ }
567
923
  }
568
924
  }
569
925