@slicemachine/manager 0.25.7-alpha.jp-figma-to-prismic.6 → 0.25.7-alpha.jp-figma-to-prismic.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,6 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1
4
  import * as t from "io-ts";
2
5
  import * as prismicCustomTypesClient from "@prismicio/custom-types-client";
3
6
  import { CustomType, traverseCustomType, traverseSharedSlice, SharedSlice } from "@prismicio/types-internal/lib/customtypes";
@@ -16,6 +19,10 @@ import { randomUUID } from "crypto";
16
19
  import { existsSync } from "fs";
17
20
  import { BaseManager } from "../BaseManager.js";
18
21
  class CustomTypesManager extends BaseManager {
22
+ constructor() {
23
+ super(...arguments);
24
+ __publicField(this, "inferSliceAbortControllers", /* @__PURE__ */ new Map());
25
+ }
19
26
  async readCustomTypeLibrary() {
20
27
  var _a;
21
28
  assertPluginsInitialized(this.sliceMachinePluginRunner);
@@ -279,276 +286,298 @@ class CustomTypesManager extends BaseManager {
279
286
  }
280
287
  async inferSlice(args) {
281
288
  var _a;
282
- const { source, imageUrl } = args;
283
- const exp = await this.telemetry.getExperimentVariant("llm-proxy-access");
284
- if ((exp == null ? void 0 : exp.value) !== "on") {
285
- throw new Error("LLM proxy access is not enabled.");
286
- }
287
- const { llmProxyUrl } = z.object({ llmProxyUrl: z.string() }).parse(exp.payload);
289
+ const { source, imageUrl, requestId } = args;
288
290
  const authToken = await this.user.getAuthenticationToken();
289
291
  const repository = await this.project.getResolvedRepositoryName();
290
- if (source === "figma") {
291
- const { libraryID } = args;
292
- console.log(`inferSlice started`);
293
- const startTime = Date.now();
294
- let tmpDir;
295
- try {
296
- const config = await this.project.getSliceMachineConfig();
297
- let framework;
298
- if (config.adapter === "@slicemachine/adapter-next") {
299
- framework = { type: "nextjs", label: "Next.js (React)" };
300
- } else if (config.adapter === "@slicemachine/adapter-nuxt" || config.adapter === "@slicemachine/adapter-nuxt2") {
301
- framework = { type: "nuxt", label: "Nuxt (Vue)" };
302
- } else if (config.adapter === "@slicemachine/adapter-sveltekit") {
303
- framework = { type: "sveltekit", label: "SvelteKit (Svelte)" };
304
- }
305
- if (!framework) {
306
- throw new Error("Could not determine framework from Slice Machine config.");
307
- }
308
- let frameworkFileExtension;
309
- if (framework.type === "nextjs") {
310
- frameworkFileExtension = "tsx";
311
- } else if (framework.type === "nuxt") {
312
- frameworkFileExtension = "vue";
313
- } else if (framework.type === "sveltekit") {
314
- frameworkFileExtension = "svelte";
315
- }
316
- if (!frameworkFileExtension) {
317
- throw new Error("Could not determine framework from Slice Machine config.");
318
- }
319
- const projectRoot = await this.project.getRoot();
320
- const libraryAbsPath = path.join(projectRoot, libraryID);
321
- tmpDir = await mkdtemp(path.join(tmpdir(), "slice-machine-infer-slice-tmp-"));
322
- const tmpImagePath = path.join(tmpDir, `${randomUUID()}.png`);
323
- const response = await fetch(imageUrl);
324
- if (!response.ok) {
325
- throw new Error(`Failed to download image: ${response.status} ${response.statusText}`);
292
+ let abortController;
293
+ if (requestId) {
294
+ abortController = new AbortController();
295
+ abortController.signal.addEventListener("abort", () => {
296
+ console.warn(`inferSlice (${source}) request ${requestId} was aborted`);
297
+ });
298
+ this.inferSliceAbortControllers.set(requestId, abortController);
299
+ }
300
+ console.info(`inferSlice (${source}) started${requestId ? ` for request ${requestId}` : ""}`);
301
+ const startTime = Date.now();
302
+ try {
303
+ if (source === "figma") {
304
+ const { libraryID } = args;
305
+ const exp = await this.telemetry.getExperimentVariant("llm-proxy-access");
306
+ if ((exp == null ? void 0 : exp.value) !== "on") {
307
+ throw new Error("User does not have access to the LLM proxy.");
326
308
  }
327
- await writeFile(tmpImagePath, Buffer.from(await response.arrayBuffer()));
328
- const queries = query({
329
- prompt: `CRITICAL INSTRUCTIONS - READ FIRST:
330
- - You MUST start immediately with Step 1.1. DO NOT read, analyze, or explore any project files first.
331
- - Work step-by-step through the numbered tasks below.
332
- - DO NOT present any summary, explanation, or completion message after finishing.
333
- - DO NOT create TODO lists while performing tasks.
334
- - Keep responses minimal - only show necessary tool calls and brief progress notes.
335
-
336
- # CONTEXT
337
-
338
- The user wants to build a new Prismic Slice based on a design image they provided.
339
- Your goal is to analyze the design image and generate the JSON model data and boilerplate code for the slice following Prismic requirements.
340
-
341
- You will work under the slice library at <slice_library_path>, where all the slices are stored.
342
-
343
- # AVAILABLE RESOURCES
344
-
345
- <design_image_path>
346
- ${tmpImagePath}
347
- </design_image_path>
348
-
349
- <slice_library_path>
350
- ${libraryAbsPath}
351
- </slice_library_path>
352
-
353
- <framework>
354
- ${framework.label}
355
- </framework>
356
-
357
- # AVAILABLE TOOLS
358
-
359
- You have access to specialized Prismic MCP tools for this task:
360
-
361
- <tool name="mcp__prismic__how_to_model_slice">
362
- <description>
363
- Provides detailed guidance on creating Prismic slice models, including field types, naming conventions, and best practices.
364
- </description>
365
- <when_to_use>
366
- Call this tool in Step 2.1 to learn how to structure the slice model data for the design you analysed.
367
- </when_to_use>
368
- </tool>
369
-
370
- <tool name="mcp__prismic__how_to_code_slice">
371
- <description>
372
- Provides guidance on implementing Prismic slice components, including how to use Prismic field components, props structure, and best practices.
373
- </description>
374
- <when_to_use>
375
- Call this tool in Step 2.1 to learn how to properly structure the slice component with Prismic fields.
376
- </when_to_use>
377
- </tool>
378
-
379
- <tool name="mcp__prismic__save_slice_data">
380
- <description>
381
- Validates and saves the slice model data to model.json. This is the ONLY way to create the model file.
382
- </description>
383
- <when_to_use>
384
- Call this tool in Step 2.3 after you have built the complete slice model structure in memory.
385
- </when_to_use>
386
- </tool>
387
-
388
- # TASK REQUIREMENTS
389
-
390
- ## Step 1: Gather information from the design image
391
- 1.1. Analyse the design image at <design_image_path>.
392
- 1.2. Identify all elements in the image that should be dynamically editable (e.g., headings, paragraphs, images, links, buttons, etc.).
393
- 1.3. List the slice directories under <slice_library_path>.
394
- 1.4. Come up with a unique name for the new slice based on the content of the image and the slice directories.
395
-
396
- ## Step 2: Model the Prismic slice
397
- 2.1. Call mcp__prismic__how_to_model_slice to learn how to structure the model for this design.
398
- - Make sure the name you use for the new slice does not yet exist in the slice library at <slice_library_path>. If it does, use a different name.
399
- 2.2. Build the complete slice JSON model data in memory based on the guidance received and the information extracted from the image.
400
- 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_path>.
401
-
402
- ## Step 3: Code a boilerplate slice component based on the model
403
- 3.1. Call mcp__prismic__how_to_code_slice to learn how to properly structure the slice component with Prismic fields.
404
- 3.2. Update the slice component code at <slice_library_path>/index.${frameworkFileExtension}, replacing the placeholder code with boilerplate code with the following requirements:
405
- - Must NOT be based on existing slices or components from the codebase.
406
- - Must render all the Prismic components to display the fields of the slice model created at <slice_model_path>.
407
- - Must be a valid ${framework.label} component.
408
- - Must NOT have any styling/CSS. No inlines styles or classNames. Just the skeleton component structure.
409
- - Must NOT use any other custom component or functions from the user's codebase.
410
- - Avoid creating unnecessary wrapper elements, like if they only wrap a single component (e.g., <div><PrismicRichText /></div>).
411
-
412
- ## Step 4: Present the newly created slice path
413
- 4.1. Present the path to the newly created slice in the following format: <new_slice_path>${libraryAbsPath}/MyNewSlice</new_slice_path>.
414
- - "MyNewSlice" must be the name of the directory of the newly created slice.
415
-
416
- # EXAMPLE OF CORRECT EXECUTION
417
-
418
- <example>
419
- Assistant: Step 1.1: Analysing design image...
420
- [reads <design_image_path>]
421
-
422
- Step 1.2: Identifying editable content elements...
423
- [identifies: title field, description field, buttonText field, buttonLink field, backgroundImage field]
424
-
425
- Step 1.3: Listing slice directories under <slice_library_path>...
426
- [lists slice directories: Hero, Hero2, Hero3]
427
-
428
- Step 1.4: Coming up with a unique name for the new slice...
429
- [comes up with a unique name for the new slice: Hero4]
430
-
431
- Step 2.1: Getting Prismic modeling guidance...
432
- [calls mcp__prismic__how_to_model_slice]
433
-
434
- Step 2.2: Building slice model based on guidance and the information extracted...
435
- [creates model with title field, description field, buttonText field, buttonLink field, backgroundImage field]
436
-
437
- Step 2.3: Saving slice model...
438
- [calls mcp__prismic__save_slice_data]
439
-
440
- Step 3.1: Learning Prismic slice coding requirements...
441
- [calls mcp__prismic__how_to_code_slice]
442
-
443
- Step 3.2: Coding boilerplate slice component based on the model...
444
- [updates component with Prismic field components, no styling, no other components]
445
-
446
- Step 4.1: Presenting the path to the newly created slice...
447
- [presents <new_slice_path>${path.join(libraryAbsPath, "MyNewSlice")}</new_slice_path>]
448
-
449
- # DELIVERABLES
450
- - Slice model saved to <slice_library_path>/model.json using mcp__prismic__save_slice_data
451
- - Slice component at <slice_library_path>/index.${frameworkFileExtension} updated with boilerplate code
452
- - New slice path presented in the format mentioned in Step 3.1
453
-
454
- YOU ARE NOT FINISHED UNTIL YOU HAVE THESE DELIVERABLES.
455
-
456
- ---
457
-
458
- FINAL REMINDERS:
459
- - You MUST use mcp__prismic__save_slice_data to save the model
460
- - You MUST call mcp__prismic__how_to_code_slice in Step 3.1
461
- - DO NOT ATTEMPT TO BUILD THE APPLICATION
462
- - START IMMEDIATELY WITH STEP 1.1 - NO PRELIMINARY ANALYSIS;`,
463
- options: {
464
- cwd: libraryAbsPath,
465
- stderr: (data) => console.error(data),
466
- model: "claude-haiku-4-5",
467
- permissionMode: "bypassPermissions",
468
- allowedTools: [
469
- "Bash",
470
- "Read",
471
- "FileSearch",
472
- "Grep",
473
- "Glob",
474
- "Task",
475
- "Edit",
476
- "Write",
477
- "MultiEdit",
478
- "mcp__prismic__how_to_model_slice",
479
- "mcp__prismic__how_to_code_slice",
480
- "mcp__prismic__save_slice_data"
481
- ],
482
- disallowedTools: [
483
- `Edit(**/model.json)`,
484
- `Write(**/model.json)`,
485
- "Edit(**/mocks.json)",
486
- "Write(**/mocks.json)"
487
- ],
488
- env: {
489
- ...process.env,
490
- ANTHROPIC_BASE_URL: llmProxyUrl,
491
- ANTHROPIC_CUSTOM_HEADERS: `x-prismic-token: ${authToken}
309
+ const { llmProxyUrl } = z.object({ llmProxyUrl: z.string().url() }).parse(exp.payload);
310
+ let tmpDir;
311
+ try {
312
+ const config = await this.project.getSliceMachineConfig();
313
+ let framework;
314
+ if (config.adapter === "@slicemachine/adapter-next") {
315
+ framework = { type: "nextjs", label: "Next.js (React)" };
316
+ } else if (config.adapter === "@slicemachine/adapter-nuxt" || config.adapter === "@slicemachine/adapter-nuxt2") {
317
+ framework = { type: "nuxt", label: "Nuxt (Vue)" };
318
+ } else if (config.adapter === "@slicemachine/adapter-sveltekit") {
319
+ framework = { type: "sveltekit", label: "SvelteKit (Svelte)" };
320
+ }
321
+ if (!framework) {
322
+ throw new Error("Could not determine framework from Slice Machine config.");
323
+ }
324
+ let frameworkFileExtension;
325
+ if (framework.type === "nextjs") {
326
+ frameworkFileExtension = "tsx";
327
+ } else if (framework.type === "nuxt") {
328
+ frameworkFileExtension = "vue";
329
+ } else if (framework.type === "sveltekit") {
330
+ frameworkFileExtension = "svelte";
331
+ }
332
+ if (!frameworkFileExtension) {
333
+ throw new Error("Could not determine framework from Slice Machine config.");
334
+ }
335
+ const projectRoot = await this.project.getRoot();
336
+ const libraryAbsPath = path.join(projectRoot, libraryID);
337
+ tmpDir = await mkdtemp(path.join(tmpdir(), "slice-machine-infer-slice-tmp-"));
338
+ const tmpImagePath = path.join(tmpDir, `${randomUUID()}.png`);
339
+ const response = await fetch(imageUrl);
340
+ if (!response.ok) {
341
+ throw new Error(`Failed to download image: ${response.status} ${response.statusText}`);
342
+ }
343
+ await writeFile(tmpImagePath, Buffer.from(await response.arrayBuffer()));
344
+ const queries = query({
345
+ prompt: `CRITICAL INSTRUCTIONS - READ FIRST:
346
+ - You MUST start immediately with Step 1.1. DO NOT read, analyze, or explore any project files first.
347
+ - Work step-by-step through the numbered tasks below.
348
+ - DO NOT present any summary, explanation, or completion message after finishing.
349
+ - DO NOT create TODO lists while performing tasks.
350
+ - Keep responses minimal - only show necessary tool calls and brief progress notes.
351
+
352
+ # CONTEXT
353
+
354
+ The user wants to build a new Prismic Slice based on a design image they provided.
355
+ Your goal is to analyze the design image and generate the JSON model data and boilerplate code for the slice following Prismic requirements.
356
+
357
+ You will work under the slice library at <slice_library_path>, where all the slices are stored.
358
+
359
+ # AVAILABLE RESOURCES
360
+
361
+ <design_image_path>
362
+ ${tmpImagePath}
363
+ </design_image_path>
364
+
365
+ <slice_library_path>
366
+ ${libraryAbsPath}
367
+ </slice_library_path>
368
+
369
+ <framework>
370
+ ${framework.label}
371
+ </framework>
372
+
373
+ # AVAILABLE TOOLS
374
+
375
+ You have access to specialized Prismic MCP tools for this task:
376
+
377
+ <tool name="mcp__prismic__how_to_model_slice">
378
+ <description>
379
+ Provides detailed guidance on creating Prismic slice models, including field types, naming conventions, and best practices.
380
+ </description>
381
+ <when_to_use>
382
+ Call this tool in Step 2.1 to learn how to structure the slice model data for the design you analysed.
383
+ </when_to_use>
384
+ </tool>
385
+
386
+ <tool name="mcp__prismic__how_to_code_slice">
387
+ <description>
388
+ Provides guidance on implementing Prismic slice components, including how to use Prismic field components, props structure, and best practices.
389
+ </description>
390
+ <when_to_use>
391
+ Call this tool in Step 2.1 to learn how to properly structure the slice component with Prismic fields.
392
+ </when_to_use>
393
+ </tool>
394
+
395
+ <tool name="mcp__prismic__save_slice_data">
396
+ <description>
397
+ Validates and saves the slice model data to model.json. This is the ONLY way to create the model file.
398
+ </description>
399
+ <when_to_use>
400
+ Call this tool in Step 2.3 after you have built the complete slice model structure in memory.
401
+ </when_to_use>
402
+ </tool>
403
+
404
+ # TASK REQUIREMENTS
405
+
406
+ ## Step 1: Gather information from the design image
407
+ 1.1. Analyse the design image at <design_image_path>.
408
+ 1.2. Identify all elements in the image that should be dynamically editable (e.g., headings, paragraphs, images, links, buttons, etc.).
409
+ 1.3. List the slice directories under <slice_library_path>.
410
+ 1.4. Come up with a unique name for the new slice based on the content of the image and the slice directories.
411
+
412
+ ## Step 2: Model the Prismic slice
413
+ 2.1. Call mcp__prismic__how_to_model_slice to learn how to structure the model for this design.
414
+ - Make sure the name you use for the new slice does not yet exist in the slice library at <slice_library_path>. If it does, use a different name.
415
+ 2.2. Build the complete slice JSON model data in memory based on the guidance received and the information extracted from the image.
416
+ 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_path>.
417
+
418
+ ## Step 3: Code a boilerplate slice component based on the model
419
+ 3.1. Call mcp__prismic__how_to_code_slice to learn how to properly structure the slice component with Prismic fields.
420
+ 3.2. Update the slice component code at <slice_library_path>/index.${frameworkFileExtension}, replacing the placeholder code with boilerplate code with the following requirements:
421
+ - Must NOT be based on existing slices or components from the codebase.
422
+ - Must render all the Prismic components to display the fields of the slice model created at <slice_model_path>.
423
+ - Must be a valid ${framework.label} component.
424
+ - Must NOT have any styling/CSS. No inlines styles or classNames. Just the skeleton component structure.
425
+ - Must NOT use any other custom component or functions from the user's codebase.
426
+ - Avoid creating unnecessary wrapper elements, like if they only wrap a single component (e.g., <div><PrismicRichText /></div>).
427
+
428
+ ## Step 4: Present the newly created slice path
429
+ 4.1. Present the path to the newly created slice in the following format: <new_slice_path>${libraryAbsPath}/MyNewSlice</new_slice_path>.
430
+ - "MyNewSlice" must be the name of the directory of the newly created slice.
431
+
432
+ # EXAMPLE OF CORRECT EXECUTION
433
+
434
+ <example>
435
+ Assistant: Step 1.1: Analysing design image...
436
+ [reads <design_image_path>]
437
+
438
+ Step 1.2: Identifying editable content elements...
439
+ [identifies: title field, description field, buttonText field, buttonLink field, backgroundImage field]
440
+
441
+ Step 1.3: Listing slice directories under <slice_library_path>...
442
+ [lists slice directories: Hero, Hero2, Hero3]
443
+
444
+ Step 1.4: Coming up with a unique name for the new slice...
445
+ [comes up with a unique name for the new slice: Hero4]
446
+
447
+ Step 2.1: Getting Prismic modeling guidance...
448
+ [calls mcp__prismic__how_to_model_slice]
449
+
450
+ Step 2.2: Building slice model based on guidance and the information extracted...
451
+ [creates model with title field, description field, buttonText field, buttonLink field, backgroundImage field]
452
+
453
+ Step 2.3: Saving slice model...
454
+ [calls mcp__prismic__save_slice_data]
455
+
456
+ Step 3.1: Learning Prismic slice coding requirements...
457
+ [calls mcp__prismic__how_to_code_slice]
458
+
459
+ Step 3.2: Coding boilerplate slice component based on the model...
460
+ [updates component with Prismic field components, no styling, no other components]
461
+
462
+ Step 4.1: Presenting the path to the newly created slice...
463
+ [presents <new_slice_path>${path.join(libraryAbsPath, "MyNewSlice")}</new_slice_path>]
464
+
465
+ # DELIVERABLES
466
+ - Slice model saved to <slice_library_path>/model.json using mcp__prismic__save_slice_data
467
+ - Slice component at <slice_library_path>/index.${frameworkFileExtension} updated with boilerplate code
468
+ - New slice path presented in the format mentioned in Step 3.1
469
+
470
+ YOU ARE NOT FINISHED UNTIL YOU HAVE THESE DELIVERABLES.
471
+
472
+ ---
473
+
474
+ FINAL REMINDERS:
475
+ - You MUST use mcp__prismic__save_slice_data to save the model
476
+ - You MUST call mcp__prismic__how_to_code_slice in Step 3.1
477
+ - DO NOT ATTEMPT TO BUILD THE APPLICATION
478
+ - START IMMEDIATELY WITH STEP 1.1 - NO PRELIMINARY ANALYSIS;`,
479
+ options: {
480
+ cwd: libraryAbsPath,
481
+ stderr: (data) => console.error("inferSlice error:" + data),
482
+ model: "claude-haiku-4-5",
483
+ permissionMode: "bypassPermissions",
484
+ allowedTools: [
485
+ "Bash",
486
+ "Read",
487
+ "FileSearch",
488
+ "Grep",
489
+ "Glob",
490
+ "Task",
491
+ "Edit",
492
+ "Write",
493
+ "MultiEdit",
494
+ "mcp__prismic__how_to_model_slice",
495
+ "mcp__prismic__how_to_code_slice",
496
+ "mcp__prismic__save_slice_data"
497
+ ],
498
+ disallowedTools: [
499
+ `Edit(**/model.json)`,
500
+ `Write(**/model.json)`,
501
+ "Edit(**/mocks.json)",
502
+ "Write(**/mocks.json)"
503
+ ],
504
+ env: {
505
+ ...process.env,
506
+ ANTHROPIC_BASE_URL: llmProxyUrl,
507
+ ANTHROPIC_CUSTOM_HEADERS: `x-prismic-token: ${authToken}
492
508
  x-prismic-repository: ${repository}
493
509
  `
494
- },
495
- mcpServers: {
496
- prismic: {
497
- type: "stdio",
498
- command: "npx",
499
- args: ["-y", "@prismicio/mcp-server@0.0.20-alpha.6"]
500
- }
510
+ },
511
+ mcpServers: {
512
+ prismic: {
513
+ type: "stdio",
514
+ command: "npx",
515
+ args: ["-y", "@prismicio/mcp-server@0.0.20-alpha.6"]
516
+ }
517
+ },
518
+ ...abortController && { abortController }
519
+ }
520
+ });
521
+ let newSliceAbsPath;
522
+ for await (const query2 of queries) {
523
+ switch (query2.type) {
524
+ case "result":
525
+ if (query2.subtype === "success") {
526
+ newSliceAbsPath = (_a = query2.result.match(/<new_slice_path>(.*)<\/new_slice_path>/s)) == null ? void 0 : _a[1];
527
+ }
528
+ break;
501
529
  }
502
530
  }
503
- });
504
- let newSliceAbsPath;
505
- for await (const query2 of queries) {
506
- switch (query2.type) {
507
- case "result":
508
- if (query2.subtype === "success") {
509
- newSliceAbsPath = (_a = query2.result.match(/<new_slice_path>(.*)<\/new_slice_path>/s)) == null ? void 0 : _a[1];
510
- }
511
- break;
531
+ if (!newSliceAbsPath) {
532
+ throw new Error("Could not find path for the newly created slice.");
533
+ }
534
+ const model = await readFile(path.join(newSliceAbsPath, "model.json"), "utf8");
535
+ if (!model) {
536
+ throw new Error("Could not find model for the newly created slice.");
537
+ }
538
+ await rename(tmpImagePath, path.join(newSliceAbsPath, "screenshot-default.png"));
539
+ return InferSliceResponse.parse({ slice: JSON.parse(model) });
540
+ } finally {
541
+ if (tmpDir && existsSync(tmpDir)) {
542
+ await rm(tmpDir, { recursive: true });
512
543
  }
513
544
  }
514
- if (!newSliceAbsPath) {
515
- throw new Error("Could not find path for the newly created slice.");
516
- }
517
- const model = await readFile(path.join(newSliceAbsPath, "model.json"), "utf8");
518
- if (!model) {
519
- throw new Error("Could not find model for the newly created slice.");
520
- }
521
- await rename(tmpImagePath, path.join(newSliceAbsPath, "screenshot-default.png"));
522
- await rm(tmpDir, { recursive: true });
523
- const elapsedTimeSeconds = (Date.now() - startTime) / 1e3;
524
- console.log(`inferSlice took ${elapsedTimeSeconds}s`);
525
- return InferSliceResponse.parse({ slice: JSON.parse(model) });
526
- } catch (error) {
527
- if (tmpDir && existsSync(tmpDir)) {
528
- await rm(tmpDir, { recursive: true });
545
+ } else {
546
+ const searchParams = new URLSearchParams({ repository });
547
+ const url = new URL("./slices/infer", API_ENDPOINTS.CustomTypeService);
548
+ url.search = searchParams.toString();
549
+ const response = await fetch(url.toString(), {
550
+ method: "POST",
551
+ headers: { Authorization: `Bearer ${authToken}` },
552
+ body: JSON.stringify({ imageUrl }),
553
+ ...abortController && { signal: abortController.signal }
554
+ });
555
+ if (!response.ok) {
556
+ throw new Error(`Failed to infer slice: ${response.statusText}`);
529
557
  }
530
- throw error;
558
+ const json = await response.json();
559
+ return InferSliceResponse.parse(json);
531
560
  }
532
- } else {
533
- const headers = {
534
- Authorization: `Bearer ${authToken}`
535
- };
536
- const searchParams = new URLSearchParams({
537
- repository
538
- });
539
- const url = new URL("./slices/infer", API_ENDPOINTS.CustomTypeService);
540
- url.search = searchParams.toString();
541
- const response = await fetch(url.toString(), {
542
- method: "POST",
543
- headers,
544
- body: JSON.stringify({ imageUrl })
545
- });
546
- if (!response.ok) {
547
- throw new Error(`Failed to infer slice: ${response.statusText}`);
561
+ } catch (error) {
562
+ console.error(`inferSlice (${source}) failed${requestId ? ` for request ${requestId}` : ""}`, error);
563
+ throw error;
564
+ } finally {
565
+ if (requestId) {
566
+ this.inferSliceAbortControllers.delete(requestId);
548
567
  }
549
- const json = await response.json();
550
- return InferSliceResponse.parse(json);
568
+ const elapsedTimeSeconds = (Date.now() - startTime) / 1e3;
569
+ console.info(`inferSlice took ${elapsedTimeSeconds}s${requestId ? ` for request ${requestId}` : ""}`);
570
+ }
571
+ }
572
+ async cancelInferSlice(args) {
573
+ const { requestId } = args;
574
+ const abortController = this.inferSliceAbortControllers.get(requestId);
575
+ if (abortController) {
576
+ abortController.abort();
577
+ this.inferSliceAbortControllers.delete(requestId);
578
+ return { cancelled: true };
551
579
  }
580
+ return { cancelled: false };
552
581
  }
553
582
  }
554
583
  const InferSliceResponse = z.object({