@widgetic/creator 0.3.80 → 0.4.0

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 (62) hide show
  1. package/README.md +157 -0
  2. package/dist/CreatorApp.svelte +1159 -624
  3. package/dist/CreatorApp.svelte.d.ts +22 -0
  4. package/dist/components/BrandKitPanel.svelte +48 -40
  5. package/dist/components/BrandKitPanel.svelte.d.ts +1 -1
  6. package/dist/components/DesignQuickEdit.svelte +13 -4
  7. package/dist/components/EditableName.svelte +13 -8
  8. package/dist/components/EditableName.svelte.d.ts +2 -2
  9. package/dist/components/FileUrlSourceControl.svelte +21 -8
  10. package/dist/components/HoverTooltip.svelte +1 -1
  11. package/dist/components/SelectorDropdown.svelte +19 -15
  12. package/dist/components/SelectorDropdown.svelte.d.ts +2 -2
  13. package/dist/components/VersionDropdownRow.svelte +14 -11
  14. package/dist/components/WidgetDetails.svelte +118 -92
  15. package/dist/components/WidgetShapeLivePreviews.svelte +105 -46
  16. package/dist/creator-types.d.ts +96 -0
  17. package/dist/host/creatorHost.d.ts +176 -0
  18. package/dist/host/creatorHost.js +242 -0
  19. package/dist/host/limitRefusal.d.ts +64 -0
  20. package/dist/host/limitRefusal.js +109 -0
  21. package/dist/i18n/index.d.ts +5 -0
  22. package/dist/i18n/index.js +5 -0
  23. package/dist/i18n/labels.d.ts +14 -0
  24. package/dist/i18n/labels.js +39 -0
  25. package/dist/i18n/language.d.ts +559 -0
  26. package/dist/i18n/language.js +47 -0
  27. package/dist/i18n/languageKit.d.ts +52 -0
  28. package/dist/i18n/languageKit.js +45 -0
  29. package/dist/i18n/messages.d.ts +526 -0
  30. package/dist/i18n/messages.js +548 -0
  31. package/dist/i18n/slots.d.ts +22 -0
  32. package/dist/i18n/slots.js +42 -0
  33. package/dist/i18n/statusText.d.ts +22 -0
  34. package/dist/i18n/statusText.js +223 -0
  35. package/dist/index.d.ts +1 -0
  36. package/dist/index.js +2 -0
  37. package/dist/stores/userSession.d.ts +8 -1
  38. package/dist/stores/userSession.js +18 -25
  39. package/dist/stores/websocketStore.d.ts +6 -0
  40. package/dist/stores/websocketStore.js +39 -4
  41. package/dist/utils/designIntentTelemetry.d.ts +8 -0
  42. package/dist/utils/designIntentTelemetry.js +52 -34
  43. package/dist/utils/directionPlacement.d.ts +51 -0
  44. package/dist/utils/directionPlacement.js +55 -0
  45. package/dist/utils/embedCode.d.ts +0 -1
  46. package/dist/utils/embedCode.js +0 -4
  47. package/dist/utils/nativeScrollbarPadding.js +1 -1
  48. package/dist/utils/pickedFile.d.ts +15 -0
  49. package/dist/utils/pickedFile.js +21 -0
  50. package/dist/utils/widgeticChatUpload.d.ts +9 -0
  51. package/dist/utils/widgeticChatUpload.js +24 -2
  52. package/package.json +5 -3
  53. package/dist/retiredSurface.test.d.ts +0 -1
  54. package/dist/retiredSurface.test.js +0 -113
  55. package/dist/utils/designIntentResolver.test.d.ts +0 -1
  56. package/dist/utils/designIntentResolver.test.js +0 -246
  57. package/dist/utils/designIntentTelemetry.test.d.ts +0 -1
  58. package/dist/utils/designIntentTelemetry.test.js +0 -385
  59. package/dist/utils/designQuickEditValues.test.d.ts +0 -1
  60. package/dist/utils/designQuickEditValues.test.js +0 -100
  61. package/dist/utils/widgeticChatUpload.test.d.ts +0 -1
  62. package/dist/utils/widgeticChatUpload.test.js +0 -257
