@adminide-stack/yantra-mobile 12.0.162-alpha.0 → 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,302 @@
1
+ import {failed,runGql}from'../data/graphql.js';import {namesFromRefs,buildRefsForDelete,validateSecretName,validateSecretValue,buildRefsForSave,secretsCredentialName,buildCreateCredentialInput,refsFromCredential}from'./secrets.js';const CREDENTIAL_QUERY = `
2
+ query formBuilderCredential($id: ID!) {
3
+ formBuilderCredential(id: $id) {
4
+ id
5
+ name
6
+ vaultSecretRefs {
7
+ fieldName
8
+ secret {
9
+ secretKey
10
+ }
11
+ }
12
+ }
13
+ }
14
+ `;
15
+ const CREDENTIALS_BY_NAME_QUERY = `
16
+ query formBuilderCredentials($filter: FormBuilderCredentialFilter, $limit: Int) {
17
+ formBuilderCredentials(filter: $filter, limit: $limit) {
18
+ data {
19
+ id
20
+ name
21
+ }
22
+ }
23
+ }
24
+ `;
25
+ const CREATE_CREDENTIAL_MUTATION = `
26
+ mutation createFormBuilderCredential($input: FormBuilderCredentialInput!) {
27
+ createFormBuilderCredential(input: $input) {
28
+ id
29
+ }
30
+ }
31
+ `;
32
+ const UPDATE_CREDENTIAL_MUTATION = `
33
+ mutation updateFormBuilderCredential($id: ID!, $input: UpdateFormBuilderCredentialInput!) {
34
+ updateFormBuilderCredential(id: $id, input: $input) {
35
+ id
36
+ }
37
+ }
38
+ `;
39
+ const NOT_SAVED = "The secret was not saved.";
40
+ function createSecretsService(opts) {
41
+ const {
42
+ transport,
43
+ data,
44
+ store
45
+ } = opts;
46
+ const notFoundMessage = "Could not reach the credentials service.";
47
+ const resolveId = async (channelId) => {
48
+ const s = await data.getSettings(channelId);
49
+ if (s.ok && s.value.secretsCredentialId) {
50
+ store.set(channelId, s.value.secretsCredentialId);
51
+ return {
52
+ ok: true,
53
+ value: {
54
+ id: s.value.secretsCredentialId,
55
+ settingsOk: true
56
+ }
57
+ };
58
+ }
59
+ if (!s.ok && !s.outdated) return {
60
+ ok: false,
61
+ message: s.message
62
+ };
63
+ const cached = store.get(channelId);
64
+ if (cached) {
65
+ const u = s.ok ? await data.updateSettings(channelId, {
66
+ secretsCredentialId: cached
67
+ }) : null;
68
+ return {
69
+ ok: true,
70
+ value: {
71
+ id: cached,
72
+ settingsOk: Boolean(u == null ? void 0 : u.ok)
73
+ }
74
+ };
75
+ }
76
+ const orgName = opts.scope().orgName;
77
+ if (orgName) {
78
+ const found = await runGql(() => transport.query(CREDENTIALS_BY_NAME_QUERY, {
79
+ filter: {
80
+ orgName,
81
+ name: secretsCredentialName(channelId)
82
+ },
83
+ limit: 5
84
+ }), (d) => {
85
+ var _a, _b;
86
+ return (_b = (_a = d.formBuilderCredentials) == null ? void 0 : _a.data) != null ? _b : [];
87
+ });
88
+ const match = found.ok ? found.value.find((c) => c && c.name === secretsCredentialName(channelId) && c.id) : void 0;
89
+ if (match == null ? void 0 : match.id) {
90
+ store.set(channelId, match.id);
91
+ const u = s.ok ? await data.updateSettings(channelId, {
92
+ secretsCredentialId: match.id
93
+ }) : null;
94
+ return {
95
+ ok: true,
96
+ value: {
97
+ id: match.id,
98
+ settingsOk: Boolean(u == null ? void 0 : u.ok)
99
+ }
100
+ };
101
+ }
102
+ }
103
+ return {
104
+ ok: true,
105
+ value: {
106
+ id: null,
107
+ settingsOk: s.ok
108
+ }
109
+ };
110
+ };
111
+ const readRefs = async (id) => runGql(() => transport.query(CREDENTIAL_QUERY, {
112
+ id
113
+ }), (d) => d.formBuilderCredential === void 0 ? void 0 : d.formBuilderCredential ? refsFromCredential(d.formBuilderCredential) : null, {
114
+ outdatedMessage: notFoundMessage
115
+ });
116
+ const writeRefs = (id, refs) => runGql(() => transport.mutate(UPDATE_CREDENTIAL_MUTATION, {
117
+ id,
118
+ input: {
119
+ vaultSecretRefs: refs
120
+ }
121
+ }), (d) => {
122
+ var _a;
123
+ return ((_a = d.updateFormBuilderCredential) == null ? void 0 : _a.id) ? d.updateFormBuilderCredential.id : void 0;
124
+ }, {
125
+ outdatedMessage: notFoundMessage
126
+ });
127
+ const list = async (channelId) => {
128
+ const resolved = await resolveId(channelId);
129
+ if (!resolved.ok) return failed(resolved);
130
+ const id = resolved.value.id;
131
+ if (!id) {
132
+ store.set(channelId, null);
133
+ return {
134
+ ok: true,
135
+ value: {
136
+ credentialId: null,
137
+ names: []
138
+ }
139
+ };
140
+ }
141
+ const refs = await readRefs(id);
142
+ if (!refs.ok) return failed(refs);
143
+ if (!refs.value) {
144
+ store.set(channelId, null);
145
+ return {
146
+ ok: true,
147
+ value: {
148
+ credentialId: null,
149
+ names: []
150
+ }
151
+ };
152
+ }
153
+ return {
154
+ ok: true,
155
+ value: {
156
+ credentialId: id,
157
+ names: namesFromRefs(refs.value)
158
+ }
159
+ };
160
+ };
161
+ const saveMany = async (channelId, values) => {
162
+ const entries = Object.entries(values);
163
+ if (!entries.length) return {
164
+ ok: false,
165
+ message: NOT_SAVED
166
+ };
167
+ for (const [name, value] of entries) {
168
+ const nameCheck = validateSecretName(name);
169
+ if (!nameCheck.ok) return {
170
+ ok: false,
171
+ message: nameCheck.error || NOT_SAVED
172
+ };
173
+ const valueCheck = validateSecretValue(value);
174
+ if (!valueCheck.ok) return {
175
+ ok: false,
176
+ message: valueCheck.error || NOT_SAVED
177
+ };
178
+ }
179
+ const savedNames = entries.map(([name]) => name);
180
+ const resolved = await resolveId(channelId);
181
+ if (!resolved.ok) return failed(resolved);
182
+ let id = resolved.value.id;
183
+ let refs = null;
184
+ if (id) {
185
+ const r = await readRefs(id);
186
+ if (!r.ok) return failed(r);
187
+ refs = r.value;
188
+ if (!refs) id = null;
189
+ }
190
+ if (id && refs) {
191
+ const w = await writeRefs(id, buildRefsForSave(channelId, refs, values));
192
+ if (!w.ok) return {
193
+ ok: false,
194
+ message: w.message
195
+ };
196
+ const names = namesFromRefs([...refs.filter((r) => !savedNames.includes(r.fieldName)), ...savedNames.map((fieldName) => ({
197
+ fieldName
198
+ }))]);
199
+ return {
200
+ ok: true,
201
+ value: {
202
+ credentialId: id,
203
+ names,
204
+ settingsSaved: resolved.value.settingsOk
205
+ }
206
+ };
207
+ }
208
+ const project = opts.scope().project;
209
+ if (!project) {
210
+ return {
211
+ ok: false,
212
+ message: "Couldn't tell which Yantra project to keep secrets in. Open the webbuilder from your project, or sign in again."
213
+ };
214
+ }
215
+ const created = await runGql(() => transport.mutate(CREATE_CREDENTIAL_MUTATION, {
216
+ input: buildCreateCredentialInput({
217
+ channelId,
218
+ project,
219
+ values
220
+ })
221
+ }), (d) => {
222
+ var _a;
223
+ return ((_a = d.createFormBuilderCredential) == null ? void 0 : _a.id) ? d.createFormBuilderCredential.id : void 0;
224
+ }, {
225
+ outdatedMessage: notFoundMessage
226
+ });
227
+ if (!created.ok) return {
228
+ ok: false,
229
+ message: created.message
230
+ };
231
+ const newId = created.value;
232
+ store.set(channelId, newId);
233
+ const saved = resolved.value.settingsOk ? await data.updateSettings(channelId, {
234
+ secretsCredentialId: newId
235
+ }) : null;
236
+ return {
237
+ ok: true,
238
+ value: {
239
+ credentialId: newId,
240
+ names: namesFromRefs(savedNames.map((fieldName) => ({
241
+ fieldName
242
+ }))),
243
+ settingsSaved: Boolean(saved == null ? void 0 : saved.ok)
244
+ }
245
+ };
246
+ };
247
+ const save = (channelId, name, value) => saveMany(channelId, {
248
+ [name]: value
249
+ });
250
+ const remove = async (channelId, name) => {
251
+ const resolved = await resolveId(channelId);
252
+ if (!resolved.ok) return failed(resolved);
253
+ const id = resolved.value.id;
254
+ if (!id) return {
255
+ ok: true,
256
+ value: {
257
+ credentialId: null,
258
+ names: []
259
+ }
260
+ };
261
+ const r = await readRefs(id);
262
+ if (!r.ok) return failed(r);
263
+ if (!r.value) return {
264
+ ok: true,
265
+ value: {
266
+ credentialId: null,
267
+ names: []
268
+ }
269
+ };
270
+ if (!r.value.some((x) => x.fieldName === name)) {
271
+ return {
272
+ ok: true,
273
+ value: {
274
+ credentialId: id,
275
+ names: namesFromRefs(r.value)
276
+ }
277
+ };
278
+ }
279
+ const w = await writeRefs(id, buildRefsForDelete(channelId, r.value, name));
280
+ if (!w.ok) return {
281
+ ok: false,
282
+ message: w.message
283
+ };
284
+ return {
285
+ ok: true,
286
+ value: {
287
+ credentialId: id,
288
+ names: namesFromRefs(r.value.filter((x) => x.fieldName !== name))
289
+ }
290
+ };
291
+ };
292
+ return {
293
+ list,
294
+ save,
295
+ saveMany,
296
+ remove,
297
+ credentialIdFor: (channelId) => {
298
+ var _a;
299
+ return (_a = store.get(channelId)) != null ? _a : null;
300
+ }
301
+ };
302
+ }export{CREATE_CREDENTIAL_MUTATION,CREDENTIALS_BY_NAME_QUERY,CREDENTIAL_QUERY,UPDATE_CREDENTIAL_MUTATION,createSecretsService};//# sourceMappingURL=secretsApi.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secretsApi.js","sources":["../../../../../src/features/webbuilder/web/secrets/secretsApi.ts"],"sourcesContent":["/**\n * W27: app-secrets calls - the project's one credential through the\n * FormBuilderCredential GraphQL API (user's token), its id kept in project\n * settings. See `secrets.ts` for the storage contract and where the project id\n * comes from. Values pass straight from the caller into the mutation variables;\n * nothing here logs, caches or returns them.\n */\n\nimport { runGql, type DataResult, type GraphqlTransport, failed } from '../data/graphql';\nimport type { WebBuilderDataService } from '../data/dataApi';\nimport {\n buildCreateCredentialInput,\n buildRefsForDelete,\n buildRefsForSave,\n namesFromRefs,\n refsFromCredential,\n secretsCredentialName,\n validateSecretName,\n validateSecretValue,\n type StoredSecretRef,\n type TokenScope,\n} from './secrets';\nimport type { SecretsCredentialStore } from './secretsStore';\n/** The build a restart applies secrets to (native: the web artifact's fields this module reads). */\ntype WebBuilderArtifact = { channelId?: string | null; sandboxId?: string | null; [key: string]: unknown };\n\nexport const CREDENTIAL_QUERY = `\n query formBuilderCredential($id: ID!) {\n formBuilderCredential(id: $id) {\n id\n name\n vaultSecretRefs {\n fieldName\n secret {\n secretKey\n }\n }\n }\n }\n`;\n\nexport const CREDENTIALS_BY_NAME_QUERY = `\n query formBuilderCredentials($filter: FormBuilderCredentialFilter, $limit: Int) {\n formBuilderCredentials(filter: $filter, limit: $limit) {\n data {\n id\n name\n }\n }\n }\n`;\n\nexport const CREATE_CREDENTIAL_MUTATION = `\n mutation createFormBuilderCredential($input: FormBuilderCredentialInput!) {\n createFormBuilderCredential(input: $input) {\n id\n }\n }\n`;\n\nexport const UPDATE_CREDENTIAL_MUTATION = `\n mutation updateFormBuilderCredential($id: ID!, $input: UpdateFormBuilderCredentialInput!) {\n updateFormBuilderCredential(id: $id, input: $input) {\n id\n }\n }\n`;\n\nexport interface SecretsList {\n credentialId: string | null;\n names: string[];\n}\n\nexport interface SecretsSaveResult extends SecretsList {\n /** False when the id could only be kept in this browser (old server). */\n settingsSaved: boolean;\n}\n\nexport interface WebBuilderSecretsService {\n list: (channelId: string) => Promise<DataResult<SecretsList>>;\n /** Add or replace one value. The value is used once and dropped. */\n save: (channelId: string, name: string, value: string) => Promise<DataResult<SecretsSaveResult>>;\n /**\n * Set several values in ONE credential write: all of them are stored, or\n * none (a failure leaves the credential as it was).\n */\n saveMany: (channelId: string, values: Record<string, string>) => Promise<DataResult<SecretsSaveResult>>;\n remove: (channelId: string, name: string) => Promise<DataResult<SecretsList>>;\n /** Cached id for turns / deploys (synchronous). */\n credentialIdFor: (channelId: string | null | undefined) => string | null;\n /** Edit-free preview restart applying the secrets (host-provided; absent -> next turn applies them). */\n restartPreview?: (\n creation: WebBuilderArtifact,\n names: string[],\n removed?: string[],\n ) => Promise<{ ok: boolean; message?: string }>;\n}\n\nconst NOT_SAVED = 'The secret was not saved.';\n\nexport function createSecretsService(opts: {\n transport: GraphqlTransport;\n data: WebBuilderDataService;\n store: SecretsCredentialStore;\n /** Org + project of the signed-in user's token (read at call time). */\n scope: () => TokenScope;\n}): WebBuilderSecretsService {\n const { transport, data, store } = opts;\n const notFoundMessage = 'Could not reach the credentials service.';\n\n /** The project's credential id: settings, then this browser, then a lookup by name. */\n const resolveId = async (channelId: string): Promise<DataResult<{ id: string | null; settingsOk: boolean }>> => {\n const s = await data.getSettings(channelId);\n if (s.ok && s.value.secretsCredentialId) {\n store.set(channelId, s.value.secretsCredentialId);\n return { ok: true, value: { id: s.value.secretsCredentialId, settingsOk: true } };\n }\n if (!s.ok && !s.outdated) return { ok: false, message: s.message };\n const cached = store.get(channelId);\n if (cached) {\n // Kept only in this browser so far (an older server): record it on the project now.\n const u = s.ok ? await data.updateSettings(channelId, { secretsCredentialId: cached }) : null;\n return { ok: true, value: { id: cached, settingsOk: Boolean(u?.ok) } };\n }\n const orgName = opts.scope().orgName;\n if (orgName) {\n const found = await runGql(\n () =>\n transport.query<{\n formBuilderCredentials?: { data?: Array<{ id?: string; name?: string } | null> };\n }>(CREDENTIALS_BY_NAME_QUERY, {\n filter: { orgName, name: secretsCredentialName(channelId) },\n limit: 5,\n }),\n (d) => d.formBuilderCredentials?.data ?? [],\n );\n const match = found.ok\n ? found.value.find((c) => c && c.name === secretsCredentialName(channelId) && c.id)\n : undefined;\n if (match?.id) {\n store.set(channelId, match.id);\n const u = s.ok ? await data.updateSettings(channelId, { secretsCredentialId: match.id }) : null;\n return { ok: true, value: { id: match.id, settingsOk: Boolean(u?.ok) } };\n }\n }\n return { ok: true, value: { id: null, settingsOk: s.ok } };\n };\n\n const readRefs = async (id: string): Promise<DataResult<StoredSecretRef[] | null>> =>\n runGql(\n () => transport.query<{ formBuilderCredential?: unknown }>(CREDENTIAL_QUERY, { id }),\n (d) =>\n d.formBuilderCredential === undefined\n ? undefined\n : d.formBuilderCredential\n ? refsFromCredential(d.formBuilderCredential)\n : null,\n { outdatedMessage: notFoundMessage },\n );\n\n const writeRefs = (id: string, refs: ReturnType<typeof buildRefsForDelete>) =>\n runGql(\n () =>\n transport.mutate<{ updateFormBuilderCredential?: { id?: string } | null }>(UPDATE_CREDENTIAL_MUTATION, {\n id,\n input: { vaultSecretRefs: refs },\n }),\n (d) => (d.updateFormBuilderCredential?.id ? d.updateFormBuilderCredential.id : undefined),\n { outdatedMessage: notFoundMessage },\n );\n\n const list = async (channelId: string): Promise<DataResult<SecretsList>> => {\n const resolved = await resolveId(channelId);\n if (!resolved.ok) return failed(resolved);\n const id = resolved.value.id;\n if (!id) {\n store.set(channelId, null);\n return { ok: true, value: { credentialId: null, names: [] } };\n }\n const refs = await readRefs(id);\n if (!refs.ok) return failed(refs);\n if (!refs.value) {\n // The credential is gone (deleted elsewhere): start over on the next save.\n store.set(channelId, null);\n return { ok: true, value: { credentialId: null, names: [] } };\n }\n return { ok: true, value: { credentialId: id, names: namesFromRefs(refs.value) } };\n };\n\n const saveMany = async (\n channelId: string,\n values: Record<string, string>,\n ): Promise<DataResult<SecretsSaveResult>> => {\n const entries = Object.entries(values);\n if (!entries.length) return { ok: false, message: NOT_SAVED };\n // Check every name and value before anything is written.\n for (const [name, value] of entries) {\n const nameCheck = validateSecretName(name);\n if (!nameCheck.ok) return { ok: false, message: nameCheck.error || NOT_SAVED };\n const valueCheck = validateSecretValue(value);\n if (!valueCheck.ok) return { ok: false, message: valueCheck.error || NOT_SAVED };\n }\n const savedNames = entries.map(([name]) => name);\n\n const resolved = await resolveId(channelId);\n if (!resolved.ok) return failed(resolved);\n let id = resolved.value.id;\n let refs: StoredSecretRef[] | null = null;\n if (id) {\n const r = await readRefs(id);\n if (!r.ok) return failed(r);\n refs = r.value;\n if (!refs) id = null;\n }\n\n if (id && refs) {\n const w = await writeRefs(id, buildRefsForSave(channelId, refs, values));\n if (!w.ok) return { ok: false, message: w.message };\n const names = namesFromRefs([\n ...refs.filter((r) => !savedNames.includes(r.fieldName)),\n ...savedNames.map((fieldName) => ({ fieldName })),\n ]);\n return { ok: true, value: { credentialId: id, names, settingsSaved: resolved.value.settingsOk } };\n }\n\n const project = opts.scope().project;\n if (!project) {\n return {\n ok: false,\n message:\n \"Couldn't tell which Yantra project to keep secrets in. Open the webbuilder from your project, or sign in again.\",\n };\n }\n const created = await runGql(\n () =>\n transport.mutate<{ createFormBuilderCredential?: { id?: string } | null }>(CREATE_CREDENTIAL_MUTATION, {\n input: buildCreateCredentialInput({ channelId, project, values }),\n }),\n (d) => (d.createFormBuilderCredential?.id ? d.createFormBuilderCredential.id : undefined),\n { outdatedMessage: notFoundMessage },\n );\n if (!created.ok) return { ok: false, message: created.message };\n const newId = created.value;\n store.set(channelId, newId);\n const saved = resolved.value.settingsOk\n ? await data.updateSettings(channelId, { secretsCredentialId: newId })\n : null;\n return {\n ok: true,\n value: {\n credentialId: newId,\n names: namesFromRefs(savedNames.map((fieldName) => ({ fieldName }))),\n settingsSaved: Boolean(saved?.ok),\n },\n };\n };\n\n const save = (channelId: string, name: string, value: string): Promise<DataResult<SecretsSaveResult>> =>\n saveMany(channelId, { [name]: value });\n\n const remove = async (channelId: string, name: string): Promise<DataResult<SecretsList>> => {\n const resolved = await resolveId(channelId);\n if (!resolved.ok) return failed(resolved);\n const id = resolved.value.id;\n if (!id) return { ok: true, value: { credentialId: null, names: [] } };\n const r = await readRefs(id);\n if (!r.ok) return failed(r);\n if (!r.value) return { ok: true, value: { credentialId: null, names: [] } };\n if (!r.value.some((x) => x.fieldName === name)) {\n return { ok: true, value: { credentialId: id, names: namesFromRefs(r.value) } };\n }\n const w = await writeRefs(id, buildRefsForDelete(channelId, r.value, name));\n if (!w.ok) return { ok: false, message: w.message };\n return {\n ok: true,\n value: { credentialId: id, names: namesFromRefs(r.value.filter((x) => x.fieldName !== name)) },\n };\n };\n\n return {\n list,\n save,\n saveMany,\n remove,\n credentialIdFor: (channelId) => store.get(channelId) ?? null,\n };\n}\n"],"names":[],"mappings":"uOAkBO,MAAM,gBAAmB,GAAA;AAAA;AAAA;AAAA;AAAA;AA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,CAAA,KAAnB,IAAwB,GAAA,EAAA,GAAA,IAAA;AAAA;AAAA,GACxD;AACF"}
@@ -0,0 +1,39 @@
1
+ import {storageKeys}from'../state/storageKeys.js';var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+ const ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
5
+ class SecretsCredentialStore {
6
+ constructor(storage) {
7
+ __publicField(this, "memory", /* @__PURE__ */ new Map());
8
+ __publicField(this, "storage");
9
+ this.storage = storage != null ? storage : null;
10
+ }
11
+ /** The cached id; `null` = known to have none; `undefined` = not known yet. */
12
+ get(channelId) {
13
+ var _a;
14
+ const key = String(channelId || "").trim();
15
+ if (!key) return null;
16
+ if (this.memory.has(key)) return this.memory.get(key);
17
+ try {
18
+ const stored = (_a = this.storage) == null ? void 0 : _a.getItem(storageKeys.secretsCredentialId(key));
19
+ if (stored && ID_RE.test(stored)) {
20
+ this.memory.set(key, stored);
21
+ return stored;
22
+ }
23
+ } catch (e) {
24
+ }
25
+ return void 0;
26
+ }
27
+ set(channelId, credentialId) {
28
+ var _a, _b;
29
+ const key = String(channelId || "").trim();
30
+ if (!key) return;
31
+ const id = credentialId && ID_RE.test(credentialId) ? credentialId : null;
32
+ this.memory.set(key, id);
33
+ try {
34
+ if (id) (_a = this.storage) == null ? void 0 : _a.setItem(storageKeys.secretsCredentialId(key), id);
35
+ else (_b = this.storage) == null ? void 0 : _b.removeItem(storageKeys.secretsCredentialId(key));
36
+ } catch (e) {
37
+ }
38
+ }
39
+ }export{SecretsCredentialStore};//# sourceMappingURL=secretsStore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secretsStore.js","sources":["../../../../../src/features/webbuilder/web/secrets/secretsStore.ts"],"sourcesContent":["/**\n * W27: which credential holds each project's app secrets (channelId ->\n * credential id). The server copy is `settings.secretsCredentialId` (Phase 5\n * spec §3); this cache lets every turn and every deploy add\n * `secretsCredentialId` synchronously, and keeps working (per browser) on a\n * server that doesn't have project settings yet. Ids only, never values.\n */\n\nimport { storageKeys } from '../state/storageKeys';\n\nexport interface KeyValueStorage {\n getItem: (key: string) => string | null;\n setItem: (key: string, value: string) => void;\n removeItem: (key: string) => void;\n}\n\nconst ID_RE = /^[A-Za-z0-9_-]{1,64}$/;\n\nexport class SecretsCredentialStore {\n private readonly memory = new Map<string, string | null>();\n private readonly storage: KeyValueStorage | null;\n\n constructor(storage?: KeyValueStorage | null) {\n this.storage = storage ?? null;\n }\n\n /** The cached id; `null` = known to have none; `undefined` = not known yet. */\n get(channelId: string | null | undefined): string | null | undefined {\n const key = String(channelId || '').trim();\n if (!key) return null;\n if (this.memory.has(key)) return this.memory.get(key);\n try {\n const stored = this.storage?.getItem(storageKeys.secretsCredentialId(key));\n if (stored && ID_RE.test(stored)) {\n this.memory.set(key, stored);\n return stored;\n }\n } catch {\n /* storage blocked */\n }\n return undefined;\n }\n\n set(channelId: string | null | undefined, credentialId: string | null): void {\n const key = String(channelId || '').trim();\n if (!key) return;\n const id = credentialId && ID_RE.test(credentialId) ? credentialId : null;\n this.memory.set(key, id);\n try {\n if (id) this.storage?.setItem(storageKeys.secretsCredentialId(key), id);\n else this.storage?.removeItem(storageKeys.secretsCredentialId(key));\n } catch {\n /* storage blocked */\n }\n }\n}\n"],"names":[],"mappings":";;;AAcA,MAAM,KAAQ,GAAA,uBAAA;AACP,MAAM,sBAAuB,CAAA;AAAA,EAGlC,YAAY,OAAkC,EAAA;AAF9C,IAAiB,aAAA,CAAA,IAAA,EAAA,QAAA,sBAAa,GAA2B,EAAA,CAAA;AACzD,IAAiB,aAAA,CAAA,IAAA,EAAA,SAAA,CAAA;AAEf,IAAA,IAAA,CAAK,UAAU,OAAW,IAAA,IAAA,GAAA,OAAA,GAAA,IAAA;AAAA;AAC5B;AAAA,EAGA,IA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,GAAA,EAAA,CAAc,UAAW,CAAA,WAAA,CAAY,oBAAoB,GAAG,CAAA,CAAA;AAAA,KACnI,CAAA,OAAA,CAAA,EAAA;AAAA;AAER;AAEJ"}
@@ -0,0 +1,40 @@
1
+ import {jsonValue}from'../data/graphql.js';function isRec(v) {
2
+ return Boolean(v) && typeof v === "object" && !Array.isArray(v);
3
+ }
4
+ function okErrorText(rec, fallback = "Something went wrong.") {
5
+ const parts = [];
6
+ if (typeof rec.error === "string" && rec.error.trim()) parts.push(rec.error.trim());
7
+ if (isRec(rec.error) && typeof rec.error.message === "string") parts.push(rec.error.message.trim());
8
+ if (Array.isArray(rec.errors)) {
9
+ for (const e of rec.errors) {
10
+ if (typeof e === "string" && e.trim()) parts.push(e.trim());
11
+ else if (isRec(e) && typeof e.message === "string" && e.message.trim()) parts.push(e.message.trim());
12
+ }
13
+ }
14
+ if (typeof rec.message === "string" && rec.message.trim() && !parts.length) parts.push(rec.message.trim());
15
+ return parts.filter(Boolean).join(" ").slice(0, 500) || fallback;
16
+ }
17
+ function unwrapOk(raw, payloadKeys = []) {
18
+ const value = jsonValue(raw);
19
+ if (!isRec(value) || typeof value.ok !== "boolean") return {
20
+ ok: true,
21
+ value
22
+ };
23
+ if (!value.ok) return {
24
+ ok: false,
25
+ message: okErrorText(value)
26
+ };
27
+ for (const key of payloadKeys) {
28
+ if (value[key] !== void 0) return {
29
+ ok: true,
30
+ value: jsonValue(value[key])
31
+ };
32
+ }
33
+ return {
34
+ ok: true,
35
+ value
36
+ };
37
+ }
38
+ function unwrapResult(r, payloadKeys = []) {
39
+ return r.ok ? unwrapOk(r.value, payloadKeys) : r;
40
+ }export{okErrorText,unwrapOk,unwrapResult};//# sourceMappingURL=okResult.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"okResult.js","sources":["../../../../../src/features/webbuilder/web/sharing/okResult.ts"],"sourcesContent":["/**\n * The page-creator webbuilder resolvers answer `{ ok: true, ...payload }` or\n * `{ ok: false, error }` / `{ ok: false, errors: string[] }` inside `data`\n * (see `webbuilder-project.ts`). A GraphQL reply without `errors` is NOT\n * success by itself: unwrap `ok` first. Pure: tested with node:test.\n */\n\nimport { jsonValue, type DataResult } from '../data/graphql';\n\ntype Rec = Record<string, unknown>;\n\nfunction isRec(v: unknown): v is Rec {\n return Boolean(v) && typeof v === 'object' && !Array.isArray(v);\n}\n\n/** `error` / `errors` (strings or `{ message }`) -> one line for the user. */\nexport function okErrorText(rec: Rec, fallback = 'Something went wrong.'): string {\n const parts: string[] = [];\n if (typeof rec.error === 'string' && rec.error.trim()) parts.push(rec.error.trim());\n if (isRec(rec.error) && typeof rec.error.message === 'string') parts.push(rec.error.message.trim());\n if (Array.isArray(rec.errors)) {\n for (const e of rec.errors) {\n if (typeof e === 'string' && e.trim()) parts.push(e.trim());\n else if (isRec(e) && typeof e.message === 'string' && e.message.trim()) parts.push(e.message.trim());\n }\n }\n if (typeof rec.message === 'string' && rec.message.trim() && !parts.length) parts.push(rec.message.trim());\n return parts.filter(Boolean).join(' ').slice(0, 500) || fallback;\n}\n\n/**\n * Unwrap one field's value. `{ ok: false }` -> failure with the server's\n * message; `{ ok: true, <key> }` -> the first present payload key (or the\n * whole record when none is); anything without `ok` passes through as is.\n */\nexport function unwrapOk(raw: unknown, payloadKeys: readonly string[] = []): DataResult<unknown> {\n const value = jsonValue(raw);\n if (!isRec(value) || typeof value.ok !== 'boolean') return { ok: true, value };\n if (!value.ok) return { ok: false, message: okErrorText(value) };\n for (const key of payloadKeys) {\n if (value[key] !== undefined) return { ok: true, value: jsonValue(value[key]) };\n }\n return { ok: true, value };\n}\n\n/** Apply `unwrapOk` to a `runGql` result. */\nexport function unwrapResult(r: DataResult<unknown>, payloadKeys: readonly string[] = []): DataResult<unknown> {\n return r.ok ? unwrapOk(r.value, payloadKeys) : r;\n}\n"],"names":[],"mappings":"2CASA,SAAS,MAAM,CAAsB,EAAA;AACnC,EAAO,OAAA,OAAA,CAAQ,CAAC,CAAK,IAAA,OAAO,MA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AAG,EAAA,GAAG,CAAK,IAAA,QAAA;AAC1D;AAOO,SAAS,QAAS,CAAA,GAAA,EAAc,WAAiC,GAAA,EAAyB,EAAA;AAC/F,EAAM,MAAA,KAAA,GAAQ,UAAU,GAAG,CAAA;AAC3B,EAAI,IAAA,CAAC,MAAM,KAAK,CAAA,IAAK,OAAO,KAAM,CAAA,EAAA,KAAO,WAAkB,OAAA;AAAA,IACzD,EAAI,EAAA,IAAA;AAAA,IACJ;AAAA,GACF;AACA,EAAI,IAAA,CAAC,KAAM,CAAA,EAAA,EAAW,OAAA;AAAA,IACpB,EAAI,EAAA,KAAA;AAAA,IACJ,OAAA,EAAS,YAAY,KAAK;AAAA,GAC5B;AACA,EAAA,KAAA,MAAW,OAAO,WAAa,EAAA;AAC7B,IAAA,IAAI,KAAM,CAAA,GAAG,CAAM,KAAA,MAAA,EAAkB,OAAA;AAAA,MACnC,EAAI,EAAA,IAAA;AAAA,MACJ,KAAO,EAAA,SAAA,CAAU,KAAM,CAAA,GAAG,CAAC;AAAA,KAC7B;AAAA;AAEF,EAAO,OAAA;AAAA,IACL,EAAI,EAAA,IAAA;AAAA,IACJ;AAAA,GACF;AACF;AAGO,SAAS,YAAa,CAAA,CAAA,EAAwB,WAAiC,GAAA,EAAyB,EAAA;AAC7G,EAAA,OAAO,EAAE,EAAK,GAAA,QAAA,CAAS,CAAE,CAAA,KAAA,EAAO,WAAW,CAAI,GAAA,CAAA;AACjD"}
@@ -0,0 +1,3 @@
1
+ function roleCan(role, action) {
2
+ return true;
3
+ }export{roleCan};//# sourceMappingURL=roles.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"roles.js","sources":["../../../../../src/features/webbuilder/web/sharing/roles.ts"],"sourcesContent":["/**\n * W31 sharing and roles (Phase 6 spec §2), surface side. Pure: tested with node:test.\n *\n * `roleCan` mirrors the server's checks in page-creator (stream P6):\n * - viewers can look (preview, code, history, read-only data views) and comment;\n * - editors can do everything except share, change roles, remove members, delete,\n * open the database Studio, run SQL, change database components, and change\n * GitHub sync or secrets settings;\n * - owners can do everything. The channel creator is always an owner.\n * The server enforces all of this; the surface only hides what would be refused.\n * An unknown role (old server, members not loaded) means \"no restriction shown\".\n */\n\nexport type ProjectRole = 'owner' | 'editor' | 'viewer';\n\nexport const PROJECT_ROLES: readonly ProjectRole[] = ['owner', 'editor', 'viewer'];\n/** Roles an owner can give when inviting (owners are made by changing a role). */\nexport const INVITE_ROLES: readonly ProjectRole[] = ['editor', 'viewer'];\n\nexport type RoleAction =\n | 'view'\n | 'comment'\n /** Build and edit turns (the composer, canvas Ask AI, \"Ask AI to fix\", Try to fix). */\n | 'build'\n /** Hand edits on the canvas and in the code editor. */\n | 'editCanvas'\n | 'editCode'\n | 'restoreVersion'\n | 'publish'\n | 'pushGithub'\n /** GitHub sync settings (auto-sync on or off). */\n | 'githubSync'\n /** Secrets settings (add, change, remove). */\n | 'secrets'\n | 'integrations'\n /** The database Studio link (full database access). */\n | 'databaseStudio'\n /** Cloud panel: data (read and edit rows), health, auth users and storage. Editors and owners. */\n | 'database'\n /** Cloud panel: the raw SQL runner (owners). */\n | 'databaseSql'\n /** Cloud panel: turn database components on or off (owners). */\n | 'databaseComponents'\n | 'updateSettings'\n /** Resolve production errors in the Health panel (editors and owners). */\n | 'resolveSiteErrors'\n /** The Health panel's alert settings (owners). */\n | 'siteAlerts'\n | 'share'\n | 'changeRole'\n | 'removeMember'\n | 'delete';\n\nconst VIEWER_ACTIONS: ReadonlySet<RoleAction> = new Set(['view', 'comment']);\nconst OWNER_ONLY: ReadonlySet<RoleAction> = new Set([\n 'share',\n 'changeRole',\n 'removeMember',\n 'delete',\n 'databaseStudio',\n 'databaseSql',\n 'databaseComponents',\n 'githubSync',\n 'secrets',\n 'siteAlerts',\n]);\n\nexport function normalizeRole(raw: unknown): ProjectRole | null {\n const r = typeof raw === 'string' ? raw.trim().toLowerCase() : '';\n return r === 'owner' || r === 'editor' || r === 'viewer' ? r : null;\n}\n\n/** May `role` do `action`? `null` (unknown) allows everything: the server still checks. */\nexport function roleCan(role: ProjectRole | null | undefined, action: RoleAction): boolean {\n if (!role) return true;\n if (role === 'owner') return true;\n if (role === 'editor') return !OWNER_ONLY.has(action);\n return VIEWER_ACTIONS.has(action);\n}\n\nexport interface ProjectMember {\n userId: string;\n name?: string;\n email?: string;\n role: ProjectRole;\n}\n\ntype Rec = Record<string, unknown>;\n\nfunction isRec(v: unknown): v is Rec {\n return Boolean(v) && typeof v === 'object' && !Array.isArray(v);\n}\n\nfunction text(v: unknown, max: number): string | undefined {\n if (typeof v !== 'string') return undefined;\n const t = v.trim();\n return t ? t.slice(0, max) : undefined;\n}\n\n/** `aiCodeProjectMembers` JSON (an array, or `{ members }`, maybe as a string) -> members, owners first. */\nexport function parseMembers(raw: unknown): ProjectMember[] {\n let value = raw;\n if (typeof value === 'string') {\n try {\n value = JSON.parse(value) as unknown;\n } catch {\n return [];\n }\n }\n if (isRec(value) && Array.isArray(value.members)) value = value.members;\n if (!Array.isArray(value)) return [];\n const seen = new Set<string>();\n const out: ProjectMember[] = [];\n for (const item of value) {\n if (!isRec(item)) continue;\n const userId = text(item.userId ?? item.id, 100);\n const role = normalizeRole(item.role);\n if (!userId || !role || seen.has(userId)) continue;\n seen.add(userId);\n const name = text(item.name, 200);\n const email = text(item.email, 320);\n out.push({ userId, role, ...(name ? { name } : {}), ...(email ? { email } : {}) });\n }\n const rank: Record<ProjectRole, number> = { owner: 0, editor: 1, viewer: 2 };\n return out.sort((a, b) => rank[a.role] - rank[b.role] || memberLabel(a).localeCompare(memberLabel(b)));\n}\n\n/** The current user's role among `members`; null when they aren't listed (unknown). */\nexport function roleOf(members: readonly ProjectMember[], userId: string | null | undefined): ProjectRole | null {\n if (!userId) return null;\n return members.find((m) => m.userId === userId)?.role ?? null;\n}\n\nexport function memberLabel(m: Pick<ProjectMember, 'name' | 'email' | 'userId'>): string {\n return m.name || m.email || `User ${m.userId.slice(-6)}`;\n}\n\nexport const ROLE_LABELS: Record<ProjectRole, string> = {\n owner: 'Owner',\n editor: 'Can edit',\n viewer: 'Can view',\n};\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/;\n\nexport function normalizeEmail(raw: string): string | null {\n const e = raw.trim().toLowerCase();\n return e.length <= 320 && EMAIL_RE.test(e) ? e : null;\n}\n\n/**\n * Spec §2: the last owner can't be removed or demoted. Returns the reason to\n * show, or null when the change is fine.\n */\nexport function lastOwnerProblem(\n members: readonly ProjectMember[],\n userId: string,\n next: ProjectRole | 'removed',\n): string | null {\n const target = members.find((m) => m.userId === userId);\n if (!target || target.role !== 'owner' || next === 'owner') return null;\n const owners = members.filter((m) => m.role === 'owner').length;\n if (owners > 1) return null;\n return next === 'removed'\n ? \"The project's only owner can't be removed. Make someone else an owner first.\"\n : \"The project's only owner can't be changed. Make someone else an owner first.\";\n}\n\n/** Board badge: shared with you when someone else created the channel. */\nexport function isSharedWithMe(creatorId: string | null | undefined, myUserId: string | null | undefined): boolean {\n if (!creatorId || !myUserId) return false;\n return creatorId !== myUserId;\n}\n\n/** The composer line while the open project is view-only (through `setExternalBusy`). */\nexport const VIEWER_BLOCKED_REASON = 'You have view access to this project. Ask an owner for edit access to change it.';\n\n/** `failure.stage === 'permission'` from the pipeline (spec §2 \"Limits\"). */\nexport const PERMISSION_FAILURE_TITLE = \"You can't change this project\";\n\nexport function permissionFailureText(message?: string | null): string {\n const m = String(message || '').trim();\n return m || 'You have view access to this project, so the AI did not change it. Ask an owner for edit access.';\n}\n\n/** Turn a server error from a sharing mutation into something a person can act on. */\nexport function sharingErrorText(message: string): string {\n const m = message.trim();\n if (/not (?:a )?member of|not in (?:the|your) org|same org|organization/i.test(m)) {\n return `${m.replace(/\\.?$/, '.')} Only people in your organization can be added.`;\n }\n if (/forbidden|not allowed|only owners|permission/i.test(m)) return 'Only owners can change who has access.';\n return m || 'Something went wrong.';\n}\n"],"names":[],"mappings":"AAoCgB,SAAA,OAAA,CAAQ,MAAsC,MAA6B,EAAA;AACzF,EAAkB,OAAA,IAAA;AAIpB"}
@@ -0,0 +1,59 @@
1
+ const USER_PREFIX = "wbu:";
2
+ const CHAT_LANE_STORAGE_PREFIX = "webbuilder_chat_lane:";
3
+ const CHAT_OUTBOX_PREFIX = "webbuilder_chat_outbox:";
4
+ const APOLLO_CACHE_PREFIX = "wb-apollo-cache:";
5
+ const CHAT_LANE_NO_CHANNEL = "_";
6
+ const CHAT_LANE_ANON = "anon";
7
+ let owner = "";
8
+ function segment(v, fallback) {
9
+ return (String(v != null ? v : "").trim() || fallback).replace(/:/g, "_").slice(0, 200);
10
+ }
11
+ function userKey(name, id) {
12
+ const base = `${USER_PREFIX}${segment(owner, CHAT_LANE_ANON)}:${name}`;
13
+ return id == null ? base : `${base}:${String(id)}`;
14
+ }
15
+ const storageKeys = {
16
+ // Device, localStorage.
17
+ signedOut: () => "yantra.webbuilder.signedOut.v1",
18
+ storageOwner: () => "yantra.webbuilder.storageOwner.v1",
19
+ themeMode: () => "yantra-webbuilder-theme-mode",
20
+ chatPanelWidth: () => "yantra.webbuilder.chatPanelWidth.v1",
21
+ suggestStyles: () => "webbuilder.suggestStyles",
22
+ agentModel: () => "webbuilder.agentModel",
23
+ demoDatabase: () => "webbuilder.demoDatabaseSlug",
24
+ businessCategory: () => "webbuilder.businessCategory",
25
+ // Device, sessionStorage (one-shot handoffs and the tab id).
26
+ mobileHandoff: () => "webbuilder_mobile_handoff",
27
+ remixPending: () => "webbuilder_remix_pending",
28
+ remixNotice: () => "webbuilder_remix_notice",
29
+ realtimeSession: () => "yantra.webbuilder.realtimeSession",
30
+ // User, sessionStorage.
31
+ apolloCache: (graphqlUrl, token) => `${APOLLO_CACHE_PREFIX}${graphqlUrl}:${token.slice(-16)}`,
32
+ /** The Code view's open folders, per project. */
33
+ codeTreeExpanded: (projectKey) => userKey("codeTreeExpanded", projectKey),
34
+ // User, localStorage.
35
+ agentChannel: () => userKey("agentChannel"),
36
+ agentInFlight: () => userKey("agentInFlight"),
37
+ adoptedChannels: () => userKey("adoptedChannels"),
38
+ agentBuilds: () => userKey("agentBuilds"),
39
+ /** Sandboxes a project moved away from -> the project's channel, so an old build link still opens it. */
40
+ sandboxMoves: () => userKey("sandboxMoves"),
41
+ session: () => userKey("session"),
42
+ brandKit: () => userKey("brandKit"),
43
+ lastSiteScore: () => userKey("lastSiteScore"),
44
+ healthNoticeDismissed: (channelId) => userKey("healthNoticeDismissed", channelId),
45
+ restoredSandbox: (channelId) => userKey("restoredSandbox", channelId),
46
+ githubSyncPending: (channelId) => userKey("githubSyncPending", channelId),
47
+ secretsCredentialId: (channelId) => userKey("secretsCredentialId", channelId),
48
+ projectKnowledge: (projectKey) => userKey("projectKnowledge", projectKey),
49
+ projectTitle: (projectKey) => userKey("projectTitle", projectKey),
50
+ projectSettingsMigrated: (projectKey) => userKey("projectSettingsMigrated", projectKey),
51
+ projectExtra: (projectKey) => userKey("projectExtra", projectKey),
52
+ customDomain: (projectName) => userKey("customDomain", projectName),
53
+ unpublished: (projectName) => userKey("unpublished", projectName),
54
+ plans: (channelId) => userKey("plans", channelId),
55
+ planNotes: (planId) => userKey("planNotes", planId),
56
+ /** Plain chat kept per user and channel (the user is the server's id for the lane). */
57
+ chatLane: (userId, channelId) => `${CHAT_LANE_STORAGE_PREFIX}${segment(userId, CHAT_LANE_ANON)}:${segment(channelId, CHAT_LANE_NO_CHANNEL)}`,
58
+ chatOutbox: (userId) => `${CHAT_OUTBOX_PREFIX}${segment(userId, CHAT_LANE_ANON)}`
59
+ };export{CHAT_LANE_ANON,CHAT_LANE_NO_CHANNEL,CHAT_LANE_STORAGE_PREFIX,CHAT_OUTBOX_PREFIX,storageKeys};//# sourceMappingURL=storageKeys.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storageKeys.js","sources":["../../../../../src/features/webbuilder/web/state/storageKeys.ts"],"sourcesContent":["/** Every Web Storage key the surface uses; user keys live under `wbu:<uid>:` and go on sign-out or account change. */\n\nexport type KeyValueStore = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'> & {\n readonly length?: number;\n key?(index: number): string | null;\n};\n\nconst USER_PREFIX = 'wbu:';\nexport const CHAT_LANE_STORAGE_PREFIX = 'webbuilder_chat_lane:';\nexport const CHAT_OUTBOX_PREFIX = 'webbuilder_chat_outbox:';\nconst APOLLO_CACHE_PREFIX = 'wb-apollo-cache:';\nexport const CHAT_LANE_NO_CHANNEL = '_';\nexport const CHAT_LANE_ANON = 'anon';\n\nlet owner = '';\n\nfunction segment(v: string | null | undefined, fallback: string): string {\n return (String(v ?? '').trim() || fallback).replace(/:/g, '_').slice(0, 200);\n}\n\n/** The account user keys are scoped to (the token `sub`); '' until a token is known. */\nexport function storageOwner(): string {\n return owner;\n}\n\nexport function setStorageOwner(uid: string | null | undefined): void {\n owner = String(uid ?? '').trim();\n}\n\nfunction userKey(name: string, id?: string | null): string {\n const base = `${USER_PREFIX}${segment(owner, CHAT_LANE_ANON)}:${name}`;\n return id == null ? base : `${base}:${String(id)}`;\n}\n\nexport const REATTACH_WINDOW_MS = 30 * 60_000;\nexport const HANDOFF_TTL_MS = 15 * 60_000;\n\nexport const storageKeys = {\n // Device, localStorage.\n signedOut: () => 'yantra.webbuilder.signedOut.v1',\n storageOwner: () => 'yantra.webbuilder.storageOwner.v1',\n themeMode: () => 'yantra-webbuilder-theme-mode',\n chatPanelWidth: () => 'yantra.webbuilder.chatPanelWidth.v1',\n suggestStyles: () => 'webbuilder.suggestStyles',\n agentModel: () => 'webbuilder.agentModel',\n demoDatabase: () => 'webbuilder.demoDatabaseSlug',\n businessCategory: () => 'webbuilder.businessCategory',\n // Device, sessionStorage (one-shot handoffs and the tab id).\n mobileHandoff: () => 'webbuilder_mobile_handoff',\n remixPending: () => 'webbuilder_remix_pending',\n remixNotice: () => 'webbuilder_remix_notice',\n realtimeSession: () => 'yantra.webbuilder.realtimeSession',\n // User, sessionStorage.\n apolloCache: (graphqlUrl: string, token: string) => `${APOLLO_CACHE_PREFIX}${graphqlUrl}:${token.slice(-16)}`,\n /** The Code view's open folders, per project. */\n codeTreeExpanded: (projectKey: string) => userKey('codeTreeExpanded', projectKey),\n // User, localStorage.\n agentChannel: () => userKey('agentChannel'),\n agentInFlight: () => userKey('agentInFlight'),\n adoptedChannels: () => userKey('adoptedChannels'),\n agentBuilds: () => userKey('agentBuilds'),\n /** Sandboxes a project moved away from -> the project's channel, so an old build link still opens it. */\n sandboxMoves: () => userKey('sandboxMoves'),\n session: () => userKey('session'),\n brandKit: () => userKey('brandKit'),\n lastSiteScore: () => userKey('lastSiteScore'),\n healthNoticeDismissed: (channelId: string) => userKey('healthNoticeDismissed', channelId),\n restoredSandbox: (channelId: string) => userKey('restoredSandbox', channelId),\n githubSyncPending: (channelId: string) => userKey('githubSyncPending', channelId),\n secretsCredentialId: (channelId: string) => userKey('secretsCredentialId', channelId),\n projectKnowledge: (projectKey: string) => userKey('projectKnowledge', projectKey),\n projectTitle: (projectKey: string) => userKey('projectTitle', projectKey),\n projectSettingsMigrated: (projectKey: string) => userKey('projectSettingsMigrated', projectKey),\n projectExtra: (projectKey: string) => userKey('projectExtra', projectKey),\n customDomain: (projectName: string) => userKey('customDomain', projectName),\n unpublished: (projectName: string) => userKey('unpublished', projectName),\n plans: (channelId: string) => userKey('plans', channelId),\n planNotes: (planId: string) => userKey('planNotes', planId),\n /** Plain chat kept per user and channel (the user is the server's id for the lane). */\n chatLane: (userId: string | null | undefined, channelId: string | null | undefined) =>\n `${CHAT_LANE_STORAGE_PREFIX}${segment(userId, CHAT_LANE_ANON)}:${segment(channelId, CHAT_LANE_NO_CHANNEL)}`,\n chatOutbox: (userId: string | null | undefined) => `${CHAT_OUTBOX_PREFIX}${segment(userId, CHAT_LANE_ANON)}`,\n};\n\ntype PerIdKey = {\n [K in keyof typeof storageKeys]: Parameters<(typeof storageKeys)[K]> extends [string] ? K : never;\n}[keyof typeof storageKeys];\n\n/** Unscoped keys from before the registry: read once into the owner's keys, then removed. */\nconst LEGACY_SINGLE: ReadonlyArray<[string, () => string]> = [\n ['yantra.webbuilder.agentChannel.v1', storageKeys.agentChannel],\n ['yantra.webbuilder.agentInFlight.v1', storageKeys.agentInFlight],\n ['yantra.webbuilder.adoptedChannels.v1', storageKeys.adoptedChannels],\n ['yantra.webbuilder.agentBuilds.v1', storageKeys.agentBuilds],\n ['webbuilder_session', storageKeys.session],\n ['yantra.webbuilder.brandKit.v1', storageKeys.brandKit],\n ['yantra.webbuilder.lastSiteScore.v1', storageKeys.lastSiteScore],\n];\n\nconst LEGACY_PER_ID: ReadonlyArray<[string, PerIdKey]> = [\n ['webbuilder.healthNotice.dismissed.', 'healthNoticeDismissed'],\n ['webbuilder-restored-sandbox-', 'restoredSandbox'],\n ['wb:githubSyncPending:', 'githubSyncPending'],\n ['wb:secretsCredentialId:', 'secretsCredentialId'],\n ['wb:projectKnowledge:', 'projectKnowledge'],\n ['wb:projectTitle:', 'projectTitle'],\n ['wb:projectSettingsMigrated:', 'projectSettingsMigrated'],\n ['wb:projectExtra:', 'projectExtra'],\n ['webbuilder-custom-domain-', 'customDomain'],\n ['webbuilder-unpublished-', 'unpublished'],\n ['webbuilder_plans:', 'plans'],\n ['webbuilder_plan_notes:', 'planNotes'],\n];\n\n/** Keys nothing reads or writes any more. */\nconst DEAD_KEYS = ['webbuilder_workflow'];\nconst DEAD_PREFIXES = [\n 'preview-github-repo-',\n 'preview-github-url-',\n 'preview-cloudflare-project-',\n 'preview-cloudflare-domain-',\n];\n\n/** Keys with a lifetime, and where their write time lives in the stored JSON. */\nconst TTL: ReadonlyArray<{ key: () => string; ttlMs: number; stampOf: (v: Record<string, unknown>) => unknown }> = [\n { key: storageKeys.agentInFlight, ttlMs: REATTACH_WINDOW_MS, stampOf: (v) => v.startedAt },\n { key: storageKeys.mobileHandoff, ttlMs: HANDOFF_TTL_MS, stampOf: (v) => v.savedAt },\n { key: storageKeys.remixPending, ttlMs: HANDOFF_TTL_MS, stampOf: (v) => v.savedAt },\n];\n\n/** True when a stored write time is older than `ttlMs`; values without a time never expire. */\nexport function isExpired(savedAt: unknown, ttlMs: number, now: number = Date.now()): boolean {\n return typeof savedAt === 'number' && Number.isFinite(savedAt) && now - savedAt > ttlMs;\n}\n\nfunction allKeys(store: KeyValueStore | null): string[] {\n const out: string[] = [];\n try {\n if (!store || typeof store.key !== 'function' || typeof store.length !== 'number') return out;\n for (let i = 0; i < store.length; i++) {\n const k = store.key(i);\n if (k) out.push(k);\n }\n } catch {\n /* unreadable */\n }\n return out;\n}\n\nfunction get(store: KeyValueStore | null, key: string): string | null {\n try {\n return store?.getItem(key) ?? null;\n } catch {\n return null;\n }\n}\n\nfunction remove(store: KeyValueStore | null, key: string): void {\n try {\n store?.removeItem(key);\n } catch {\n /* storage unavailable */\n }\n}\n\nfunction moveOnce(store: KeyValueStore, from: string, to: string): void {\n const raw = get(store, from);\n if (raw === null) return;\n try {\n if (store.getItem(to) === null) store.setItem(to, raw);\n } catch {\n /* quota: the legacy value is dropped */\n }\n remove(store, from);\n}\n\nfunction isLegacyOrDead(key: string): boolean {\n return (\n LEGACY_SINGLE.some(([k]) => k === key) ||\n DEAD_KEYS.includes(key) ||\n [...LEGACY_PER_ID.map(([p]) => p), ...DEAD_PREFIXES].some((p) => key.startsWith(p))\n );\n}\n\nfunction isUserKey(key: string): boolean {\n return (\n key.startsWith(USER_PREFIX) ||\n key.startsWith(CHAT_LANE_STORAGE_PREFIX) ||\n key.startsWith(CHAT_OUTBOX_PREFIX) ||\n key.startsWith(APOLLO_CACHE_PREFIX)\n );\n}\n\n/** Copy the pre-registry unscoped keys into the current owner's keys and drop the dead ones. */\nexport function migrateLegacyKeys(store: KeyValueStore | null): void {\n if (!store) return;\n for (const [from, to] of LEGACY_SINGLE) moveOnce(store, from, to());\n const keys = allKeys(store);\n for (const [prefix, name] of LEGACY_PER_ID) {\n for (const k of keys) {\n if (k.startsWith(prefix) && k.length > prefix.length)\n moveOnce(store, k, storageKeys[name](k.slice(prefix.length)));\n }\n }\n removeDeadKeys(store);\n}\n\nexport function removeDeadKeys(store: KeyValueStore | null): void {\n for (const k of allKeys(store))\n if (DEAD_KEYS.includes(k) || DEAD_PREFIXES.some((p) => k.startsWith(p))) remove(store, k);\n}\n\n/** Remove every user key (any account), legacy and dead key. Device preferences stay. */\nexport function clearUserStorage(...stores: Array<KeyValueStore | null>): void {\n for (const store of stores) {\n for (const k of allKeys(store)) if (isUserKey(k) || isLegacyOrDead(k)) remove(store, k);\n }\n}\n\n/** Drop keys whose stored write time is past their TTL. */\nexport function pruneExpired(stores: Array<KeyValueStore | null>, now: number = Date.now()): void {\n for (const store of stores) {\n for (const { key, ttlMs, stampOf } of TTL) {\n const raw = get(store, key());\n if (!raw) continue;\n try {\n const v = JSON.parse(raw) as unknown;\n if (v && typeof v === 'object' && isExpired(stampOf(v as Record<string, unknown>), ttlMs, now)) {\n remove(store, key());\n }\n } catch {\n remove(store, key());\n }\n }\n }\n}\n\nexport type OwnerChange = 'same' | 'adopted' | 'changed';\n\n/** A different `sub` than the stored owner wipes every user key; the first owner adopts the legacy keys. */\nexport function adoptStorageOwner(\n sub: string,\n local: KeyValueStore | null,\n session: KeyValueStore | null = null,\n now: number = Date.now(),\n): OwnerChange {\n const uid = String(sub || '').trim();\n setStorageOwner(uid);\n pruneExpired([local, session], now);\n if (!uid) return 'same';\n const prev = get(local, storageKeys.storageOwner());\n let change: OwnerChange = 'same';\n if (prev && prev !== uid) {\n clearUserStorage(local, session);\n change = 'changed';\n } else if (!prev) {\n change = 'adopted';\n }\n if (change !== 'changed') migrateLegacyKeys(local);\n try {\n local?.setItem(storageKeys.storageOwner(), uid);\n } catch {\n /* storage unavailable */\n }\n return change;\n}\n\n/** Sign-out: every user key goes and storage belongs to no one. */\nexport function forgetStorageOwner(local: KeyValueStore | null, session: KeyValueStore | null = null): void {\n clearUserStorage(local, session);\n remove(local, storageKeys.storageOwner());\n setStorageOwner('');\n}\n"],"names":[],"mappings":"AAMA,MAAM,WAAc,GAAA,MAAA;AACb,MAAM,wBAA2B,GAAA;AACjC,M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