@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.
- package/lib/components/CustomDrawer.js +70 -3
- package/lib/components/CustomDrawer.js.map +1 -1
- package/lib/compute.js +3 -1
- package/lib/config/env-config.js +4 -0
- package/lib/config/env-config.js.map +1 -1
- package/lib/features/credits/credits.js +151 -0
- package/lib/features/credits/credits.js.map +1 -0
- package/lib/features/credits/useLlmCredits.js +87 -0
- package/lib/features/credits/useLlmCredits.js.map +1 -0
- package/lib/features/design/surface/agentWriter.js +39 -0
- package/lib/features/design/surface/agentWriter.js.map +1 -0
- package/lib/features/design/surface/brandKit.js +9 -3
- package/lib/features/design/surface/brandKit.js.map +1 -1
- package/lib/features/design/surface/useBrandKitInUse.js.map +1 -1
- package/lib/features/design/surface/useDesignSurface.js +5 -39
- package/lib/features/design/surface/useDesignSurface.js.map +1 -1
- package/lib/features/webbuilder/WebBuilderExperience.js +64 -23
- package/lib/features/webbuilder/WebBuilderExperience.js.map +1 -1
- package/lib/features/webbuilder/brandKitMove.js +52 -0
- package/lib/features/webbuilder/brandKitMove.js.map +1 -0
- package/lib/features/webbuilder/codeToolbox.js +129 -0
- package/lib/features/webbuilder/codeToolbox.js.map +1 -0
- package/lib/features/webbuilder/components/CloudSheet.js +1451 -0
- package/lib/features/webbuilder/components/CloudSheet.js.map +1 -0
- package/lib/features/webbuilder/components/CodeActionsSheet.js +125 -0
- package/lib/features/webbuilder/components/CodeActionsSheet.js.map +1 -0
- package/lib/features/webbuilder/components/CodeView.js +10 -3
- package/lib/features/webbuilder/components/CodeView.js.map +1 -1
- package/lib/features/webbuilder/components/Composer.js.map +1 -1
- package/lib/features/webbuilder/components/IntegrationsPanel.js +643 -0
- package/lib/features/webbuilder/components/IntegrationsPanel.js.map +1 -0
- package/lib/features/webbuilder/components/ProjectChat.js +57 -44
- package/lib/features/webbuilder/components/ProjectChat.js.map +1 -1
- package/lib/features/webbuilder/components/SecretsSheet.js +235 -0
- package/lib/features/webbuilder/components/SecretsSheet.js.map +1 -0
- package/lib/features/webbuilder/components/StudioHome.js +38 -1
- package/lib/features/webbuilder/components/StudioHome.js.map +1 -1
- package/lib/features/webbuilder/studioCatalog.js +4 -19
- package/lib/features/webbuilder/studioCatalog.js.map +1 -1
- package/lib/features/webbuilder/web/data/cloud.js +387 -0
- package/lib/features/webbuilder/web/data/cloud.js.map +1 -0
- package/lib/features/webbuilder/web/data/dataApi.js +227 -0
- package/lib/features/webbuilder/web/data/dataApi.js.map +1 -0
- package/lib/features/webbuilder/web/data/database.js +190 -0
- package/lib/features/webbuilder/web/data/database.js.map +1 -0
- package/lib/features/webbuilder/web/data/graphql.js +95 -0
- package/lib/features/webbuilder/web/data/graphql.js.map +1 -0
- package/lib/features/webbuilder/web/design/directions.js +343 -0
- package/lib/features/webbuilder/web/design/directions.js.map +1 -0
- package/lib/features/webbuilder/web/integrations/appToken.js +165 -0
- package/lib/features/webbuilder/web/integrations/appToken.js.map +1 -0
- package/lib/features/webbuilder/web/integrations/catalog.js +238 -0
- package/lib/features/webbuilder/web/integrations/catalog.js.map +1 -0
- package/lib/features/webbuilder/web/integrations/siteBilling.js +67 -0
- package/lib/features/webbuilder/web/integrations/siteBilling.js.map +1 -0
- package/lib/features/webbuilder/web/integrations/siteMail.js +190 -0
- package/lib/features/webbuilder/web/integrations/siteMail.js.map +1 -0
- package/lib/features/webbuilder/web/project/projectSettings.js +11 -0
- package/lib/features/webbuilder/web/project/projectSettings.js.map +1 -0
- package/lib/features/webbuilder/web/project/restorePoint.js +16 -0
- package/lib/features/webbuilder/web/project/restorePoint.js.map +1 -0
- package/lib/features/webbuilder/web/project/serverSettings.js +157 -0
- package/lib/features/webbuilder/web/project/serverSettings.js.map +1 -0
- package/lib/features/webbuilder/web/secrets/secrets.js +162 -0
- package/lib/features/webbuilder/web/secrets/secrets.js.map +1 -0
- package/lib/features/webbuilder/web/secrets/secretsApi.js +302 -0
- package/lib/features/webbuilder/web/secrets/secretsApi.js.map +1 -0
- package/lib/features/webbuilder/web/secrets/secretsStore.js +39 -0
- package/lib/features/webbuilder/web/secrets/secretsStore.js.map +1 -0
- package/lib/features/webbuilder/web/sharing/okResult.js +40 -0
- package/lib/features/webbuilder/web/sharing/okResult.js.map +1 -0
- package/lib/features/webbuilder/web/sharing/roles.js +3 -0
- package/lib/features/webbuilder/web/sharing/roles.js.map +1 -0
- package/lib/features/webbuilder/web/state/storageKeys.js +59 -0
- package/lib/features/webbuilder/web/state/storageKeys.js.map +1 -0
- package/lib/features/webbuilder/web/webServices.js +282 -0
- package/lib/features/webbuilder/web/webServices.js.map +1 -0
- package/lib/features/webbuilder/workflow.js +1 -1
- package/lib/features/webbuilder/workflow.js.map +1 -1
- package/lib/routes.json +3 -1
- package/lib/screens/Account/AccountSheets.js +1049 -0
- package/lib/screens/Account/AccountSheets.js.map +1 -0
- package/lib/screens/Account/WorkspaceSection.js +271 -0
- package/lib/screens/Account/WorkspaceSection.js.map +1 -0
- package/lib/screens/Account/accountRules.js +103 -0
- package/lib/screens/Account/accountRules.js.map +1 -0
- package/lib/screens/Account/index.js +563 -259
- package/lib/screens/Account/index.js.map +1 -1
- package/lib/screens/Account/useAccountPreferences.js +87 -0
- package/lib/screens/Account/useAccountPreferences.js.map +1 -0
- package/lib/screens/WebBuilderNative/index.js +1 -1
- package/lib/screens/WebBuilderNative/index.js.map +1 -1
- package/lib/screens/WebBuilderNative/useWebBuilderHost.js +122 -12
- package/lib/screens/WebBuilderNative/useWebBuilderHost.js.map +1 -1
- package/lib/utils/authUserDisplay.js +1 -9
- package/lib/utils/authUserDisplay.js.map +1 -1
- package/package.json +4 -4
- package/lib/features/webbuilder/brandKitStorage.js +0 -69
- package/lib/features/webbuilder/brandKitStorage.js.map +0 -1
- package/lib/features/webbuilder/components/BrandKitSheet.js +0 -197
- package/lib/features/webbuilder/components/BrandKitSheet.js.map +0 -1
- package/lib/screens/Account/splitDisplayName.js +0 -15
- package/lib/screens/Account/splitDisplayName.js.map +0 -1
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __defProps = Object.defineProperties;
|
|
3
|
+
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
4
|
+
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
7
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
8
|
+
var __spreadValues = (a, b) => {
|
|
9
|
+
for (var prop in b || (b = {}))
|
|
10
|
+
if (__hasOwnProp.call(b, prop))
|
|
11
|
+
__defNormalProp(a, prop, b[prop]);
|
|
12
|
+
if (__getOwnPropSymbols)
|
|
13
|
+
for (var prop of __getOwnPropSymbols(b)) {
|
|
14
|
+
if (__propIsEnum.call(b, prop))
|
|
15
|
+
__defNormalProp(a, prop, b[prop]);
|
|
16
|
+
}
|
|
17
|
+
return a;
|
|
18
|
+
};
|
|
19
|
+
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
|
20
|
+
const CREDITS_PER_USD = 1e3;
|
|
21
|
+
let reportedCreditsPerUsd = null;
|
|
22
|
+
function rememberCreditsPerUsd(rate, now = Date.now()) {
|
|
23
|
+
if (typeof rate === "number" && Number.isFinite(rate) && rate > 0) {
|
|
24
|
+
reportedCreditsPerUsd = rate;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
const creditsPerUsdNow = () => reportedCreditsPerUsd != null ? reportedCreditsPerUsd : CREDITS_PER_USD;
|
|
28
|
+
const toCredits = (usd, creditsPerUsd = creditsPerUsdNow()) => Math.round(Math.max(0, usd) * creditsPerUsd);
|
|
29
|
+
const HOUR_MS = 36e5;
|
|
30
|
+
const DAY_MS = 24 * HOUR_MS;
|
|
31
|
+
function formatReset(resetAt, now = Date.now()) {
|
|
32
|
+
if (!resetAt) return null;
|
|
33
|
+
const d = new Date(resetAt);
|
|
34
|
+
if (Number.isNaN(d.getTime())) return null;
|
|
35
|
+
const ms = d.getTime() - now;
|
|
36
|
+
if (ms <= 0) return "Your free credits refresh shortly.";
|
|
37
|
+
const hours = Math.round(ms / HOUR_MS);
|
|
38
|
+
if (hours < 1) {
|
|
39
|
+
const mins = Math.max(1, Math.round(ms / 6e4));
|
|
40
|
+
return `Refreshes in about ${mins} minute${mins === 1 ? "" : "s"}.`;
|
|
41
|
+
}
|
|
42
|
+
if (hours < 24) return `Refreshes in about ${hours} hour${hours === 1 ? "" : "s"}.`;
|
|
43
|
+
const days = Math.round(hours / 24);
|
|
44
|
+
if (days <= 1) return "Refreshes tomorrow.";
|
|
45
|
+
return `Refreshes on ${d.toLocaleDateString(void 0, {
|
|
46
|
+
month: "short",
|
|
47
|
+
day: "numeric"
|
|
48
|
+
})}.`;
|
|
49
|
+
}
|
|
50
|
+
const DAY_WINDOW_MAX_MS = DAY_MS + 6e4;
|
|
51
|
+
function instantOf(iso) {
|
|
52
|
+
if (!iso) return null;
|
|
53
|
+
const t = new Date(iso).getTime();
|
|
54
|
+
return Number.isNaN(t) ? null : t;
|
|
55
|
+
}
|
|
56
|
+
function boundsOf(window) {
|
|
57
|
+
const start = instantOf(window == null ? void 0 : window.periodStart);
|
|
58
|
+
const end = instantOf(window == null ? void 0 : window.resetAt);
|
|
59
|
+
return start !== null && end !== null && end > start ? {
|
|
60
|
+
start,
|
|
61
|
+
end
|
|
62
|
+
} : null;
|
|
63
|
+
}
|
|
64
|
+
function periodOfSpan({
|
|
65
|
+
start,
|
|
66
|
+
end
|
|
67
|
+
}) {
|
|
68
|
+
if (end - start <= DAY_WINDOW_MAX_MS) return "today";
|
|
69
|
+
const from = new Date(start);
|
|
70
|
+
const oneUtcMonth = start === Date.UTC(from.getUTCFullYear(), from.getUTCMonth(), 1) && end === Date.UTC(from.getUTCFullYear(), from.getUTCMonth() + 1, 1);
|
|
71
|
+
return oneUtcMonth ? "this month" : "this period";
|
|
72
|
+
}
|
|
73
|
+
function periodOfReset(resetAt, now) {
|
|
74
|
+
if (!resetAt) return "this period";
|
|
75
|
+
const t = new Date(resetAt).getTime();
|
|
76
|
+
if (Number.isNaN(t)) return "this period";
|
|
77
|
+
const d = new Date(t);
|
|
78
|
+
const utcMidnight = d.getUTCHours() === 0 && d.getUTCMinutes() === 0 && d.getUTCSeconds() === 0 && d.getUTCMilliseconds() === 0;
|
|
79
|
+
if (!utcMidnight) return "this period";
|
|
80
|
+
if (t - now <= DAY_MS) return "today";
|
|
81
|
+
return d.getUTCDate() === 1 ? "this month" : "this period";
|
|
82
|
+
}
|
|
83
|
+
function periodOf(window, now) {
|
|
84
|
+
const bounds = boundsOf(window);
|
|
85
|
+
return bounds ? periodOfSpan(bounds) : periodOfReset(window == null ? void 0 : window.resetAt, now);
|
|
86
|
+
}
|
|
87
|
+
function withWindowStart(verdict, window) {
|
|
88
|
+
if (!verdict || !(window == null ? void 0 : window.periodStart)) return verdict;
|
|
89
|
+
const end = instantOf(window.resetAt);
|
|
90
|
+
return end !== null && end === instantOf(verdict.resetAt) ? __spreadProps(__spreadValues({}, verdict), {
|
|
91
|
+
periodStart: window.periodStart
|
|
92
|
+
}) : verdict;
|
|
93
|
+
}
|
|
94
|
+
const toPackCredits = (usd, creditsPerUsd) => Math.floor(Math.max(0, usd != null ? usd : 0) * creditsPerUsd + 1e-6);
|
|
95
|
+
function creditsSummary(verdict, now = Date.now(), packRemainingUsd = null, creditsPerUsd = creditsPerUsdNow()) {
|
|
96
|
+
var _a, _b;
|
|
97
|
+
const includedUsd = (_a = verdict == null ? void 0 : verdict.includedUsd) != null ? _a : 0;
|
|
98
|
+
const packCredits = toPackCredits(packRemainingUsd, creditsPerUsd);
|
|
99
|
+
const packLine = packCredits > 0 ? `${packCredits.toLocaleString()} pack credits left, which never expire.` : "";
|
|
100
|
+
if (includedUsd <= 0) {
|
|
101
|
+
if (packCredits <= 0) return null;
|
|
102
|
+
return {
|
|
103
|
+
total: 0,
|
|
104
|
+
used: 0,
|
|
105
|
+
remaining: 0,
|
|
106
|
+
packCredits,
|
|
107
|
+
available: packCredits,
|
|
108
|
+
pct: 0,
|
|
109
|
+
creditsPerUsd,
|
|
110
|
+
period: "this period",
|
|
111
|
+
resetText: null,
|
|
112
|
+
short: `${packCredits.toLocaleString()} pack credits left`,
|
|
113
|
+
long: packLine
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
const total = toCredits(includedUsd, creditsPerUsd);
|
|
117
|
+
const remaining = Math.min(total, toCredits((_b = verdict == null ? void 0 : verdict.remainingUsd) != null ? _b : 0, creditsPerUsd));
|
|
118
|
+
const used = total - remaining;
|
|
119
|
+
const pct = Math.min(100, Math.round(used / total * 100));
|
|
120
|
+
const period = periodOf(verdict, now);
|
|
121
|
+
const resetText = formatReset(verdict == null ? void 0 : verdict.resetAt, now);
|
|
122
|
+
const available = remaining + packCredits;
|
|
123
|
+
return {
|
|
124
|
+
total,
|
|
125
|
+
used,
|
|
126
|
+
remaining,
|
|
127
|
+
packCredits,
|
|
128
|
+
available,
|
|
129
|
+
pct,
|
|
130
|
+
creditsPerUsd,
|
|
131
|
+
period,
|
|
132
|
+
resetText,
|
|
133
|
+
short: packCredits > 0 ? `${available.toLocaleString()} left` : `${remaining.toLocaleString()} left ${period}`,
|
|
134
|
+
long: `${used.toLocaleString()} of ${total.toLocaleString()} credits used ${period}.${resetText ? ` ${resetText}` : ""}${packLine ? ` ${packLine}` : ""}`
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
function creditsLeftLabel(count) {
|
|
138
|
+
const credits = Math.max(0, Math.floor(count));
|
|
139
|
+
return `${credits.toLocaleString()} ${credits === 1 ? "credit" : "credits"} left`;
|
|
140
|
+
}
|
|
141
|
+
const LOW_CREDITS_PCT = 80;
|
|
142
|
+
function creditsLine(summary) {
|
|
143
|
+
const packs = summary.packCredits > 0;
|
|
144
|
+
return {
|
|
145
|
+
label: creditsLeftLabel(summary.available),
|
|
146
|
+
left: !packs && summary.total > 0 ? Math.min(1, Math.max(0, summary.remaining / summary.total)) : null,
|
|
147
|
+
low: summary.available <= 0 || !packs && summary.pct >= LOW_CREDITS_PCT,
|
|
148
|
+
detail: summary.long
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
const meterWidth = (left) => left > 0 ? Math.max(3, left * 100) : 0;export{CREDITS_PER_USD,LOW_CREDITS_PCT,creditsLeftLabel,creditsLine,creditsPerUsdNow,creditsSummary,formatReset,meterWidth,rememberCreditsPerUsd,toCredits,withWindowStart};//# sourceMappingURL=credits.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"credits.js","sources":["../../../src/features/credits/credits.ts"],"sourcesContent":["/**\n * The web's credits arithmetic (account/browser features/chat/credits.ts) and its sidebar footer's\n * line (features/chat/sidebar/sidebarModel.ts `creditsLine`), so the phone words the same verdict\n * the same way.\n *\n * The backend accounts allowance in USD; the product speaks in credits at the rate the\n * backend reports (`creditRate.creditsPerUsd`, MODEL_CREDITS_PER_USD_MONTH in\n * billing-api-server): 1,000 / $1 since 2026-10-29, 500 / $1 before its switch migration ran.\n */\nexport const CREDITS_PER_USD = 1_000;\n\n/** The last rate the backend reported, and when; every surface converts with it once one has been read. */\nlet reportedCreditsPerUsd: number | null = null;\nlet reportedAt = 0;\n/** When a read last brought back no rate. */\nlet failedAt = Number.NEGATIVE_INFINITY;\n\n/** The rate changes once (the 2026-10-29 switch), so a reported one is re-read only this often. */\nexport const CREDITS_RATE_REREAD_MS = 10 * 60_000;\n\n/** A read that brought back no rate (the network, a failing backend) is not repeated for this long. */\nexport const CREDITS_RATE_RETRY_MS = 60_000;\n\n/** Keeps the rate the backend reported; a read without one (not a positive number) is noted as failed. */\nexport function rememberCreditsPerUsd(rate: number | null | undefined, now: number = Date.now()): void {\n if (typeof rate === 'number' && Number.isFinite(rate) && rate > 0) {\n reportedCreditsPerUsd = rate;\n reportedAt = now;\n failedAt = Number.NEGATIVE_INFINITY;\n } else {\n failedAt = now;\n }\n}\n\n/** Whether the backend's rate was read recently enough, or failed recently enough, not to ask again. */\nexport const creditsPerUsdIsFresh = (now: number = Date.now()): boolean =>\n (reportedCreditsPerUsd !== null && now - reportedAt < CREDITS_RATE_REREAD_MS) ||\n now - failedAt < CREDITS_RATE_RETRY_MS;\n\n/** Credits per $1 to convert with: the backend's rate once read, else {@link CREDITS_PER_USD}. */\nexport const creditsPerUsdNow = (): number => reportedCreditsPerUsd ?? CREDITS_PER_USD;\n\nexport const toCredits = (usd: number, creditsPerUsd: number = creditsPerUsdNow()): number =>\n Math.round(Math.max(0, usd) * creditsPerUsd);\n\n/** The slice of a checkLLMSpend verdict the credit displays read. */\nexport interface CreditsVerdict {\n includedUsd?: number | null;\n remainingUsd?: number | null;\n resetAt?: string | null;\n /**\n * When the window began (checkLLMSpend.periodStart, read apart from the verdict: see\n * withWindowStart). With resetAt it names the window; without it the reset alone does.\n */\n periodStart?: string | null;\n}\n\nexport type CreditsPeriod = 'today' | 'this month' | 'this period';\n\nexport interface CreditsSummary {\n /** The plan's credits for the period (0 when it includes none). */\n total: number;\n used: number;\n remaining: number;\n /** Credit pack credits left: they never expire and are spent after the plan's credits. */\n packCredits: number;\n /** Everything that can still be spent: the plan's credits left plus the packs. */\n available: number;\n /** Whole percent of the allowance used, 0-100. */\n pct: number;\n /** Credits per $1 the figures are in (the backend's rate): \"1,000 credits = $1\". */\n creditsPerUsd: number;\n period: CreditsPeriod;\n /** \"Refreshes in about 5 hours.\" - null when the verdict carries no reset. */\n resetText: string | null;\n /** Chip label: \"1,000 left today\". */\n short: string;\n /** Tooltip / subtitle: \"0 of 1,000 credits used today. Refreshes in about 5 hours.\" */\n long: string;\n}\n\nconst HOUR_MS = 3_600_000;\nconst DAY_MS = 24 * HOUR_MS;\n\n/** Human \"refreshes in…\" line from the reset timestamp; null when unknown. */\nexport function formatReset(resetAt?: string | null, now: number = Date.now()): string | null {\n if (!resetAt) return null;\n const d = new Date(resetAt);\n if (Number.isNaN(d.getTime())) return null;\n const ms = d.getTime() - now;\n if (ms <= 0) return 'Your free credits refresh shortly.';\n const hours = Math.round(ms / HOUR_MS);\n if (hours < 1) {\n const mins = Math.max(1, Math.round(ms / 60_000));\n return `Refreshes in about ${mins} minute${mins === 1 ? '' : 's'}.`;\n }\n if (hours < 24) return `Refreshes in about ${hours} hour${hours === 1 ? '' : 's'}.`;\n const days = Math.round(hours / 24);\n if (days <= 1) return 'Refreshes tomorrow.';\n return `Refreshes on ${d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })}.`;\n}\n\n/** The window a credit allowance is counted over, as checkLLMSpend reports it. */\nexport interface CreditWindow {\n periodStart?: string | null;\n resetAt?: string | null;\n}\n\n/** The longest window named \"today\": a day, with a minute to spare. */\nconst DAY_WINDOW_MAX_MS = DAY_MS + 60_000;\n\n/** The instant an ISO timestamp names; null when it is missing or unreadable. */\nfunction instantOf(iso: string | null | undefined): number | null {\n if (!iso) return null;\n const t = new Date(iso).getTime();\n return Number.isNaN(t) ? null : t;\n}\n\n/**\n * A window's start and end (epoch ms); null without both, with an unreadable one, or when it\n * does not end after it starts.\n */\nfunction boundsOf(window: CreditWindow | null | undefined): { start: number; end: number } | null {\n const start = instantOf(window?.periodStart);\n const end = instantOf(window?.resetAt);\n return start !== null && end !== null && end > start ? { start, end } : null;\n}\n\n/**\n * Which window the allowance belongs to, named from its span, never from the time left in it:\n * the free daily drip is a UTC day, \"today\"; the free monthly pot a UTC calendar month, \"this\n * month\", on its last day too, when it refills within hours as a day's would; anything else\n * \"this period\" - a paid plan's billing period, or the month of a yearly plan's term, which run\n * from the second the subscription started, the last day included.\n */\nfunction periodOfSpan({ start, end }: { start: number; end: number }): CreditsPeriod {\n if (end - start <= DAY_WINDOW_MAX_MS) return 'today';\n const from = new Date(start);\n const oneUtcMonth =\n start === Date.UTC(from.getUTCFullYear(), from.getUTCMonth(), 1) &&\n end === Date.UTC(from.getUTCFullYear(), from.getUTCMonth() + 1, 1);\n return oneUtcMonth ? 'this month' : 'this period';\n}\n\n/**\n * Which window the allowance belongs to, read off the reset instant alone, for a backend that\n * does not send the window's start: the free daily drip resets at the next UTC midnight (under\n * a day away), the free monthly cap on the first of next month, and a paid plan at its billing\n * period end (a yearly plan's at the end of the month of its term) - the second its\n * subscription started, so a paid plan's last day is still \"this period\", not \"today\". The\n * monthly cap's last day reads \"today\" here: its reset is as near as a day's.\n */\nfunction periodOfReset(resetAt: string | null | undefined, now: number): CreditsPeriod {\n if (!resetAt) return 'this period';\n const t = new Date(resetAt).getTime();\n if (Number.isNaN(t)) return 'this period';\n const d = new Date(t);\n const utcMidnight =\n d.getUTCHours() === 0 && d.getUTCMinutes() === 0 && d.getUTCSeconds() === 0 && d.getUTCMilliseconds() === 0;\n if (!utcMidnight) return 'this period';\n if (t - now <= DAY_MS) return 'today';\n return d.getUTCDate() === 1 ? 'this month' : 'this period';\n}\n\n/** The window's word: from its span when the backend names its start, else from its reset alone. */\nfunction periodOf(window: CreditWindow | null | undefined, now: number): CreditsPeriod {\n const bounds = boundsOf(window);\n return bounds ? periodOfSpan(bounds) : periodOfReset(window?.resetAt, now);\n}\n\n/**\n * The verdict with the start of its window, which is read apart from it (checkLLMSpend\n * { periodStart resetAt }: a backend that predates periodStart rejects the field, and that must\n * never cost the verdict). Only when that window ends where the verdict resets, so the two always\n * describe one window: a verdict and a window read either side of a reset are never paired.\n * Otherwise the verdict as it is, named from its reset alone.\n */\nexport function withWindowStart(\n verdict: CreditsVerdict | null,\n window: CreditWindow | null | undefined,\n): CreditsVerdict | null {\n if (!verdict || !window?.periodStart) return verdict;\n const end = instantOf(window.resetAt);\n return end !== null && end === instantOf(verdict.resetAt)\n ? { ...verdict, periodStart: window.periodStart }\n : verdict;\n}\n\n/** The span the Usage page reports spend over. */\nexport interface UsageWindow {\n start: Date;\n end: Date;\n /** True when this is the AI-credit window, so spend can be measured against the allowance. */\n creditPeriod: boolean;\n}\n\nfunction calendarMonth(now: Date): UsageWindow {\n return {\n start: new Date(now.getFullYear(), now.getMonth(), 1),\n end: new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999),\n creditPeriod: false,\n };\n}\n\n/**\n * The window the Usage page reports on: the AI-credit window when the backend names one\n * longer than a day - a paid plan's billing period, the month of a yearly plan's term, the\n * free tier's month - so the page's spend and its budget describe the same span as the\n * allowance (a plan billed from the 9th showed calendar-month spend of $49.60 against a $10\n * allowance whose period began that day). Otherwise the calendar month: a daily free-tier\n * window (the one the credits are \"today\" in) is too short to report history on, and an\n * older backend does not name the window at all.\n */\nexport function usageWindow(window: CreditWindow | null | undefined, now: Date = new Date()): UsageWindow {\n const bounds = boundsOf(window);\n if (bounds && periodOfSpan(bounds) !== 'today') {\n return { start: new Date(bounds.start), end: new Date(bounds.end), creditPeriod: true };\n }\n return calendarMonth(now);\n}\n\n/** Pack credits from USD, floored so a balance never shows a credit it cannot pay for. */\nconst toPackCredits = (usd: number | null | undefined, creditsPerUsd: number): number =>\n Math.floor(Math.max(0, usd ?? 0) * creditsPerUsd + 1e-6);\n\n/**\n * Credits view of a verdict and the credit pack balance, or null when there is nothing to\n * spend from at all - no allowance and no packs - which is the out-of-credits dialog's case,\n * not a meter's.\n */\nexport function creditsSummary(\n verdict: CreditsVerdict | null | undefined,\n now: number = Date.now(),\n packRemainingUsd: number | null = null,\n creditsPerUsd: number = creditsPerUsdNow(),\n): CreditsSummary | null {\n const includedUsd = verdict?.includedUsd ?? 0;\n const packCredits = toPackCredits(packRemainingUsd, creditsPerUsd);\n const packLine = packCredits > 0 ? `${packCredits.toLocaleString()} pack credits left, which never expire.` : '';\n\n if (includedUsd <= 0) {\n if (packCredits <= 0) return null;\n return {\n total: 0,\n used: 0,\n remaining: 0,\n packCredits,\n available: packCredits,\n pct: 0,\n creditsPerUsd,\n period: 'this period',\n resetText: null,\n short: `${packCredits.toLocaleString()} pack credits left`,\n long: packLine,\n };\n }\n\n const total = toCredits(includedUsd, creditsPerUsd);\n const remaining = Math.min(total, toCredits(verdict?.remainingUsd ?? 0, creditsPerUsd));\n const used = total - remaining;\n const pct = Math.min(100, Math.round((used / total) * 100));\n const period = periodOf(verdict, now);\n const resetText = formatReset(verdict?.resetAt, now);\n const available = remaining + packCredits;\n\n return {\n total,\n used,\n remaining,\n packCredits,\n available,\n pct,\n creditsPerUsd,\n period,\n resetText,\n short: packCredits > 0 ? `${available.toLocaleString()} left` : `${remaining.toLocaleString()} left ${period}`,\n long: `${used.toLocaleString()} of ${total.toLocaleString()} credits used ${period}.${resetText ? ` ${resetText}` : ''}${packLine ? ` ${packLine}` : ''}`,\n };\n}\n\n/** \"1 credit left\", \"1,250 credits left\". */\nexport function creditsLeftLabel(count: number): string {\n const credits = Math.max(0, Math.floor(count));\n return `${credits.toLocaleString()} ${credits === 1 ? 'credit' : 'credits'} left`;\n}\n\n/** Used from here on, credits are running low: the Usage page's amber line. */\nexport const LOW_CREDITS_PCT = 80;\n\nexport interface CreditsLine {\n /** \"1 credit left\": everything that can still be spent, the plan's and the packs'. */\n label: string;\n /** Share of the plan's credits still left, 0-1, for the meter. Null with packs on hand, or a plan with none. */\n left: number | null;\n /** Nothing left, or most of the plan's credits used with no packs behind them: \"Top up\" shows. */\n low: boolean;\n /** \"980 of 1,000 credits used today. Refreshes in about 5 hours.\" */\n detail: string;\n}\n\nexport function creditsLine(summary: CreditsSummary): CreditsLine {\n const packs = summary.packCredits > 0;\n return {\n label: creditsLeftLabel(summary.available),\n left: !packs && summary.total > 0 ? Math.min(1, Math.max(0, summary.remaining / summary.total)) : null,\n low: summary.available <= 0 || (!packs && summary.pct >= LOW_CREDITS_PCT),\n detail: summary.long,\n };\n}\n\n/** The meter never draws a sliver too thin to see while anything is left. */\nexport const meterWidth = (left: number) => (left > 0 ? Math.max(3, left * 100) : 0);\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AASO,MAAM,eAAkB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I,KAAK,GAAI,CAAA,CAAA,EAAG,IAAO,GAAA,GAAG,CAAI,GAAA"}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import {useState,useCallback,useEffect,useMemo}from'react';import {gql,useApolloClient}from'@apollo/client/index.js';import {creditsPerUsdNow,rememberCreditsPerUsd,creditsSummary,withWindowStart}from'./credits.js';const CHECK_LLM_SPEND = gql`
|
|
2
|
+
query CheckLLMSpend {
|
|
3
|
+
checkLLMSpend {
|
|
4
|
+
allowed
|
|
5
|
+
state
|
|
6
|
+
reason
|
|
7
|
+
remainingUsd
|
|
8
|
+
paygRemainingUsd
|
|
9
|
+
availableUsd
|
|
10
|
+
includedUsd
|
|
11
|
+
resetAt
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
`;
|
|
15
|
+
const CHECK_LLM_CREDIT_WINDOW = gql`
|
|
16
|
+
query CheckLLMCreditWindow {
|
|
17
|
+
checkLLMSpend {
|
|
18
|
+
periodStart
|
|
19
|
+
resetAt
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
`;
|
|
23
|
+
const CHECK_LLM_PACK_CREDITS = gql`
|
|
24
|
+
query CheckLLMPackCredits {
|
|
25
|
+
checkLLMSpend {
|
|
26
|
+
packRemainingUsd
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
`;
|
|
30
|
+
const CREDIT_RATE = gql`
|
|
31
|
+
query CreditRate {
|
|
32
|
+
creditRate {
|
|
33
|
+
creditsPerUsd
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
`;
|
|
37
|
+
const CREDITS_REFRESH_INTERVAL_MS = 5 * 6e4;
|
|
38
|
+
function useLlmCredits({
|
|
39
|
+
orgName,
|
|
40
|
+
enabled
|
|
41
|
+
}) {
|
|
42
|
+
const client = useApolloClient();
|
|
43
|
+
const [verdict, setVerdict] = useState(null);
|
|
44
|
+
const [window, setWindow] = useState(null);
|
|
45
|
+
const [packRemainingUsd, setPackRemainingUsd] = useState(null);
|
|
46
|
+
const [creditsPerUsd, setCreditsPerUsd] = useState(creditsPerUsdNow);
|
|
47
|
+
const refresh = useCallback(() => {
|
|
48
|
+
if (!orgName) return;
|
|
49
|
+
const read = (query) => client.query({
|
|
50
|
+
query,
|
|
51
|
+
context: {
|
|
52
|
+
headers: {
|
|
53
|
+
orgname: orgName
|
|
54
|
+
}
|
|
55
|
+
},
|
|
56
|
+
fetchPolicy: "network-only"
|
|
57
|
+
}).then((result) => result.data).catch(() => null);
|
|
58
|
+
void read(CHECK_LLM_SPEND).then((data) => {
|
|
59
|
+
if (data == null ? void 0 : data.checkLLMSpend) setVerdict(data.checkLLMSpend);
|
|
60
|
+
});
|
|
61
|
+
void read(CHECK_LLM_CREDIT_WINDOW).then((data) => {
|
|
62
|
+
if (data == null ? void 0 : data.checkLLMSpend) setWindow(data.checkLLMSpend);
|
|
63
|
+
});
|
|
64
|
+
void read(CHECK_LLM_PACK_CREDITS).then((data) => {
|
|
65
|
+
var _a;
|
|
66
|
+
const value = (_a = data == null ? void 0 : data.checkLLMSpend) == null ? void 0 : _a.packRemainingUsd;
|
|
67
|
+
if (typeof value === "number" && Number.isFinite(value)) setPackRemainingUsd(value);
|
|
68
|
+
});
|
|
69
|
+
void read(CREDIT_RATE).then((data) => {
|
|
70
|
+
var _a;
|
|
71
|
+
const rate = (_a = data == null ? void 0 : data.creditRate) == null ? void 0 : _a.creditsPerUsd;
|
|
72
|
+
rememberCreditsPerUsd(rate);
|
|
73
|
+
if (typeof rate === "number" && rate > 0) setCreditsPerUsd(rate);
|
|
74
|
+
});
|
|
75
|
+
}, [client, orgName]);
|
|
76
|
+
useEffect(() => {
|
|
77
|
+
if (!enabled || !orgName) return void 0;
|
|
78
|
+
refresh();
|
|
79
|
+
const timer = setInterval(refresh, CREDITS_REFRESH_INTERVAL_MS);
|
|
80
|
+
return () => clearInterval(timer);
|
|
81
|
+
}, [enabled, orgName, refresh]);
|
|
82
|
+
const summary = useMemo(() => creditsSummary(withWindowStart(verdict, window), Date.now(), packRemainingUsd, creditsPerUsd), [verdict, window, packRemainingUsd, creditsPerUsd]);
|
|
83
|
+
return {
|
|
84
|
+
summary,
|
|
85
|
+
refresh
|
|
86
|
+
};
|
|
87
|
+
}export{CREDITS_REFRESH_INTERVAL_MS,useLlmCredits};//# sourceMappingURL=useLlmCredits.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useLlmCredits.js","sources":["../../../src/features/credits/useLlmCredits.ts"],"sourcesContent":["/**\n * The org's AI-credit allowance as the spend gate sees it, read as the web's useLlmCredits does:\n * the verdict, the window it is counted in, the credit packs and the rate, each its own query so\n * a backend without the newer fields never loses the verdict. They go through the app's Apollo\n * client with the org in the `orgname` header (freeCredits.ts). The last good figures stay when a\n * read fails, so a blip never blanks the meter.\n *\n * The web also imports the agent's usage into the ledger before reading, right after a turn; the\n * phone reads when the drawer opens and every few minutes, by which time the backend's own sweep\n * has folded it in.\n */\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { gql, useApolloClient } from '@apollo/client';\nimport { creditsPerUsdNow, creditsSummary, rememberCreditsPerUsd, withWindowStart, type CreditWindow } from './credits';\n\nconst CHECK_LLM_SPEND = gql`\n query CheckLLMSpend {\n checkLLMSpend {\n allowed\n state\n reason\n remainingUsd\n paygRemainingUsd\n availableUsd\n includedUsd\n resetAt\n }\n }\n`;\n\nconst CHECK_LLM_CREDIT_WINDOW = gql`\n query CheckLLMCreditWindow {\n checkLLMSpend {\n periodStart\n resetAt\n }\n }\n`;\n\nconst CHECK_LLM_PACK_CREDITS = gql`\n query CheckLLMPackCredits {\n checkLLMSpend {\n packRemainingUsd\n }\n }\n`;\n\nconst CREDIT_RATE = gql`\n query CreditRate {\n creditRate {\n creditsPerUsd\n }\n }\n`;\n\nexport const CREDITS_REFRESH_INTERVAL_MS = 5 * 60_000;\n\ninterface Verdict {\n includedUsd?: number | null;\n remainingUsd?: number | null;\n resetAt?: string | null;\n}\n\nexport function useLlmCredits({ orgName, enabled }: { orgName?: string | null; enabled: boolean }) {\n const client = useApolloClient();\n const [verdict, setVerdict] = useState<Verdict | null>(null);\n const [window, setWindow] = useState<CreditWindow | null>(null);\n const [packRemainingUsd, setPackRemainingUsd] = useState<number | null>(null);\n const [creditsPerUsd, setCreditsPerUsd] = useState(creditsPerUsdNow);\n\n const refresh = useCallback(() => {\n if (!orgName) return;\n const read = <T>(query: typeof CHECK_LLM_SPEND) =>\n client\n .query<T>({ query, context: { headers: { orgname: orgName } }, fetchPolicy: 'network-only' })\n .then((result) => result.data)\n .catch(() => null);\n void read<{ checkLLMSpend: Verdict | null }>(CHECK_LLM_SPEND).then((data) => {\n if (data?.checkLLMSpend) setVerdict(data.checkLLMSpend);\n });\n void read<{ checkLLMSpend: CreditWindow | null }>(CHECK_LLM_CREDIT_WINDOW).then((data) => {\n if (data?.checkLLMSpend) setWindow(data.checkLLMSpend);\n });\n void read<{ checkLLMSpend: { packRemainingUsd?: number | null } | null }>(CHECK_LLM_PACK_CREDITS).then(\n (data) => {\n const value = data?.checkLLMSpend?.packRemainingUsd;\n if (typeof value === 'number' && Number.isFinite(value)) setPackRemainingUsd(value);\n },\n );\n void read<{ creditRate: { creditsPerUsd?: number | null } | null }>(CREDIT_RATE).then((data) => {\n const rate = data?.creditRate?.creditsPerUsd;\n rememberCreditsPerUsd(rate);\n if (typeof rate === 'number' && rate > 0) setCreditsPerUsd(rate);\n });\n }, [client, orgName]);\n\n useEffect(() => {\n if (!enabled || !orgName) return undefined;\n refresh();\n const timer = setInterval(refresh, CREDITS_REFRESH_INTERVAL_MS);\n return () => clearInterval(timer);\n }, [enabled, orgName, refresh]);\n\n const summary = useMemo(\n () => creditsSummary(withWindowStart(verdict, window), Date.now(), packRemainingUsd, creditsPerUsd),\n [verdict, window, packRemainingUsd, creditsPerUsd],\n );\n return { summary, refresh };\n}\n"],"names":[],"mappings":"sNAcA,MAAM,eAAkB,GAAA,GAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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,OAAA,EAAA;AACR,IAAM,MAAA,KAAA,GAAQ,WAAY,CAAA,OAAA,EAAS,2BAA2B,CAAA;AAC9D,IAAO,OAAA,MAAM,cAAc,KAAK,CAAA;AAAA,GAC/B,EAAA,CAAC,OAAS,EAAA,OAAA,EAAS,OAAO,CAAC,CAAA;AAC9B,EAAA,MAAM,UAAU,OAAQ,CAAA,MAAM,eAAe,eAAgB,CAAA,OAAA,EAAS,MAAM,CAAG,EAAA,IAAA,CAAK,KAAO,EAAA,gBAAA,EAAkB,aAAa,CAAG,EAAA,CAAC,SAAS,MAAQ,EAAA,gBAAA,EAAkB,aAAa,CAAC,CAAA;AAC/K,EAAO,OAAA;AAAA,IACL,OAAA;AAAA,IACA;AAAA,GACF;AACF"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import {deriveAgentEndpoint}from'../../canvas/videoEditor/remoteMediaClient.js';import {jsonInReply}from'./brandKit.js';function createAgentCompleteJson(token, indexUrl) {
|
|
2
|
+
return async ({
|
|
3
|
+
tier,
|
|
4
|
+
system,
|
|
5
|
+
prompt,
|
|
6
|
+
timeoutMs = 12e4
|
|
7
|
+
}) => {
|
|
8
|
+
var _a, _b, _c, _d;
|
|
9
|
+
if (!token) throw new Error("Sign in to use the writer.");
|
|
10
|
+
const controller = new AbortController();
|
|
11
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
12
|
+
try {
|
|
13
|
+
const resp = await fetch(`${deriveAgentEndpoint(indexUrl)}/v1/chat/completions`, {
|
|
14
|
+
method: "POST",
|
|
15
|
+
headers: {
|
|
16
|
+
"Content-Type": "application/json",
|
|
17
|
+
Authorization: `Bearer ${token}`
|
|
18
|
+
},
|
|
19
|
+
body: JSON.stringify({
|
|
20
|
+
model: tier,
|
|
21
|
+
stream: false,
|
|
22
|
+
messages: [{
|
|
23
|
+
role: "system",
|
|
24
|
+
content: system
|
|
25
|
+
}, {
|
|
26
|
+
role: "user",
|
|
27
|
+
content: prompt
|
|
28
|
+
}]
|
|
29
|
+
}),
|
|
30
|
+
signal: controller.signal
|
|
31
|
+
});
|
|
32
|
+
if (!resp.ok) throw new Error(`The writer is unavailable (HTTP ${resp.status}).`);
|
|
33
|
+
const body = await resp.json();
|
|
34
|
+
return jsonInReply((_d = (_c = (_b = (_a = body.choices) == null ? void 0 : _a[0]) == null ? void 0 : _b.message) == null ? void 0 : _c.content) != null ? _d : "");
|
|
35
|
+
} finally {
|
|
36
|
+
clearTimeout(timer);
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
}export{createAgentCompleteJson};//# sourceMappingURL=agentWriter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agentWriter.js","sources":["../../../../src/features/design/surface/agentWriter.ts"],"sourcesContent":["/**\n * One JSON answer from the person's agent's writer (web `completeViaAgent`): what a brand kit's\n * \"Import from your website\" and \"Find what buyers want\" ask. Shared by Design and the web builder.\n */\nimport { deriveAgentEndpoint } from '../../canvas/videoEditor/remoteMediaClient';\nimport { jsonInReply, type CompleteJson } from './brandKit';\n\nexport function createAgentCompleteJson(token: string | null | undefined, indexUrl: string): CompleteJson {\n return async ({ tier, system, prompt, timeoutMs = 120_000 }) => {\n if (!token) throw new Error('Sign in to use the writer.');\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const resp = await fetch(`${deriveAgentEndpoint(indexUrl)}/v1/chat/completions`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },\n body: JSON.stringify({\n model: tier,\n stream: false,\n messages: [\n { role: 'system', content: system },\n { role: 'user', content: prompt },\n ],\n }),\n signal: controller.signal,\n });\n if (!resp.ok) throw new Error(`The writer is unavailable (HTTP ${resp.status}).`);\n const body = (await resp.json()) as { choices?: Array<{ message?: { content?: string } }> };\n return jsonInReply(body.choices?.[0]?.message?.content ?? '');\n } finally {\n clearTimeout(timer);\n }\n };\n}\n"],"names":[],"mappings":"wHAMgB,SAAA,uBAAA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,GAAA,CAAA,EAAA,GAAA,CAAA,EAAA,GAAA,IAAA,CAAA,OAAA,KAAL,IAAe,GAAA,KAAA,CAAA,GAAA,EAAA,CAAA,CAAA,CAAA,KAAf,mBAAmB,OAAnB,KAAA,IAAA,GAAA,KAAA,CAAA,GAAA,EAAA,CAA4B,OAA5B,KAAA,IAAA,GAAA,EAAA,GAAuC,EAAE,CAAA;AAAA,KAC5D,SAAA;AACA,MAAA,YAAA,CAAa,KAAK,CAAA;AAAA;AACpB,GACF;AACF"}
|
|
@@ -111,6 +111,11 @@ Make it for this brand - use its name, logo and voice; colours and type come fro
|
|
|
111
111
|
|
|
112
112
|
Make it for this brand - build its colours, type, logo and voice in, and do not invent a palette: ${brief}`;
|
|
113
113
|
}
|
|
114
|
+
function brandKitNote(brand) {
|
|
115
|
+
const brief = brandBrief(brand);
|
|
116
|
+
return brief ? `[Brand kit] Make it for this brand - its colours, type, logo and voice:
|
|
117
|
+
${brief}` : "";
|
|
118
|
+
}
|
|
114
119
|
function brandKitsErrorMessage(err) {
|
|
115
120
|
const msg = err instanceof Error ? err.message : String(err);
|
|
116
121
|
return /not found in connector|available actions|unknown action|no such action|unknown collection/i.test(msg) ? NOT_AVAILABLE : msg;
|
|
@@ -195,10 +200,11 @@ async function findDesires(complete, kit) {
|
|
|
195
200
|
prompt: `Brand: ${kit.name || "unnamed"}${kit.industry ? ` (${kit.industry})` : ""}.
|
|
196
201
|
What they sell: ${kit.description}
|
|
197
202
|
Who buys: ${kit.audience || "not given - infer it from what they sell"}
|
|
198
|
-
|
|
199
|
-
` : ""
|
|
203
|
+
${((_a = kit.valueProps) == null ? void 0 : _a.length) ? `Key benefits: ${kit.valueProps.join("; ")}
|
|
204
|
+
` : ""}
|
|
205
|
+
What desires does this product fulfil for the people who buy it, and what is the psychology behind wanting it? Return JSON {"desires": [4-6 strings, each "<the desire, as the buyer would say it> - <what an ad should show to prove the product delivers it>"]}, strongest first. No feature lists, and nothing the description does not support.`
|
|
200
206
|
});
|
|
201
207
|
const desires = strings(out.desires).map((d) => d.trim()).filter(Boolean);
|
|
202
208
|
if (!desires.length) throw new Error("The writer came back with nothing - try again.");
|
|
203
209
|
return desires.slice(0, 6).map((d) => d.slice(0, 240));
|
|
204
|
-
}export{BRAND_KITS_CONNECTOR,activeBrandKitOf,brandBrief,brandKitsErrorMessage,brandNote,colourName,deleteBrandKit,emptyBrandKit,findDesires,importBrandKit,jsonInReply,listBrandKits,normalizeBrandKit,paletteWords,saveBrandKit,siteUrl,typeFeel,validColors};//# sourceMappingURL=brandKit.js.map
|
|
210
|
+
}export{BRAND_KITS_CONNECTOR,activeBrandKitOf,brandBrief,brandKitNote,brandKitsErrorMessage,brandNote,colourName,deleteBrandKit,emptyBrandKit,findDesires,importBrandKit,jsonInReply,listBrandKits,normalizeBrandKit,paletteWords,saveBrandKit,siteUrl,typeFeel,validColors};//# sourceMappingURL=brandKit.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"brandKit.js","sources":["../../../../src/features/design/surface/brandKit.ts"],"sourcesContent":["/**\n * Brand kits - native twin of surface-kit `brandKit/`. The kits live in the\n * person's studio document on their agent (the `brands` collection of the\n * yantra-social-ads connector), so a kit made in Ads, Canvas, Design or the web\n * builder is the same kit here. Picking one picks it for every native app that\n * reads the kit in use; \"No brand\" is Design's own choice.\n *\n * Pure apart from the injected runner and storage: runs under jest as-is.\n */\nimport type { RunMediaAction } from '../../canvas/videoEditor/mediaActions';\n\n/** Fields this module does not know stay on the record, so a save here never loses them. */\nexport interface BrandKit {\n id: string;\n name: string;\n tagline?: string;\n website?: string;\n description: string;\n industry?: string;\n imageStyle?: string;\n logoDescription?: string;\n audience?: string;\n voice?: string;\n valueProps?: string[];\n desires?: string[];\n logoUrl?: string;\n colors: string[];\n fonts?: string[];\n cta?: string;\n competitors?: string[];\n /** The countries it sells in (ISO codes: US, GB). */\n markets?: string[];\n}\n\nexport type BrandKitDraft = Omit<BrandKit, 'id'> & { id?: string };\n\nexport const BRAND_KITS_CONNECTOR = 'yantra-social-ads';\nconst COLLECTION = 'brands';\nconst NOT_AVAILABLE = 'Brand kits are not available on your agent yet - its studio store needs an update.';\n\nexport function emptyBrandKit(): BrandKitDraft {\n return { name: '', description: '', colors: ['#f97316', '#1f2937'] };\n}\n\n/** Up to six `#rrggbb` colours, lower-cased; anything else dropped. */\nexport function validColors(colors: unknown): string[] {\n const list = Array.isArray(colors) ? colors : colors && typeof colors === 'object' ? Object.values(colors) : [];\n return list\n .map((c) =>\n String(c && typeof c === 'object' ? (c as { hex?: unknown }).hex : c)\n .trim()\n .toLowerCase(),\n )\n .filter((c) => /^#[0-9a-f]{6}$/.test(c))\n .slice(0, 6);\n}\n\nconst strings = (v: unknown): string[] =>\n (Array.isArray(v) ? v : v && typeof v === 'object' ? Object.values(v) : []).filter(\n (x): x is string => typeof x === 'string',\n );\n\n/** Agents write kits too, so a record is made whole once, as it is read (web `normalizeBrandKit`). */\nexport function normalizeBrandKit(record: BrandKit): BrandKit {\n const text = (v: unknown) =>\n typeof v === 'string' ? v : Array.isArray(v) ? strings(v).join(', ') || undefined : undefined;\n return {\n ...record,\n name: text(record.name) ?? '',\n description: text(record.description) ?? '',\n tagline: text(record.tagline),\n audience: text(record.audience),\n voice: text(record.voice),\n imageStyle: text(record.imageStyle),\n logoDescription: text(record.logoDescription),\n logoUrl: typeof record.logoUrl === 'string' ? record.logoUrl : undefined,\n valueProps: strings(record.valueProps),\n desires: strings(record.desires),\n competitors: strings(record.competitors),\n markets: strings(record.markets)\n .map((c) => c.trim().toUpperCase())\n .filter((c) => /^[A-Z]{2}$/.test(c)),\n industry: text(record.industry),\n cta: text(record.cta),\n fonts: strings(record.fonts),\n colors: validColors(record.colors),\n };\n}\n\nconst HUES: Array<[number, string]> = [\n [12, 'red'],\n [42, 'orange'],\n [66, 'yellow'],\n [95, 'yellow-green'],\n [160, 'green'],\n [185, 'teal'],\n [205, 'sky blue'],\n [255, 'blue'],\n [290, 'purple'],\n [335, 'magenta'],\n [361, 'red'],\n];\n\n/** \"#c2410c\" -> \"deep orange\": a colour as a painter would say it, never the code (web `colourName`). */\nexport function colourName(hex: string): string {\n const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim());\n if (!m) return '';\n const [r, g, b] = [0, 2, 4].map((i) => parseInt(m[1].slice(i, i + 2), 16) / 255);\n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n const l = (max + min) / 2;\n const d = max - min;\n const s = d === 0 ? 0 : d / (1 - Math.abs(2 * l - 1));\n let hue = 0;\n if (d) hue = max === r ? 60 * (((g - b) / d) % 6) : max === g ? 60 * ((b - r) / d + 2) : 60 * ((r - g) / d + 4);\n if (hue < 0) hue += 360;\n const warm = hue < 70 || hue >= 330;\n if (l < 0.13) return s > 0.3 ? `${warm ? 'warm' : 'cool'} near-black` : 'near-black';\n if (l > 0.92) return s > 0.3 ? (warm ? 'warm cream' : 'cool off-white') : 'off-white';\n if (s < 0.12) return l < 0.35 ? 'charcoal grey' : l < 0.7 ? 'mid grey' : 'light grey';\n if ((hue < 50 || hue >= 345) && l < 0.36 && (hue >= 10 || s < 0.5)) return l < 0.2 ? 'dark brown' : 'brown';\n if (!warm && s < 0.35 && l < 0.25) return 'dark slate';\n const name = HUES.find(([until]) => hue < until)?.[1] ?? 'red';\n if ((name === 'magenta' && l > 0.55) || (name === 'red' && l > 0.7)) return 'pink';\n const tone =\n l < 0.3 ? 'dark ' : l < 0.45 ? 'deep ' : l > 0.8 ? 'pale ' : l > 0.65 ? 'light ' : s > 0.75 ? 'bright ' : '';\n return `${tone}${name}`;\n}\n\n/** The palette as words, e.g. \"deep orange, near-black and warm cream\". */\nexport function paletteWords(colors: string[]): string {\n const names = [...new Set(colors.map(colourName).filter(Boolean))];\n return names.length > 1 ? `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}` : (names[0] ?? '');\n}\n\n/** The type feel without the font's name: \"Bricolage Grotesque\" -> \"clean modern sans-serif type\". */\nexport function typeFeel(fonts: string[] | undefined): string {\n const all = (fonts ?? []).join(' ').toLowerCase();\n if (!all) return '';\n if (/mono|code|courier/.test(all)) return 'monospaced, technical type';\n if (/script|hand|brush|pacifico|lobster|dancing|caveat|satisfy/.test(all)) return 'hand-lettered script accents';\n if (\n (/serif/.test(all) && !/sans/.test(all)) ||\n /garamond|playfair|georgia|times|baskerville|merriweather|lora|fraunces|bodoni|didot|caslon/.test(all)\n )\n return 'elegant serif type';\n if (\n /grotesk|grotesque|sans|inter\\b|helvetica|arial|roboto|poppins|montserrat|manrope|geist|futura|avenir|nunito|lato|outfit|satoshi|raleway/.test(\n all,\n )\n )\n return 'clean modern sans-serif type';\n return '';\n}\n\n/**\n * The kit as a brief for generation (web `brandBrief` with the logo). `forMedia` is for image and\n * video models, which letter whatever looks like a label: the palette and type as words, no\n * codes, font names or logo address.\n */\nexport function brandBrief(brand: BrandKit | null | undefined, { forMedia = false } = {}): string {\n if (!brand) return '';\n const palette = forMedia ? paletteWords(brand.colors) : brand.colors.join(', ');\n const type = forMedia ? typeFeel(brand.fonts) : (brand.fonts ?? []).join(', ');\n return [\n `Brand: ${brand.name}.`,\n brand.tagline && !forMedia ? `Tagline: \"${brand.tagline}\".` : '',\n brand.description ? `About: ${brand.description}` : '',\n brand.audience ? `Audience: ${brand.audience}.` : '',\n brand.voice ? `Voice: ${brand.voice}.` : '',\n brand.valueProps?.length ? `Key benefits: ${brand.valueProps.join('; ')}.` : '',\n brand.desires?.length && !forMedia ? `What buyers really want: ${brand.desires.join('; ')}.` : '',\n palette ? `Brand colours: ${palette}.` : '',\n type ? `Typeface feel: ${type}.` : '',\n brand.imageStyle ? `Image style: ${brand.imageStyle}.` : '',\n !forMedia && brand.logoUrl\n ? `Logo image: ${brand.logoUrl}${brand.logoDescription ? ` (${brand.logoDescription})` : ''}.`\n : '',\n forMedia\n ? \"Never show another company's product, packaging or logo.\"\n : `Never name, show or compare with another company, product or brand${brand.competitors?.length ? ` - above all ${brand.competitors.join(', ')}` : ''}.`,\n ]\n .filter(Boolean)\n .join(' ');\n}\n\n/**\n * The kit in the connector's brief, never in the person's own words. With a\n * design system picked, the system keeps every token and the kit gives the name,\n * logo and voice; without one, the kit's colours and type are the palette.\n */\nexport function brandNote(brand: BrandKit | null | undefined, systemId?: string): string {\n const brief = brandBrief(brand);\n if (!brief) return '';\n return systemId\n ? `\\n\\nMake it for this brand - use its name, logo and voice; colours and type come from the design system: ${brief}`\n : `\\n\\nMake it for this brand - build its colours, type, logo and voice in, and do not invent a palette: ${brief}`;\n}\n\nexport function brandKitsErrorMessage(err: unknown): string {\n const msg = err instanceof Error ? err.message : String(err);\n return /not found in connector|available actions|unknown action|no such action|unknown collection/i.test(msg)\n ? NOT_AVAILABLE\n : msg;\n}\n\nexport async function listBrandKits(run: RunMediaAction): Promise<BrandKit[]> {\n const res = (await run(BRAND_KITS_CONNECTOR as never, 'YANTRA_SOCIAL_ADS_STUDIO_LIST', {\n collection: COLLECTION,\n limit: 200,\n offset: 0,\n })) as { items?: BrandKit[] };\n return (Array.isArray(res?.items) ? res.items : []).map(normalizeBrandKit);\n}\n\nexport async function saveBrandKit(run: RunMediaAction, draft: BrandKitDraft): Promise<BrandKit> {\n const res = (await run(BRAND_KITS_CONNECTOR as never, 'YANTRA_SOCIAL_ADS_STUDIO_SAVE', {\n collection: COLLECTION,\n item: draft,\n })) as { item?: BrandKit };\n if (!res?.item?.id) throw new Error('the studio store did not return the saved brand kit');\n return normalizeBrandKit(res.item);\n}\n\nexport async function deleteBrandKit(run: RunMediaAction, id: string): Promise<void> {\n await run(BRAND_KITS_CONNECTOR as never, 'YANTRA_SOCIAL_ADS_STUDIO_DELETE', { collection: COLLECTION, id });\n}\n\n/** The kit in use among `kits`: the one picked, else the newest. */\nexport function activeBrandKitOf(kits: readonly BrandKit[], activeId: string): BrandKit | null {\n return kits.find((k) => k.id === activeId) ?? kits[0] ?? null;\n}\n\n// ── Made from what is already there (web `importer.ts`) ────────────────────\n\n/** Ask the agent's writer for one JSON answer, on a routing tier. */\nexport type CompleteJson = <T>(request: {\n tier: 'small' | 'medium';\n system: string;\n prompt: string;\n timeoutMs?: number;\n}) => Promise<T>;\n\n/** The first JSON object in a reply, fenced or bare. */\nexport function jsonInReply<T>(text: string): T {\n const start = text.indexOf('{');\n const end = text.lastIndexOf('}');\n if (start < 0 || end <= start) throw new Error('The writer came back with nothing - try again.');\n return JSON.parse(text.slice(start, end + 1)) as T;\n}\n\nconst PROSE_SHAPE =\n '{\"name\": string, \"description\": string (2-3 sentences, what they sell and why it is different), \"industry\": string, \"audience\": string (who buys, one sentence), \"voice\": string (tone of voice in 3-6 words), \"valueProps\": string[] (3-5 short benefit phrases), \"cta\": string (their main call to action), \"colors\": string[] (hex, primary first), \"logoUrl\": string (absolute URL of the logo image, or \"\")}';\n\n/** `yourbrand.com` as a URL; throws on what cannot be one. */\nexport function siteUrl(input: string): string {\n const raw = input.trim();\n const url = /^https?:\\/\\//i.test(raw) ? raw : `https://${raw}`;\n if (!/^https?:\\/\\/[^\\s/]+\\.[^\\s/]+/i.test(url)) throw new Error('Enter a website like yourbrand.com.');\n return url;\n}\n\n/** A kit drafted from the brand's website: the writer reads the site. */\nexport async function importBrandKit(complete: CompleteJson, input: string): Promise<BrandKitDraft> {\n const url = siteUrl(input);\n const prose = await complete<Partial<BrandKit>>({\n tier: 'medium',\n timeoutMs: 240_000,\n system: 'You are a brand strategist with web access. Read the site before answering; never invent facts you did not read.',\n prompt: `Open ${url} and read its home page. Then fill a brand kit as JSON of the shape ${PROSE_SHAPE}. colors must be hex values used on the site.`,\n });\n if (!prose.name && !prose.description) throw new Error(`Could not read ${url}`);\n const host = /^https?:\\/\\/(?:www\\.)?([^/]+)/i.exec(url)?.[1] ?? url;\n return {\n name: String(prose.name ?? '').trim() || host,\n website: url,\n description: String(prose.description ?? '').trim(),\n ...(prose.industry ? { industry: String(prose.industry).trim() } : {}),\n ...(prose.audience ? { audience: String(prose.audience).trim() } : {}),\n ...(prose.voice ? { voice: String(prose.voice).trim() } : {}),\n valueProps: strings(prose.valueProps)\n .map((v) => v.trim())\n .filter(Boolean)\n .slice(0, 6),\n ...(prose.cta ? { cta: String(prose.cta).trim() } : {}),\n ...(/^https:\\/\\//.test(prose.logoUrl ?? '') ? { logoUrl: prose.logoUrl } : {}),\n colors: validColors(prose.colors).slice(0, 3),\n };\n}\n\n/** What buyers really want, read from the kit's own words: work shows the want being met, not a feature list. */\nexport async function findDesires(\n complete: CompleteJson,\n kit: Pick<BrandKit, 'name' | 'description' | 'audience' | 'industry' | 'valueProps'>,\n): Promise<string[]> {\n if (!kit.description.trim()) throw new Error('Describe what you sell first - the desires are read from it.');\n const out = await complete<{ desires?: unknown }>({\n tier: 'medium',\n system: 'You are a direct-response ad strategist. You name what buyers actually pay for - the feeling, status, relief or time they get back - in their own words, and only what this product can honestly deliver.',\n prompt:\n `Brand: ${kit.name || 'unnamed'}${kit.industry ? ` (${kit.industry})` : ''}.\\nWhat they sell: ${kit.description}\\n` +\n `Who buys: ${kit.audience || 'not given - infer it from what they sell'}\\n` +\n (kit.valueProps?.length ? `Key benefits: ${kit.valueProps.join('; ')}\\n` : '') +\n '\\nWhat desires does this product fulfil for the people who buy it, and what is the psychology behind wanting it? ' +\n 'Return JSON {\"desires\": [4-6 strings, each \"<the desire, as the buyer would say it> - <what an ad should show to prove the product delivers it>\"]}, strongest first. ' +\n 'No feature lists, and nothing the description does not support.',\n });\n const desires = strings(out.desires)\n .map((d) => d.trim())\n .filter(Boolean);\n if (!desires.length) throw new Error('The writer came back with nothing - try again.');\n return desires.slice(0, 6).map((d) => d.slice(0, 240));\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAoCO,MAAM,oBAAuB,GAAA;AACpC,MAAM,UAAa,GAAA,QAAA;AACnB,MAAM,aAAgB,GAAA,oFAAA;AACf,SAAS,aAA+B,GAAA;AAC7C,EAAO,OAAA;AAAA,IACL,IAAM,EAAA,EAAA;AAAA,IACN,WAAa,EAAA,EAAA;AAAA,IACb,MAAA,EAAQ,CA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EAAA,GAAA,CAAI,YAAY,0CAA0C;AAAA,CAAQ,IAAA,CAAA,CAAA,EAAA,GAAA,GAAA,CAAI,eAAJ,IAAgB,GAAA,MAAA,GAAA,EAAA,CAAA,MAAA,IAAS,iBAAiB,GAAI,CAAA,UAAA,CAAW,IAAK,CAAA,IAAI,CAAC;AAAA,CAAA,GAAO,EAAM,CAAA,GAAA;AAAA,GAC9R,CAAA;AACD,EAAA,MAAM,OAAU,GAAA,OAAA,CAAQ,GAAI,CAAA,OAAO,CAAE,CAAA,GAAA,CAAI,CAAK,CAAA,KAAA,CAAA,CAAE,IAAK,EAAC,CAAE,CAAA,MAAA,CAAO,OAAO,CAAA;AACtE,EAAA,IAAI,CAAC,OAAQ,CAAA,MAAA,EAAc,MAAA,IAAI,MAAM,gDAAgD,CAAA;AACrF,EAAO,OAAA,OAAA,CAAQ,KAAM,CAAA,CAAA,EAAG,CAAC,CAAA,CAAE,GAAI,CAAA,CAAA,CAAA,KAAK,CAAE,CAAA,KAAA,CAAM,CAAG,EAAA,GAAG,CAAC,CAAA;AACrD"}
|
|
1
|
+
{"version":3,"file":"brandKit.js","sources":["../../../../src/features/design/surface/brandKit.ts"],"sourcesContent":["/**\n * Brand kits - native twin of surface-kit `brandKit/`. The kits live in the\n * person's studio document on their agent (the `brands` collection of the\n * yantra-social-ads connector), so a kit made in Ads, Canvas, Design or the web\n * builder is the same kit here. Picking one picks it for every native app that\n * reads the kit in use; \"No brand\" is Design's own choice.\n *\n * Pure apart from the injected runner and storage: runs under jest as-is.\n */\nimport type { RunMediaAction } from '../../canvas/videoEditor/mediaActions';\n\n/** Fields this module does not know stay on the record, so a save here never loses them. */\nexport interface BrandKit {\n id: string;\n name: string;\n tagline?: string;\n website?: string;\n description: string;\n industry?: string;\n imageStyle?: string;\n logoDescription?: string;\n audience?: string;\n voice?: string;\n valueProps?: string[];\n desires?: string[];\n logoUrl?: string;\n colors: string[];\n fonts?: string[];\n cta?: string;\n competitors?: string[];\n /** The countries it sells in (ISO codes: US, GB). */\n markets?: string[];\n}\n\nexport type BrandKitDraft = Omit<BrandKit, 'id'> & { id?: string };\n\nexport const BRAND_KITS_CONNECTOR = 'yantra-social-ads';\nconst COLLECTION = 'brands';\nconst NOT_AVAILABLE = 'Brand kits are not available on your agent yet - its studio store needs an update.';\n\nexport function emptyBrandKit(): BrandKitDraft {\n return { name: '', description: '', colors: ['#f97316', '#1f2937'] };\n}\n\n/** Up to six `#rrggbb` colours, lower-cased; anything else dropped. */\nexport function validColors(colors: unknown): string[] {\n const list = Array.isArray(colors) ? colors : colors && typeof colors === 'object' ? Object.values(colors) : [];\n return list\n .map((c) =>\n String(c && typeof c === 'object' ? (c as { hex?: unknown }).hex : c)\n .trim()\n .toLowerCase(),\n )\n .filter((c) => /^#[0-9a-f]{6}$/.test(c))\n .slice(0, 6);\n}\n\nconst strings = (v: unknown): string[] =>\n (Array.isArray(v) ? v : v && typeof v === 'object' ? Object.values(v) : []).filter(\n (x): x is string => typeof x === 'string',\n );\n\n/** Agents write kits too, so a record is made whole once, as it is read (web `normalizeBrandKit`). */\nexport function normalizeBrandKit(record: BrandKit): BrandKit {\n const text = (v: unknown) =>\n typeof v === 'string' ? v : Array.isArray(v) ? strings(v).join(', ') || undefined : undefined;\n return {\n ...record,\n name: text(record.name) ?? '',\n description: text(record.description) ?? '',\n tagline: text(record.tagline),\n audience: text(record.audience),\n voice: text(record.voice),\n imageStyle: text(record.imageStyle),\n logoDescription: text(record.logoDescription),\n logoUrl: typeof record.logoUrl === 'string' ? record.logoUrl : undefined,\n valueProps: strings(record.valueProps),\n desires: strings(record.desires),\n competitors: strings(record.competitors),\n markets: strings(record.markets)\n .map((c) => c.trim().toUpperCase())\n .filter((c) => /^[A-Z]{2}$/.test(c)),\n industry: text(record.industry),\n cta: text(record.cta),\n fonts: strings(record.fonts),\n colors: validColors(record.colors),\n };\n}\n\nconst HUES: Array<[number, string]> = [\n [12, 'red'],\n [42, 'orange'],\n [66, 'yellow'],\n [95, 'yellow-green'],\n [160, 'green'],\n [185, 'teal'],\n [205, 'sky blue'],\n [255, 'blue'],\n [290, 'purple'],\n [335, 'magenta'],\n [361, 'red'],\n];\n\n/** \"#c2410c\" -> \"deep orange\": a colour as a painter would say it, never the code (web `colourName`). */\nexport function colourName(hex: string): string {\n const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim());\n if (!m) return '';\n const [r, g, b] = [0, 2, 4].map((i) => parseInt(m[1].slice(i, i + 2), 16) / 255);\n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n const l = (max + min) / 2;\n const d = max - min;\n const s = d === 0 ? 0 : d / (1 - Math.abs(2 * l - 1));\n let hue = 0;\n if (d) hue = max === r ? 60 * (((g - b) / d) % 6) : max === g ? 60 * ((b - r) / d + 2) : 60 * ((r - g) / d + 4);\n if (hue < 0) hue += 360;\n const warm = hue < 70 || hue >= 330;\n if (l < 0.13) return s > 0.3 ? `${warm ? 'warm' : 'cool'} near-black` : 'near-black';\n if (l > 0.92) return s > 0.3 ? (warm ? 'warm cream' : 'cool off-white') : 'off-white';\n if (s < 0.12) return l < 0.35 ? 'charcoal grey' : l < 0.7 ? 'mid grey' : 'light grey';\n if ((hue < 50 || hue >= 345) && l < 0.36 && (hue >= 10 || s < 0.5)) return l < 0.2 ? 'dark brown' : 'brown';\n if (!warm && s < 0.35 && l < 0.25) return 'dark slate';\n const name = HUES.find(([until]) => hue < until)?.[1] ?? 'red';\n if ((name === 'magenta' && l > 0.55) || (name === 'red' && l > 0.7)) return 'pink';\n const tone =\n l < 0.3 ? 'dark ' : l < 0.45 ? 'deep ' : l > 0.8 ? 'pale ' : l > 0.65 ? 'light ' : s > 0.75 ? 'bright ' : '';\n return `${tone}${name}`;\n}\n\n/** The palette as words, e.g. \"deep orange, near-black and warm cream\". */\nexport function paletteWords(colors: string[]): string {\n const names = [...new Set(colors.map(colourName).filter(Boolean))];\n return names.length > 1 ? `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}` : (names[0] ?? '');\n}\n\n/** The type feel without the font's name: \"Bricolage Grotesque\" -> \"clean modern sans-serif type\". */\nexport function typeFeel(fonts: string[] | undefined): string {\n const all = (fonts ?? []).join(' ').toLowerCase();\n if (!all) return '';\n if (/mono|code|courier/.test(all)) return 'monospaced, technical type';\n if (/script|hand|brush|pacifico|lobster|dancing|caveat|satisfy/.test(all)) return 'hand-lettered script accents';\n if (\n (/serif/.test(all) && !/sans/.test(all)) ||\n /garamond|playfair|georgia|times|baskerville|merriweather|lora|fraunces|bodoni|didot|caslon/.test(all)\n )\n return 'elegant serif type';\n if (\n /grotesk|grotesque|sans|inter\\b|helvetica|arial|roboto|poppins|montserrat|manrope|geist|futura|avenir|nunito|lato|outfit|satoshi|raleway/.test(\n all,\n )\n )\n return 'clean modern sans-serif type';\n return '';\n}\n\n/**\n * The kit as a brief for generation (web `brandBrief` with the logo). `forMedia` is for image and\n * video models, which letter whatever looks like a label: the palette and type as words, no\n * codes, font names or logo address.\n */\nexport function brandBrief(brand: BrandKit | null | undefined, { forMedia = false } = {}): string {\n if (!brand) return '';\n const palette = forMedia ? paletteWords(brand.colors) : brand.colors.join(', ');\n const type = forMedia ? typeFeel(brand.fonts) : (brand.fonts ?? []).join(', ');\n return [\n `Brand: ${brand.name}.`,\n brand.tagline && !forMedia ? `Tagline: \"${brand.tagline}\".` : '',\n brand.description ? `About: ${brand.description}` : '',\n brand.audience ? `Audience: ${brand.audience}.` : '',\n brand.voice ? `Voice: ${brand.voice}.` : '',\n brand.valueProps?.length ? `Key benefits: ${brand.valueProps.join('; ')}.` : '',\n brand.desires?.length && !forMedia ? `What buyers really want: ${brand.desires.join('; ')}.` : '',\n palette ? `Brand colours: ${palette}.` : '',\n type ? `Typeface feel: ${type}.` : '',\n brand.imageStyle ? `Image style: ${brand.imageStyle}.` : '',\n !forMedia && brand.logoUrl\n ? `Logo image: ${brand.logoUrl}${brand.logoDescription ? ` (${brand.logoDescription})` : ''}.`\n : '',\n forMedia\n ? \"Never show another company's product, packaging or logo.\"\n : `Never name, show or compare with another company, product or brand${brand.competitors?.length ? ` - above all ${brand.competitors.join(', ')}` : ''}.`,\n ]\n .filter(Boolean)\n .join(' ');\n}\n\n/**\n * The kit in the connector's brief, never in the person's own words. With a\n * design system picked, the system keeps every token and the kit gives the name,\n * logo and voice; without one, the kit's colours and type are the palette.\n */\nexport function brandNote(brand: BrandKit | null | undefined, systemId?: string): string {\n const brief = brandBrief(brand);\n if (!brief) return '';\n return systemId\n ? `\\n\\nMake it for this brand - use its name, logo and voice; colours and type come from the design system: ${brief}`\n : `\\n\\nMake it for this brand - build its colours, type, logo and voice in, and do not invent a palette: ${brief}`;\n}\n\n/**\n * The kit as a note on a message to an agent that builds something (a page, a design): the whole\n * brief with the logo, under a label the agent can tell from the person's own words (surface-kit\n * `brandKitNote`). Empty with no kit.\n */\nexport function brandKitNote(brand: BrandKit | null | undefined): string {\n const brief = brandBrief(brand);\n return brief ? `[Brand kit] Make it for this brand - its colours, type, logo and voice:\\n${brief}` : '';\n}\n\nexport function brandKitsErrorMessage(err: unknown): string {\n const msg = err instanceof Error ? err.message : String(err);\n return /not found in connector|available actions|unknown action|no such action|unknown collection/i.test(msg)\n ? NOT_AVAILABLE\n : msg;\n}\n\nexport async function listBrandKits(run: RunMediaAction): Promise<BrandKit[]> {\n const res = (await run(BRAND_KITS_CONNECTOR as never, 'YANTRA_SOCIAL_ADS_STUDIO_LIST', {\n collection: COLLECTION,\n limit: 200,\n offset: 0,\n })) as { items?: BrandKit[] };\n return (Array.isArray(res?.items) ? res.items : []).map(normalizeBrandKit);\n}\n\nexport async function saveBrandKit(run: RunMediaAction, draft: BrandKitDraft): Promise<BrandKit> {\n const res = (await run(BRAND_KITS_CONNECTOR as never, 'YANTRA_SOCIAL_ADS_STUDIO_SAVE', {\n collection: COLLECTION,\n item: draft,\n })) as { item?: BrandKit };\n if (!res?.item?.id) throw new Error('the studio store did not return the saved brand kit');\n return normalizeBrandKit(res.item);\n}\n\nexport async function deleteBrandKit(run: RunMediaAction, id: string): Promise<void> {\n await run(BRAND_KITS_CONNECTOR as never, 'YANTRA_SOCIAL_ADS_STUDIO_DELETE', { collection: COLLECTION, id });\n}\n\n/** The kit in use among `kits`: the one picked, else the newest. */\nexport function activeBrandKitOf(kits: readonly BrandKit[], activeId: string): BrandKit | null {\n return kits.find((k) => k.id === activeId) ?? kits[0] ?? null;\n}\n\n// ── Made from what is already there (web `importer.ts`) ────────────────────\n\n/** Ask the agent's writer for one JSON answer, on a routing tier. */\nexport type CompleteJson = <T>(request: {\n tier: 'small' | 'medium';\n system: string;\n prompt: string;\n timeoutMs?: number;\n}) => Promise<T>;\n\n/** The first JSON object in a reply, fenced or bare. */\nexport function jsonInReply<T>(text: string): T {\n const start = text.indexOf('{');\n const end = text.lastIndexOf('}');\n if (start < 0 || end <= start) throw new Error('The writer came back with nothing - try again.');\n return JSON.parse(text.slice(start, end + 1)) as T;\n}\n\nconst PROSE_SHAPE =\n '{\"name\": string, \"description\": string (2-3 sentences, what they sell and why it is different), \"industry\": string, \"audience\": string (who buys, one sentence), \"voice\": string (tone of voice in 3-6 words), \"valueProps\": string[] (3-5 short benefit phrases), \"cta\": string (their main call to action), \"colors\": string[] (hex, primary first), \"logoUrl\": string (absolute URL of the logo image, or \"\")}';\n\n/** `yourbrand.com` as a URL; throws on what cannot be one. */\nexport function siteUrl(input: string): string {\n const raw = input.trim();\n const url = /^https?:\\/\\//i.test(raw) ? raw : `https://${raw}`;\n if (!/^https?:\\/\\/[^\\s/]+\\.[^\\s/]+/i.test(url)) throw new Error('Enter a website like yourbrand.com.');\n return url;\n}\n\n/** A kit drafted from the brand's website: the writer reads the site. */\nexport async function importBrandKit(complete: CompleteJson, input: string): Promise<BrandKitDraft> {\n const url = siteUrl(input);\n const prose = await complete<Partial<BrandKit>>({\n tier: 'medium',\n timeoutMs: 240_000,\n system: 'You are a brand strategist with web access. Read the site before answering; never invent facts you did not read.',\n prompt: `Open ${url} and read its home page. Then fill a brand kit as JSON of the shape ${PROSE_SHAPE}. colors must be hex values used on the site.`,\n });\n if (!prose.name && !prose.description) throw new Error(`Could not read ${url}`);\n const host = /^https?:\\/\\/(?:www\\.)?([^/]+)/i.exec(url)?.[1] ?? url;\n return {\n name: String(prose.name ?? '').trim() || host,\n website: url,\n description: String(prose.description ?? '').trim(),\n ...(prose.industry ? { industry: String(prose.industry).trim() } : {}),\n ...(prose.audience ? { audience: String(prose.audience).trim() } : {}),\n ...(prose.voice ? { voice: String(prose.voice).trim() } : {}),\n valueProps: strings(prose.valueProps)\n .map((v) => v.trim())\n .filter(Boolean)\n .slice(0, 6),\n ...(prose.cta ? { cta: String(prose.cta).trim() } : {}),\n ...(/^https:\\/\\//.test(prose.logoUrl ?? '') ? { logoUrl: prose.logoUrl } : {}),\n colors: validColors(prose.colors).slice(0, 3),\n };\n}\n\n/** What buyers really want, read from the kit's own words: work shows the want being met, not a feature list. */\nexport async function findDesires(\n complete: CompleteJson,\n kit: Pick<BrandKit, 'name' | 'description' | 'audience' | 'industry' | 'valueProps'>,\n): Promise<string[]> {\n if (!kit.description.trim()) throw new Error('Describe what you sell first - the desires are read from it.');\n const out = await complete<{ desires?: unknown }>({\n tier: 'medium',\n system: 'You are a direct-response ad strategist. You name what buyers actually pay for - the feeling, status, relief or time they get back - in their own words, and only what this product can honestly deliver.',\n prompt:\n `Brand: ${kit.name || 'unnamed'}${kit.industry ? ` (${kit.industry})` : ''}.\\nWhat they sell: ${kit.description}\\n` +\n `Who buys: ${kit.audience || 'not given - infer it from what they sell'}\\n${\n kit.valueProps?.length ? `Key benefits: ${kit.valueProps.join('; ')}\\n` : ''\n }\\nWhat desires does this product fulfil for the people who buy it, and what is the psychology behind wanting it? ` +\n `Return JSON {\"desires\": [4-6 strings, each \"<the desire, as the buyer would say it> - <what an ad should show to prove the product delivers it>\"]}, strongest first. ` +\n `No feature lists, and nothing the description does not support.`,\n });\n const desires = strings(out.desires)\n .map((d) => d.trim())\n .filter(Boolean);\n if (!desires.length) throw new Error('The writer came back with nothing - try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ent":["/**\n * The person's brand kit for a surface - native twin of surface-kit\n * `useBrandKitInUse`: the kit in use is one pick for every surface (the key Ads\n * has always used); \"No brand\" is each surface's own.\n */\nimport { useCallback, useEffect, useState } from 'react';\nimport type { RunMediaAction } from '../../canvas/videoEditor/mediaActions';\nimport {\n activeBrandKitOf,\n brandKitsErrorMessage,\n deleteBrandKit,\n listBrandKits,\n saveBrandKit,\n type BrandKit,\n type BrandKitDraft,\n} from './brandKit';\nimport { freshLinksIn } from './freshLinks';\n\nconst ACTIVE_BRAND_KEY = 'yantra_ads_active_brand';\nconst brandOffKey = (surface: BrandSurface) => `yantra_brand_kit_off:${surface}`;\n\nexport type BrandSurface = 'design' | 'canvas';\n\ntype Storage = { getItem: (k: string) => Promise<string | null>; setItem: (k: string, v: string) => Promise<void> };\n\n/** A remote without the native storage module keeps these for the session. */\nfunction storage(): Storage | null {\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires, global-require\n return require('@react-native-async-storage/async-storage').default ?? null;\n } catch {\n return null;\n }\n}\nconst readStored = async (key: string): Promise<string | null> =>\n storage()\n ?.getItem(key)\n .catch(() => null) ?? null;\nconst writeStored = (key: string, value: string): void => {\n void storage()\n ?.setItem(key, value)\n .catch(() => undefined);\n};\n\nexport interface BrandKitInUse {\n kits: BrandKit[];\n /** The kit picked (or newest), whatever `off` says: the sheet shows it either way. */\n active: BrandKit | null;\n /** The kit a generation applies: null under \"No brand\". */\n kit: BrandKit | null;\n off: boolean;\n loading: boolean;\n error: string | null;\n pick: (id: string) => void;\n setOff: (off: boolean) => void;\n save: (draft: BrandKitDraft) => Promise<void>;\n remove: (id: string) => Promise<void>;\n}\n\n/** `run` absent (signed out, no connector) reads nothing and saves nothing. */\nexport function useBrandKitInUse(run: RunMediaAction | undefined, surface: BrandSurface): BrandKitInUse {\n const [kits, setKits] = useState<BrandKit[]>([]);\n const [activeId, setActiveId] = useState('');\n const [off, setOffState] = useState(false);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n useEffect(() => {\n void readStored(ACTIVE_BRAND_KEY).then((id) => id && setActiveId(id));\n void readStored(brandOffKey(surface)).then((v) => v === '1' && setOffState(true));\n }, [surface]);\n useEffect(() => {\n if (!run) return;\n setLoading(true);\n void listBrandKits(run)\n .then(async (listed) => {\n // Uploaded logos are 7-day signed links.\n const fresh = await Promise.all(\n listed.map(async (k) => (k.logoUrl ? { ...k, logoUrl: await freshLinksIn(k.logoUrl, run) } : k)),\n );\n setKits(fresh);\n setError(null);\n })\n .catch((err) => setError(brandKitsErrorMessage(err)))\n .finally(() => setLoading(false));\n }, [run]);\n const active = activeBrandKitOf(kits, activeId);\n const pick = useCallback((id: string) => {\n setActiveId(id);\n writeStored(ACTIVE_BRAND_KEY, id);\n }, []);\n const setOff = useCallback(\n (next: boolean) => {\n setOffState(next);\n writeStored(brandOffKey(surface), next ? '1' : '');\n },\n [surface],\n );\n const save = useCallback(\n async (draft: BrandKitDraft) => {\n if (!run) throw new Error('Sign in to save your brand.');\n const saved = await saveBrandKit(run, draft);\n setKits((prev) => [saved, ...prev.filter((k) => k.id !== saved.id)]);\n },\n [run],\n );\n const remove = useCallback(\n async (id: string) => {\n if (!run) return;\n await deleteBrandKit(run, id);\n setKits((prev) => prev.filter((k) => k.id !== id));\n },\n [run],\n );\n return { kits, active, kit: off ? null : active, off, loading, error, pick, setOff, save, remove };\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AASA,MAAM,gBAAmB,GAAA,yBAAA;AACzB,MAAM,WAAc,GAAA,CAAC,OAA0B,KAAA,CAAA,qBAAA,EAAwB,OAAO,CAAA,CAAA;AAQ9E,SAAS,OAA0B,GAAA;AAlBnC,EAAA,IAAA,EAAA;AAmBE,EAAI,IAAA;AAEF,IAAA,OAAA,CAAO,EAAQ,GAAA,OAAA,CAAA,2CAA2C,CAAE,CAAA,OAAA,KAArD,IAAgE,GAAA,EAAA,GAAA,IAAA;AAAA,GACjE,CAAA,OAAA,CAAA,EAAA;AACN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nD,EAAG,CAAC,OAAO,CAAC,CAAA;AACZ,EAAM,MAAA,IAAA,GAAO,WAAY,CAAA,OAAO,KAAyB,KAAA;AACvD,IAAA,IAAI,CAAC,GAAA,EAAW,MAAA,IAAI,MAAM,6BAA6B,CAAA;AACvD,IAAA,MAAM,KAAQ,GAAA,MAAM,YAAa,CAAA,GAAA,EAAK,KAAK,CAAA;AAC3C,IAAA,OAAA,CAAQ,CAAQ,IAAA,KAAA,CAAC,KAAO,EAAA,GAAG,IAAK,CAAA,MAAA,CAAO,CAAK,CAAA,KAAA,CAAA,CAAE,EAAO,KAAA,KAAA,CAAM,EAAE,CAAC,CAAC,CAAA;AAAA,GACjE,EAAG,CAAC,GAAG,CAAC,CAAA;AACR,EAAM,MAAA,MAAA,GAAS,WAAY,CAAA,OAAO,EAAe,KAAA;AAC/C,IAAA,IAAI,CAAC,GAAK,EAAA;AACV,IAAM,MAAA,cAAA,CAAe,KAAK,EAAE,CAAA;AAC5B,IAAA,OAAA,CAAQ,UAAQ,IAAK,CAAA,MAAA,CAAO,OAAK,CAAE,CAAA,EAAA,KAAO,EAAE,CAAC,CAAA;AAAA,GAC/C,EAAG,CAAC,GAAG,CAAC,CAAA;AACR,EAAO,OAAA;AAAA,IACL,IAAA;AAAA,IACA,MAAA;AAAA,IACA,GAAA,EAAK,MAAM,IAAO,GAAA,MAAA;AAAA,IAClB,GAAA;AAAA,IACA,OAAA;AAAA,IACA,KAAA;AAAA,IACA,IAAA;AAAA,IACA,MAAA;AAAA,IACA,IAAA;AAAA,IACA;AAAA,GACF;AACF"}
|
|
1
|
+
{"version":3,"file":"useBrandKitInUse.js","sources":["../../../../src/features/design/surface/useBrandKitInUse.ts"],"sourcesContent":["/**\n * The person's brand kit for a surface - native twin of surface-kit\n * `useBrandKitInUse`: the kit in use is one pick for every surface (the key Ads\n * has always used); \"No brand\" is each surface's own.\n */\nimport { useCallback, useEffect, useState } from 'react';\nimport type { RunMediaAction } from '../../canvas/videoEditor/mediaActions';\nimport {\n activeBrandKitOf,\n brandKitsErrorMessage,\n deleteBrandKit,\n listBrandKits,\n saveBrandKit,\n type BrandKit,\n type BrandKitDraft,\n} from './brandKit';\nimport { freshLinksIn } from './freshLinks';\n\nconst ACTIVE_BRAND_KEY = 'yantra_ads_active_brand';\nconst brandOffKey = (surface: BrandSurface) => `yantra_brand_kit_off:${surface}`;\n\nexport type BrandSurface = 'design' | 'canvas' | 'webbuilder';\n\ntype Storage = { getItem: (k: string) => Promise<string | null>; setItem: (k: string, v: string) => Promise<void> };\n\n/** A remote without the native storage module keeps these for the session. */\nfunction storage(): Storage | null {\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires, global-require\n return require('@react-native-async-storage/async-storage').default ?? null;\n } catch {\n return null;\n }\n}\nconst readStored = async (key: string): Promise<string | null> =>\n storage()\n ?.getItem(key)\n .catch(() => null) ?? null;\nconst writeStored = (key: string, value: string): void => {\n void storage()\n ?.setItem(key, value)\n .catch(() => undefined);\n};\n\nexport interface BrandKitInUse {\n kits: BrandKit[];\n /** The kit picked (or newest), whatever `off` says: the sheet shows it either way. */\n active: BrandKit | null;\n /** The kit a generation applies: null under \"No brand\". */\n kit: BrandKit | null;\n off: boolean;\n loading: boolean;\n error: string | null;\n pick: (id: string) => void;\n setOff: (off: boolean) => void;\n save: (draft: BrandKitDraft) => Promise<void>;\n remove: (id: string) => Promise<void>;\n}\n\n/** `run` absent (signed out, no connector) reads nothing and saves nothing. */\nexport function useBrandKitInUse(run: RunMediaAction | undefined, surface: BrandSurface): BrandKitInUse {\n const [kits, setKits] = useState<BrandKit[]>([]);\n const [activeId, setActiveId] = useState('');\n const [off, setOffState] = useState(false);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n useEffect(() => {\n void readStored(ACTIVE_BRAND_KEY).then((id) => id && setActiveId(id));\n void readStored(brandOffKey(surface)).then((v) => v === '1' && setOffState(true));\n }, [surface]);\n useEffect(() => {\n if (!run) return;\n setLoading(true);\n void listBrandKits(run)\n .then(async (listed) => {\n // Uploaded logos are 7-day signed links.\n const fresh = await Promise.all(\n listed.map(async (k) => (k.logoUrl ? { ...k, logoUrl: await freshLinksIn(k.logoUrl, run) } : k)),\n );\n setKits(fresh);\n setError(null);\n })\n .catch((err) => setError(brandKitsErrorMessage(err)))\n .finally(() => setLoading(false));\n }, [run]);\n const active = activeBrandKitOf(kits, activeId);\n const pick = useCallback((id: string) => {\n setActiveId(id);\n writeStored(ACTIVE_BRAND_KEY, id);\n }, []);\n const setOff = useCallback(\n (next: boolean) => {\n setOffState(next);\n writeStored(brandOffKey(surface), next ? '1' : '');\n },\n [surface],\n );\n const save = useCallback(\n async (draft: BrandKitDraft) => {\n if (!run) throw new Error('Sign in to save your brand.');\n const saved = await saveBrandKit(run, draft);\n setKits((prev) => [saved, ...prev.filter((k) => k.id !== saved.id)]);\n },\n [run],\n );\n const remove = useCallback(\n async (id: string) => {\n if (!run) return;\n await deleteBrandKit(run, id);\n setKits((prev) => prev.filter((k) => k.id !== id));\n },\n [run],\n );\n return { kits, active, kit: off ? null : active, off, loading, error, pick, setOff, save, remove };\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AASA,MAAM,gBAAmB,GAAA,yBAAA;AACzB,MAAM,WAAc,GAAA,CAAC,OAA0B,KAAA,CAAA,qBAAA,EAAwB,OAAO,CAAA,CAAA;AAQ9E,SAAS,OAA0B,GAAA;AAlBnC,EAAA,IAAA,EAAA;AAmBE,EAAI,IAAA;AAEF,IAAA,OAAA,CAAO,EAAQ,GAAA,OAAA,CAAA,2CAA2C,CAAE,CAAA,OAAA,KAArD,IAAgE,GAAA,EAAA,GAAA,IAAA;AAAA,GACjE,CAAA,OAAA,CAAA,EAAA;AACN,IAAO,OAAA,IAAA;AAAA;AAEX;AACA,MAAM,UAAA,GAAa,OAAO,GAAqC,KAAA;AA1B/D,EAAA,IAAA,EAAA,EAAA,EAAA;AA0BkE,EAAA,OAAA,CAAA,EAAA,GAAA,CAAA,EAAA,GAA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vD,IAAA,MAAM,KAAQ,GAAA,MAAM,YAAa,CAAA,GAAA,EAAK,KAAK,CAAA;AAC3C,IAAA,OAAA,CAAQ,CAAQ,IAAA,KAAA,CAAC,KAAO,EAAA,GAAG,IAAK,CAAA,MAAA,CAAO,CAAK,CAAA,KAAA,CAAA,CAAE,EAAO,KAAA,KAAA,CAAM,EAAE,CAAC,CAAC,CAAA;AAAA,GACjE,EAAG,CAAC,GAAG,CAAC,CAAA;AACR,EAAM,MAAA,MAAA,GAAS,WAAY,CAAA,OAAO,EAAe,KAAA;AAC/C,IAAA,IAAI,CAAC,GAAK,EAAA;AACV,IAAM,MAAA,cAAA,CAAe,KAAK,EAAE,CAAA;AAC5B,IAAA,OAAA,CAAQ,UAAQ,IAAK,CAAA,MAAA,CAAO,OAAK,CAAE,CAAA,EAAA,KAAO,EAAE,CAAC,CAAA;AAAA,GAC/C,EAAG,CAAC,GAAG,CAAC,CAAA;AACR,EAAO,OAAA;AAAA,IACL,IAAA;AAAA,IACA,MAAA;AAAA,IACA,GAAA,EAAK,MAAM,IAAO,GAAA,MAAA;AAAA,IAClB,GAAA;AAAA,IACA,OAAA;AAAA,IACA,KAAA;AAAA,IACA,IAAA;AAAA,IACA,MAAA;AAAA,IACA,IAAA;AAAA,IACA;AAAA,GACF;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {useMemo,useState,useCallback,useRef,useEffect}from'react';import {deleteDesignArtifact}from'../doc/artifacts.js';import {createAgentTurnTransport}from'./agentTurn.js';import {
|
|
1
|
+
import {useMemo,useState,useCallback,useRef,useEffect}from'react';import {deleteDesignArtifact}from'../doc/artifacts.js';import {createAgentTurnTransport}from'./agentTurn.js';import {importBrandKit,findDesires}from'./brandKit.js';import {toUserMessage,isCreditsRefusal}from'./designErrors.js';import {offerCredits}from'../../canvas/creditsOffer.js';import {useBrandKitInUse}from'./useBrandKitInUse.js';import {pullDesignVersion,deleteDesignBoard,pullDesignBoard,needsResave,designBoardSignature,newBoardId,buildDesignBoardState,pushDesignBoard,creationKey,applyEdit,landCreation}from'./designBoard.js';import {DesignQuestionError,extractSystem,listTemplates,listSystems,listTools}from'./designConnector.js';import {runDesignSend}from'./designRun.js';import {listWorkPage,groupWork,listChatWork,deleteChatWork}from'./workList.js';import {createExecTransport}from'./execStream.js';import {createAgentCompleteJson}from'./agentWriter.js';import {fetchChannelHistory,freshDesigns,ensureChatChannel}from'./designChannel.js';import {useMediaSigning}from'../../canvas/useBoardMediaRefresh.js';import {createRemoteConnectorExec,deriveBackendGraphqlUrl}from'../../canvas/videoEditor/remoteMediaClient.js';var __defProp = Object.defineProperty;
|
|
2
2
|
var __defProps = Object.defineProperties;
|
|
3
3
|
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
4
4
|
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
@@ -61,43 +61,7 @@ function useDesignSurface({
|
|
|
61
61
|
save: saveBrand,
|
|
62
62
|
remove: deleteBrand
|
|
63
63
|
} = useBrandKitInUse(ready ? (_a = index == null ? void 0 : index.run) != null ? _a : void 0 : void 0, "design");
|
|
64
|
-
const completeJson =
|
|
65
|
-
tier,
|
|
66
|
-
system,
|
|
67
|
-
prompt,
|
|
68
|
-
timeoutMs = 12e4
|
|
69
|
-
}) => {
|
|
70
|
-
var _a2, _b2, _c2, _d2;
|
|
71
|
-
if (!token) throw new Error("Sign in to use the writer.");
|
|
72
|
-
const controller = new AbortController();
|
|
73
|
-
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
74
|
-
try {
|
|
75
|
-
const resp = await fetch(`${deriveAgentEndpoint(indexUrl)}/v1/chat/completions`, {
|
|
76
|
-
method: "POST",
|
|
77
|
-
headers: {
|
|
78
|
-
"Content-Type": "application/json",
|
|
79
|
-
Authorization: `Bearer ${token}`
|
|
80
|
-
},
|
|
81
|
-
body: JSON.stringify({
|
|
82
|
-
model: tier,
|
|
83
|
-
stream: false,
|
|
84
|
-
messages: [{
|
|
85
|
-
role: "system",
|
|
86
|
-
content: system
|
|
87
|
-
}, {
|
|
88
|
-
role: "user",
|
|
89
|
-
content: prompt
|
|
90
|
-
}]
|
|
91
|
-
}),
|
|
92
|
-
signal: controller.signal
|
|
93
|
-
});
|
|
94
|
-
if (!resp.ok) throw new Error(`The writer is unavailable (HTTP ${resp.status}).`);
|
|
95
|
-
const body = await resp.json();
|
|
96
|
-
return jsonInReply((_d2 = (_c2 = (_b2 = (_a2 = body.choices) == null ? void 0 : _a2[0]) == null ? void 0 : _b2.message) == null ? void 0 : _c2.content) != null ? _d2 : "");
|
|
97
|
-
} finally {
|
|
98
|
-
clearTimeout(timer);
|
|
99
|
-
}
|
|
100
|
-
}, [token, indexUrl]);
|
|
64
|
+
const completeJson = useMemo(() => createAgentCompleteJson(token, indexUrl), [token, indexUrl]);
|
|
101
65
|
const importBrand = useCallback((site) => importBrandKit(completeJson, site), [completeJson]);
|
|
102
66
|
const findBrandDesires = useCallback((draft) => findDesires(completeJson, draft), [completeJson]);
|
|
103
67
|
const [workFilter, setWorkFilter] = useState("all");
|
|
@@ -355,7 +319,9 @@ function useDesignSurface({
|
|
|
355
319
|
});
|
|
356
320
|
updateBoard(boardId, (creations) => result.replaced ? applyEdit(creations, result.replaced, landed) : landCreation(creations, landed));
|
|
357
321
|
if (result.replaced) {
|
|
358
|
-
const
|
|
322
|
+
const {
|
|
323
|
+
replaced
|
|
324
|
+
} = result;
|
|
359
325
|
setPriorVersions((prev) => {
|
|
360
326
|
var _a3;
|
|
361
327
|
return __spreadProps(__spreadValues({}, prev), {
|