Merge remote-tracking branch 'origin/main' into feat-mfa-factors-policy-card

# Conflicts:
#	bun.lock
This commit is contained in:
harsh mahajan committed 2026-08-17 15:53:22 +05:30
commit a97d8874e1
48 files changed
+703 -1175

No files matched your search

@@ -8,6 +8,7 @@
import { Link } from '$lib/elements';
import { page } from '$app/state';
import { IconPlus, IconX } from '@appwrite.io/pink-icons-svelte';
import { validateVariables } from '$lib/helpers/variables';
export type ProductLabel = 'site' | 'function';
@@ -39,13 +40,13 @@
newVariables = newVariables.map((variable) => ({ ...variable, secret: true }));
}
newVariables.forEach((variable) => {
if (('' + variable.value).length > 8192) {
throw new Error(
`Variable ${variable.key} is longer than 8192 allowed characters`
);
}
});
const validationError = validateVariables(
newVariables.filter((variable) => variable.key || variable.value)
);
if (validationError) {
throw new Error(validationError);
}
const updatedVariables = [...variables];
newVariables.forEach((newVar) => {
if (!newVar.key) {
@@ -22,6 +22,7 @@
import UpdateVariableModal from './updateVariableModal.svelte';
import { Click, trackEvent } from '$lib/actions/analytics';
import { isSmallViewport } from '$lib/stores/viewport';
import { isValidVariableKey } from '$lib/helpers/variables';
const DOCS_LINKS: Record<ProductLabel, string> = {
site: 'https://appwrite.io/docs/products/sites/develop#accessing-environment-variables',
@@ -146,7 +147,28 @@
</svelte:fragment>
{#each paginatedItems as variable}
<Table.Row.Base {root}>
<Table.Cell column="key" {root}>{variable.key}</Table.Cell>
<Table.Cell column="key" {root}>
<Layout.Stack
gap="xxs"
alignItems="center"
direction="row"
inline>
{#if !isValidVariableKey(variable.key)}
<Tooltip maxWidth="26rem">
<span
class="icon-exclamation u-color-text-danger"
aria-hidden="true"></span>
<svelte:fragment slot="tooltip">
This key can't be used as an environment
variable name. Rename it using only letters,
digits and underscores, without starting
with a digit.
</svelte:fragment>
</Tooltip>
{/if}
{variable.key}
</Layout.Stack>
</Table.Cell>
<Table.Cell column="value" {root}>
<!-- TODO: fix max width -->
<div style="max-width: 100%">
@@ -7,6 +7,7 @@
import { Icon, Layout, Selector, Tooltip, Typography, Upload } from '@appwrite.io/pink-svelte';
import { parse } from '$lib/helpers/envfile';
import { removeFile } from '$lib/helpers/files';
import { validateVariables } from '$lib/helpers/variables';
export let show = false;
export let variables: Partial<Models.Variable>[];
@@ -35,19 +36,20 @@
if (!Object.keys(uploaded).length) {
throw new Error('No variables found');
}
const entries = Object.entries(uploaded);
// Drop the valueless entries first. They are never written, so an
// invalid key on one of them must not reject the whole file.
const entries = Object.entries(uploaded).filter(([, value]) => !!value);
for (const [key, value] of entries) {
if (value.length > 8192) {
throw new Error(`Variable ${key} is longer than 8192 allowed characters`);
}
const validationError = validateVariables(
entries.map(([key, value]) => ({ key, value }))
);
if (validationError) {
throw new Error(validationError);
}
entries
.filter(([, value]) => !!value)
.forEach(([key, value]) => {
variables.push({ key, value, secret });
});
entries.forEach(([key, value]) => {
variables.push({ key, value, secret });
});
show = false;
} catch (e) {
@@ -7,6 +7,7 @@
import { Layout, Selector } from '@appwrite.io/pink-svelte';
import { Link } from '$lib/elements';
import { page } from '$app/state';
import { validateVariables } from '$lib/helpers/variables';
export let show = false;
export let selectedVar: Partial<Models.Variable>;
@@ -20,7 +21,15 @@
secret: selectedVar?.secret
};
let error = '';
function handleVariable() {
const validationError = validateVariables([pair]);
if (validationError) {
error = validationError;
return;
}
if (selectedVar) {
variables = variables.map((variable) => {
const match = selectedVar.$id
@@ -39,7 +48,7 @@
}
</script>
<Modal bind:show onSubmit={handleVariable} title="Update variable">
<Modal bind:show onSubmit={handleVariable} title="Update variable" bind:error>
<span slot="description">
Update the environment variable for your {productLabel}. Global variables can be set in
<Link
@@ -5,6 +5,7 @@
import Button from '$lib/elements/forms/button.svelte';
import { addNotification } from '$lib/stores/notifications';
import { parse } from '$lib/helpers/envfile';
import { validateVariables } from '$lib/helpers/variables';
import { Alert, Icon, Layout, Tabs } from '@appwrite.io/pink-svelte';
import { IconDownload, IconDuplicate } from '@appwrite.io/pink-icons-svelte';
import { InputTextarea } from '$lib/elements/forms';
@@ -47,10 +48,11 @@
const vars = tab === 'env' ? parse(envCode) : JSON.parse(jsonCode ? jsonCode : '{}');
const entries = Object.entries(vars);
for (const [key, value] of entries) {
if (('' + value).length > 8192) {
throw new Error(`Variable ${key} is longer than 8192 allowed characters`);
}
const validationError = validateVariables(
entries.map(([key, value]) => ({ key, value }))
);
if (validationError) {
throw new Error(validationError);
}
// Update or remove editable variables
+7
View File
@@ -0,0 +1,7 @@
import { getApiEndpoint } from '$lib/stores/sdk';
export function getCampaignImageUrl(image: string) {
const endpoint = getApiEndpoint();
const url = new URL(image, endpoint);
return url.toString();
}
+27
View File
@@ -0,0 +1,27 @@
import { describe, expect, it } from 'vitest';
import { resolveOAuth2AppLogoUrl } from './oauth2-app-logo';
describe('resolveOAuth2AppLogoUrl', () => {
it('uses the square Appwrite icon for the first-party CLI client', () => {
expect(
resolveOAuth2AppLogoUrl({
$id: 'appwrite-cli',
logoUri: 'https://example.com/wordmark.svg'
})
).toBe('/console/logos/appwrite-icon.svg');
});
it('keeps third-party logoUri values', () => {
expect(
resolveOAuth2AppLogoUrl({
$id: 'other-app',
logoUri: 'https://example.com/logo.png'
})
).toBe('https://example.com/logo.png');
});
it('returns an empty string when no logo is available', () => {
expect(resolveOAuth2AppLogoUrl({ $id: 'other-app', logoUri: ' ' })).toBe('');
expect(resolveOAuth2AppLogoUrl(null)).toBe('');
});
});
+18
View File
@@ -0,0 +1,18 @@
import { base } from '$app/paths';
/**
* First-party clients may register a wide wordmark as `logoUri`. Consent and
* outcome avatars are square, so `object-fit: cover` crops those marks into
* unreadable fragments (see #3159 for Appwrite CLI). Prefer the square icon.
*/
const FIRST_PARTY_ICON_CLIENTS = new Set(['appwrite-cli']);
export function resolveOAuth2AppLogoUrl(
app: { $id?: string; logoUri?: string } | null | undefined
): string {
if (app?.$id && FIRST_PARTY_ICON_CLIENTS.has(app.$id)) {
return `${base}/logos/appwrite-icon.svg`;
}
return app?.logoUri?.trim() ?? '';
}
+76
View File
@@ -0,0 +1,76 @@
import { cimdDocumentToApp, isCimdClientId } from '$lib/helpers/oauth2-cimd';
import { describe, expect, it } from 'vitest';
describe('isCimdClientId', () => {
it('accepts https URLs', () => {
expect(isCimdClientId('https://example.com/oauth/client-metadata.json')).toBe(true);
});
it('accepts http only for loopback', () => {
expect(isCimdClientId('http://localhost:3000/client.json')).toBe(true);
expect(isCimdClientId('http://127.0.0.1/client.json')).toBe(true);
expect(isCimdClientId('http://example.com/client.json')).toBe(false);
});
it('rejects plain app IDs and non-http schemes', () => {
expect(isCimdClientId('my-app_1.0')).toBe(false);
expect(isCimdClientId('64f1e2a9b3c4d5e6f7a8')).toBe(false);
expect(isCimdClientId('javascript:alert(1)')).toBe(false);
});
});
describe('cimdDocumentToApp', () => {
const clientId = 'https://example.com/oauth/client-metadata.json';
it('maps RFC 7591 metadata onto the App model', () => {
const app = cimdDocumentToApp(clientId, {
client_id: clientId,
client_name: 'Example App',
client_uri: 'https://example.com',
logo_uri: 'https://example.com/logo.png',
policy_uri: 'https://example.com/privacy',
tos_uri: 'https://example.com/terms',
contacts: ['support@example.com'],
redirect_uris: ['https://example.com/callback'],
token_endpoint_auth_method: 'none',
grant_types: ['authorization_code', 'urn:ietf:params:oauth:grant-type:device_code']
});
expect(app.$id).toBe(clientId);
expect(app.name).toBe('Example App');
expect(app.clientUri).toBe('https://example.com');
expect(app.logoUri).toBe('https://example.com/logo.png');
expect(app.privacyPolicyUrl).toBe('https://example.com/privacy');
expect(app.termsUrl).toBe('https://example.com/terms');
expect(app.contacts).toEqual(['support@example.com']);
expect(app.redirectUris).toEqual(['https://example.com/callback']);
expect(app.type).toBe('public');
expect(app.deviceFlow).toBe(true);
expect(app.enabled).toBe(true);
});
it('falls back to the hostname when client_name is missing', () => {
const app = cimdDocumentToApp(clientId, { client_id: clientId });
expect(app.name).toBe('example.com');
expect(app.deviceFlow).toBe(false);
});
it('rejects a document whose client_id does not match its URL', () => {
expect(() =>
cimdDocumentToApp(clientId, { client_id: 'https://evil.example/other.json' })
).toThrow();
expect(() => cimdDocumentToApp(clientId, 'not an object')).toThrow();
});
it('drops unrenderable URI values', () => {
const app = cimdDocumentToApp(clientId, {
client_id: clientId,
logo_uri: 'javascript:alert(1)',
client_uri: 'not a url',
contacts: ['ok', 42]
});
expect(app.logoUri).toBe('');
expect(app.clientUri).toBe('');
expect(app.contacts).toEqual(['ok']);
});
});
+108
View File
@@ -0,0 +1,108 @@
import { sdk } from '$lib/stores/sdk';
import type { Models } from '@appwrite.io/console';
// CIMD (Client ID Metadata Document): a client_id may be an HTTPS URL pointing
// to a JSON document of RFC 7591 client metadata. The Appwrite API no longer
// resolves these, so the console fetches the document itself for branding.
const FETCH_TIMEOUT = 10_000;
const DEVICE_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:device_code';
const HTTP_URL = /^https?:\/\//i;
type CimdDocument = {
client_id?: unknown;
client_name?: unknown;
client_uri?: unknown;
logo_uri?: unknown;
policy_uri?: unknown;
tos_uri?: unknown;
contacts?: unknown;
redirect_uris?: unknown;
post_logout_redirect_uris?: unknown;
token_endpoint_auth_method?: unknown;
grant_types?: unknown;
};
// Plain app IDs never parse as URLs; http is allowed for local development only.
export function isCimdClientId(clientId: string): boolean {
try {
const url = new URL(clientId);
return (
url.protocol === 'https:' ||
(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))
);
} catch {
return false;
}
}
export function cimdDocumentToApp(clientId: string, document: unknown): Models.App {
if (typeof document !== 'object' || document === null) {
throw new Error('CIMD document is not a JSON object');
}
const doc = document as CimdDocument;
// The document's client_id must equal the URL it was fetched from.
if (doc.client_id !== clientId) {
throw new Error('CIMD document client_id does not match its URL');
}
const name = typeof doc.client_name === 'string' ? doc.client_name.trim() : '';
return {
$id: clientId,
$createdAt: '',
$updatedAt: '',
name: name || new URL(clientId).hostname,
description: '',
// Untrusted values rendered in href/src must be http(s) URLs.
clientUri:
typeof doc.client_uri === 'string' && HTTP_URL.test(doc.client_uri)
? doc.client_uri
: '',
logoUri:
typeof doc.logo_uri === 'string' && HTTP_URL.test(doc.logo_uri) ? doc.logo_uri : '',
privacyPolicyUrl:
typeof doc.policy_uri === 'string' && HTTP_URL.test(doc.policy_uri)
? doc.policy_uri
: '',
termsUrl: typeof doc.tos_uri === 'string' && HTTP_URL.test(doc.tos_uri) ? doc.tos_uri : '',
contacts: Array.isArray(doc.contacts)
? doc.contacts.filter((contact) => typeof contact === 'string')
: [],
tagline: '',
tags: [],
images: [],
supportUrl: '',
dataDeletionUrl: '',
redirectUris: Array.isArray(doc.redirect_uris)
? doc.redirect_uris.filter((uri) => typeof uri === 'string')
: [],
postLogoutRedirectUris: Array.isArray(doc.post_logout_redirect_uris)
? doc.post_logout_redirect_uris.filter((uri) => typeof uri === 'string')
: [],
enabled: true,
type: doc.token_endpoint_auth_method === 'none' ? 'public' : 'confidential',
deviceFlow: Array.isArray(doc.grant_types) && doc.grant_types.includes(DEVICE_GRANT_TYPE),
teamId: '',
userId: '',
secrets: []
};
}
// Plain IDs resolve via the API; CIMD URLs are fetched directly. Fetch or
// validation failures fall back to hostname-only branding rather than blocking
// the flow — the server still validates the client during authorization.
export async function getOAuth2App(appId: string): Promise<Models.App> {
if (!isCimdClientId(appId)) {
return sdk.forConsole.apps.get({ appId });
}
try {
const response = await fetch(appId, {
headers: { accept: 'application/json' },
credentials: 'omit',
signal: AbortSignal.timeout(FETCH_TIMEOUT)
});
if (!response.ok) throw new Error(`CIMD document request failed: ${response.status}`);
return cimdDocumentToApp(appId, await response.json());
} catch {
return cimdDocumentToApp(appId, { client_id: appId });
}
}
+49
View File
@@ -0,0 +1,49 @@
import { expect, test } from 'vitest';
import {
getVariableKeyError,
isValidVariableKey,
validateVariables,
VARIABLE_KEY_MAX_LENGTH,
VARIABLE_VALUE_MAX_LENGTH
} from '$lib/helpers/variables';
test('accept keys that are valid environment variable names', () => {
expect(isValidVariableKey('APP_TEST')).toBe(true);
expect(isValidVariableKey('_PRIVATE')).toBe(true);
expect(isValidVariableKey('key1')).toBe(true);
expect(isValidVariableKey('a'.repeat(VARIABLE_KEY_MAX_LENGTH))).toBe(true);
});
test('reject keys that cannot be used as environment variable names', () => {
expect(isValidVariableKey('MY-KEY')).toBe(false);
expect(isValidVariableKey('MY.KEY')).toBe(false);
expect(isValidVariableKey('MY KEY')).toBe(false);
expect(isValidVariableKey('9KEY')).toBe(false);
expect(isValidVariableKey('KÉY')).toBe(false);
expect(isValidVariableKey('KEY\t')).toBe(false);
expect(isValidVariableKey('')).toBe(false);
expect(isValidVariableKey('a'.repeat(VARIABLE_KEY_MAX_LENGTH + 1))).toBe(false);
});
test('report a missing key separately from an invalid one', () => {
expect(getVariableKeyError('')).toEqual('Variable key is required');
expect(getVariableKeyError('MY-KEY')).toContain('is invalid');
expect(getVariableKeyError('a'.repeat(VARIABLE_KEY_MAX_LENGTH + 1))).toContain('longer than');
expect(getVariableKeyError('APP_TEST')).toBeNull();
});
test('validate a list of variables and name the offending key', () => {
expect(validateVariables([{ key: 'APP_TEST', value: 'value' }])).toBeNull();
expect(validateVariables([{ key: 'APP_TEST', value: '' }])).toBeNull();
expect(
validateVariables([
{ key: 'APP_TEST', value: 'value' },
{ key: 'MY-KEY', value: 'value' }
])
).toContain('MY-KEY');
expect(
validateVariables([{ key: 'APP_TEST', value: 'v'.repeat(VARIABLE_VALUE_MAX_LENGTH + 1) }])
).toContain('APP_TEST');
});
+66
View File
@@ -1,5 +1,71 @@
import type { Models } from '@appwrite.io/console';
export const VARIABLE_KEY_MAX_LENGTH = 255;
export const VARIABLE_VALUE_MAX_LENGTH = 8192;
/**
* Variable keys become environment variable names at build and runtime, so the
* API only accepts C-style identifiers. Keys stored before that rule existed
* can still fail this check, which is why `isValidVariableKey` is also used to
* flag them in the variables table.
*/
const VARIABLE_KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
export function isValidVariableKey(key: string): boolean {
return (
typeof key === 'string' &&
key.length <= VARIABLE_KEY_MAX_LENGTH &&
VARIABLE_KEY_PATTERN.test(key)
);
}
export function getVariableKeyError(key: string): string | null {
if (!key) {
return 'Variable key is required';
}
if (key.length > VARIABLE_KEY_MAX_LENGTH) {
return `Variable key "${key}" is longer than ${VARIABLE_KEY_MAX_LENGTH} allowed characters`;
}
if (!VARIABLE_KEY_PATTERN.test(key)) {
return `Variable key "${key}" is invalid. Keys can only contain letters, digits and underscores, and cannot start with a digit`;
}
return null;
}
export function getVariableValueError(key: string, value: unknown): string | null {
if (('' + (value ?? '')).length > VARIABLE_VALUE_MAX_LENGTH) {
return `Variable ${key} is longer than ${VARIABLE_VALUE_MAX_LENGTH} allowed characters`;
}
return null;
}
/**
* Returns the first problem found, or null when every variable is accepted by
* the API. Call before submitting so a rejected key is reported against the
* file or row it came from instead of as a bare server error.
*/
export function validateVariables(
variables: Array<{ key?: string; value?: unknown }>
): string | null {
for (const { key, value } of variables) {
const keyError = getVariableKeyError(key);
if (keyError) {
return keyError;
}
const valueError = getVariableValueError(key, value);
if (valueError) {
return valueError;
}
}
return null;
}
export function normalizeDetectedVariables(
detected: Models.DetectionVariable[] = []
): Partial<Models.Variable>[] {
+1 -1
View File
@@ -7,7 +7,7 @@
import LoginLight from '$lib/images/login/login-light-mode.png';
import { app } from '$lib/stores/app';
import { Typography, Layout, Avatar } from '@appwrite.io/pink-svelte';
import { getCampaignImageUrl } from '$routes/(public)/card/helpers';
import { getCampaignImageUrl } from '$lib/helpers/campaign';
import { isSmallViewport } from '$lib/stores/viewport';
import type { Models } from '@appwrite.io/console';
-6
View File
@@ -1,9 +1,3 @@
import type { Models } from '@appwrite.io/console';
export type FrameworkAdapterWithStartCommand = Models.FrameworkAdapter & {
startCommand?: string;
};
export function getFrameworkIcon(framework: string) {
switch (true) {
case framework.toLocaleLowerCase().includes('sveltekit'):
-29
View File
@@ -1,29 +0,0 @@
import { readable, type Readable } from 'svelte/store';
function isCurrentWindowFocused(): boolean {
if (!window) return false;
if (!window.document) return false;
if (typeof window.document.hasFocus !== 'function') return false;
return window.document.hasFocus();
}
export function windowFocusStore(): Readable<boolean> {
const visibility = readable(isCurrentWindowFocused(), (set) => {
function handler() {
set(isCurrentWindowFocused());
}
if (window) {
window.addEventListener('focus', handler);
window.addEventListener('blur', handler);
return () => {
window.removeEventListener('focus', handler);
window.removeEventListener('blur', handler);
};
}
});
return visibility;
}
-1
View File
@@ -331,7 +331,6 @@
<CommandCenter />
<Shell
showSideNavigation={page.url.pathname !== '/' &&
!page.url.pathname.includes(base + '/card') &&
!page.url.pathname.includes(base + '/onboarding')}
showHeader={!page.url.pathname.includes(base + '/onboarding/create-project')}
showFooter={!page.url.pathname.includes(base + '/onboarding/create-project')}
@@ -1,5 +1,5 @@
import { Dependencies } from '$lib/constants';
import { sdk } from '$lib/stores/sdk';
import { getOAuth2App } from '$lib/helpers/oauth2-cimd';
import type { Models } from '@appwrite.io/console';
import type { PageLoad } from './$types';
@@ -19,7 +19,7 @@ export const load: PageLoad = async ({ depends, parent }) => {
const connectedApps = await Promise.all(
grants.map(async (identity) => {
const appId = identity.provider.slice(OAUTH2_PREFIX.length);
const app = await sdk.forConsole.apps.get({ appId }).catch(() => null);
const app = await getOAuth2App(appId).catch(() => null);
return { identity, appId, app };
})
);
@@ -52,7 +52,7 @@
await invalidate(Dependencies.USER);
addNotification({
message: `${$user.name || $user.email || $user.phone || 'The account'} has been ${
$user.phoneVerification ? 'unverified' : 'verified'
!$user.phoneVerification ? 'unverified' : 'verified'
}`,
type: 'success'
});
@@ -9,12 +9,14 @@
import { Alert, Layout, Selector, Button as PinkButton, Icon } from '@appwrite.io/pink-svelte';
import { Link } from '$lib/elements';
import { IconPlus, IconX } from '@appwrite.io/pink-icons-svelte';
import { validateVariables } from '$lib/helpers/variables';
export let isGlobal: boolean;
export let product: 'function' | 'site' = 'function';
export let showCreate = false;
let newVariables: Partial<Models.Variable>[] = [{ key: '', value: '' }];
let secret = false;
let error = '';
const dispatch = createEventDispatcher();
@@ -26,12 +28,16 @@
if (secret) {
newVariables = newVariables.map((variable) => ({ ...variable, secret: true }));
}
newVariables.forEach((variable) => {
if (('' + variable.value).length > 8192) {
throw new Error(`Variable ${variable.key} is longer than 8192 allowed characters`);
}
});
dispatch('created', newVariables);
const filled = newVariables.filter((variable) => variable.key || variable.value);
const validationError = validateVariables(filled);
if (validationError) {
error = validationError;
return;
}
dispatch('created', filled);
close();
}
@@ -48,6 +54,7 @@
<Modal
bind:show={showCreate}
bind:error
onSubmit={handleVariable}
title={`Create ${isGlobal ? 'global' : 'environment'} variables`}>
<svelte:fragment slot="description">
@@ -88,7 +88,7 @@
{:else}
<!-- the `on:click` is from string > array mode for advanced edit button -->
<svelte:component
this={column.array || (isSpatialType(column) && limited)
this={array || (isSpatialType(column) && limited)
? columnsTypeMap['string']
: columnsTypeMap[column.type]}
{id}
@@ -25,6 +25,7 @@
import { getLatestTag } from '$lib/helpers/github';
import { writable } from 'svelte/store';
import Link from '$lib/elements/link.svelte';
import { validateVariables } from '$lib/helpers/variables';
let {
data
@@ -97,6 +98,13 @@
$isSubmitting = true;
try {
// Reject an unusable key before the resource is created, so a
// rejected variable can't leave a half-configured resource behind.
const validationError = validateVariables(variables);
if (validationError) {
throw new Error(validationError);
}
if (!latestTag) {
latestTag = await getLatestTag(data.repository.owner, data.repository.name);
}
@@ -28,6 +28,7 @@
import { humanFileSize } from '$lib/helpers/sizeConvertion';
import { currentPlan } from '$lib/stores/organization';
import { uploader } from '$lib/stores/uploader';
import { validateVariables } from '$lib/helpers/variables';
export let data;
@@ -69,6 +70,13 @@
let func: Models.Function | null = null;
try {
// Reject an unusable key before the resource is created, so a
// rejected variable can't leave a half-configured resource behind.
const validationError = validateVariables(variables);
if (validationError) {
throw new Error(validationError);
}
func = await sdk.forProject(page.params.region, page.params.project).functions.create({
functionId: id || ID.unique(),
name,
@@ -22,7 +22,11 @@
import RepoCard from './repoCard.svelte';
import { getIconFromRuntime } from '$lib/stores/runtimes';
import { regionalConsoleVariables } from '$routes/(console)/project-[region]-[project]/store';
import { normalizeDetectedVariables, mergeVariables } from '$lib/helpers/variables';
import {
normalizeDetectedVariables,
mergeVariables,
validateVariables
} from '$lib/helpers/variables';
export let data;
@@ -104,6 +108,13 @@
async function create() {
try {
// Reject an unusable key before the resource is created, so a
// rejected variable can't leave a half-configured resource behind.
const validationError = validateVariables(variables);
if (validationError) {
throw new Error(validationError);
}
const func = await sdk
.forProject(page.params.region, page.params.project)
.functions.create({
@@ -38,6 +38,7 @@
import { getIconFromRuntime } from '$lib/stores/runtimes';
import { regionalConsoleVariables } from '$routes/(console)/project-[region]-[project]/store';
import type { PageData } from './$types';
import { validateVariables } from '$lib/helpers/variables';
let { data }: { data: PageData } = $props();
@@ -148,6 +149,15 @@
return;
} else {
try {
// Reject an unusable key before the resource is created, so a
// rejected variable can't leave a half-configured resource behind.
const validationError = validateVariables(
variables.map((variable) => ({ key: variable.name, value: variable.value }))
);
if (validationError) {
throw new Error(validationError);
}
const rt = data.template.runtimes.find((r) => r.name === runtime);
const func = await sdk
@@ -6,6 +6,7 @@
import { addNotification } from '$lib/stores/notifications';
import type { Models } from '@appwrite.io/console';
import { parse } from '$lib/helpers/envfile';
import { validateVariables } from '$lib/helpers/variables';
import { Icon, InlineCode, Layout, Tabs } from '@appwrite.io/pink-svelte';
import { InputTextarea } from '$lib/elements/forms';
import {
@@ -35,7 +36,7 @@
) => Promise<unknown>;
export let sdkUpdateVariable: (
variableId: string,
key: string,
key: string | undefined,
value: string,
secret?: boolean
) => Promise<unknown>;
@@ -74,10 +75,10 @@
}
function validateEntries(entries: DraftVariable[]) {
for (const { key, value } of entries) {
if (value.length > 8192) {
throw new Error(`Variable ${key} is longer than 8192 allowed characters`);
}
const validationError = validateVariables(entries);
if (validationError) {
throw new Error(validationError);
}
}
@@ -146,22 +147,30 @@
const editableVariables = variableList.variables.filter((variable) => !variable.secret);
const secretVariables = variableList.variables.filter((variable) => variable.secret);
await Promise.all(
const existingKeys = editableVariables.map((variable) => variable.key);
const existingResults = await Promise.allSettled(
editableVariables.map(async (variable) => {
const newValue = vars[variable.key] ?? null;
// Claim the key up front. A rejected write must not leave it
// behind for the second pass, which would retry it as a new
// variable and send the stored key along with it.
delete vars[variable.key];
if (newValue === null) {
await sdkDeleteVariable(variable.$id);
} else if (newValue !== variable.value) {
await sdkUpdateVariable(variable.$id, variable.key, newValue, false);
// The key is unchanged here, so leave it out and let
// the API keep the stored one.
await sdkUpdateVariable(variable.$id, undefined, newValue, false);
}
delete vars[variable.key];
})
);
// Add new variables, skipping keys that exist in secret variables
await Promise.all(
Object.keys(vars).map(async (key) => {
const newKeys = Object.keys(vars);
const newResults = await Promise.allSettled(
newKeys.map(async (key) => {
const existingVariable = variableList.variables.find(
(variable) => variable.key === key
);
@@ -178,6 +187,22 @@
await sdkCreateVariable(key, vars[key], false);
})
);
// Every variable is written on its own, so name the keys that
// failed rather than surfacing a single rejection.
const failed = [
...existingResults.map((result, index) =>
result.status === 'rejected' ? existingKeys[index] : null
),
...newResults.map((result, index) =>
result.status === 'rejected' ? newKeys[index] : null
)
].filter(Boolean);
if (failed.length) {
throw new Error(`Failed to update variables: ${failed.join(', ')}`);
}
// Ensure secret variables are preserved
variableList.variables = [
...secretVariables,
@@ -3,16 +3,15 @@
import { Fieldset, Layout, Accordion } from '@appwrite.io/pink-svelte';
import type { Models } from '@appwrite.io/console';
import { iconPath } from '$lib/stores/app';
import { getFrameworkIcon, type FrameworkAdapterWithStartCommand } from '$lib/stores/sites';
import { getFrameworkIcon } from '$lib/stores/sites';
import { EnvironmentVariables } from '$lib/components/variables';
export let frameworks: Models.Framework[];
export let selectedFramework: Models.Framework;
$: frameworkData = frameworks.find((framework) => framework.key === selectedFramework?.key);
$: adapterData = (frameworkData?.adapters.find((adapter) => adapter.key === 'ssr') ??
frameworkData?.adapters.find(
(adapter) => adapter.key === 'static'
)) as FrameworkAdapterWithStartCommand;
$: adapterData =
frameworkData?.adapters.find((adapter) => adapter.key === 'ssr') ??
frameworkData?.adapters.find((adapter) => adapter.key === 'static');
export let variables: Partial<Models.Variable>[] = [];
export let isLoading = false;
@@ -28,8 +27,8 @@
$: if (frameworkData && adapterDefaultsKey !== lastAdapterDefaultsKey) {
installCommand = adapterData?.installCommand ?? '';
buildCommand = adapterData?.buildCommand ?? '';
startCommand = adapterData?.startCommand ?? '';
outputDirectory = adapterData?.outputDirectory ?? '';
startCommand = '';
lastAdapterDefaultsKey = adapterDefaultsKey;
}
</script>
@@ -92,16 +91,7 @@
id="startCommand"
label="Start command"
bind:value={startCommand}
placeholder={adapterData?.startCommand ||
'Enter start command'} />
<Button
secondary
size="s"
disabled={(adapterData?.startCommand ?? '') ===
(startCommand ?? '')}
on:click={() => (startCommand = adapterData?.startCommand)}>
Reset
</Button>
placeholder="Enter start command" />
</Layout.Stack>
{/if}
<Layout.Stack gap="s" direction="row" alignItems="flex-end">
@@ -27,7 +27,7 @@
import { writable } from 'svelte/store';
import { getLatestTag } from '$lib/helpers/github';
import Link from '$lib/elements/link.svelte';
import type { FrameworkAdapterWithStartCommand } from '$lib/stores/sites';
import { validateVariables } from '$lib/helpers/variables';
let {
data
@@ -94,7 +94,6 @@
const adapter = fw.adapters[0];
installCommand = adapter.installCommand || '';
buildCommand = adapter.buildCommand || '';
startCommand = (adapter as FrameworkAdapterWithStartCommand).startCommand || '';
outputDirectory = adapter.outputDirectory || '';
}
}
@@ -124,7 +123,6 @@
const adapter = fw.adapters[0];
installCommand = adapter.installCommand || '';
buildCommand = adapter.buildCommand || '';
startCommand = (adapter as FrameworkAdapterWithStartCommand).startCommand || '';
outputDirectory = adapter.outputDirectory || '';
}
}
@@ -147,6 +145,13 @@
$isSubmitting = true;
try {
// Reject an unusable key before the resource is created, so a
// rejected variable can't leave a half-configured resource behind.
const validationError = validateVariables(variables);
if (validationError) {
throw new Error(validationError);
}
// Create site with build configuration
let site = await sdk.forProject(page.params.region, page.params.project).sites.create({
siteId: id || ID.unique(),
@@ -264,7 +269,8 @@
label="Framework"
placeholder="Select framework"
bind:value={framework}
options={frameworkSelectOptions} />
options={frameworkSelectOptions}
on:change={() => (startCommand = '')} />
</Layout.Stack>
</Fieldset>
@@ -26,7 +26,7 @@
import { currentPlan } from '$lib/stores/organization';
import Domain from '../domain.svelte';
import { uploader } from '$lib/stores/uploader';
import type { FrameworkAdapterWithStartCommand } from '$lib/stores/sites';
import { validateVariables } from '$lib/helpers/variables';
export let data;
let showExitModal = false;
@@ -41,10 +41,10 @@
let framework: Models.Framework =
data.frameworks.frameworks?.find((f) => f.key === 'other') ??
data.frameworks.frameworks?.[0];
let adapter = framework?.adapters[0] as FrameworkAdapterWithStartCommand;
let adapter = framework?.adapters[0];
let installCommand = adapter?.installCommand;
let buildCommand = adapter?.buildCommand;
let startCommand = adapter?.startCommand;
let startCommand = '';
let outputDirectory = adapter?.outputDirectory;
let variables: Partial<Models.Variable>[] = [];
let files: FileList;
@@ -60,6 +60,13 @@
let site: Models.Site | null = null;
try {
// Reject an unusable key before the resource is created, so a
// rejected variable can't leave a half-configured resource behind.
const validationError = validateVariables(variables);
if (validationError) {
throw new Error(validationError);
}
if (!domainIsValid) {
addNotification({
type: 'error',
@@ -27,8 +27,11 @@
import Configuration from '../../configuration.svelte';
import Domain from '../../domain.svelte';
import { regionalConsoleVariables } from '$routes/(console)/project-[region]-[project]/store';
import { normalizeDetectedVariables, mergeVariables } from '$lib/helpers/variables';
import type { FrameworkAdapterWithStartCommand } from '$lib/stores/sites';
import {
normalizeDetectedVariables,
mergeVariables,
validateVariables
} from '$lib/helpers/variables';
export let data;
let showExitModal = false;
@@ -39,12 +42,12 @@
let name = '';
let id = ID.unique();
let framework: Models.Framework = data.frameworks.frameworks.find((f) => f.key === 'other');
let adapter = framework?.adapters[0] as FrameworkAdapterWithStartCommand;
let adapter = framework?.adapters[0];
let branch: string;
let rootDir = './';
let installCommand = adapter?.installCommand;
let buildCommand = adapter?.buildCommand;
let startCommand = adapter?.startCommand;
let startCommand = '';
let outputDirectory = adapter?.outputDirectory;
let variables: Partial<Models.Variable>[] = [];
let silentMode = false;
@@ -83,10 +86,9 @@
if (!framework) {
framework = data.frameworks.frameworks.find((f) => f.key === 'other');
}
adapter = framework?.adapters[0] as FrameworkAdapterWithStartCommand;
adapter = framework?.adapters[0];
installCommand = adapter?.installCommand;
buildCommand = adapter?.buildCommand;
startCommand = adapter?.startCommand;
outputDirectory = adapter?.outputDirectory;
const detectedVariables = normalizeDetectedVariables(response?.variables);
if (detectedVariables.length) {
@@ -113,6 +115,13 @@
return;
}
try {
// Reject an unusable key before the resource is created, so a
// rejected variable can't leave a half-configured resource behind.
const validationError = validateVariables(variables);
if (validationError) {
throw new Error(validationError);
}
const fr = Object.values(Framework).find((f) => f === framework.key);
const buildRuntime = Object.values(BuildRuntime).find(
(f) => f === framework.buildRuntime
@@ -45,6 +45,7 @@
import { getFrameworkIcon } from '$lib/stores/sites';
import { regionalConsoleVariables } from '$routes/(console)/project-[region]-[project]/store';
import { getTemplateSourceUrl } from '$lib/helpers/templateSource';
import { validateVariables } from '$lib/helpers/variables';
export let data;
@@ -117,6 +118,15 @@
return;
} else {
try {
// Reject an unusable key before the resource is created, so a
// rejected variable can't leave a half-configured resource behind.
const validationError = validateVariables(
variables.map((variable) => ({ key: variable.name, value: variable.value }))
);
if (validationError) {
throw new Error(validationError);
}
const fr = Object.values(Framework).find((f) => f === framework.key);
const buildRuntime = Object.values(BuildRuntime).find(
(f) => f === framework.buildRuntime
@@ -12,7 +12,7 @@
import { Link } from '$lib/elements';
import { IconInfo } from '@appwrite.io/pink-icons-svelte';
import { adapterDataList } from './store';
import { getFrameworkIcon, type FrameworkAdapterWithStartCommand } from '$lib/stores/sites';
import { getFrameworkIcon } from '$lib/stores/sites';
import { page } from '$app/state';
let {
@@ -50,9 +50,8 @@
(fallback ?? '') === (site?.fallbackFile ?? '') &&
(adapter ?? '') === (site?.adapter ?? '')
);
let frameworkAdapterData: FrameworkAdapterWithStartCommand = $derived(
(selectedFramework.adapters.find((a) => a.key === adapter) ??
selectedFramework.adapters[0]) as FrameworkAdapterWithStartCommand
let frameworkAdapterData = $derived(
selectedFramework.adapters.find((a) => a.key === adapter) ?? selectedFramework.adapters[0]
);
$effect(() => {
@@ -77,17 +76,19 @@
}
//Update values
const data = (selectedFramework.adapters.find((a) => a.key === adapter) ??
selectedFramework.adapters[0]) as FrameworkAdapterWithStartCommand;
const data =
selectedFramework.adapters.find((a) => a.key === adapter) ??
selectedFramework.adapters[0];
installCommand = data.installCommand;
buildCommand = data.buildCommand;
startCommand = data.startCommand;
startCommand = '';
outputDirectory = data.outputDirectory;
adapter = data.key as Adapter;
fallback = data.fallbackFile;
} else if (hasFrameworkSelectionChanged) {
const data = (selectedFramework.adapters.find((a) => a.key === adapter) ??
selectedFramework.adapters[0]) as FrameworkAdapterWithStartCommand;
const data =
selectedFramework.adapters.find((a) => a.key === adapter) ??
selectedFramework.adapters[0];
const isOriginalAdapter = adapter === site.adapter;
installCommand = isOriginalAdapter
@@ -96,9 +97,7 @@
buildCommand = isOriginalAdapter
? (site?.buildCommand ?? frameworkAdapterData.buildCommand)
: data.buildCommand;
startCommand = isOriginalAdapter
? (site?.startCommand ?? frameworkAdapterData.startCommand)
: data.startCommand;
startCommand = isOriginalAdapter ? (site?.startCommand ?? '') : '';
outputDirectory = isOriginalAdapter
? (site?.outputDirectory ?? frameworkAdapterData.outputDirectory)
: data.outputDirectory;
@@ -162,7 +161,7 @@
timeout: site.timeout || undefined,
installCommand: installCommand || undefined,
buildCommand: buildCommand || undefined,
startCommand: startCommand || undefined,
startCommand: adptr?.key === 'ssr' ? startCommand || undefined : undefined,
outputDirectory: outputDirectory || undefined,
buildRuntime: (site?.buildRuntime as BuildRuntime) || undefined,
adapter: (adptr?.key as Adapter) || undefined,
@@ -193,17 +192,13 @@
}
}
function reset(type: 'installCommand' | 'buildCommand' | 'startCommand' | 'outputDirectory') {
const data = selectedFramework.adapters.find(
(a) => a.key === adapter
) as FrameworkAdapterWithStartCommand;
function reset(type: 'installCommand' | 'buildCommand' | 'outputDirectory') {
const data = selectedFramework.adapters.find((a) => a.key === adapter);
if (type === 'installCommand') {
installCommand = data.installCommand;
} else if (type === 'buildCommand') {
buildCommand = data.buildCommand;
} else if (type === 'startCommand') {
startCommand = data.startCommand;
} else if (type === 'outputDirectory') {
outputDirectory = data.outputDirectory;
}
@@ -338,16 +333,7 @@
id="startCommand"
label="Start command"
bind:value={startCommand}
placeholder={frameworkAdapterData?.startCommand ||
'Enter start command'} />
<Button
secondary
size="s"
disabled={(startCommand ?? '') ===
(frameworkAdapterData?.startCommand ?? '')}
on:click={() => reset('startCommand')}>
Reset
</Button>
placeholder="Enter start command" />
</Layout.Stack>
{/if}
<Layout.Stack gap="s" direction="row" alignItems="flex-end">
@@ -5,6 +5,7 @@
import { CardGrid, Empty, Output, PaginationInline } from '$lib/components';
import UploadVariables from './uploadVariablesModal.svelte';
import { variablesOperation, type VariablesOperationItem } from './variablesOperation';
import { isValidVariableKey, validateVariables } from '$lib/helpers/variables';
import { goto, invalidate } from '$app/navigation';
import { Click, Submit, trackError, trackEvent } from '$lib/actions/analytics';
import { Dependencies } from '$lib/constants';
@@ -21,6 +22,7 @@
Layout,
Popover,
Table,
Tooltip,
Alert
} from '@appwrite.io/pink-svelte';
import {
@@ -55,7 +57,7 @@
) => Promise<unknown>;
export let sdkUpdateVariable: (
variableId: string,
key: string,
key: string | undefined,
value: string,
secret?: boolean
) => Promise<unknown>;
@@ -127,10 +129,24 @@
async function handleVariableCreated(event: CustomEvent<Models.Variable[]>) {
const variables = event.detail;
try {
const promises = variables.map((variable) =>
sdkCreateVariable(variable.key, variable.value, variable?.secret || false)
const results = await Promise.allSettled(
variables.map((variable) =>
sdkCreateVariable(variable.key, variable.value, variable?.secret || false)
)
);
await Promise.all(promises);
// Each variable is created on its own, so name the keys that failed
// instead of reporting a single rejection for the whole batch.
const failed = results
.map((result, index) =>
result.status === 'rejected' ? variables[index].key : null
)
.filter(Boolean);
if (failed.length) {
throw new Error(`Failed to create variables: ${failed.join(', ')}`);
}
fullVariableList = undefined;
showVariablesModal = false;
addNotification({
@@ -174,7 +190,10 @@
async function handleVariableSecret(event: CustomEvent<Models.Variable>) {
const variable = event.detail;
try {
await sdkUpdateVariable(variable.$id, variable.key, variable.value, variable.secret);
// Marking a variable secret never changes its key, so leave the key
// out and keep the stored one — including keys that predate the
// identifier rule.
await sdkUpdateVariable(variable.$id, undefined, variable.value, variable.secret);
fullVariableList = undefined;
selectedVar = null;
showVariablesModal = false;
@@ -237,6 +256,14 @@
async function handleVariablePromoted(variable: Models.Variable) {
try {
// Promoting a conflicting key deletes the existing global variable
// before recreating it, so refuse a key the API would reject rather
// than deleting one and failing to create its replacement.
const validationError = validateVariables([variable]);
if (validationError) {
throw new Error(validationError);
}
const globalVariable = globalVariableList
? globalVariableList.variables.find(
(globalVariable) => globalVariable.key === variable.key
@@ -507,6 +534,19 @@
class="icon-exclamation u-color-text-warning"
aria-hidden="true"></span>
{/if}
{#if !isValidVariableKey(variable.key)}
<Tooltip>
<span
class="icon-exclamation u-color-text-danger"
aria-hidden="true"></span>
<svelte:fragment slot="tooltip">
This key can't be used as an environment variable
name, so it is ignored at build and runtime. Rename
it using only letters, digits and underscores,
without starting with a digit.
</svelte:fragment>
</Tooltip>
{/if}
<Copy value={variable.key} />
<Output value={variable.key} hideCopyIcon>
{variable.key}
@@ -8,6 +8,7 @@
import { base } from '$app/paths';
import { Alert, Layout, Selector } from '@appwrite.io/pink-svelte';
import { Link } from '$lib/elements';
import { getVariableValueError, validateVariables } from '$lib/helpers/variables';
export let isGlobal: boolean;
export let product: 'function' | 'site' = 'function';
@@ -21,6 +22,10 @@
secret: selectedVar?.secret
};
const originalKey = selectedVar?.key;
let error = '';
const dispatch = createEventDispatcher();
function close() {
@@ -29,7 +34,21 @@
}
function handleVariable() {
dispatch('updated', pair);
const keyChanged = pair.key !== originalKey;
// A key stored before the identifier rule existed is left untouched so
// its value stays editable; only a key the user actually changed has to
// satisfy the rule.
const validationError = keyChanged
? validateVariables([pair])
: getVariableValueError(pair.key, pair.value);
if (validationError) {
error = validationError;
return;
}
dispatch('updated', { ...pair, key: keyChanged ? pair.key : undefined });
close();
}
@@ -41,6 +60,7 @@
<Modal
bind:show
bind:error
onSubmit={handleVariable}
title={`Update ${isGlobal ? 'global' : 'environment'} variable`}>
<svelte:fragment slot="description">
@@ -16,6 +16,7 @@
} from '@appwrite.io/pink-svelte';
import { parse } from '$lib/helpers/envfile';
import { removeFile } from '$lib/helpers/files';
import { validateVariables } from '$lib/helpers/variables';
import type { VariablesOperationItem } from './variablesOperation';
export let show = false;
@@ -27,7 +28,7 @@
) => Promise<unknown>;
export let sdkUpdateVariable: (
variableId: string,
key: string,
key: string | undefined,
value: string,
secret?: boolean
) => Promise<unknown>;
@@ -64,18 +65,19 @@
const entries = Object.entries(uploaded);
for (const [key, value] of entries) {
if (value.length > 8192) {
throw new Error(`Variable ${key} is longer than 8192 allowed characters`);
}
}
const filteredEntries = entries.filter(([, value]) => !!value);
if (!filteredEntries.length) {
throw new Error('No variables found');
}
const validationError = validateVariables(
filteredEntries.map(([key, value]) => ({ key, value }))
);
if (validationError) {
throw new Error(validationError);
}
if (filteredEntries.length > 100) {
throw new Error('Please upload a file with fewer than 100 environment variables.');
}
@@ -93,7 +95,7 @@
show = false;
await Promise.all(
const results = await Promise.allSettled(
filteredEntries.map(([key, value]) => {
const found = variableList.variables.find((variable) => variable.key === key);
return found
@@ -102,6 +104,18 @@
})
);
// Each variable is written on its own, so report which keys failed
// instead of letting one rejection hide the ones that landed.
const failed = results
.map((result, index) =>
result.status === 'rejected' ? filteredEntries[index][0] : null
)
.filter(Boolean);
if (failed.length) {
throw new Error(`Failed to upload variables: ${failed.join(', ')}`);
}
onStatusChange({
id: importId,
count: uploadCount,
-9
View File
@@ -1,9 +0,0 @@
<script>
import { Shell } from '$lib/layout';
import Footer from '$lib/layout/footer.svelte';
</script>
<Shell>
<slot />
<Footer slot="footer" />
</Shell>
-10
View File
@@ -1,10 +0,0 @@
import { isCloud } from '$lib/system';
import { redirect } from '@sveltejs/kit';
export async function load({ parent }) {
if (!isCloud) redirect(303, '/');
const { account } = await parent();
if (!account) redirect(303, '/login');
redirect(303, `/card/${account.$id}`);
}
-458
View File
@@ -1,458 +0,0 @@
<script lang="ts" context="module">
// Helpers
const round = (num: number, fix = 3) => parseFloat(num.toFixed(fix));
const clamp = (num: number, min = -20, max = 20) => Math.min(Math.max(num, min), max);
function isTouchEvent(e: MouseEvent | TouchEvent): e is TouchEvent {
return e.type === 'touchmove';
}
</script>
<script lang="ts">
import { windowFocusStore } from '$lib/stores/windowFocus';
import { spring } from 'svelte/motion';
let cardEl: HTMLDivElement | undefined;
export let active = false;
export let isFlipped = false;
export let base64: { front: string; back: string };
let interacting = false;
const springR = { stiffness: 0.066, damping: 0.25 };
const springD = { stiffness: 0.03, damping: 0.45 };
const THICKNESS = 3;
let springRotate = spring({ x: 0, y: 0 }, springR);
let springGlare = spring({ x: 50, y: 50, o: 0.25 }, springR);
let springBackground = spring({ x: 50, y: 50 }, springR);
let springRotateDelta = spring({ x: 0, y: 0 }, springD);
let springTranslate = spring({ x: 0, y: 0 }, springD);
let springScale = spring(1, springD);
let angle = 0;
let centerProximity = spring(0, springR);
let springRotateZ = spring(-15, springD);
// Events
const interact = (e: MouseEvent | TouchEvent) => {
if (!active) return;
interacting = true;
const clientX = isTouchEvent(e) ? e.touches[0].clientX : e.clientX;
const clientY = isTouchEvent(e) ? e.touches[0].clientY : e.clientY;
const el = e.target as HTMLElement;
const rect = el.getBoundingClientRect(); // get element's current size/position
const absolute = {
x: clientX - rect.left, // get mouse position from left
y: clientY - rect.top // get mouse position from right
};
const percent = {
x: round((100 / rect.width) * absolute.x),
y: round((100 / rect.height) * absolute.y)
};
const center = {
x: percent.x - 50,
y: (percent.y - 50) * (isFlipped ? -1 : 1)
};
springBackground.stiffness = springR.stiffness;
springBackground.damping = springR.damping;
springBackground.set({
x: round(50 + percent.x / 4 - 12.5),
y: round(50 + percent.y / 3 - 16.67)
});
springRotate.stiffness = springR.stiffness;
springRotate.damping = springR.damping;
springRotate.set({
x: round(-(center.x / 3.5)),
y: round(center.y / 2)
});
springGlare.stiffness = springR.stiffness;
springGlare.damping = springR.damping;
springGlare.set({
x: percent.x,
y: percent.y,
o: 1
});
// get angle of mouse position relative to center of element
angle = Math.atan2(center.y, center.x) * (180 / Math.PI);
// get proximity to center of element. 0 = center, 1 = edge
$centerProximity = Math.sqrt(center.x * center.x + center.y * center.y) / 50 - 0.1;
};
const interactEnd = (_: unknown, delay = 500) => {
if (!active) return;
setTimeout(function () {
const snapStiff = 0.01;
const snapDamp = 0.06;
interacting = false;
springRotate.stiffness = snapStiff;
springRotate.damping = snapDamp;
springRotate.set({ x: 0, y: 0 });
springGlare.stiffness = snapStiff;
springGlare.damping = snapDamp;
springGlare.set({ x: 50, y: 50, o: 0 });
springBackground.stiffness = snapStiff;
springBackground.damping = snapDamp;
springBackground.set({ x: 50, y: 50 });
$centerProximity = 0;
}, delay);
};
const setCenter = () => {
if (!cardEl) return;
const rect = cardEl.getBoundingClientRect(); // get element's size/position
const view = document.documentElement; // get window/viewport size
const delta = {
x: round(view.clientWidth / 2 - rect.x - rect.width / 2),
y: round(view.clientHeight / 2 - rect.y - rect.height / 2)
};
springTranslate.set({
x: delta.x,
y: delta.y
});
};
const popover = () => {
if (!cardEl) return;
const rect = cardEl.getBoundingClientRect(); // get element's size/position
let delay = 100;
let scaleW = (window.innerWidth / rect.width) * 0.65;
let scaleH = (window.innerHeight / rect.height) * 0.65;
let scaleF = 1.5;
setCenter();
delay = 1000;
springRotateDelta.set({
x: 360,
y: 0
});
springRotateZ.set(0);
springScale.set(Math.min(scaleW, scaleH, scaleF));
interactEnd(null, delay);
};
const retreat = () => {
springScale.set(1);
springTranslate.set({ x: 0, y: 0 });
springRotateDelta.set({ x: 0, y: 0 });
springRotate.set({ x: 0, y: 0 });
springGlare.set({ x: 50, y: 50, o: 0 });
$centerProximity = 0;
springRotateZ.set(-15);
};
const handleClick = () => {
active = !active;
};
const windowKeyDown = (e: KeyboardEvent) => {
if (e.key === 'q') {
springRotateDelta.update((old) => {
return {
...old,
x: old.x + 360
};
});
}
if (!active) return;
if (e.key === 'q') {
isFlipped = !isFlipped;
} else if (e.key === 'Escape') {
active = false;
}
};
$: if (!active) {
isFlipped = false;
} else {
springRotateDelta.update((old) => ({
x: isFlipped ? 180 : 360,
y: old.y
}));
}
// Reactive
$: if (active) {
popover();
interacting = true;
} else {
retreat();
}
windowFocusStore().subscribe((focused) => {
if (focused) {
active = false;
springScale.set(1, { hard: true });
springTranslate.set({ x: 0, y: 0 }, { hard: true });
springRotateDelta.set({ x: 0, y: 0 }, { hard: true });
springRotate.set({ x: 0, y: 0 }, { hard: true });
springRotateZ.set(-15, { hard: true });
centerProximity.set(0, { hard: true });
}
});
$: styles = `
--mx: ${$springGlare.x}%;
--my: ${$springGlare.y}%;
--tx: ${$springTranslate.x}px;
--ty: ${$springTranslate.y}px;
--s: ${$springScale};
--o: ${$springGlare.o};
--rx: ${$springRotate.x + $springRotateDelta.x}deg;
--ry: ${$springRotate.y + $springRotateDelta.y}deg;
--rz: ${$springRotateZ}deg;
--pos: ${$springBackground.x}% ${$springBackground.y}%;
--posx: ${$springBackground.x}%;
--posy: ${$springBackground.y}%;
--hyp: ${clamp(
Math.sqrt(
($springGlare.y - 50) * ($springGlare.y - 50) +
($springGlare.x - 50) * ($springGlare.x - 50)
) / 50,
0,
1
)};
--angle: ${angle}deg;
--center: ${$centerProximity};
`;
</script>
<svelte:window on:keydown={windowKeyDown} />
<div class="cb-card" class:active class:interacting style={styles} bind:this={cardEl}>
<div class="card__translator">
<button
class="card__rotator"
aria-label="Expand the Card"
tabindex="0"
on:pointermove={interact}
on:mouseout={interactEnd}
on:click={handleClick}
on:blur={() => {
/* noop */
}}>
<div class="card__back">
<img
class="invisible"
src={base64.back}
alt="The back of the Card"
loading="lazy"
width="450"
height="274" />
<img
class="abs"
src={base64.back}
alt="The back of the Card"
loading="lazy"
width="450"
height="274" />
<div class="card__glare"></div>
</div>
{#each new Array(THICKNESS) as _, i (i)}
<div class="card__thick" style:--i={i + 1}></div>
{/each}
<div class="card__front" style:--thickness={THICKNESS}>
<img class="invisible" src={base64.front} alt="" />
<img class="abs" src={base64.front} alt="The front of the card" />
<div class="card__glare"></div>
</div>
</button>
</div>
</div>
<style lang="scss">
.invisible {
opacity: 0;
}
@media (prefers-reduced-motion: reduce) {
.cb-card,
.cb-card * {
transition: none !important;
animation: none !important;
pointer-events: none !important;
}
}
:root {
--mx: 50%;
--my: 50%;
--s: 1;
--o: 0;
--tx: 0px;
--ty: 0px;
--rx: 0deg;
--ry: 0deg;
--pos: 50% 50%;
--posx: 50%;
--posy: 50%;
--hyp: 0;
}
:global(.theme-dark) .cb-card {
--shadow-clr: transparent;
}
.cb-card {
--radius: 12px;
--shadow-clr: hsl(var(--color-neutral-30));
z-index: calc(var(--s) * 100);
transform: translate3d(0, 0, 0.1px);
-webkit-transform: translate3d(0, 0, 0.1px);
will-change: transform, visibility;
transform-style: preserve-3d;
-webkit-transform-style: preserve-3d;
&.interacting {
z-index: calc(var(--s) * 120);
}
}
.cb-card.active .card__translator,
.cb-card.active .card__rotator {
touch-action: none;
}
.card__translator,
.card__rotator {
display: grid;
perspective: 600px;
transform-origin: center;
-webkit-transform-origin: center;
will-change: transform;
}
.card__translator {
width: auto;
position: relative;
transform: translate3d(var(--tx), var(--ty), 0) scale(var(--s));
-webkit-transform: translate3d(var(--tx), var(--ty), 0) scale(var(--s));
}
.card__rotator {
-webkit-transform: rotateY(var(--rx)) rotateX(var(--ry)) rotateZ(var(--rz));
-webkit-transform-style: preserve-3d;
transform: rotateY(var(--rx)) rotateX(var(--ry)) rotateZ(var(--rz));
transform-style: preserve-3d;
box-shadow: 0px 10px 20px -5px var(--shadow-clr);
border-radius: var(--radius);
outline: none;
appearance: none;
-webkit-appearance: none;
border: none;
background: top;
padding: 0;
:global(*) {
width: 100%;
display: grid;
grid-area: 1/1;
border-radius: var(--radius);
image-rendering: optimizeQuality;
transform-style: preserve-3d;
-webkit-transform-style: preserve-3d;
}
img {
outline: 1px solid transparent;
height: auto;
}
}
.card__thick {
background-color: transparent;
position: absolute;
width: 100%;
height: 100%;
transform: translateZ(calc(var(--i) * 1px));
}
.card__back {
transform: rotateY(180deg) translateZ(0px);
-webkit-transform: rotateY(180deg) translateZ(0px);
backface-visibility: hidden;
&::before {
--resolved-angle: calc(calc(var(--angle) * -1) + 60deg);
}
}
.card__front {
opacity: 1;
transition: opacity 0.33s ease-out;
transform: translateZ(calc(var(--thickness) * 1px));
position: relative;
backface-visibility: hidden;
* {
backface-visibility: hidden;
}
&::before {
--resolved-angle: calc(var(--angle) + 65deg);
}
}
.card__front,
.card__back {
.abs {
display: block;
position: absolute;
left: 50%;
top: 50%;
translate: -50% -50%;
width: 200%;
scale: calc(100 / 200);
max-inline-size: initial;
max-block-size: initial;
}
}
.card__front::before,
.card__back::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: conic-gradient(
from var(--resolved-angle),
rgba(255, 255, 255, 0) 0%,
rgba(255, 255, 255, 1) 7.5%,
rgba(255, 255, 255, 0) 15%
);
scale: 1.01;
border-radius: calc(var(--radius) * 1.2);
opacity: var(--center);
}
.card__glare {
border-radius: calc(var(--radius) + 3px);
transform: translateZ(1px);
z-index: 4;
background: radial-gradient(
farthest-corner circle at var(--mx) var(--my),
rgba(255, 255, 255, 0.8) 10%,
rgba(255, 255, 255, 0.65) 20%,
rgba(0, 0, 0, 0.5) 90%
);
mix-blend-mode: overlay;
opacity: calc(var(--o) * 0.5);
}
</style>
-433
View File
@@ -1,433 +0,0 @@
<script lang="ts">
import { browser } from '$app/environment';
import { Modal } from '$lib/components';
import Code from '$lib/components/code.svelte';
import Button from '$lib/elements/forms/button.svelte';
import { copy } from '$lib/helpers/copy';
import { addNotification } from '$lib/stores/notifications';
import { Confetti } from 'svelte-confetti';
import { fade } from 'svelte/transition';
import Card from '../Card.svelte';
import { base } from '$app/paths';
export let data;
const base64 = data.base64;
const variant = data.isOwner ? 'owner' : 'external';
const userId = data.userId;
const { frontImg } = data.imgUrls;
let triggerConfettiKey = 1;
const confettiColors = [
'hsl(var(--color-primary-100))',
'hsl(var(--color-primary-200))',
'hsl(var(--color-primary-300))',
'#F05088',
'#FF86BB',
'#FFFFFF80'
];
let cardActive = false;
let cardIsFlipped = false;
let showEmbedCode = false;
$: title =
variant === 'owner' ? 'Welcome to Cloud Public Beta' : 'Join Appwrite Cloud Public Beta';
$: shareableLink =
typeof window !== 'undefined' ? `${window.location.origin}/card/${userId}` : '';
$: embedCode = [
`<a href="${shareableLink}">`,
`\t<img width="350" src="${frontImg}" alt="Appwrite Cloud Card" />`,
`</a>`
].join('\n');
$: twitterText = encodeURIComponent(
[
`Guess what I just received? 💳 My personalized Cloud card from @appwrite! 🚀`,
``,
`Appwrite Cloud just announced their Public Beta!`,
``,
`🌥️ Sign up now and claim your own card at ${shareableLink}`,
``,
`#AppwriteCloud`
].join('\n')
);
function copyShareableLink() {
copy(shareableLink);
addNotification({
message: 'The link has been copied',
type: 'success'
});
}
function copyEmbedCode() {
copy(embedCode);
addNotification({
message: 'Embed code has been copied',
type: 'success'
});
showEmbedCode = false;
}
const seo = {
title: 'Appwrite Cloud Card',
description:
'Cloud is live in public beta, create your Cloud account and unlock your exclusive card!'
};
</script>
<svelte:head>
<!-- HTML Meta Tags -->
<title>{seo.title}</title>
<meta name="description" content={seo.description} />
</svelte:head>
<div class="wrapper">
<div class="card">
<h3 class="heading-level-3 no-text-select">
{title}
<button class="confetti-btn" on:click={() => triggerConfettiKey++}>
🎉
{#each Array(triggerConfettiKey) as _, i (i)}
<Confetti
delay={i === 0 ? [500, 500] : [0, 100]}
x={[0.5, 2]}
y={[0, 1.5]}
amount={30}
fallDistance="50px"
colorArray={confettiColors} />
{/each}
</button>
</h3>
<div class="content">
<div>
{#if variant === 'owner'}
<h4 class="eyebrow-heading-3 is-only-desktop">Share your card</h4>
{:else if variant === 'external'}
<h4 class="eyebrow-heading-3 is-only-desktop">Share card</h4>
{/if}
{#if variant === 'external'}
<a
href={`${base}/register`}
class="button u-width-full-line u-main-center u-margin-block-start-16 external-btn-top"
data-sveltekit-reload>Claim your card</a>
{/if}
</div>
</div>
<img class="card-preview" src={base64.front} alt="The front of the card" />
<ul class="buttons-list u-margin-block-start-16">
<li class="buttons-list-item">
<a
class="button is-text"
href="https://twitter.com/intent/tweet?text={twitterText}"
target="_blank"
rel="noreferrer">
<span class="icon-twitter" aria-hidden="true"></span>
<span class="text">Tweet it</span>
</a>
</li>
{#if variant === 'owner'}
<li class="buttons-list-item embed-btn">
<button class="button is-text" on:click={() => (showEmbedCode = true)}>
<span class="icon-code" aria-hidden="true"></span>
<span class="text">Get embed code</span>
</button>
</li>
{/if}
<li class="buttons-list-item">
<button class="button is-text" on:click={copyShareableLink}>
<span class="icon-link" aria-hidden="true"></span>
<span class="text">Get a link</span>
</button>
</li>
</ul>
<div class="card-footer">
{#if variant === 'owner'}
<a data-sveltekit-reload href={base} class="button">Go to console</a>
{:else}
<a data-sveltekit-reload href={`${base}/card`} class="button external-btn-bottom"
>Claim your card</a>
{/if}
</div>
</div>
<div class="cbc-wrapper">
{#if !cardActive}
<div class="cbc-confetti" transition:fade>
<Confetti
x={[-1.75, 1.85]}
y={[-1.875, 1]}
amount={100}
size={10}
infinite
delay={[2000, 7000]}
colorArray={confettiColors}
fallDistance="50px" />
</div>
{/if}
{#if browser}
<Card bind:active={cardActive} bind:isFlipped={cardIsFlipped} {base64} />
{/if}
</div>
{#if cardActive}
<div
class="overlay"
on:click={() => (cardActive = false)}
on:keydown={() => {
/* no-op */
}}
transition:fade
role="button"
tabindex="0">
</div>
{/if}
<div class="controls" class:invisible={!cardActive}>
<button
class="button is-text"
on:click={() => (cardIsFlipped = !cardIsFlipped)}
aria-label="Rotate card">
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true">
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M2 11C2 8.2 6.5 6 12 6C17.5 6 22 8.2 22 11C22 12.8414 20.0779 14.3752 17.2449 15.2644C16.615 15.4621 16 14.9707 16 14.3105C16 13.8351 16.3283 13.4267 16.7816 13.2837C18.8093 12.6442 20 11.6237 20 11C20 9.9 17 8 12 8C7 8 4 9.9 4 11C4 11.7821 6.79551 13.1137 9.91054 13.7336C10.0265 13.7566 10.1405 13.7886 10.2509 13.8305C10.308 13.8187 10.3669 13.8125 10.4273 13.8125L9.26357 12.6004C8.9121 12.2343 8.9121 11.6407 9.26357 11.2746C9.61504 10.9085 10.1849 10.9085 10.5364 11.2746L13.2364 14.0871C13.4051 14.2629 13.5 14.5013 13.5 14.75C13.5 14.9986 13.4051 15.2371 13.2364 15.4129L10.5364 18.2254C10.1849 18.5915 9.61504 18.5915 9.26357 18.2254C8.9121 17.8593 8.9121 17.2657 9.26357 16.8996L10.2838 15.8369C6.24683 15.1056 2 13.1614 2 11Z"
fill="currentColor" />
</svg>
<span class="text">Spin</span>
</button>
</div>
</div>
<Modal title="Get Embed Code" bind:show={showEmbedCode}>
<div class="u-overflow-hidden">
<Code language="html" code={embedCode} noMargin />
</div>
<svelte:fragment slot="footer">
<Button on:click={copyEmbedCode}>Copy</Button>
</svelte:fragment>
</Modal>
<style lang="scss">
:global(.theme-dark) .wrapper {
--glow: hsl(var(--color-primary-100));
--beta-bg: hsl(var(--color-neutral-120));
--beta-fg: hsl(var(--color-neutral-0));
--sep-clr: hsl(var(--color-neutral-150));
}
:global(.main-content) {
display: flex;
flex-direction: column;
align-items: stretch;
flex-grow: 1;
}
.wrapper {
--glow: transparent;
--beta-bg: rgba(240, 46, 101, 0.16);
--beta-fg: rgba(240, 46, 101, 0.8);
--sep-clr: hsl(var(--color-neutral-10));
display: grid;
place-items: center;
justify-content: center;
flex-grow: 1;
position: relative;
grid-template-columns: 620px 400px;
padding-block: 4rem;
gap: max(4rem, 10vw);
overflow: hidden;
}
.card {
max-width: 660px;
.content {
display: flex;
align-items: center;
gap: 1.5rem;
margin-block-start: 2.5rem;
}
.card-preview {
display: none;
}
.card-footer {
display: flex;
justify-content: flex-end;
border-top: 1px solid var(--sep-clr);
margin-block-start: 2rem;
padding-block-start: 2rem;
margin-inline: -2rem;
padding-inline: 2rem;
}
}
.cbc-wrapper {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
height: 500px;
position: relative;
}
.cbc-confetti {
position: absolute;
top: 30%;
left: 50%;
translate: -50% -50%;
}
@keyframes shake {
0% {
translate: 0;
}
25% {
translate: 0 -4px;
}
50% {
translate: 0 0px;
}
75% {
translate: 0 0px;
}
100% {
translate: 0 0px;
}
}
.confetti-btn {
animation: shake 2000ms ease infinite;
user-select: none;
display: inline-flex;
place-items: center;
position: relative;
:global(.confetti-holder) {
position: absolute !important;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
}
.controls {
display: flex;
align-items: center;
gap: 0.5rem;
position: absolute;
bottom: 5vh;
left: 50%;
translate: -50%;
transition: opacity 250ms ease;
&.invisible {
opacity: 0;
}
}
.buttons-list-item:first-child .button {
padding-inline-start: 0;
}
.overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: hsl(var(--p-body-bg-color));
backdrop-filter: blur(80px);
opacity: 0.5;
}
.external-btn-top {
display: none;
}
.no-text-select {
user-select: none;
}
@media (max-width: 1024px) {
.external-btn-top {
display: flex;
}
.external-btn-bottom {
display: none !important;
}
.embed-btn {
order: 2;
border: none !important;
}
.wrapper {
display: block;
padding-block: 2rem;
max-width: min(100%, 500px);
margin: 0 auto;
}
.card {
background-color: transparent;
border: none;
padding-inline: 1rem;
padding-block: 0;
.content {
flex-direction: column;
align-items: stretch;
margin-block-start: 1rem;
padding-block-end: 2rem;
// border-block-end: 1px solid var(--sep-clr);
}
.card-preview {
display: block;
margin-block-start: 2rem;
}
.buttons-list {
flex-wrap: wrap;
justify-content: center;
.buttons-list-item:last-child {
border: none !important;
}
}
.card-footer {
border: none;
padding-block-start: 0;
.button {
display: grid;
place-items: center;
text-align: center;
width: 100%;
}
}
}
.cbc-wrapper {
display: none;
}
}
</style>
-57
View File
@@ -1,57 +0,0 @@
import { getApiEndpoint } from '$lib/stores/sdk';
import { redirect } from '@sveltejs/kit';
function getCardImgUrls(userId: string, endpoint: string) {
const resolved = endpoint;
const frontImg = `${resolved}/cards/cloud?userId=${userId}`;
const backImg = `${resolved}/cards/cloud-back?userId=${userId}`;
const ogImg = `${resolved}/cards/cloud-og?userId=${userId}`;
return { frontImg, backImg, ogImg };
}
async function urlContentToDataUri(url: string): Promise<string> {
const res = await fetch(url);
const blob = await res.blob();
return await new Promise((callback) => {
const reader = new FileReader();
reader.onload = function () {
if (typeof this.result !== 'string') return '';
callback(this.result);
};
reader.readAsDataURL(blob);
});
}
export async function load({ params, parent }) {
const { account } = await parent();
const endpoint = getApiEndpoint();
const userId = params.uid;
const { frontImg, backImg } = getCardImgUrls(userId, endpoint);
try {
const res = await fetch(frontImg);
if (!res.ok) {
redirect(303, '/');
}
return {
userId: params.uid,
base64: {
front: await urlContentToDataUri(frontImg),
back: await urlContentToDataUri(backImg)
},
isOwner: account && account.$id === userId,
imgUrls: {
frontImg,
backImg
}
};
} catch (e) {
console.error(e);
redirect(303, '/');
}
}
-17
View File
@@ -1,17 +0,0 @@
import { getApiEndpoint } from '$lib/stores/sdk';
export function getCardImgUrls(userId: string, endpoint: string) {
const resolved = endpoint;
const frontImg = `${resolved}/cards/cloud?userId=${userId}`;
const backImg = `${resolved}/cards/cloud-back?userId=${userId}`;
const ogImg = `${resolved}/cards/cloud-og?userId=${userId}`;
return { frontImg, backImg, ogImg };
}
export function getCampaignImageUrl(image: string) {
const endpoint = getApiEndpoint();
const url = new URL(image, endpoint);
return url.toString();
}
+11 -3
View File
@@ -48,6 +48,7 @@
type ResourcePage,
type ResourceNameMap
} from '$lib/helpers/oauth2-authorization-details';
import { resolveOAuth2AppLogoUrl } from '$lib/helpers/oauth2-app-logo';
import ResourceSelector from './resource-selector.svelte';
export type OAuth2Flow = 'authorization' | 'device';
@@ -110,6 +111,7 @@
);
const redirectHost = $derived(hostnameOf(grant.redirectUri));
const appLogoUrl = $derived(resolveOAuth2AppLogoUrl(app));
const appInitial = $derived((app.name || '?').charAt(0).toUpperCase());
const accountInitial = $derived((accountLabel || '?').charAt(0).toUpperCase());
@@ -493,8 +495,8 @@
<div class="consent">
<header class="header">
<div class="identity">
{#if app.logoUri}
<img src={app.logoUri} alt={app.name} class="avatar" />
{#if appLogoUrl}
<img src={appLogoUrl} alt={app.name} class="avatar" />
{:else}
<div class="avatar placeholder">{appInitial}</div>
{/if}
@@ -902,12 +904,18 @@
width: 3.5rem;
height: 3.5rem;
border-radius: var(--border-radius-l, 0.85rem);
object-fit: cover;
flex-shrink: 0;
border: 1px solid var(--border-neutral-strong);
background: var(--bgcolor-neutral-primary);
}
/* Keep wordmarks readable inside the square avatar (cover crops them). */
img.avatar {
object-fit: contain;
padding: 0.4rem;
box-sizing: border-box;
}
.avatar.placeholder {
display: flex;
align-items: center;
@@ -9,6 +9,7 @@
import { sdk } from '$lib/stores/sdk';
import { logout } from '$lib/helpers/logout';
import { isWebRedirect } from '$lib/helpers/oauth2-redirect';
import { getOAuth2App } from '$lib/helpers/oauth2-cimd';
import OAuth2ConsentCard, { type OAuth2Outcome } from '../consent-card.svelte';
import OAuth2OutcomeCard from '../outcome-card.svelte';
import { OAuth2ErrorMessage, OAuth2ErrorType } from '../errors';
@@ -85,7 +86,7 @@
): Promise<void> {
const loadedGrant = await sdk.forConsole.oauth2.getGrant({ grantId });
const [loadedApp, loadedAccount] = await Promise.all([
sdk.forConsole.apps.get({ appId: loadedGrant.appId }),
getOAuth2App(loadedGrant.appId),
knownAccount !== undefined ? Promise.resolve(knownAccount) : getAccount()
]);
if (cancelled()) return;
@@ -122,9 +123,7 @@
if (!isWebRedirect(result.redirectUrl)) {
completedRedirectUrl = result.redirectUrl;
account = loggedInAccount;
app = clientId
? await sdk.forConsole.apps.get({ appId: clientId }).catch(() => null)
: null;
app = clientId ? await getOAuth2App(clientId).catch(() => null) : null;
if (cancelled()) return;
phase = 'approved';
}
@@ -10,6 +10,7 @@
import { addNotification } from '$lib/stores/notifications';
import { sdk } from '$lib/stores/sdk';
import { Submit, trackError, trackEvent } from '$lib/actions/analytics';
import { getOAuth2App } from '$lib/helpers/oauth2-cimd';
import OAuth2ConsentCard, { type OAuth2Flow, type OAuth2Outcome } from '../consent-card.svelte';
import OAuth2OutcomeCard from '../outcome-card.svelte';
@@ -95,9 +96,7 @@
const loadedGrant = await sdk.forConsole.oauth2.createGrant({
userCode: normalized
});
const loadedApp = await sdk.forConsole.apps.get({
appId: loadedGrant.appId
});
const loadedApp = await getOAuth2App(loadedGrant.appId);
// A fresh `user_code` may have arrived while we awaited. Ignore this
// now-stale result so we never show consent for a superseded request.
if (normalizeUserCode(code) !== normalized) return;
+11 -3
View File
@@ -3,6 +3,7 @@
import { Card, Typography, Icon } from '@appwrite.io/pink-svelte';
import { IconCheck, IconX, IconLockClosed } from '@appwrite.io/pink-icons-svelte';
import { Button } from '$lib/elements/forms';
import { resolveOAuth2AppLogoUrl } from '$lib/helpers/oauth2-app-logo';
import type { OAuth2Flow, OAuth2Outcome } from './consent-card.svelte';
interface Props {
@@ -28,6 +29,7 @@
const approved = $derived(outcome === 'approved');
const appName = $derived(app?.name ?? 'the application');
const appLogoUrl = $derived(resolveOAuth2AppLogoUrl(app));
const appInitial = $derived((app?.name || '?').charAt(0).toUpperCase());
const accountInitial = $derived((accountLabel || '?').charAt(0).toUpperCase());
@@ -53,8 +55,8 @@
<div class="outcome" class:approved>
<header class="header">
<div class="identity">
{#if app?.logoUri}
<img src={app.logoUri} alt={appName} class="avatar" />
{#if appLogoUrl}
<img src={appLogoUrl} alt={appName} class="avatar" />
{:else}
<div class="avatar placeholder">{appInitial}</div>
{/if}
@@ -158,12 +160,18 @@
width: 3.5rem;
height: 3.5rem;
border-radius: var(--border-radius-l, 0.85rem);
object-fit: cover;
flex-shrink: 0;
border: 1px solid var(--border-neutral-strong);
background: var(--bgcolor-neutral-primary);
}
/* Keep wordmarks readable inside the square avatar (cover crops them). */
img.avatar {
object-fit: contain;
padding: 0.4rem;
box-sizing: border-box;
}
.avatar.placeholder {
display: flex;
align-items: center;