@@ -0,0 +1,51 @@
1
+ import type { TextDirection } from '@widgetic/design-system/components/textDirection';
2
+ /**
3
+ * Where things are put and how far they are dragged, on a screen that follows the direction of its language.
4
+ *
5
+ * The creator draws its panels with the start and the end of a line (so a right to left screen mirrors them by itself), but
6
+ * a distance measured on the screen, a pointer moving along it or a list put under a button, is measured from the left
7
+ * edge of the window. These helpers say what that means at the start and at the end of the line.
8
+ */
9
+ /** The two edges of a box that are measured on the screen: how far its left and its right edge are from the left edge of the window. */
10
+ export interface HorizontalEdges {
11
+ left: number;
12
+ right: number;
13
+ }
14
+ /**
15
+ * How far a pointer has moved toward the END of the line since it was pressed, in pixels: to the right on a left to right
16
+ * screen, to the left on a right to left one. A divider between two columns that follow the direction of the line is
17
+ * dragged by this, because the first column is the one at the start of the line, and the end of a right to left line is the
18
+ * left of the screen.
19
+ */
20
+ export declare function distanceTowardEnd(direction: TextDirection, startX: number, currentX: number): number;
21
+ /**
22
+ * The style that puts a list (a fixed box) under a cluster of controls, lined up with the END edge of the cluster and
23
+ * sticking out past it by `overhang` pixels: the right edge on a left to right screen, the left edge on a right to left one,
24
+ * where the cluster is at the other end of its row and the list grows toward the middle of the panel. `windowWidth` is the
25
+ * width the right edge is measured from.
26
+ */
27
+ export declare function listAlignedToEnd(direction: TextDirection, cluster: HorizontalEdges, windowWidth: number, overhang: number): string;
28
+ /**
29
+ * How wide a name can be before it runs into the box that stands beyond it on the same line, in pixels. The name starts at
30
+ * its START edge and grows toward the END of the line, so the room is measured from the left edge of the name to the left
31
+ * edge of the neighbour on a left to right screen, and from the right edge of the name to the right edge of the neighbour on
32
+ * a right to left one, where the neighbour is on the left of the name. (Measured the left to right way it came out negative
33
+ * there, and the name was cut down to its smallest width: a title that showed as a dot.)
34
+ */
35
+ export declare function roomBeforeNeighbour(direction: TextDirection, name: HorizontalEdges, neighbour: HorizontalEdges, gap: number): number;
36
+ /**
37
+ * Which side of a shape a panel opens on, `true` for its right.
38
+ *
39
+ * On a left to right screen it opens on the side that has more room: on the right when the shape is left of the middle of the
40
+ * view, on the left otherwise (a shape exactly in the middle included, as it always was). A right to left screen is the mirror
41
+ * image of that: on the left when the shape is right of the middle, on the right otherwise. The panel with the properties of
42
+ * the shape is docked at the END of the line (the right of a left to right screen, the left of a right to left one), so a shape
43
+ * exactly in the middle is given its panel on the side away from the properties, in both directions.
44
+ */
45
+ export declare function opensOnRightOfShape(direction: TextDirection, shapeCenterX: number, viewCenterX: number): boolean;
46
+ /**
47
+ * The left edge of a pop-up that hangs from a button, in pixels from the left edge of the window: its START edge lined up with
48
+ * the START edge of the button, so that it grows toward the end of the line the way the words in it do, and kept inside the
49
+ * window by `margin` pixels.
50
+ */
51
+ export declare function popUpLeftFromAnchor(direction: TextDirection, anchor: HorizontalEdges, popUpWidth: number, windowWidth: number, margin: number): number;
@@ -0,0 +1,55 @@
1
+ /**
2
+ * How far a pointer has moved toward the END of the line since it was pressed, in pixels: to the right on a left to right
3
+ * screen, to the left on a right to left one. A divider between two columns that follow the direction of the line is
4
+ * dragged by this, because the first column is the one at the start of the line, and the end of a right to left line is the
5
+ * left of the screen.
6
+ */
7
+ export function distanceTowardEnd(direction, startX, currentX) {
8
+ return direction === 'rtl' ? startX - currentX : currentX - startX;
9
+ }
10
+ /**
11
+ * The style that puts a list (a fixed box) under a cluster of controls, lined up with the END edge of the cluster and
12
+ * sticking out past it by `overhang` pixels: the right edge on a left to right screen, the left edge on a right to left one,
13
+ * where the cluster is at the other end of its row and the list grows toward the middle of the panel. `windowWidth` is the
14
+ * width the right edge is measured from.
15
+ */
16
+ export function listAlignedToEnd(direction, cluster, windowWidth, overhang) {
17
+ if (direction === 'rtl') {
18
+ return `left: ${Math.round(cluster.left) - overhang}px;`; // rtl-ok: the end edge of a right to left cluster is its left edge
19
+ }
20
+ return `right: ${Math.round(windowWidth - cluster.right) - overhang}px;`; // rtl-ok: the end edge of a left to right cluster is its right edge
21
+ }
22
+ /**
23
+ * How wide a name can be before it runs into the box that stands beyond it on the same line, in pixels. The name starts at
24
+ * its START edge and grows toward the END of the line, so the room is measured from the left edge of the name to the left
25
+ * edge of the neighbour on a left to right screen, and from the right edge of the name to the right edge of the neighbour on
26
+ * a right to left one, where the neighbour is on the left of the name. (Measured the left to right way it came out negative
27
+ * there, and the name was cut down to its smallest width: a title that showed as a dot.)
28
+ */
29
+ export function roomBeforeNeighbour(direction, name, neighbour, gap) {
30
+ const room = direction === 'rtl' ? name.right - neighbour.right : neighbour.left - name.left;
31
+ return Math.floor(room - gap);
32
+ }
33
+ /**
34
+ * Which side of a shape a panel opens on, `true` for its right.
35
+ *
36
+ * On a left to right screen it opens on the side that has more room: on the right when the shape is left of the middle of the
37
+ * view, on the left otherwise (a shape exactly in the middle included, as it always was). A right to left screen is the mirror
38
+ * image of that: on the left when the shape is right of the middle, on the right otherwise. The panel with the properties of
39
+ * the shape is docked at the END of the line (the right of a left to right screen, the left of a right to left one), so a shape
40
+ * exactly in the middle is given its panel on the side away from the properties, in both directions.
41
+ */
42
+ export function opensOnRightOfShape(direction, shapeCenterX, viewCenterX) {
43
+ if (shapeCenterX === viewCenterX)
44
+ return direction === 'rtl';
45
+ return shapeCenterX < viewCenterX;
46
+ }
47
+ /**
48
+ * The left edge of a pop-up that hangs from a button, in pixels from the left edge of the window: its START edge lined up with
49
+ * the START edge of the button, so that it grows toward the end of the line the way the words in it do, and kept inside the
50
+ * window by `margin` pixels.
51
+ */
52
+ export function popUpLeftFromAnchor(direction, anchor, popUpWidth, windowWidth, margin) {
53
+ const wanted = direction === 'rtl' ? anchor.right - popUpWidth : anchor.left;
54
+ return Math.max(margin, Math.min(wanted, windowWidth - popUpWidth - margin));
55
+ }
@@ -6,7 +6,6 @@
6
6
  */
