@adminide-stack/yantra-mobile 12.0.162-alpha.1 → 12.0.162-alpha.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.
Files changed (103) hide show
  1. package/lib/components/CustomDrawer.js +70 -3
  2. package/lib/components/CustomDrawer.js.map +1 -1
  3. package/lib/compute.js +3 -1
  4. package/lib/config/env-config.js +4 -0
  5. package/lib/config/env-config.js.map +1 -1
  6. package/lib/features/credits/credits.js +151 -0
  7. package/lib/features/credits/credits.js.map +1 -0
  8. package/lib/features/credits/useLlmCredits.js +87 -0
  9. package/lib/features/credits/useLlmCredits.js.map +1 -0
  10. package/lib/features/design/surface/agentWriter.js +39 -0
  11. package/lib/features/design/surface/agentWriter.js.map +1 -0
  12. package/lib/features/design/surface/brandKit.js +9 -3
  13. package/lib/features/design/surface/brandKit.js.map +1 -1
  14. package/lib/features/design/surface/useBrandKitInUse.js.map +1 -1
  15. package/lib/features/design/surface/useDesignSurface.js +5 -39
  16. package/lib/features/design/surface/useDesignSurface.js.map +1 -1
  17. package/lib/features/webbuilder/WebBuilderExperience.js +64 -23
  18. package/lib/features/webbuilder/WebBuilderExperience.js.map +1 -1
  19. package/lib/features/webbuilder/brandKitMove.js +52 -0
  20. package/lib/features/webbuilder/brandKitMove.js.map +1 -0
  21. package/lib/features/webbuilder/codeToolbox.js +129 -0
  22. package/lib/features/webbuilder/codeToolbox.js.map +1 -0
  23. package/lib/features/webbuilder/components/CloudSheet.js +1451 -0
  24. package/lib/features/webbuilder/components/CloudSheet.js.map +1 -0
  25. package/lib/features/webbuilder/components/CodeActionsSheet.js +125 -0
  26. package/lib/features/webbuilder/components/CodeActionsSheet.js.map +1 -0
  27. package/lib/features/webbuilder/components/CodeView.js +10 -3
  28. package/lib/features/webbuilder/components/CodeView.js.map +1 -1
  29. package/lib/features/webbuilder/components/Composer.js.map +1 -1
  30. package/lib/features/webbuilder/components/IntegrationsPanel.js +643 -0
  31. package/lib/features/webbuilder/components/IntegrationsPanel.js.map +1 -0
  32. package/lib/features/webbuilder/components/ProjectChat.js +57 -44
  33. package/lib/features/webbuilder/components/ProjectChat.js.map +1 -1
  34. package/lib/features/webbuilder/components/SecretsSheet.js +235 -0
  35. package/lib/features/webbuilder/components/SecretsSheet.js.map +1 -0
  36. package/lib/features/webbuilder/components/StudioHome.js +38 -1
  37. package/lib/features/webbuilder/components/StudioHome.js.map +1 -1
  38. package/lib/features/webbuilder/studioCatalog.js +4 -19
  39. package/lib/features/webbuilder/studioCatalog.js.map +1 -1
  40. package/lib/features/webbuilder/web/data/cloud.js +387 -0
  41. package/lib/features/webbuilder/web/data/cloud.js.map +1 -0
  42. package/lib/features/webbuilder/web/data/dataApi.js +227 -0
  43. package/lib/features/webbuilder/web/data/dataApi.js.map +1 -0
  44. package/lib/features/webbuilder/web/data/database.js +190 -0
  45. package/lib/features/webbuilder/web/data/database.js.map +1 -0
  46. package/lib/features/webbuilder/web/data/graphql.js +95 -0
  47. package/lib/features/webbuilder/web/data/graphql.js.map +1 -0
  48. package/lib/features/webbuilder/web/design/directions.js +343 -0
  49. package/lib/features/webbuilder/web/design/directions.js.map +1 -0
  50. package/lib/features/webbuilder/web/integrations/appToken.js +165 -0
  51. package/lib/features/webbuilder/web/integrations/appToken.js.map +1 -0
  52. package/lib/features/webbuilder/web/integrations/catalog.js +238 -0
  53. package/lib/features/webbuilder/web/integrations/catalog.js.map +1 -0
  54. package/lib/features/webbuilder/web/integrations/siteBilling.js +67 -0
  55. package/lib/features/webbuilder/web/integrations/siteBilling.js.map +1 -0
  56. package/lib/features/webbuilder/web/integrations/siteMail.js +190 -0
  57. package/lib/features/webbuilder/web/integrations/siteMail.js.map +1 -0
  58. package/lib/features/webbuilder/web/project/projectSettings.js +11 -0
  59. package/lib/features/webbuilder/web/project/projectSettings.js.map +1 -0
  60. package/lib/features/webbuilder/web/project/restorePoint.js +16 -0
  61. package/lib/features/webbuilder/web/project/restorePoint.js.map +1 -0
  62. package/lib/features/webbuilder/web/project/serverSettings.js +157 -0
  63. package/lib/features/webbuilder/web/project/serverSettings.js.map +1 -0
  64. package/lib/features/webbuilder/web/secrets/secrets.js +162 -0
  65. package/lib/features/webbuilder/web/secrets/secrets.js.map +1 -0
  66. package/lib/features/webbuilder/web/secrets/secretsApi.js +302 -0
  67. package/lib/features/webbuilder/web/secrets/secretsApi.js.map +1 -0
  68. package/lib/features/webbuilder/web/secrets/secretsStore.js +39 -0
  69. package/lib/features/webbuilder/web/secrets/secretsStore.js.map +1 -0
  70. package/lib/features/webbuilder/web/sharing/okResult.js +40 -0
  71. package/lib/features/webbuilder/web/sharing/okResult.js.map +1 -0
  72. package/lib/features/webbuilder/web/sharing/roles.js +3 -0
  73. package/lib/features/webbuilder/web/sharing/roles.js.map +1 -0
  74. package/lib/features/webbuilder/web/state/storageKeys.js +59 -0
  75. package/lib/features/webbuilder/web/state/storageKeys.js.map +1 -0
  76. package/lib/features/webbuilder/web/webServices.js +282 -0
  77. package/lib/features/webbuilder/web/webServices.js.map +1 -0
  78. package/lib/features/webbuilder/workflow.js +1 -1
  79. package/lib/features/webbuilder/workflow.js.map +1 -1
  80. package/lib/routes.json +3 -1
  81. package/lib/screens/Account/AccountSheets.js +1049 -0
  82. package/lib/screens/Account/AccountSheets.js.map +1 -0
  83. package/lib/screens/Account/WorkspaceSection.js +271 -0
  84. package/lib/screens/Account/WorkspaceSection.js.map +1 -0
  85. package/lib/screens/Account/accountRules.js +103 -0
  86. package/lib/screens/Account/accountRules.js.map +1 -0
  87. package/lib/screens/Account/index.js +563 -259
  88. package/lib/screens/Account/index.js.map +1 -1
  89. package/lib/screens/Account/useAccountPreferences.js +87 -0
  90. package/lib/screens/Account/useAccountPreferences.js.map +1 -0
  91. package/lib/screens/WebBuilderNative/index.js +1 -1
  92. package/lib/screens/WebBuilderNative/index.js.map +1 -1
  93. package/lib/screens/WebBuilderNative/useWebBuilderHost.js +122 -12
  94. package/lib/screens/WebBuilderNative/useWebBuilderHost.js.map +1 -1
  95. package/lib/utils/authUserDisplay.js +1 -9
  96. package/lib/utils/authUserDisplay.js.map +1 -1
  97. package/package.json +4 -4
  98. package/lib/features/webbuilder/brandKitStorage.js +0 -69
  99. package/lib/features/webbuilder/brandKitStorage.js.map +0 -1
  100. package/lib/features/webbuilder/components/BrandKitSheet.js +0 -197
  101. package/lib/features/webbuilder/components/BrandKitSheet.js.map +0 -1
  102. package/lib/screens/Account/splitDisplayName.js +0 -15
  103. package/lib/screens/Account/splitDisplayName.js.map +0 -1
@@ -0,0 +1,343 @@
1
+ const PALETTE_ROLES = ["background", "surface", "text", "muted", "primary", "accent"];
2
+ const RADIUS_STYLES = ["none", "sm", "md", "lg", "full"];
3
+ const DENSITY_STYLES = ["compact", "comfortable", "airy"];
4
+ const IMAGERY_STYLES = ["photo", "illustration", "gradient", "geometric", "texture", "minimal"];
5
+ const MAX_NAME_CHARS = 40;
6
+ const MAX_MOOD_CHARS = 160;
7
+ const AA_CONTRAST = 4.5;
8
+ const GOOGLE_FONTS = {
9
+ Inter: {
10
+ category: "sans-serif",
11
+ bold: true
12
+ },
13
+ Roboto: {
14
+ category: "sans-serif",
15
+ bold: true
16
+ },
17
+ "Open Sans": {
18
+ category: "sans-serif",
19
+ bold: true
20
+ },
21
+ Lato: {
22
+ category: "sans-serif",
23
+ bold: true
24
+ },
25
+ Montserrat: {
26
+ category: "sans-serif",
27
+ bold: true
28
+ },
29
+ Poppins: {
30
+ category: "sans-serif",
31
+ bold: true
32
+ },
33
+ Nunito: {
34
+ category: "sans-serif",
35
+ bold: true
36
+ },
37
+ "Nunito Sans": {
38
+ category: "sans-serif",
39
+ bold: true
40
+ },
41
+ Raleway: {
42
+ category: "sans-serif",
43
+ bold: true
44
+ },
45
+ "Work Sans": {
46
+ category: "sans-serif",
47
+ bold: true
48
+ },
49
+ Rubik: {
50
+ category: "sans-serif",
51
+ bold: true
52
+ },
53
+ Karla: {
54
+ category: "sans-serif",
55
+ bold: true
56
+ },
57
+ Mulish: {
58
+ category: "sans-serif",
59
+ bold: true
60
+ },
61
+ Manrope: {
62
+ category: "sans-serif",
63
+ bold: true
64
+ },
65
+ "DM Sans": {
66
+ category: "sans-serif",
67
+ bold: true
68
+ },
69
+ "Plus Jakarta Sans": {
70
+ category: "sans-serif",
71
+ bold: true
72
+ },
73
+ Outfit: {
74
+ category: "sans-serif",
75
+ bold: true
76
+ },
77
+ Sora: {
78
+ category: "sans-serif",
79
+ bold: true
80
+ },
81
+ "Space Grotesk": {
82
+ category: "sans-serif",
83
+ bold: true
84
+ },
85
+ "IBM Plex Sans": {
86
+ category: "sans-serif",
87
+ bold: true
88
+ },
89
+ Archivo: {
90
+ category: "sans-serif",
91
+ bold: true
92
+ },
93
+ "Libre Franklin": {
94
+ category: "sans-serif",
95
+ bold: true
96
+ },
97
+ "Source Sans 3": {
98
+ category: "sans-serif",
99
+ bold: true
100
+ },
101
+ Figtree: {
102
+ category: "sans-serif",
103
+ bold: true
104
+ },
105
+ Lexend: {
106
+ category: "sans-serif",
107
+ bold: true
108
+ },
109
+ Urbanist: {
110
+ category: "sans-serif",
111
+ bold: true
112
+ },
113
+ Quicksand: {
114
+ category: "sans-serif",
115
+ bold: true
116
+ },
117
+ Barlow: {
118
+ category: "sans-serif",
119
+ bold: true
120
+ },
121
+ "Josefin Sans": {
122
+ category: "sans-serif",
123
+ bold: true
124
+ },
125
+ Syne: {
126
+ category: "sans-serif",
127
+ bold: true
128
+ },
129
+ Fredoka: {
130
+ category: "sans-serif",
131
+ bold: true
132
+ },
133
+ Oswald: {
134
+ category: "sans-serif",
135
+ bold: true
136
+ },
137
+ "Archivo Black": {
138
+ category: "display",
139
+ bold: false
140
+ },
141
+ "Bebas Neue": {
142
+ category: "display",
143
+ bold: false
144
+ },
145
+ Anton: {
146
+ category: "display",
147
+ bold: false
148
+ },
149
+ "Abril Fatface": {
150
+ category: "display",
151
+ bold: false
152
+ },
153
+ Righteous: {
154
+ category: "display",
155
+ bold: false
156
+ },
157
+ "DM Serif Display": {
158
+ category: "serif",
159
+ bold: false
160
+ },
161
+ "Playfair Display": {
162
+ category: "serif",
163
+ bold: true
164
+ },
165
+ Lora: {
166
+ category: "serif",
167
+ bold: true
168
+ },
169
+ Merriweather: {
170
+ category: "serif",
171
+ bold: true
172
+ },
173
+ "Libre Baskerville": {
174
+ category: "serif",
175
+ bold: true
176
+ },
177
+ "Cormorant Garamond": {
178
+ category: "serif",
179
+ bold: true
180
+ },
181
+ "EB Garamond": {
182
+ category: "serif",
183
+ bold: true
184
+ },
185
+ Fraunces: {
186
+ category: "serif",
187
+ bold: true
188
+ },
189
+ "Source Serif 4": {
190
+ category: "serif",
191
+ bold: true
192
+ },
193
+ "Crimson Pro": {
194
+ category: "serif",
195
+ bold: true
196
+ },
197
+ "IBM Plex Mono": {
198
+ category: "monospace",
199
+ bold: true
200
+ },
201
+ "JetBrains Mono": {
202
+ category: "monospace",
203
+ bold: true
204
+ },
205
+ "Space Mono": {
206
+ category: "monospace",
207
+ bold: true
208
+ },
209
+ Pacifico: {
210
+ category: "handwriting",
211
+ bold: false
212
+ },
213
+ Caveat: {
214
+ category: "handwriting",
215
+ bold: true
216
+ }
217
+ };
218
+ const FONT_BY_LOWER = new Map(Object.keys(GOOGLE_FONTS).map((n) => [n.toLowerCase(), n]));
219
+ function canonicalFont(name) {
220
+ var _a;
221
+ if (typeof name !== "string") return null;
222
+ const key = name.replace(/["']/g, "").replace(/\s+/g, " ").trim().toLowerCase();
223
+ return (_a = FONT_BY_LOWER.get(key)) != null ? _a : null;
224
+ }
225
+ const HEX_RE = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i;
226
+ function normalizeHex(v) {
227
+ if (typeof v !== "string") return null;
228
+ const m = HEX_RE.exec(v.trim());
229
+ if (!m) return null;
230
+ const h = m[1].length === 3 ? m[1].replace(/./g, (c) => c + c) : m[1];
231
+ return `#${h.toLowerCase()}`;
232
+ }
233
+ function rgb(hex) {
234
+ const n = parseInt(hex.slice(1), 16);
235
+ return [n >> 16 & 255, n >> 8 & 255, n & 255];
236
+ }
237
+ function toHex([r, g, b]) {
238
+ return `#${[r, g, b].map((c) => Math.round(Math.min(255, Math.max(0, c))).toString(16).padStart(2, "0")).join("")}`;
239
+ }
240
+ function relativeLuminance(hex) {
241
+ const [r, g, b] = rgb(hex).map((c) => {
242
+ const s = c / 255;
243
+ return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
244
+ });
245
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
246
+ }
247
+ function contrastRatio(a, b) {
248
+ const la = relativeLuminance(a);
249
+ const lb = relativeLuminance(b);
250
+ return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);
251
+ }
252
+ function ensureContrastOn(color, backgrounds, min = AA_CONTRAST) {
253
+ const worst = (c) => Math.min(...backgrounds.map((bg) => contrastRatio(c, bg)));
254
+ if (worst(color) >= min) return color;
255
+ const first = backgrounds[0];
256
+ const towardBlack = contrastRatio("#000000", first) >= contrastRatio("#ffffff", first);
257
+ const target = towardBlack ? [0, 0, 0] : [255, 255, 255];
258
+ const src = rgb(color);
259
+ for (let t = 0.05; t <= 1.0001; t += 0.05) {
260
+ const mixed = toHex(src.map((c, i) => c + (target[i] - c) * t));
261
+ if (worst(mixed) >= min) return mixed;
262
+ }
263
+ return worst("#000000") >= worst("#ffffff") ? "#000000" : "#ffffff";
264
+ }
265
+ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
266
+ function cleanLine(v, max) {
267
+ if (typeof v !== "string") return "";
268
+ const t = v.slice(0, max * 4).replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/[<>`{}#]/g, "").replace(/\s+/g, " ").trim();
269
+ return t.length > max ? t.slice(0, max).trim() : t;
270
+ }
271
+ function slugify(v) {
272
+ return v.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
273
+ }
274
+ const oneOf = (list, v) => typeof v === "string" && list.includes(v.trim().toLowerCase()) ? v.trim().toLowerCase() : null;
275
+ function validateDirection(raw) {
276
+ if (!isObj(raw)) return {
277
+ ok: false,
278
+ errors: ["direction must be an object"]
279
+ };
280
+ const errors = [];
281
+ const adjusted = [];
282
+ const name = cleanLine(raw.name, MAX_NAME_CHARS);
283
+ if (!name) errors.push("name is required");
284
+ const mood = cleanLine(raw.mood, MAX_MOOD_CHARS);
285
+ if (!mood) errors.push("mood is required");
286
+ const id = slugify(typeof raw.id === "string" && raw.id.trim() ? raw.id : name) || "direction";
287
+ const palette = {};
288
+ if (!isObj(raw.palette)) errors.push("palette must be an object");
289
+ else {
290
+ for (const role of PALETTE_ROLES) {
291
+ const v = raw.palette[role];
292
+ if (role === "muted" && (v === void 0 || v === null || v === "")) continue;
293
+ const hex = normalizeHex(v);
294
+ if (!hex) errors.push(`palette.${role} must be a hex colour`);
295
+ else palette[role] = hex;
296
+ }
297
+ }
298
+ const fonts = isObj(raw.fonts) ? raw.fonts : {};
299
+ const heading = canonicalFont(fonts.heading);
300
+ const body = canonicalFont(fonts.body);
301
+ if (!heading) errors.push("fonts.heading must be one of the allowed Google Fonts");
302
+ if (!body) errors.push("fonts.body must be one of the allowed Google Fonts");
303
+ const radius = oneOf(RADIUS_STYLES, raw.radius);
304
+ if (!radius) errors.push(`radius must be one of ${RADIUS_STYLES.join(", ")}`);
305
+ const density = oneOf(DENSITY_STYLES, raw.density);
306
+ if (!density) errors.push(`density must be one of ${DENSITY_STYLES.join(", ")}`);
307
+ const imagery = oneOf(IMAGERY_STYLES, raw.imagery);
308
+ if (!imagery) errors.push(`imagery must be one of ${IMAGERY_STYLES.join(", ")}`);
309
+ if (errors.length) return {
310
+ ok: false,
311
+ errors
312
+ };
313
+ const grounds = [palette.background, palette.surface];
314
+ const text = ensureContrastOn(palette.text, grounds);
315
+ if (text !== palette.text) adjusted.push(`text ${palette.text} -> ${text} (contrast on background / surface)`);
316
+ palette.text = text;
317
+ if (palette.muted) {
318
+ const muted = ensureContrastOn(palette.muted, grounds);
319
+ if (muted !== palette.muted) adjusted.push(`muted ${palette.muted} -> ${muted} (contrast on background / surface)`);
320
+ palette.muted = muted;
321
+ }
322
+ return {
323
+ ok: true,
324
+ adjusted,
325
+ direction: {
326
+ id,
327
+ name,
328
+ mood,
329
+ palette,
330
+ fonts: {
331
+ heading,
332
+ body
333
+ },
334
+ radius,
335
+ density,
336
+ imagery
337
+ }
338
+ };
339
+ }
340
+ function toDesignDirection(raw) {
341
+ const r = validateDirection(raw);
342
+ return r.ok ? r.direction : null;
343
+ }export{AA_CONTRAST,DENSITY_STYLES,GOOGLE_FONTS,IMAGERY_STYLES,MAX_MOOD_CHARS,MAX_NAME_CHARS,PALETTE_ROLES,RADIUS_STYLES,canonicalFont,cleanLine,contrastRatio,ensureContrastOn,normalizeHex,relativeLuminance,slugify,toDesignDirection,validateDirection};//# sourceMappingURL=directions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"directions.js","sources":["../../../../../src/features/webbuilder/web/design/directions.ts"],"sourcesContent":["/**\n * G4 (aicode-stack#343): guided style directions before a NEW build.\n *\n * The user sees three distinct directions (palette, font pair, radius /\n * density / imagery) and picks one or skips; the pick rides the build as\n * `props.designDirection` and is saved in the project settings so later edits\n * keep the same tokens.\n *\n * - `validateDirection`: hex colours, fonts from an allow-list of common\n * Google Fonts, enums, and a COMPUTED WCAG AA check (text and muted text on\n * the background); a failing text colour is adjusted, never assumed fine.\n * - `CURATED_DIRECTIONS` + `pickDirectionsForBrief`: works with no AI call.\n * - `buildDirectionsPrompt` / `parseDirectionsReply` / `resolveDirections`:\n * the optional AI lane (plain chat, strict JSON), best-effort with a\n * timeout and the curated set as the fallback.\n *\n * Pure: no React, no browser globals - runs under `node --test`. The server\n * re-validates with the same rules (page-creator `webbuilderDesignDirection.ts`);\n * keep the font allow-list and the enums in step with it.\n */\n\nexport const PALETTE_ROLES = ['background', 'surface', 'text', 'muted', 'primary', 'accent'] as const;\nexport type PaletteRole = (typeof PALETTE_ROLES)[number];\n/** `muted` is optional (5-6 colours); the others are required. */\nexport type DesignPalette = Record<Exclude<PaletteRole, 'muted'>, string> & { muted?: string };\n\nexport const RADIUS_STYLES = ['none', 'sm', 'md', 'lg', 'full'] as const;\nexport type RadiusStyle = (typeof RADIUS_STYLES)[number];\nexport const DENSITY_STYLES = ['compact', 'comfortable', 'airy'] as const;\nexport type DensityStyle = (typeof DENSITY_STYLES)[number];\nexport const IMAGERY_STYLES = ['photo', 'illustration', 'gradient', 'geometric', 'texture', 'minimal'] as const;\nexport type ImageryStyle = (typeof IMAGERY_STYLES)[number];\n\nexport interface DesignDirection {\n /** Slug, e.g. `golden-hour`. */\n id: string;\n name: string;\n /** One line: how the site should feel. */\n mood: string;\n palette: DesignPalette;\n fonts: { heading: string; body: string };\n radius: RadiusStyle;\n density: DensityStyle;\n imagery: ImageryStyle;\n}\n\nexport const MAX_NAME_CHARS = 40;\nexport const MAX_MOOD_CHARS = 160;\n/** WCAG 2.x AA for normal text. */\nexport const AA_CONTRAST = 4.5;\n\n// ---------------------------------------------------------------- fonts\n\nexport type FontCategory = 'sans-serif' | 'serif' | 'display' | 'monospace' | 'handwriting';\ninterface FontSpec {\n category: FontCategory;\n /** False: the family has one weight (400); the css2 API refuses a `wght@…;700` request for it. */\n bold: boolean;\n}\n\n/** Common Google Fonts the agent may use. Keys are the exact family names. */\nexport const GOOGLE_FONTS: Readonly<Record<string, FontSpec>> = {\n Inter: { category: 'sans-serif', bold: true },\n Roboto: { category: 'sans-serif', bold: true },\n 'Open Sans': { category: 'sans-serif', bold: true },\n Lato: { category: 'sans-serif', bold: true },\n Montserrat: { category: 'sans-serif', bold: true },\n Poppins: { category: 'sans-serif', bold: true },\n Nunito: { category: 'sans-serif', bold: true },\n 'Nunito Sans': { category: 'sans-serif', bold: true },\n Raleway: { category: 'sans-serif', bold: true },\n 'Work Sans': { category: 'sans-serif', bold: true },\n Rubik: { category: 'sans-serif', bold: true },\n Karla: { category: 'sans-serif', bold: true },\n Mulish: { category: 'sans-serif', bold: true },\n Manrope: { category: 'sans-serif', bold: true },\n 'DM Sans': { category: 'sans-serif', bold: true },\n 'Plus Jakarta Sans': { category: 'sans-serif', bold: true },\n Outfit: { category: 'sans-serif', bold: true },\n Sora: { category: 'sans-serif', bold: true },\n 'Space Grotesk': { category: 'sans-serif', bold: true },\n 'IBM Plex Sans': { category: 'sans-serif', bold: true },\n Archivo: { category: 'sans-serif', bold: true },\n 'Libre Franklin': { category: 'sans-serif', bold: true },\n 'Source Sans 3': { category: 'sans-serif', bold: true },\n Figtree: { category: 'sans-serif', bold: true },\n Lexend: { category: 'sans-serif', bold: true },\n Urbanist: { category: 'sans-serif', bold: true },\n Quicksand: { category: 'sans-serif', bold: true },\n Barlow: { category: 'sans-serif', bold: true },\n 'Josefin Sans': { category: 'sans-serif', bold: true },\n Syne: { category: 'sans-serif', bold: true },\n Fredoka: { category: 'sans-serif', bold: true },\n Oswald: { category: 'sans-serif', bold: true },\n 'Archivo Black': { category: 'display', bold: false },\n 'Bebas Neue': { category: 'display', bold: false },\n Anton: { category: 'display', bold: false },\n 'Abril Fatface': { category: 'display', bold: false },\n Righteous: { category: 'display', bold: false },\n 'DM Serif Display': { category: 'serif', bold: false },\n 'Playfair Display': { category: 'serif', bold: true },\n Lora: { category: 'serif', bold: true },\n Merriweather: { category: 'serif', bold: true },\n 'Libre Baskerville': { category: 'serif', bold: true },\n 'Cormorant Garamond': { category: 'serif', bold: true },\n 'EB Garamond': { category: 'serif', bold: true },\n Fraunces: { category: 'serif', bold: true },\n 'Source Serif 4': { category: 'serif', bold: true },\n 'Crimson Pro': { category: 'serif', bold: true },\n 'IBM Plex Mono': { category: 'monospace', bold: true },\n 'JetBrains Mono': { category: 'monospace', bold: true },\n 'Space Mono': { category: 'monospace', bold: true },\n Pacifico: { category: 'handwriting', bold: false },\n Caveat: { category: 'handwriting', bold: true },\n};\n\nconst FONT_BY_LOWER = new Map(Object.keys(GOOGLE_FONTS).map((n) => [n.toLowerCase(), n]));\n\n/** The allow-listed family name (canonical case), or null. */\nexport function canonicalFont(name: unknown): string | null {\n if (typeof name !== 'string') return null;\n const key = name.replace(/[\"']/g, '').replace(/\\s+/g, ' ').trim().toLowerCase();\n return FONT_BY_LOWER.get(key) ?? null;\n}\n\n/** A CSS `font-family` value with a generic fallback: `'Playfair Display', Georgia, serif`. */\nexport function fontStack(name: string): string {\n const spec = GOOGLE_FONTS[name];\n const fallback =\n spec?.category === 'serif'\n ? 'Georgia, serif'\n : spec?.category === 'monospace'\n ? 'ui-monospace, monospace'\n : spec?.category === 'handwriting'\n ? 'cursive'\n : 'system-ui, sans-serif';\n return `'${name}', ${fallback}`;\n}\n\n/** One css2 URL for the families (allow-listed only, de-duplicated, sorted so the URL is stable). */\nexport function googleFontsHref(families: Iterable<string>): string | null {\n const names = [...new Set([...families].map(canonicalFont).filter((n): n is string => Boolean(n)))].sort();\n if (!names.length) return null;\n const params = names.map((n) => `family=${n.replace(/ /g, '+')}${GOOGLE_FONTS[n].bold ? ':wght@400;700' : ''}`);\n return `https://fonts.googleapis.com/css2?${params.join('&')}&display=swap`;\n}\n\n// ---------------------------------------------------------------- colour + contrast\n\nconst HEX_RE = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i;\n\n/** `#abc` / `ABCDEF` -> `#aabbcc` (lower case), or null. */\nexport function normalizeHex(v: unknown): string | null {\n if (typeof v !== 'string') return null;\n const m = HEX_RE.exec(v.trim());\n if (!m) return null;\n const h = m[1].length === 3 ? m[1].replace(/./g, (c) => c + c) : m[1];\n return `#${h.toLowerCase()}`;\n}\n\nfunction rgb(hex: string): [number, number, number] {\n const n = parseInt(hex.slice(1), 16);\n return [(n >> 16) & 255, (n >> 8) & 255, n & 255];\n}\n\nfunction toHex([r, g, b]: [number, number, number]): string {\n return `#${[r, g, b]\n .map((c) =>\n Math.round(Math.min(255, Math.max(0, c)))\n .toString(16)\n .padStart(2, '0'),\n )\n .join('')}`;\n}\n\n/** WCAG relative luminance of a normalized hex colour. */\nexport function relativeLuminance(hex: string): number {\n const [r, g, b] = rgb(hex).map((c) => {\n const s = c / 255;\n return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;\n });\n return 0.2126 * r + 0.7152 * g + 0.0722 * b;\n}\n\n/** WCAG contrast ratio (1-21) between two normalized hex colours. */\nexport function contrastRatio(a: string, b: string): number {\n const la = relativeLuminance(a);\n const lb = relativeLuminance(b);\n return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);\n}\n\n/**\n * `text` when it already reaches `min` on `bg`; else `text` mixed step by step\n * toward black (light backgrounds) or white (dark ones) until it does. Keeps\n * the hue as long as possible; black / white is the last resort.\n */\nexport function ensureContrast(text: string, bg: string, min = AA_CONTRAST): string {\n if (contrastRatio(text, bg) >= min) return text;\n const towardBlack = contrastRatio('#000000', bg) >= contrastRatio('#ffffff', bg);\n const target: [number, number, number] = towardBlack ? [0, 0, 0] : [255, 255, 255];\n const [r, g, b] = rgb(text);\n for (let t = 0.05; t <= 1.0001; t += 0.05) {\n const mixed = toHex([r + (target[0] - r) * t, g + (target[1] - g) * t, b + (target[2] - b) * t]);\n if (contrastRatio(mixed, bg) >= min) return mixed;\n }\n return towardBlack ? '#000000' : '#ffffff';\n}\n\n/**\n * `color` when it reaches `min` on EVERY background (page and surface); else\n * mixed toward black or white (picked by the first background) until it does.\n * When no mix works, the extreme with the best worst-case contrast.\n */\nexport function ensureContrastOn(color: string, backgrounds: string[], min = AA_CONTRAST): string {\n const worst = (c: string) => Math.min(...backgrounds.map((bg) => contrastRatio(c, bg)));\n if (worst(color) >= min) return color;\n const first = backgrounds[0];\n const towardBlack = contrastRatio('#000000', first) >= contrastRatio('#ffffff', first);\n const target = towardBlack ? [0, 0, 0] : [255, 255, 255];\n const src = rgb(color);\n for (let t = 0.05; t <= 1.0001; t += 0.05) {\n const mixed = toHex(src.map((c, i) => c + (target[i] - c) * t) as [number, number, number]);\n if (worst(mixed) >= min) return mixed;\n }\n return worst('#000000') >= worst('#ffffff') ? '#000000' : '#ffffff';\n}\n\n/**\n * Button label colour on `primary`: black or white, whichever has more\n * contrast (one of them always reaches at least 4.58:1, so labels pass AA).\n */\nexport function onColor(bg: string): string {\n return contrastRatio('#ffffff', bg) >= contrastRatio('#000000', bg) ? '#ffffff' : '#000000';\n}\n\n// ---------------------------------------------------------------- validation\n\nexport type DirectionValidation =\n | {\n ok: true;\n direction: DesignDirection;\n /** What was fixed (e.g. text colour for contrast). */ adjusted: string[];\n }\n | { ok: false; errors: string[] };\n\nconst isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);\n\n/** Identical to the server's `cleanLine` (webbuilderDesignDirection.ts), so the card and the agent show the same name. */\nexport function cleanLine(v: unknown, max: number): string {\n if (typeof v !== 'string') return '';\n const t = v\n .slice(0, max * 4)\n .replace(/[\\u0000-\\u001f\\u007f]+/g, ' ')\n .replace(/[<>`{}#]/g, '')\n .replace(/\\s+/g, ' ')\n .trim();\n return t.length > max ? t.slice(0, max).trim() : t;\n}\n\nexport function slugify(v: string): string {\n return v\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40);\n}\n\nconst oneOf = <T extends string>(list: readonly T[], v: unknown): T | null =>\n typeof v === 'string' && (list as readonly string[]).includes(v.trim().toLowerCase())\n ? (v.trim().toLowerCase() as T)\n : null;\n\n/**\n * Validate (and normalise) a direction from any source: the curated set, the\n * AI lane or stored settings. Text and muted colours that miss AA on the\n * background are adjusted (reported in `adjusted`); anything else invalid is\n * an error.\n */\nexport function validateDirection(raw: unknown): DirectionValidation {\n if (!isObj(raw)) return { ok: false, errors: ['direction must be an object'] };\n const errors: string[] = [];\n const adjusted: string[] = [];\n\n const name = cleanLine(raw.name, MAX_NAME_CHARS);\n if (!name) errors.push('name is required');\n const mood = cleanLine(raw.mood, MAX_MOOD_CHARS);\n if (!mood) errors.push('mood is required');\n const id = slugify(typeof raw.id === 'string' && raw.id.trim() ? raw.id : name) || 'direction';\n\n const palette: Partial<Record<PaletteRole, string>> = {};\n if (!isObj(raw.palette)) errors.push('palette must be an object');\n else {\n for (const role of PALETTE_ROLES) {\n const v = raw.palette[role];\n if (role === 'muted' && (v === undefined || v === null || v === '')) continue;\n const hex = normalizeHex(v);\n if (!hex) errors.push(`palette.${role} must be a hex colour`);\n else palette[role] = hex;\n }\n }\n\n const fonts = isObj(raw.fonts) ? raw.fonts : {};\n const heading = canonicalFont(fonts.heading);\n const body = canonicalFont(fonts.body);\n if (!heading) errors.push('fonts.heading must be one of the allowed Google Fonts');\n if (!body) errors.push('fonts.body must be one of the allowed Google Fonts');\n\n const radius = oneOf(RADIUS_STYLES, raw.radius);\n if (!radius) errors.push(`radius must be one of ${RADIUS_STYLES.join(', ')}`);\n const density = oneOf(DENSITY_STYLES, raw.density);\n if (!density) errors.push(`density must be one of ${DENSITY_STYLES.join(', ')}`);\n const imagery = oneOf(IMAGERY_STYLES, raw.imagery);\n if (!imagery) errors.push(`imagery must be one of ${IMAGERY_STYLES.join(', ')}`);\n\n if (errors.length) return { ok: false, errors };\n\n // Text and muted text sit on the page AND on cards: AA on both. Links use the text colour plus\n // an underline (primary is for button fills, labelled with `onColor`), so primary needs no check.\n const grounds = [palette.background!, palette.surface!];\n const text = ensureContrastOn(palette.text!, grounds);\n if (text !== palette.text) adjusted.push(`text ${palette.text} -> ${text} (contrast on background / surface)`);\n palette.text = text;\n if (palette.muted) {\n const muted = ensureContrastOn(palette.muted, grounds);\n if (muted !== palette.muted)\n adjusted.push(`muted ${palette.muted} -> ${muted} (contrast on background / surface)`);\n palette.muted = muted;\n }\n\n return {\n ok: true,\n adjusted,\n direction: {\n id,\n name,\n mood,\n palette: palette as DesignPalette,\n fonts: { heading: heading!, body: body! },\n radius: radius!,\n density: density!,\n imagery: imagery!,\n },\n };\n}\n\n/** The validated direction, or null. */\nexport function toDesignDirection(raw: unknown): DesignDirection | null {\n const r = validateDirection(raw);\n return r.ok ? r.direction : null;\n}\n\n/** `props.designDirection` for the build turn ({} when there is none). */\nexport function designDirectionTurnProps(d: DesignDirection | null | undefined): { designDirection?: DesignDirection } {\n const v = d ? toDesignDirection(d) : null;\n return v ? { designDirection: v } : {};\n}\n\nexport interface TurnDirectionPlan {\n /** Spread into the post props. `designDirection: null` = skipped on a new build (no settings fallback). */\n props: { designDirection?: DesignDirection | null };\n /** Write to the project settings after the turn is delivered (`null` clears); undefined = leave them. */\n save?: DesignDirection | null;\n}\n\n/**\n * What a connector turn sends and saves (the server falls back to settings on EDIT turns only):\n * - a new build that went through the picker (`designDirection` key present): the pick, saved; or an\n * explicit `null` when skipped / styles off, clearing an older pick in this channel's settings;\n * - an edit: the project's saved direction, so edits keep the same tokens;\n * - anything else: nothing.\n */\nexport function planTurnDirection(input: {\n isEdit: boolean;\n opts?: { designDirection?: DesignDirection | null } | null;\n saved?: DesignDirection | null;\n /** The channel was minted for this send (nothing saved to clear). */\n minted?: boolean;\n}): TurnDirectionPlan {\n const opts = input.opts;\n if (!input.isEdit && opts && 'designDirection' in opts) {\n const picked = opts.designDirection ? toDesignDirection(opts.designDirection) : null;\n if (picked) return { props: { designDirection: picked }, save: picked };\n return { props: { designDirection: null }, ...(!input.minted && input.saved ? { save: null } : {}) };\n }\n if (input.isEdit) return { props: designDirectionTurnProps(input.saved) };\n return { props: {} };\n}\n\n// ---------------------------------------------------------------- curated fallback set\n\nexport interface CuratedDirection extends DesignDirection {\n /** Brief keywords that make this direction a good fit. */\n keywords: string[];\n}\n\nexport const CURATED_DIRECTIONS: readonly CuratedDirection[] = [\n {\n id: 'quiet-minimal',\n name: 'Quiet Minimal',\n mood: 'Calm, precise and spacious - lots of white space and confident type.',\n palette: {\n background: '#ffffff',\n surface: '#f5f5f4',\n text: '#1c1917',\n muted: '#57534e',\n primary: '#1c1917',\n accent: '#a8a29e',\n },\n fonts: { heading: 'Manrope', body: 'Inter' },\n radius: 'sm',\n density: 'airy',\n imagery: 'minimal',\n keywords: [\n 'minimal',\n 'clean',\n 'simple',\n 'portfolio',\n 'architect',\n 'architecture',\n 'studio',\n 'photographer',\n 'photography',\n 'designer',\n 'resume',\n 'cv',\n ],\n },\n {\n id: 'golden-hour',\n name: 'Golden Hour',\n mood: 'Warm and welcoming, like late-afternoon light in a neighbourhood cafe.',\n palette: {\n background: '#fdf6ec',\n surface: '#f6e7d3',\n text: '#3b2a1e',\n muted: '#6b5444',\n primary: '#c2410c',\n accent: '#e9a23b',\n },\n fonts: { heading: 'Fraunces', body: 'Nunito Sans' },\n radius: 'lg',\n density: 'comfortable',\n imagery: 'photo',\n keywords: [\n 'bakery',\n 'cafe',\n 'coffee',\n 'restaurant',\n 'food',\n 'recipe',\n 'recipes',\n 'kitchen',\n 'family',\n 'home',\n 'wedding',\n 'bnb',\n 'catering',\n 'warm',\n ],\n },\n {\n id: 'loud-and-clear',\n name: 'Loud & Clear',\n mood: 'High-energy and bold - big type, hard edges, strong contrast.',\n palette: {\n background: '#0a0a0a',\n surface: '#1a1a1a',\n text: '#fafafa',\n muted: '#a3a3a3',\n primary: '#facc15',\n accent: '#ef4444',\n },\n fonts: { heading: 'Archivo Black', body: 'Archivo' },\n radius: 'none',\n density: 'compact',\n imagery: 'geometric',\n keywords: [\n 'fitness',\n 'gym',\n 'sport',\n 'sports',\n 'event',\n 'festival',\n 'music',\n 'band',\n 'launch',\n 'streetwear',\n 'bold',\n 'conference',\n 'marathon',\n ],\n },\n {\n id: 'broadsheet',\n name: 'Broadsheet',\n mood: 'Editorial and literate - classic serif headlines with a newspaper rhythm.',\n palette: {\n background: '#fbfaf7',\n surface: '#f0ede6',\n text: '#111111',\n muted: '#555048',\n primary: '#9f1239',\n accent: '#1e3a8a',\n },\n fonts: { heading: 'Playfair Display', body: 'Libre Franklin' },\n radius: 'none',\n density: 'comfortable',\n imagery: 'photo',\n keywords: [\n 'blog',\n 'magazine',\n 'news',\n 'journal',\n 'writer',\n 'writing',\n 'book',\n 'books',\n 'author',\n 'publication',\n 'newsletter',\n 'podcast',\n 'editorial',\n 'essay',\n ],\n },\n {\n id: 'candy-pop',\n name: 'Candy Pop',\n mood: 'Playful and friendly - round shapes, bright colour and a wink of fun.',\n palette: {\n background: '#fff7fb',\n surface: '#ffe4f1',\n text: '#2e1065',\n muted: '#5b4a7a',\n primary: '#db2777',\n accent: '#22c55e',\n },\n fonts: { heading: 'Fredoka', body: 'Nunito' },\n radius: 'full',\n density: 'comfortable',\n imagery: 'illustration',\n keywords: [\n 'kids',\n 'children',\n 'child',\n 'game',\n 'games',\n 'toy',\n 'toys',\n 'party',\n 'pet',\n 'pets',\n 'school',\n 'fun',\n 'candy',\n 'ice',\n 'playful',\n 'daycare',\n ],\n },\n {\n id: 'noir-gold',\n name: 'Noir & Gold',\n mood: 'Luxurious and refined - deep darks, gold accents and elegant serifs.',\n palette: {\n background: '#0f0e0c',\n surface: '#1c1a16',\n text: '#f5f0e6',\n muted: '#b5ab98',\n primary: '#c9a227',\n accent: '#8c6d1f',\n },\n fonts: { heading: 'Cormorant Garamond', body: 'Montserrat' },\n radius: 'none',\n density: 'airy',\n imagery: 'photo',\n keywords: [\n 'luxury',\n 'jewelry',\n 'jewellery',\n 'fashion',\n 'hotel',\n 'wine',\n 'watch',\n 'watches',\n 'premium',\n 'boutique',\n 'estate',\n 'perfume',\n 'cocktail',\n 'elegant',\n ],\n },\n {\n id: 'terminal-grid',\n name: 'Terminal Grid',\n mood: 'Technical and sharp - dark UI, crisp grids and a hint of neon.',\n palette: {\n background: '#0b1020',\n surface: '#131a2e',\n text: '#e2e8f0',\n muted: '#94a3b8',\n primary: '#22d3ee',\n accent: '#a78bfa',\n },\n fonts: { heading: 'Space Grotesk', body: 'IBM Plex Sans' },\n radius: 'md',\n density: 'compact',\n imagery: 'gradient',\n keywords: [\n 'saas',\n 'ai',\n 'developer',\n 'developers',\n 'api',\n 'crypto',\n 'dashboard',\n 'tech',\n 'software',\n 'analytics',\n 'data',\n 'devtools',\n 'cloud',\n 'startup',\n ],\n },\n {\n id: 'field-and-fern',\n name: 'Field & Fern',\n mood: 'Organic and grounded - earthy greens, natural textures, unhurried.',\n palette: {\n background: '#f4f1ea',\n surface: '#e6e2d3',\n text: '#23301f',\n muted: '#4f5b48',\n primary: '#3f6212',\n accent: '#b45309',\n },\n fonts: { heading: 'DM Serif Display', body: 'Karla' },\n radius: 'lg',\n density: 'airy',\n imagery: 'texture',\n keywords: [\n 'garden',\n 'gardening',\n 'farm',\n 'organic',\n 'eco',\n 'plant',\n 'plants',\n 'nature',\n 'sustainable',\n 'outdoor',\n 'florist',\n 'flowers',\n 'hiking',\n 'camping',\n ],\n },\n {\n id: 'clear-blue',\n name: 'Clear Blue',\n mood: 'Trustworthy and professional - clean layout, confident blue, no noise.',\n palette: {\n background: '#ffffff',\n surface: '#f1f5f9',\n text: '#0f172a',\n muted: '#475569',\n primary: '#2563eb',\n accent: '#0ea5e9',\n },\n fonts: { heading: 'Plus Jakarta Sans', body: 'Inter' },\n radius: 'md',\n density: 'comfortable',\n imagery: 'photo',\n keywords: [\n 'consulting',\n 'consultant',\n 'finance',\n 'law',\n 'lawyer',\n 'legal',\n 'clinic',\n 'medical',\n 'dentist',\n 'insurance',\n 'bank',\n 'accounting',\n 'business',\n 'agency',\n 'corporate',\n ],\n },\n {\n id: 'sunset-diner',\n name: 'Sunset Diner',\n mood: 'Retro and characterful - chunky display type and sun-faded colour.',\n palette: {\n background: '#fff4e0',\n surface: '#ffe3b3',\n text: '#3d1f0f',\n muted: '#6e4630',\n primary: '#c2410c',\n accent: '#0b7285',\n },\n fonts: { heading: 'Abril Fatface', body: 'Work Sans' },\n radius: 'md',\n density: 'comfortable',\n imagery: 'illustration',\n keywords: [\n 'diner',\n 'retro',\n 'vintage',\n 'barber',\n 'records',\n 'vinyl',\n 'brewery',\n 'beer',\n 'burger',\n 'pizza',\n 'taco',\n 'food truck',\n 'arcade',\n ],\n },\n {\n id: 'soft-sage',\n name: 'Soft Sage',\n mood: 'Calm and restorative - muted sage, gentle serif headings, room to breathe.',\n palette: {\n background: '#f6f8f5',\n surface: '#e7eee6',\n text: '#1f2d27',\n muted: '#4d5f56',\n primary: '#3f6b5c',\n accent: '#d4a373',\n },\n fonts: { heading: 'Lora', body: 'Mulish' },\n radius: 'lg',\n density: 'airy',\n imagery: 'photo',\n keywords: [\n 'wellness',\n 'yoga',\n 'spa',\n 'therapy',\n 'therapist',\n 'meditation',\n 'health',\n 'coach',\n 'coaching',\n 'skincare',\n 'massage',\n 'mindfulness',\n 'calm',\n ],\n },\n {\n id: 'neon-night',\n name: 'Neon Night',\n mood: 'Futuristic and electric - deep night tones lit by violet and pink glows.',\n palette: {\n background: '#09090f',\n surface: '#15152a',\n text: '#f4f4ff',\n muted: '#a1a1c2',\n primary: '#8b5cf6',\n accent: '#ec4899',\n },\n fonts: { heading: 'Sora', body: 'Outfit' },\n radius: 'lg',\n density: 'comfortable',\n imagery: 'gradient',\n keywords: [\n 'gaming',\n 'gamer',\n 'nightclub',\n 'club',\n 'esports',\n 'nft',\n 'web3',\n 'dj',\n 'synth',\n 'futuristic',\n 'nightlife',\n 'vr',\n ],\n },\n];\n\n/** Order used when the brief gives no hints: as different from each other as possible. */\nconst DEFAULT_ORDER = [\n 'quiet-minimal',\n 'golden-hour',\n 'terminal-grid',\n 'broadsheet',\n 'candy-pop',\n 'noir-gold',\n 'field-and-fern',\n 'loud-and-clear',\n 'clear-blue',\n 'soft-sage',\n 'neon-night',\n 'sunset-diner',\n];\n\nfunction keywordScore(d: CuratedDirection, brief: string): number {\n let score = 0;\n for (const k of d.keywords) {\n const re = new RegExp(`\\\\b${k.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}s?\\\\b`, 'i');\n if (re.test(brief)) score += 1;\n }\n return score;\n}\n\n/** Every curated direction, best fit for the brief first (ties keep the diverse default order). */\nexport function rankDirectionsForBrief(brief: string | null | undefined): CuratedDirection[] {\n const text = String(brief ?? '');\n const order = new Map(DEFAULT_ORDER.map((id, i) => [id, i]));\n return [...CURATED_DIRECTIONS]\n .map((d) => ({ d, score: keywordScore(d, text) }))\n .sort((a, b) => b.score - a.score || (order.get(a.d.id) ?? 99) - (order.get(b.d.id) ?? 99))\n .map((x) => x.d);\n}\n\n/** Strip the curated-only `keywords`. */\nexport function asDirection(d: DesignDirection): DesignDirection {\n const { id, name, mood, palette, fonts, radius, density, imagery } = d;\n return { id, name, mood, palette: { ...palette }, fonts: { ...fonts }, radius, density, imagery };\n}\n\n/**\n * Three distinct curated directions for the brief (keyword heuristic). `exclude`\n * (ids already shown) gives the \"Shuffle\" set; when too few are left, the\n * ranking starts over.\n */\nexport function pickDirectionsForBrief(\n brief: string | null | undefined,\n exclude: Iterable<string> = [],\n): DesignDirection[] {\n const ranked = rankDirectionsForBrief(brief);\n const skip = new Set(exclude);\n const fresh = ranked.filter((d) => !skip.has(d.id));\n const pool = fresh.length >= 3 ? fresh : [...fresh, ...ranked.filter((d) => skip.has(d.id))];\n return pool.slice(0, 3).map(asDirection);\n}\n\n// ---------------------------------------------------------------- AI lane (optional)\n\nexport const DIRECTIONS_SESSION_KEY = 'webbuilder-design-directions';\nexport const DIRECTIONS_TIMEOUT_MS = 12_000;\n\n/** One plain-chat session per build channel (reused across requests), not one per call. */\nexport function directionsSessionKey(channelId: string | null | undefined): string {\n const id = String(channelId ?? '')\n .trim()\n .replace(/[^A-Za-z0-9_-]/g, '')\n .slice(0, 80);\n return id ? `${DIRECTIONS_SESSION_KEY}-${id}` : DIRECTIONS_SESSION_KEY;\n}\n\n/** The strict-JSON prompt sent through the plain-chat lane. */\nexport function buildDirectionsPrompt(brief: string): string {\n return [\n 'You are an art director proposing visual style directions for a website BEFORE it is built.',\n 'Do NOT write code, do NOT build anything, do NOT ask questions, do NOT call any tool or connector.',\n 'Propose exactly 3 clearly DIFFERENT directions that fit the request below.',\n 'Reply with ONLY one JSON object, no prose and no code fence, in exactly this shape:',\n '{\"directions\":[{\"name\":\"2-3 words\",\"mood\":\"one sentence, max 140 characters\",' +\n '\"palette\":{\"background\":\"#rrggbb\",\"surface\":\"#rrggbb\",\"text\":\"#rrggbb\",\"muted\":\"#rrggbb\",\"primary\":\"#rrggbb\",\"accent\":\"#rrggbb\"},' +\n '\"fonts\":{\"heading\":\"<font>\",\"body\":\"<font>\"},\"radius\":\"<radius>\",\"density\":\"<density>\",\"imagery\":\"<imagery>\"}]}',\n `Fonts must be exact names from this list: ${Object.keys(GOOGLE_FONTS).join(', ')}.`,\n `radius: one of ${RADIUS_STYLES.join(', ')}. density: one of ${DENSITY_STYLES.join(', ')}. imagery: one of ${IMAGERY_STYLES.join(', ')}.`,\n 'The text and muted colours must have at least 4.5:1 contrast on both the background and the surface. Links use the text colour with an underline; primary is a button fill.',\n '',\n `Website request:\\n${String(brief ?? '')\n .trim()\n .slice(0, 2000)}`,\n ].join('\\n');\n}\n\n/** The validated directions in an AI reply (fenced or not, array or `{ directions }`); [] when none. */\nexport function parseDirectionsReply(reply: string | null | undefined): DesignDirection[] {\n let t = String(reply ?? '').trim();\n const fenced = /```(?:json)?\\s*\\n?([\\s\\S]*?)```/i.exec(t);\n if (fenced) t = fenced[1].trim();\n const start = t.search(/[[{]/);\n if (start < 0) return [];\n const end = Math.max(t.lastIndexOf('}'), t.lastIndexOf(']'));\n if (end <= start) return [];\n let data: unknown;\n try {\n data = JSON.parse(t.slice(start, end + 1));\n } catch {\n return [];\n }\n const list = Array.isArray(data) ? data : isObj(data) && Array.isArray(data.directions) ? data.directions : [];\n const out: DesignDirection[] = [];\n const seen = new Set<string>();\n for (const item of list.slice(0, 6)) {\n const d = toDesignDirection(item);\n if (!d || seen.has(d.name.toLowerCase())) continue;\n seen.add(d.name.toLowerCase());\n // A model-made id could collide with a curated one; keep ids unique.\n out.push({ ...d, id: `ai-${d.id}`.slice(0, 40) });\n }\n return out.slice(0, 3);\n}\n\nexport interface ResolvedDirections {\n directions: DesignDirection[];\n source: 'ai' | 'curated';\n}\n\n/**\n * The AI directions for the brief, topped up from the curated set; the curated\n * three on any failure, an empty reply or after `timeoutMs`. Never throws.\n */\nexport async function resolveDirections(\n brief: string,\n suggest: ((prompt: string, opts: { signal: AbortSignal }) => Promise<string>) | null | undefined,\n opts: { timeoutMs?: number; signal?: AbortSignal } = {},\n): Promise<ResolvedDirections> {\n const curated = (): ResolvedDirections => ({ directions: pickDirectionsForBrief(brief), source: 'curated' });\n if (!suggest) return curated();\n const ctrl = new AbortController();\n const onAbort = () => ctrl.abort();\n opts.signal?.addEventListener('abort', onAbort, { once: true });\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const timeout = new Promise<null>((resolve) => {\n timer = setTimeout(() => {\n ctrl.abort();\n resolve(null);\n }, opts.timeoutMs ?? DIRECTIONS_TIMEOUT_MS);\n });\n const reply = await Promise.race([\n suggest(buildDirectionsPrompt(brief), { signal: ctrl.signal }).catch(() => null),\n timeout,\n ]);\n const ai = reply ? parseDirectionsReply(reply) : [];\n if (!ai.length) return curated();\n const names = new Set(ai.map((d) => d.name.toLowerCase()));\n const fill = rankDirectionsForBrief(brief)\n .filter((d) => !names.has(d.name.toLowerCase()))\n .slice(0, 3 - ai.length)\n .map(asDirection);\n return { directions: [...ai, ...fill], source: 'ai' };\n } catch {\n return curated();\n } finally {\n if (timer) clearTimeout(timer);\n opts.signal?.removeEventListener('abort', onAbort);\n }\n}\n\n// ---------------------------------------------------------------- picker state\n\n/** The open style-direction picker for the next new build. */\nexport interface DirectionPickerState {\n brief: string;\n directions: DesignDirection[];\n source: 'ai' | 'curated';\n /** The AI lane is still working. */\n loading: boolean;\n /** The user hovered, focused or clicked the cards: never swap them under the cursor. */\n touched?: boolean;\n /** AI directions that arrived after the user touched the cards (\"Tailored styles ready\"). */\n tailored?: DesignDirection[];\n}\n\n/**\n * The AI lane answered: replace the curated cards only while the user hasn't\n * touched them; otherwise park the result behind the \"Tailored styles ready\" chip.\n */\nexport function withTailoredDirections(state: DirectionPickerState, result: ResolvedDirections): DirectionPickerState {\n const next: DirectionPickerState = { ...state, loading: false };\n if (result.source !== 'ai' || !result.directions.length) return next;\n if (state.touched) return { ...next, tailored: result.directions };\n return { ...next, directions: result.directions, source: 'ai', tailored: undefined };\n}\n\n/** \"Tailored styles ready\" clicked: show the parked AI directions. */\nexport function showTailoredDirections(state: DirectionPickerState): DirectionPickerState {\n if (!state.tailored?.length) return state;\n return { ...state, directions: state.tailored, source: 'ai', tailored: undefined };\n}\n\n// ---------------------------------------------------------------- when to offer\n\n/**\n * Directions are offered only before a NEW build: New app, a template remix or\n * \"New from this\" - never an edit of an open build, a plain chat turn, or a\n * turn that already carries a plan.\n */\nexport function isNewBuildTurn(\n opts:\n | {\n forceNew?: boolean;\n template?: unknown;\n editTarget?: unknown;\n referenceArtifact?: unknown;\n plan?: string;\n }\n | null\n | undefined,\n): boolean {\n if (!opts || opts.editTarget || opts.plan) return false;\n return Boolean(opts.forceNew || opts.template || opts.referenceArtifact);\n}\n\n/** Pixel radius used for the card preview (and documented to the agent). */\nexport const RADIUS_PX: Readonly<Record<RadiusStyle, number>> = { none: 0, sm: 6, md: 12, lg: 20, full: 9999 };\n"],"names":[],"mappings":"AAqBO,MAAM,gBAAgB,CAAC,YAAA,EAAc,WAAW,MAAQ,EAAA,OAAA,EAAS,WAAW,QAAQ;AAMpF,MAAM,gBAAgB,CAAC,MAAA,EAAQ,IAAM,EAAA,IAAA,EAAM,MAAM,MAAM;AAEvD,MAAM,cAAiB,GAAA,CAAC,SAAW,EAAA,aAAA,EAAe,MAAM;AAExD,MAAM,iBAAiB,CAAC,OAAA,EAAS,gBAAgB,UAAY,EAAA,WAAA,EAAa,WAAW,SAAS;AAiB9F,MAAM,cAAiB,GAAA;AACvB,MAAM,cAAiB,GAAA;AAEvB,MAAM,WAAc,GAAA;AAYpB,MAAM,YAAmD,GAAA;AAAA,EAC9D,KAAO,EAAA;AAAA,IACL,QAAU,EAAA,YAAA;AAAA,IACV,IAAM,EAAA;AAAA,GACR;AAAA,EACA,MAAQ,EAAA;AAAA,IACN,QAAU,EAAA,YAAA;AAAA,IACV,IAAM,EAAA;AAAA,GACR;AAAA,EACA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}
@@ -0,0 +1,165 @@
1
+ const APP_TOKEN_SECRET = "YANTRA_CONNECTOR_TOKEN";
2
+ const AGENT_URL_SECRET = "YANTRA_AGENT_URL";
3
+ const APP_TOKEN_EXPIRY_SECONDS = 90 * 24 * 60 * 60;
4
+ function createAppSecretsAdapter(secrets) {
5
+ return {
6
+ listSecretNames: async ({
7
+ channelId
8
+ }) => {
9
+ const listed = await secrets.list(channelId);
10
+ if (!listed.ok) throw new Error(listed.message || "The project's secrets couldn't be read.");
11
+ return listed.value.names;
12
+ },
13
+ setSecrets: async ({
14
+ channelId
15
+ }, values) => {
16
+ const saved = await secrets.saveMany(channelId, values);
17
+ if (!saved.ok) throw new Error(saved.message);
18
+ if (!saved.value.credentialId) throw new Error("The app secrets could not be saved.");
19
+ return {
20
+ credentialId: saved.value.credentialId
21
+ };
22
+ }
23
+ };
24
+ }
25
+ const CREATE_APP_TOKEN_MUTATION = `mutation WebbuilderCreateAppToken($input: CreateSecretApiTokenInput!) {
26
+ createSecretApiToken(input: $input) { id name expiresAt isSystemToken }
27
+ }`;
28
+ const REVEAL_APP_TOKEN_MUTATION = `mutation WebbuilderRevealAppToken($id: ID!) {
29
+ revealSecretApiToken(id: $id)
30
+ }`;
31
+ const LIST_APP_TOKENS_QUERY = `query WebbuilderListAppTokens($projectId: ID!, $environmentTagId: ID!) {
32
+ listSecretApiTokens(projectId: $projectId, environmentTagId: $environmentTagId) { id name }
33
+ }`;
34
+ const REVOKE_APP_TOKEN_MUTATION = `mutation WebbuilderRevokeAppToken($id: ID!) {
35
+ revokeSecretApiToken(id: $id)
36
+ }`;
37
+ const CHANNEL_ID_RE = /^[A-Za-z0-9_-]{6,64}$/;
38
+ function appTokenName(channelId) {
39
+ const id = channelId.trim();
40
+ return CHANNEL_ID_RE.test(id) ? `webbuilder-app:${id}` : null;
41
+ }
42
+ function createAppTokenInput(channelId, scope) {
43
+ const name = appTokenName(channelId);
44
+ const orgName = ((scope == null ? void 0 : scope.orgName) || "").trim();
45
+ const projectId = ((scope == null ? void 0 : scope.projectId) || "").trim();
46
+ const environmentTagId = ((scope == null ? void 0 : scope.environmentTagId) || "").trim();
47
+ if (!name || !orgName || !projectId || !environmentTagId) return null;
48
+ return {
49
+ name,
50
+ projectId,
51
+ orgName,
52
+ environmentTagId,
53
+ isSystemToken: false,
54
+ expiryInSeconds: APP_TOKEN_EXPIRY_SECONDS
55
+ };
56
+ }
57
+ function appTokenStatusFromNames(names) {
58
+ if (!names) return "unavailable";
59
+ return names.includes(APP_TOKEN_SECRET) ? "present" : "missing";
60
+ }
61
+ const REVOKE_BY_HAND = "Revoke it under API tokens in your Yantra settings.";
62
+ async function mintAndStoreAppToken(deps) {
63
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
64
+ const input = createAppTokenInput(deps.channelId, deps.scope);
65
+ if (!input) return {
66
+ ok: false,
67
+ message: "Couldn't find your workspace to create the token in. Sign in again and retry."
68
+ };
69
+ const agentUrl = deps.agentUrl.trim().replace(/\/+$/, "");
70
+ if (!/^https:\/\/[^\s]+$/.test(agentUrl)) return {
71
+ ok: false,
72
+ message: "The Yantra agent address is not known here."
73
+ };
74
+ const revoke = async (id2) => {
75
+ var _a2, _b2;
76
+ try {
77
+ const r = await deps.gql(REVOKE_APP_TOKEN_MUTATION, {
78
+ id: id2
79
+ });
80
+ return !((_a2 = r.errors) == null ? void 0 : _a2.length) && ((_b2 = r.data) == null ? void 0 : _b2.revokeSecretApiToken) === true;
81
+ } catch (e) {
82
+ return false;
83
+ }
84
+ };
85
+ let earlier = null;
86
+ try {
87
+ const listed = await deps.gql(LIST_APP_TOKENS_QUERY, {
88
+ projectId: input.projectId,
89
+ environmentTagId: input.environmentTagId
90
+ });
91
+ if (!((_a = listed.errors) == null ? void 0 : _a.length) && Array.isArray((_b = listed.data) == null ? void 0 : _b.listSecretApiTokens)) {
92
+ earlier = listed.data.listSecretApiTokens.filter((t) => t && t.name === input.name && typeof t.id === "string" && t.id).map((t) => String(t == null ? void 0 : t.id));
93
+ }
94
+ } catch (e) {
95
+ earlier = null;
96
+ }
97
+ const created = await deps.gql(CREATE_APP_TOKEN_MUTATION, {
98
+ input
99
+ });
100
+ const id = (_d = (_c = created.data) == null ? void 0 : _c.createSecretApiToken) == null ? void 0 : _d.id;
101
+ if (((_e = created.errors) == null ? void 0 : _e.length) || !id) {
102
+ return {
103
+ ok: false,
104
+ message: ((_g = (_f = created.errors) == null ? void 0 : _f[0]) == null ? void 0 : _g.message) || "The token couldn't be created."
105
+ };
106
+ }
107
+ const revealed = await deps.gql(REVEAL_APP_TOKEN_MUTATION, {
108
+ id
109
+ });
110
+ const token = (_h = revealed.data) == null ? void 0 : _h.revealSecretApiToken;
111
+ if (((_i = revealed.errors) == null ? void 0 : _i.length) || !token) {
112
+ const gone = await revoke(id);
113
+ const why = ((_k = (_j = revealed.errors) == null ? void 0 : _j[0]) == null ? void 0 : _k.message) || "The new token couldn't be read.";
114
+ return {
115
+ ok: false,
116
+ message: gone ? why : `${why} The new token could not be revoked either. ${REVOKE_BY_HAND}`
117
+ };
118
+ }
119
+ let credentialId;
120
+ try {
121
+ ({
122
+ credentialId
123
+ } = await deps.secrets.setSecrets({
124
+ channelId: deps.channelId,
125
+ projectId: deps.projectId
126
+ }, {
127
+ [APP_TOKEN_SECRET]: token,
128
+ [AGENT_URL_SECRET]: agentUrl
129
+ }));
130
+ } catch (e) {
131
+ const why = e instanceof Error ? e.message : String(e);
132
+ const gone = await revoke(id);
133
+ return {
134
+ ok: false,
135
+ message: gone ? `The token couldn't be saved to the project's secrets, so it was revoked: ${why}` : `The token couldn't be saved to the project's secrets (${why}), and revoking it failed. ${REVOKE_BY_HAND}`
136
+ };
137
+ }
138
+ const old = (earlier != null ? earlier : []).filter((x) => x !== id);
139
+ let failed = 0;
140
+ for (const oldId of old) {
141
+ if (!await revoke(oldId)) failed++;
142
+ }
143
+ const replaced = old.length - failed;
144
+ if (earlier === null) {
145
+ return {
146
+ ok: true,
147
+ credentialId,
148
+ replaced,
149
+ warning: `The new token is saved, but earlier app tokens for this project couldn't be checked and may still be active. ${REVOKE_BY_HAND}`
150
+ };
151
+ }
152
+ if (failed) {
153
+ return {
154
+ ok: true,
155
+ credentialId,
156
+ replaced,
157
+ warning: `The new token is saved, but ${failed === 1 ? "an earlier app token" : `${failed} earlier app tokens`} for this project couldn't be revoked and ${failed === 1 ? "is" : "are"} still active. ${REVOKE_BY_HAND}`
158
+ };
159
+ }
160
+ return {
161
+ ok: true,
162
+ credentialId,
163
+ replaced
164
+ };
165
+ }export{AGENT_URL_SECRET,APP_TOKEN_EXPIRY_SECONDS,APP_TOKEN_SECRET,CREATE_APP_TOKEN_MUTATION,LIST_APP_TOKENS_QUERY,REVEAL_APP_TOKEN_MUTATION,REVOKE_APP_TOKEN_MUTATION,appTokenName,appTokenStatusFromNames,createAppSecretsAdapter,createAppTokenInput,mintAndStoreAppToken};//# sourceMappingURL=appToken.js.map