7
7
  export type EmbedFormat = 'iframe' | 'web-component';
8
8
  export declare const EMBED_FORMATS: EmbedFormat[];
9
- export declare const EMBED_FORMAT_LABELS: Record<EmbedFormat, string>;
10
9
  export interface EmbedCodeParams {
11
10
  /** Direct widget HTML URL on the CDN (or API proxy in dev). */
12
11
  embedSrc: string;
@@ -5,10 +5,6 @@
5
5
  * web-component: embed-sdk.js + one-word `<widgetic composition-id>`.
6
6
  */
7
7
  export const EMBED_FORMATS = ['iframe', 'web-component'];
8
- export const EMBED_FORMAT_LABELS = {
9
- iframe: 'iframe',
10
- 'web-component': 'Web Component'
11
- };
12
8
  export function generateIframeEmbedCode({ embedSrc, width, height }) {
13
9
  return `<iframe src="${embedSrc}" width="${width}" height="${height}" frameborder="0" allowfullscreen></iframe>`;
14
10
  }
@@ -2,7 +2,7 @@
2
2
  export function nativeScrollbarPadding(node, padPx = 8) {
3
3
  function check() {
4
4
  const hasScrollbar = node.scrollHeight > node.clientHeight + 1;
5
- node.style.setProperty('padding-right', hasScrollbar ? '0px' : `${padPx}px`, 'important');
5
+ node.style.setProperty('padding-inline-end', hasScrollbar ? '0px' : `${padPx}px`, 'important');
6
6
  }
7
7
  const resizeObserver = new ResizeObserver(check);
8
8
  resizeObserver.observe(node);
@@ -0,0 +1,15 @@
1
+ /**
2
+ * pickedFile — what the file control (`FileUrlSourceControl.svelte`) makes of the file a person picks.
3
+ *
4
+ * An archive or a font is binary: it is read as a data URL and sent as base64, so everything before the first comma of
5
+ * the data URL (`data:font/woff2;base64`) is cut off. Any other file is text and is sent as it was read.
6
+ *
7
+ * Kept pure so the rules are testable without a DOM.
8
+ */
9
+ /** Whether the file with this name is read as binary (an archive or a font) rather than as text. */
10
+ export declare function isBinaryFileName(fileName: string): boolean;
11
+ /**
12
+ * The content to send for a picked file, from what the file reader answered. A binary file was read as a data URL, which
13
+ * loses everything up to and including its first comma (what is left is the base64); a text file is sent as it was read.
14
+ */
15
+ export declare function contentOfPickedFile(isBinary: boolean, readerResult: string): string;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * pickedFile — what the file control (`FileUrlSourceControl.svelte`) makes of the file a person picks.
3
+ *
4
+ * An archive or a font is binary: it is read as a data URL and sent as base64, so everything before the first comma of
5
+ * the data URL (`data:font/woff2;base64`) is cut off. Any other file is text and is sent as it was read.
6
+ *
7
+ * Kept pure so the rules are testable without a DOM.
8
+ */
9
+ /** The endings of the files that are read as binary: archives and fonts. */
10
+ const BINARY_FILE_NAME_PATTERN = /\.(zip|tar|tgz|gz|woff2?|ttf|otf|eot)$/i;
11
+ /** Whether the file with this name is read as binary (an archive or a font) rather than as text. */
12
+ export function isBinaryFileName(fileName) {
13
+ return BINARY_FILE_NAME_PATTERN.test(fileName);
14
+ }
15
+ /**
16
+ * The content to send for a picked file, from what the file reader answered. A binary file was read as a data URL, which
17
+ * loses everything up to and including its first comma (what is left is the base64); a text file is sent as it was read.
18
+ */
19
+ export function contentOfPickedFile(isBinary, readerResult) {
20
+ return isBinary ? readerResult.slice(readerResult.indexOf(',') + 1) : readerResult;
21
+ }
@@ -19,6 +19,15 @@ export type ChatUploadOptions = {
19
19
  onProgress?: (percentage: number) => void;
20
20
  abortSignal?: AbortSignal;
21
21
  };
22
+ /**
23
+ * An upload the API turned down. Its message is the API's own (what the chat shows); the status and the body of the
24
+ * answer are kept as well, so the creator can tell a limit (the partner's storage is full) from an ordinary failure.
25
+ */
26
+ export declare class ChatUploadRefusedError extends Error {
27
+ readonly status: number;
28
+ readonly body: unknown;
29
+ constructor(message: string, status: number, body: unknown);
30
+ }
22
31
  /**
23
32
  * POST …/complete. A 409 `TUS_UPLOAD_BUSY` means another request still has the upload (the chunk that
24
33
  * just finished, or a retried one), so ask again after a short pause. Every other answer is final: a
@@ -6,12 +6,32 @@ const DEFAULT_TUS_CHUNK_SIZE = 5 * 1024 * 1024;
6
6
  const TUS_UPLOAD_BUSY_CODE = 'TUS_UPLOAD_BUSY';
7
7
  /** Pauses before asking again after a "busy" answer: 0.5, 1, 2, 4 and 8 seconds, about 15 seconds in all. */
8
8
  const COMPLETE_BUSY_RETRY_DELAYS_MS = [500, 1000, 2000, 4000, 8000];
9
+ /** The message in the JSON body of an error answer, or the fallback. */
10
+ function messageOfErrorBody(json, fallback) {
11
+ const body = json;
12
+ const message = body?.message || body?.error?.message;
13
+ return typeof message === 'string' && message ? message : fallback;
14
+ }
9
15
  function parseErrorMessage(response, fallback) {
10
16
  return response
11
17
  .json()
12
- .then((json) => json?.message || json?.error?.message || fallback)
18
+ .then((json) => messageOfErrorBody(json, fallback))
13
19
  .catch(() => fallback);
14
20
  }
21
+ /**
22
+ * An upload the API turned down. Its message is the API's own (what the chat shows); the status and the body of the
23
+ * answer are kept as well, so the creator can tell a limit (the partner's storage is full) from an ordinary failure.
24
+ */
25
+ export class ChatUploadRefusedError extends Error {
26
+ status;
27
+ body;
28
+ constructor(message, status, body) {
29
+ super(message);
30
+ this.name = 'ChatUploadRefusedError';
31
+ this.status = status;
32
+ this.body = body;
33
+ }
34
+ }
15
35
  /** The `error.code` of a failed answer, or undefined when the body is not the API's error envelope. */
16
36
  function readErrorCode(response) {
17
37
  return response
@@ -98,7 +118,9 @@ async function uploadMultipart(file, config) {
98
118
  body: formData,
99
119
  });
100
120
  if (!response.ok) {
101
- throw new Error(await parseErrorMessage(response, `Upload failed (${response.status})`));
121
+ // Read once: the message is what the chat shows, the status and the body tell the creator whether it was a limit.
122
+ const body = await response.json().catch(() => undefined);
123
+ throw new ChatUploadRefusedError(messageOfErrorBody(body, `Upload failed (${response.status})`), response.status, body);
102
124
  }
103
125
  const json = await response.json();
104
126
  const data = (json?.data ?? json);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/creator",
3
- "version": "0.3.80",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "peerDependencies": {
6
6
  "@sveltejs/kit": "^2.20.0",
@@ -29,7 +29,9 @@
29
29
  }
30
30
  },
31
31
  "files": [
32
- "dist"
32
+ "dist",
33
+ "!dist/**/*.test.*",
34
+ "!dist/**/*.spec.*"
33
35
  ],
34
36
  "scripts": {
35
37
  "i": "rm -rf node_modules && npm i && npm run lps",
@@ -97,7 +99,7 @@
97
99
  "typescript-eslint": "^8.20.0",
98
100
  "vite": "^6.2.6",
99
101
  "vite-imagetools": "^7.0.4",
100
- "vitest": "^2.0.0"
102
+ "vitest": "^5.0.3"
101
103
  },
102
104
  "dependencies": {
103
105
  "@mdi/js": "^7.4.47",
@@ -1 +0,0 @@
1
- export {};
@@ -1,113 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { HealthApi, Configuration, ResponseError, isRetiredSurfaceError, readEnvelopeErrorCode, RETIRED_SURFACE_CODES } from '@widgetic/api-sdk';
3
- /**
4
- * The SDK must recognize the API's retired-surface 410 envelope so stale
5
- * bundles can surface an upgrade prompt instead of a generic failure.
6
- *
7
- * The API answers permanently retired routes (planner endpoints, VM flows,
8
- * VM metrics) with 410 Gone and the house error envelope:
9
- *
10
- * { success: false, error: { code: 'PLANNER_REMOVED', message: '… Use POST /agent/code/generate …', timestamp: '…' } }
11
- *
12
- * Two properties are pinned:
13
- *
14
- * 1. **End to end through the real request pipeline** — a fetch mocked to
15
- * return that envelope produces a ResponseError whose `code` is the
16
- * machine-readable value and whose `message` carries the replacement
17
- * hint; `isRetiredSurfaceError` discriminates it from every lookalike
18
- * (other statuses, other codes, non-ResponseError throws).
19
- * 2. **The envelope reader is safe by contract** — null (never a throw) for
20
- * non-JSON bodies, envelopes without a code, or empty code strings.
21
- *
22
- * These tests import the package the app imports — the built `dist` when
23
- * resolved through node_modules, or the aliased sibling source in dev —
24
- * so what is tested is exactly what a stale bundle would ship.
25
- */
26
- const RETIRED_ENVELOPE = (code) => {
27
- const message = `The ${code} surface was removed. Use POST /agent/code/generate (Direct LLM + Widget Builder).`;
28
- return {
29
- success: false,
30
- message,
31
- error: {
32
- code,
33
- message,
34
- timestamp: new Date().toISOString()
35
- }
36
- };
37
- };
38
- /** 410 response whose body is the house error envelope. */
39
- function retiredResponse(code) {
40
- return new Response(JSON.stringify(RETIRED_ENVELOPE(code)), {
41
- status: 410,
42
- headers: { 'content-type': 'application/json' }
43
- });
44
- }
45
- function apiWithFetch(fetchImpl) {
46
- return new HealthApi(new Configuration({ basePath: 'https://api.test', fetchApi: fetchImpl }));
47
- }
48
- describe('retired-surface 410 envelopes surface as typed ResponseErrors', () => {
49
- it.each(RETIRED_SURFACE_CODES)('carries the machine-readable %s code end to end', async (code) => {
50
- const api = apiWithFetch((async () => retiredResponse(code)));
51
- const err = await api.checkHealth().catch((e) => e);
52
- expect(err).toBeInstanceOf(ResponseError);
53
- const responseError = err;
54
- expect(responseError.response.status).toBe(410);
55
- expect(responseError.code).toBe(code);
56
- // The replacement hint rides the envelope message, which the SDK
57
- // already surfaces as the error message.
58
- expect(responseError.message).toContain('POST /agent/code/generate');
59
- // And the public helper discriminates exactly this shape.
60
- expect(isRetiredSurfaceError(responseError)).toBe(true);
61
- });
62
- it('does not flag a 410 without a retired code', async () => {
63
- const body = JSON.stringify({ success: false, error: { code: 'SOMETHING_ELSE', message: 'gone', timestamp: 't' } });
64
- const api = apiWithFetch((async () => new Response(body, { status: 410 })));
65
- const err = await api.checkHealth().catch((e) => e);
66
- expect(err).toBeInstanceOf(ResponseError);
67
- expect(err.code).toBe('SOMETHING_ELSE');
68
- expect(isRetiredSurfaceError(err)).toBe(false);
69
- });
70
- it('does not flag a 410 whose body has no envelope code', async () => {
71
- const api = apiWithFetch((async () => new Response('{"message":"gone"}', { status: 410 })));
72
- const err = await api.checkHealth().catch((e) => e);
73
- expect(err.code).toBeNull();
74
- expect(isRetiredSurfaceError(err)).toBe(false);
75
- });
76
- it('does not flag retired codes on other statuses', async () => {
77
- const body = JSON.stringify(RETIRED_ENVELOPE('VM_REMOVED'));
78
- const api = apiWithFetch((async () => new Response(body, { status: 503 })));
79
- const err = await api.checkHealth().catch((e) => e);
80
- // The message still surfaces (the SDK parses envelope messages), but a
81
- // non-410 must not read as "your bundle is stale" — 503 means retry.
82
- expect(isRetiredSurfaceError(err)).toBe(false);
83
- });
84
- it('rejects non-ResponseError throws and unrelated values', () => {
85
- expect(isRetiredSurfaceError(new Error('boom'))).toBe(false);
86
- expect(isRetiredSurfaceError('PLANNER_REMOVED')).toBe(false);
87
- expect(isRetiredSurfaceError(null)).toBe(false);
88
- expect(isRetiredSurfaceError(undefined)).toBe(false);
89
- });
90
- });
91
- describe('readEnvelopeErrorCode', () => {
92
- it('reads the code from a house envelope', async () => {
93
- expect(await readEnvelopeErrorCode(retiredResponse('VM_METRICS_REMOVED'))).toBe('VM_METRICS_REMOVED');
94
- });
95
- it('returns null for non-JSON bodies instead of throwing', async () => {
96
- const html = new Response('<!DOCTYPE html><html><body>error</body></html>', {
97
- status: 410,
98
- headers: { 'content-type': 'text/html' }
99
- });
100
- expect(await readEnvelopeErrorCode(html)).toBeNull();
101
- });
102
- it('returns null for JSON without an envelope code', async () => {
103
- const bare = new Response(JSON.stringify({ message: 'no code here' }), { status: 410 });
104
- expect(await readEnvelopeErrorCode(bare)).toBeNull();
105
- });
106
- it('does not consume the body it reads', async () => {
107
- const response = retiredResponse('PLANNER_REMOVED');
108
- await readEnvelopeErrorCode(response);
109
- // A clone is used internally, so the original body stays readable for
110
- // later handlers (error toasts, logging).
111
- await expect(response.json()).resolves.toBeTruthy();
112
- });
113
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,246 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { collectDesignProperties, resolveDesignIntent, toDesignControlRequest } from './designIntentResolver';
3
- /**
4
- * A widget-shaped design schema (the post-codegen shape: one componentGroup,
5
- * components carrying `properties`, options under `inputController.config`).
6
- */
7
- const SCHEMA = {
8
- componentGroups: [
9
- {
10
- name: 'Design',
11
- components: [
12
- {
13
- id: 'appearance',
14
- type: 'layoutGroup',
15
- propertyGroups: [
16
- {
17
- name: 'Colors',
18
- properties: [
19
- {
20
- id: 'backgroundColor',
21
- type: 'string',
22
- defaultValue: '#ffffff',
23
- inputController: { type: 'colorPicker', description: 'Background Color' }
24
- },
25
- {
26
- id: 'titleColor',
27
- type: 'string',
28
- defaultValue: '#111827',
29
- inputController: { type: 'colorPicker', description: 'Title Color' }
30
- },
31
- {
32
- id: 'widgetBorderColor',
33
- type: 'string',
34
- defaultValue: '#e5e7eb',
35
- inputController: { type: 'colorPicker', description: 'Border Color' }
36
- }
37
- ]
38
- },
39
- {
40
- name: 'Spacing',
41
- properties: [
42
- {
43
- id: 'padding',
44
- type: 'number',
45
- defaultValue: 16,
46
- inputController: { type: 'slider', description: 'Padding', config: { min: 0, max: 64, step: 1 } }
47
- },
48
- {
49
- id: 'borderRadius',
50
- type: 'number',
51
- defaultValue: 8,
52
- inputController: { type: 'number', description: 'Border Radius', config: { min: 0, max: 40, step: 1 } }
53
- }
54
- ]
55
- },
56
- {
57
- name: 'Layout',
58
- properties: [
59
- {
60
- id: 'layout',
61
- type: 'string',
62
- defaultValue: 'grid',
63
- inputController: {
64
- type: 'dropdown',
65
- description: 'Layout Style',
66
- config: {
67
- options: [
68
- { label: 'Grid', value: 'grid' },
69
- { label: 'List', value: 'list' },
70
- { label: 'Carousel', value: 'carousel' }
71
- ]
72
- }
73
- }
74
- },
75
- {
76
- id: 'showShadow',
77
- type: 'boolean',
78
- defaultValue: true,
79
- inputController: { type: 'switch', description: 'Drop Shadow' }
80
- },
81
- {
82
- id: 'widgetTitle',
83
- type: 'string',
84
- defaultValue: 'My Widget',
85
- inputController: { type: 'textInput', description: 'Widget Title' }
86
- }
87
- ]
88
- }
89
- ]
90
- }
91
- ]
92
- }
93
- ]
94
- };
95
- const LIVE = { backgroundColor: '#ffffff', padding: 16, borderRadius: 8, showShadow: true };
96
- describe('collectDesignProperties', () => {
97
- it('flattens nested property groups into descriptors', () => {
98
- const props = collectDesignProperties(SCHEMA);
99
- expect(props.map((p) => p.id)).toEqual([
100
- 'backgroundColor',
101
- 'titleColor',
102
- 'widgetBorderColor',
103
- 'padding',
104
- 'borderRadius',
105
- 'layout',
106
- 'showShadow',
107
- 'widgetTitle'
108
- ]);
109
- });
110
- it('reads dropdown options from inputController.config.options', () => {
111
- const dropdown = collectDesignProperties(SCHEMA).find((p) => p.id === 'layout');
112
- expect(dropdown?.options).toHaveLength(3);
113
- expect(dropdown?.options[1]).toEqual({ label: 'List', value: 'list' });
114
- });
115
- it('reads numeric constraints', () => {
116
- const padding = collectDesignProperties(SCHEMA).find((p) => p.id === 'padding');
117
- expect(padding).toMatchObject({ min: 0, max: 64, step: 1 });
118
- });
119
- });
120
- describe('resolveDesignIntent — colors', () => {
121
- it('resolves an explicit hex on the named color property', () => {
122
- const r = resolveDesignIntent('make the background #1a1a2e', SCHEMA, LIVE);
123
- expect(r?.changes).toHaveLength(1);
124
- expect(r?.changes[0]).toMatchObject({
125
- propertyId: 'backgroundColor',
126
- value: '#1a1a2e',
127
- reason: 'explicit-color'
128
- });
129
- });
130
- it('expands 3-digit hex', () => {
131
- const r = resolveDesignIntent('set the background to #abc', SCHEMA, LIVE);
132
- expect(r?.changes[0].value).toBe('#aabbcc');
133
- });
134
- it('resolves a named color', () => {
135
- const r = resolveDesignIntent('change the background to red', SCHEMA, LIVE);
136
- expect(r?.changes[0]).toMatchObject({ propertyId: 'backgroundColor', value: '#ff0000', reason: 'named-color' });
137
- });
138
- it('resolves rgb()', () => {
139
- const r = resolveDesignIntent('background rgb(26, 26, 46)', SCHEMA, LIVE);
140
- expect(r?.changes[0].value).toBe('#1a1a2e');
141
- });
142
- it('does not touch a number property when only a color is given', () => {
143
- const r = resolveDesignIntent('make the padding red', SCHEMA, LIVE);
144
- expect(r).toBeNull();
145
- });
146
- });
147
- describe('resolveDesignIntent — numbers (arithmetic stays in code)', () => {
148
- it('sets an explicit number', () => {
149
- const r = resolveDesignIntent('set the border radius to 12', SCHEMA, LIVE);
150
- expect(r?.changes[0]).toMatchObject({ propertyId: 'borderRadius', value: 12, reason: 'explicit-number' });
151
- });
152
- it('increases by an absolute delta using the current value', () => {
153
- const r = resolveDesignIntent('increase the padding by 8', SCHEMA, LIVE);
154
- expect(r?.changes[0]).toMatchObject({ propertyId: 'padding', value: 24, reason: 'delta-number' });
155
- });
156
- it('applies a percentage delta', () => {
157
- const r = resolveDesignIntent('reduce the padding by 25%', SCHEMA, LIVE);
158
- expect(r?.changes[0].value).toBe(12);
159
- });
160
- it('doubles the current value', () => {
161
- const r = resolveDesignIntent('double the border radius', SCHEMA, LIVE);
162
- expect(r?.changes[0].value).toBe(16);
163
- });
164
- it('halves the current value', () => {
165
- const r = resolveDesignIntent('half the padding', SCHEMA, LIVE);
166
- expect(r?.changes[0].value).toBe(8);
167
- });
168
- it('clamps to the schema max', () => {
169
- const r = resolveDesignIntent('increase the padding by 500', SCHEMA, LIVE);
170
- expect(r?.changes[0].value).toBe(64);
171
- });
172
- it('uses the schema default when no live value is supplied', () => {
173
- const r = resolveDesignIntent('increase the padding by 4', SCHEMA);
174
- expect(r?.changes[0]).toMatchObject({ previousValue: 16, value: 20 });
175
- });
176
- });
177
- describe('resolveDesignIntent — booleans and options', () => {
178
- it('turns a switch on', () => {
179
- const r = resolveDesignIntent('turn the drop shadow off', SCHEMA, LIVE);
180
- expect(r?.changes[0]).toMatchObject({ propertyId: 'showShadow', value: false, reason: 'boolean' });
181
- });
182
- it('enables', () => {
183
- const r = resolveDesignIntent('enable the shadow', SCHEMA, LIVE);
184
- expect(r?.changes[0]).toMatchObject({ propertyId: 'showShadow', value: true });
185
- });
186
- it('selects a dropdown option by label', () => {
187
- const r = resolveDesignIntent('switch the layout to carousel', SCHEMA, LIVE);
188
- expect(r?.changes[0]).toMatchObject({ propertyId: 'layout', value: 'carousel', reason: 'option' });
189
- });
190
- });
191
- describe('resolveDesignIntent — text', () => {
192
- it('resolves only explicitly quoted text', () => {
193
- const r = resolveDesignIntent('set the widget title to "Grocery list"', SCHEMA, LIVE);
194
- expect(r?.changes[0]).toMatchObject({ propertyId: 'widgetTitle', value: 'Grocery list' });
195
- });
196
- it('refuses unquoted text (falls through to codegen)', () => {
197
- expect(resolveDesignIntent('change the title to grocery list', SCHEMA, LIVE)).toBeNull();
198
- });
199
- });
200
- describe('resolveDesignIntent — bails out (falls through to codegen/JEV)', () => {
201
- it('returns null for vague intent', () => {
202
- expect(resolveDesignIntent('make it pop', SCHEMA, LIVE)).toBeNull();
203
- expect(resolveDesignIntent('give it more breathing room', SCHEMA, LIVE)).toBeNull();
204
- expect(resolveDesignIntent('make it feel more premium', SCHEMA, LIVE)).toBeNull();
205
- });
206
- it('returns null for a color with no named property', () => {
207
- expect(resolveDesignIntent('make it red', SCHEMA, LIVE)).toBeNull();
208
- });
209
- it('returns null for a non-design ask', () => {
210
- expect(resolveDesignIntent('add a confetti animation when the timer ends', SCHEMA, LIVE)).toBeNull();
211
- });
212
- it('returns null when two properties tie on name match', () => {
213
- // "color" alone names all three color properties equally → ambiguous.
214
- expect(resolveDesignIntent('change the color to red', SCHEMA, LIVE)).toBeNull();
215
- });
216
- it('returns null for an empty schema', () => {
217
- expect(resolveDesignIntent('make the background red', {}, LIVE)).toBeNull();
218
- });
219
- });
220
- describe('toDesignControlRequest', () => {
221
- it('carries the resolved value + constraints for the inline controller', () => {
222
- const r = resolveDesignIntent('increase the padding by 8', SCHEMA, LIVE);
223
- const card = toDesignControlRequest(r, SCHEMA, LIVE);
224
- expect(card.summary).toContain('Padding');
225
- expect(card.properties[0]).toMatchObject({
226
- id: 'padding',
227
- controllerType: 'slider',
228
- value: 24,
229
- min: 0,
230
- max: 64
231
- });
232
- });
233
- it('records the composition the change landed in, so a reload can re-attach it', () => {
234
- const r = resolveDesignIntent('increase the padding by 8', SCHEMA, LIVE);
235
- expect(toDesignControlRequest(r, SCHEMA, LIVE, 'composition-1').compositionId).toBe('composition-1');
236
- });
237
- it('omits the composition rather than recording null when there is none', () => {
238
- // A card persisted before the field existed, and one authored against a
239
- // composition that was never saved, both arrive without it — and the host
240
- // treats exactly that shape as "attached".
241
- const r = resolveDesignIntent('increase the padding by 8', SCHEMA, LIVE);
242
- expect(toDesignControlRequest(r, SCHEMA, LIVE)).not.toHaveProperty('compositionId');
243
- expect(toDesignControlRequest(r, SCHEMA, LIVE, null)).not.toHaveProperty('compositionId');
244
- expect(toDesignControlRequest(r, SCHEMA, LIVE, '')).not.toHaveProperty('compositionId');
245
- });
246
- });
@@ -1 +0,0 @@
1
- export {};