mirror of
https://github.com/HeyPuter/puter.git
synced 2026-11-13 20:12:57 -10:00
Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2bbd8a417f | ||
|
|
234994d3af | ||
|
|
eef2d089a8 | ||
|
|
711ece5800 | ||
|
|
40ea3686da | ||
|
|
db7ca8382b | ||
|
|
0f2c325598 | ||
|
|
ffcfb85749 | ||
|
|
44bf99f808 | ||
|
|
d392b6857d | ||
|
|
d8c3e01dd9 | ||
|
|
4bc679956f | ||
|
|
b751f75467 | ||
|
|
224b2f2367 | ||
|
|
80bcc4ba14 | ||
|
|
f26201649a | ||
|
|
1550be358d |
No files matched your search
@@ -259,6 +259,36 @@ no user to name), puter.js opens the dashboard's upgrade page in a new tab with
|
||||
what was refused, through a consent dialog when the click has expired or the
|
||||
tab is blocked, and `requestUpgrade()` resolves `{ upgraded: false }`.
|
||||
|
||||
## Top-up
|
||||
|
||||
`GET /embed/top-up` is the deployment's top-up dialog, where a user with a plan
|
||||
buys add-on credit, served and framed like the upgrade: a transparent GUI page
|
||||
covering the host with no box or close button, allowing `payment` and
|
||||
`otp-credentials`, with Escape left to the dialog. Its fragment names `user`.
|
||||
|
||||
puter.js frames it for the **Add credits** item of `<puter-user-menu>`, which
|
||||
shows only when whoami reports `subscribed: true` and no `team` paying for the
|
||||
account. On a page that can't frame the GUI, the item opens the dashboard with
|
||||
`?topup=` in a new tab instead.
|
||||
|
||||
The GUI reports `unavailable` unless its session belongs to `user`, the account
|
||||
has no verification or password change waiting, and the deployment defines
|
||||
`window.UITopUp` with `UITopUp.embeddable === true`. Otherwise it runs:
|
||||
|
||||
```js
|
||||
new UITopUp({ onClose }).open();
|
||||
```
|
||||
|
||||
`open()` resolves once the dialog has loaded the account and shows what it can
|
||||
buy, and `onClose({ toppedUp })` must run exactly once, when the dialog closes
|
||||
or when it declines to open for the account. The GUI then posts `{ msg: 'puterPopupFrame', state: 'closed', toppedUp }`
|
||||
and the page removes the frame. When the frame can't show the top-up, puter.js
|
||||
opens the dashboard's top-up in a new tab, as it does the upgrade.
|
||||
|
||||
While the top-up shows, a call refused for funds still rejects but opens no
|
||||
usage limit dialog over it, and `requestUpgrade()` frames nothing over it: it
|
||||
resolves `{ upgraded: false }` once the top-up closes.
|
||||
|
||||
## Email confirmation
|
||||
|
||||
`GET /embed/request-email-confirmation` walks a first-party page's user through
|
||||
@@ -292,6 +322,36 @@ app reads from the desktop's answer. A call made while the frame shows settles
|
||||
with it. A frame that is refused, never ready, or `unavailable` resolves
|
||||
`{ response: false }`, since there's no popup to fall back to.
|
||||
|
||||
## Custom domains
|
||||
|
||||
`GET /embed/attach-custom-domain` is the custom domain dialog of
|
||||
`puter.hosting.attach()`, the popup at `/action/attach-custom-domain`, served
|
||||
like the upgrade: the GUI shell with the same framing rules, redirects and
|
||||
`no-store`, run only when framed by an allowed page. puter.js frames it on a
|
||||
signed-in first-party page (the same pages as the pickers).
|
||||
|
||||
The frame covers the page with no box or close button, over a transparent GUI
|
||||
page, so the dialog floats over the host with its own scrim as it does on the
|
||||
desktop. The frame allows `clipboard-write`, for the dialog's copy buttons, as
|
||||
well as `otp-credentials`. Escape on the page is left to the dialog, which
|
||||
doesn't close while a request is in flight. Its fragment names `user` (the
|
||||
page's signed-in user), `subdomain` (the site to attach a domain to) and
|
||||
`msg_id`.
|
||||
|
||||
The GUI reports `unavailable` unless its session belongs to `user` and the
|
||||
account has no verification or password change waiting. It then runs the
|
||||
popup's action unchanged, with the framing page as the requester the dialog
|
||||
names: it posts `ready` once the dialog is on the page, answers
|
||||
`{ msg: 'customDomainAttached', domain, original_msg_id }` once the dialog has
|
||||
closed and its exit has played, and then posts `closed`. `domain` is the domain the user chose, or
|
||||
null. `attach()` resolves it. A frame that closes without an answer, or a
|
||||
loading scrim the user dismisses, resolves null.
|
||||
|
||||
A call made while the frame shows resolves null without replacing it, as a
|
||||
second call does on the desktop. A frame that is refused, never ready, or
|
||||
`unavailable` falls back to the popup, which can sign in, through a consent
|
||||
dialog when the click has expired.
|
||||
|
||||
## Checks
|
||||
|
||||
Run the GUI component/browser tests (with the SDK bundle built and Playwright
|
||||
@@ -299,7 +359,7 @@ Chromium installed), and the backend route tests:
|
||||
|
||||
```sh
|
||||
npx vitest run --config src/gui/vitest.config.js src/gui/src/UI/Dashboard/AppBrowser src/feedbackEmbed
|
||||
npx vitest run src/puter-js/src/lib/guiEmbed.test.js src/puter-js/src/modules/UI.showFeedbackDialog.test.js src/puter-js/src/modules/Auth.signInFrame.test.js src/puter-js/src/modules/UI.pickerFrame.test.js src/puter-js/src/modules/UI.requestUpgrade.test.js src/puter-js/src/lib/upgradePrompt.test.js src/puter-js/src/modules/UsageLimitDialog.upgrade.test.js
|
||||
npx vitest run src/puter-js/src/lib/guiEmbed.test.js src/puter-js/src/modules/UI.showFeedbackDialog.test.js src/puter-js/src/modules/Auth.signInFrame.test.js src/puter-js/src/modules/UI.pickerFrame.test.js src/puter-js/src/modules/UI.requestUpgrade.test.js src/puter-js/src/modules/UI.showTopUp.test.js src/puter-js/src/modules/UI.attachCustomDomainFrame.test.js src/puter-js/src/lib/upgradePrompt.test.js src/puter-js/src/modules/UsageLimitDialog.upgrade.test.js
|
||||
npx vitest run --config src/gui/vitest.config.js src/gui/src/helpers/popupFrame.test.js
|
||||
npx vitest run --config src/backend/vitest.config.ts src/backend/server.test.ts
|
||||
```
|
||||
@@ -261,6 +261,26 @@ describe('whoami extension — handleWhoami', () => {
|
||||
expect(body).toHaveProperty('taskbar_items');
|
||||
});
|
||||
|
||||
it('leaves out a desktop background saved on the account', async () => {
|
||||
const user = await seedUser();
|
||||
await server.stores.user.update(user.id as number, {
|
||||
desktop_bg_url: 'https://cdn.test/wallpaper.png',
|
||||
desktop_bg_color: '#000000',
|
||||
desktop_bg_fit: 'cover',
|
||||
});
|
||||
const { res, captured } = makeRes();
|
||||
|
||||
await runWithContext(
|
||||
{ actor: { user: { uuid: user.uuid, id: user.id as number } } },
|
||||
() => handleWhoami(makeReq(), res),
|
||||
);
|
||||
|
||||
const body = captured.body as Record<string, unknown>;
|
||||
expect(body).not.toHaveProperty('desktop_bg_url');
|
||||
expect(body).not.toHaveProperty('desktop_bg_color');
|
||||
expect(body).not.toHaveProperty('desktop_bg_fit');
|
||||
});
|
||||
|
||||
it('reports the SMS-to-card fallback only once a send has opened it', async () => {
|
||||
const user = await server.stores.user.create({
|
||||
username: `wuser_${Math.random().toString(36).slice(2, 8)}`,
|
||||
@@ -322,7 +342,7 @@ describe('whoami extension — handleWhoami', () => {
|
||||
expect(flags.payment_bypass).toBeUndefined();
|
||||
});
|
||||
|
||||
it('strips desktop_bg_*, created_ts and human_readable_age fields for app actors', async () => {
|
||||
it('strips created_ts and human_readable_age fields for app actors', async () => {
|
||||
const user = await seedUser();
|
||||
const { res, captured } = makeRes();
|
||||
|
||||
@@ -340,9 +360,6 @@ describe('whoami extension — handleWhoami', () => {
|
||||
expect(body.app_name).toBe('app-test-actor');
|
||||
// is_user_token is stripped for app actors.
|
||||
expect(body.is_user_token).toBeUndefined();
|
||||
expect(body.desktop_bg_url).toBeUndefined();
|
||||
expect(body.desktop_bg_color).toBeUndefined();
|
||||
expect(body.desktop_bg_fit).toBeUndefined();
|
||||
expect(body.human_readable_age).toBeUndefined();
|
||||
// Account age, in either form, is not exposed to apps.
|
||||
expect(body.created_ts).toBeUndefined();
|
||||
|
||||
@@ -81,9 +81,6 @@ export const handleWhoami = async (
|
||||
delete details.email;
|
||||
delete details.unconfirmed_email;
|
||||
}
|
||||
delete details.desktop_bg_url;
|
||||
delete details.desktop_bg_color;
|
||||
delete details.desktop_bg_fit;
|
||||
delete details.human_readable_age;
|
||||
delete details.created_ts;
|
||||
delete details.is_user_token;
|
||||
@@ -121,8 +118,7 @@ export const handleWhoami = async (
|
||||
}
|
||||
|
||||
const subscription = details.subscription as
|
||||
| { offering?: Record<string, unknown> }
|
||||
| undefined;
|
||||
{ offering?: Record<string, unknown> } | undefined;
|
||||
if (subscription?.offering) {
|
||||
delete subscription.offering.group;
|
||||
delete subscription.offering.benefits;
|
||||
|
||||
@@ -29,14 +29,13 @@ const ALLOWED_SORT_ORDER = ['asc', 'desc'];
|
||||
*
|
||||
* Two categories:
|
||||
*
|
||||
* - User-level: desktop background, taskbar items (UserStore)
|
||||
* - User-level: taskbar items (UserStore)
|
||||
* - Folder-level: layout, sort_by/sort_order (fsentries table)
|
||||
*/
|
||||
/**
|
||||
* Desktop preference writes — background, taskbar, layout, sort order. All four
|
||||
* persist to the user row on every call, and the GUI fires them on direct user
|
||||
* action, so a per-minute ceiling well above human speed is enough to catch a
|
||||
* stuck client.
|
||||
* Desktop preference writes — taskbar, layout, sort order. Each persists on
|
||||
* every call, and the GUI fires them on direct user action, so a per-minute
|
||||
* ceiling well above human speed is enough to catch a stuck client.
|
||||
*/
|
||||
const PREFERENCE_WRITE_LIMIT = {
|
||||
scope: 'desktop-preference',
|
||||
@@ -47,62 +46,6 @@ const PREFERENCE_WRITE_LIMIT = {
|
||||
|
||||
export class DesktopController extends PuterController {
|
||||
registerRoutes(router) {
|
||||
// -- Desktop background --------------------------------------
|
||||
|
||||
router.post(
|
||||
'/set-desktop-bg',
|
||||
{
|
||||
subdomain: 'api',
|
||||
requireUserActor: true,
|
||||
allowFullAccessToken: true,
|
||||
rateLimit: PREFERENCE_WRITE_LIMIT,
|
||||
},
|
||||
async (req, res) => {
|
||||
const { url, color, fit } = req.body ?? {};
|
||||
|
||||
const patch = {};
|
||||
if (url !== undefined) {
|
||||
if (url !== null && typeof url !== 'string') {
|
||||
throw new HttpError(
|
||||
400,
|
||||
'`url` must be a string or null',
|
||||
{ legacyCode: 'bad_request' },
|
||||
);
|
||||
}
|
||||
patch.desktop_bg_url = url;
|
||||
}
|
||||
if (color !== undefined) {
|
||||
if (color !== null && typeof color !== 'string') {
|
||||
throw new HttpError(
|
||||
400,
|
||||
'`color` must be a string or null',
|
||||
{ legacyCode: 'bad_request' },
|
||||
);
|
||||
}
|
||||
patch.desktop_bg_color = color;
|
||||
}
|
||||
if (fit !== undefined) {
|
||||
if (fit !== null && typeof fit !== 'string') {
|
||||
throw new HttpError(
|
||||
400,
|
||||
'`fit` must be a string or null',
|
||||
{ legacyCode: 'bad_request' },
|
||||
);
|
||||
}
|
||||
patch.desktop_bg_fit = fit;
|
||||
}
|
||||
|
||||
if (Object.keys(patch).length === 0) {
|
||||
throw new HttpError(400, 'No fields provided', {
|
||||
legacyCode: 'bad_request',
|
||||
});
|
||||
}
|
||||
|
||||
await this.stores.user.update(req.actor.user.id, patch);
|
||||
res.json({});
|
||||
},
|
||||
);
|
||||
|
||||
// -- Taskbar items -------------------------------------------
|
||||
|
||||
router.post(
|
||||
|
||||
@@ -130,102 +130,11 @@ const callRoute = async (
|
||||
});
|
||||
};
|
||||
|
||||
// ── /set-desktop-bg ─────────────────────────────────────────────────
|
||||
|
||||
describe('DesktopController POST /set-desktop-bg', () => {
|
||||
it('persists url/color/fit on the user row', async () => {
|
||||
const { actor, userId } = await makeUser();
|
||||
const { res, captured } = makeRes();
|
||||
await callRoute(
|
||||
'post',
|
||||
'/set-desktop-bg',
|
||||
makeReq({
|
||||
body: {
|
||||
url: 'https://cdn.test/wallpaper.png',
|
||||
color: '#000000',
|
||||
fit: 'cover',
|
||||
},
|
||||
actor,
|
||||
}),
|
||||
res,
|
||||
);
|
||||
expect(captured.body).toEqual({});
|
||||
|
||||
const refreshed = await server.stores.user.getById(userId);
|
||||
expect(refreshed?.desktop_bg_url).toBe(
|
||||
'https://cdn.test/wallpaper.png',
|
||||
);
|
||||
expect(refreshed?.desktop_bg_color).toBe('#000000');
|
||||
expect(refreshed?.desktop_bg_fit).toBe('cover');
|
||||
});
|
||||
|
||||
it('persists only the supplied fields (partial update)', async () => {
|
||||
const { actor, userId } = await makeUser();
|
||||
const { res } = makeRes();
|
||||
await callRoute(
|
||||
'post',
|
||||
'/set-desktop-bg',
|
||||
makeReq({ body: { color: '#ffffff' }, actor }),
|
||||
res,
|
||||
);
|
||||
const refreshed = await server.stores.user.getById(userId);
|
||||
expect(refreshed?.desktop_bg_color).toBe('#ffffff');
|
||||
// Untouched fields remain at their column default.
|
||||
expect(refreshed?.desktop_bg_url).toBeFalsy();
|
||||
expect(refreshed?.desktop_bg_fit).toBeFalsy();
|
||||
});
|
||||
|
||||
it('passes through `null` to clear a field', async () => {
|
||||
const { actor, userId } = await makeUser();
|
||||
// First populate, then clear.
|
||||
const populate = makeRes();
|
||||
await callRoute(
|
||||
'post',
|
||||
'/set-desktop-bg',
|
||||
makeReq({
|
||||
body: { url: 'https://cdn.test/x.png' },
|
||||
actor,
|
||||
}),
|
||||
populate.res,
|
||||
);
|
||||
const before = await server.stores.user.getById(userId);
|
||||
expect(before?.desktop_bg_url).toBe('https://cdn.test/x.png');
|
||||
|
||||
const clear = makeRes();
|
||||
await callRoute(
|
||||
'post',
|
||||
'/set-desktop-bg',
|
||||
makeReq({ body: { url: null }, actor }),
|
||||
clear.res,
|
||||
);
|
||||
const after = await server.stores.user.getById(userId);
|
||||
expect(after?.desktop_bg_url).toBeNull();
|
||||
});
|
||||
|
||||
it('throws 400 when url is not a string or null', async () => {
|
||||
const { actor } = await makeUser();
|
||||
const { res } = makeRes();
|
||||
await expect(
|
||||
callRoute(
|
||||
'post',
|
||||
'/set-desktop-bg',
|
||||
makeReq({ body: { url: 123 }, actor }),
|
||||
res,
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
|
||||
it('throws 400 when no fields are provided', async () => {
|
||||
const { actor } = await makeUser();
|
||||
const { res } = makeRes();
|
||||
await expect(
|
||||
callRoute(
|
||||
'post',
|
||||
'/set-desktop-bg',
|
||||
makeReq({ body: {}, actor }),
|
||||
res,
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
describe('DesktopController routes', () => {
|
||||
it('has no desktop background route', () => {
|
||||
expect(
|
||||
router.routes.some((r) => r.path === '/set-desktop-bg'),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -501,6 +501,29 @@ describe('DriverController.#handleCall (via captured router)', () => {
|
||||
expect(body.service.name).toBe('puter-kvstore');
|
||||
});
|
||||
|
||||
it('treats null `args` as no arguments', async () => {
|
||||
const actor = await makeUserActor();
|
||||
await server.stores.permission.setFlatUserPerm(
|
||||
actor.user!.id!,
|
||||
'service:puter-subdomains:ii:puter-subdomains',
|
||||
{
|
||||
permission: 'service:puter-subdomains:ii:puter-subdomains',
|
||||
deleted: false,
|
||||
issuer_user_id: actor.user!.id!,
|
||||
} as never,
|
||||
);
|
||||
|
||||
const res = makeRes();
|
||||
const req = makeReq(
|
||||
{ interface: 'puter-subdomains', method: 'select', args: null },
|
||||
actor,
|
||||
);
|
||||
await runWithContext({ actor }, () =>
|
||||
routes['POST /call'](req, res as unknown as Response, () => {}),
|
||||
);
|
||||
expect((res.body as { success: boolean }).success).toBe(true);
|
||||
});
|
||||
|
||||
it('pipes a stream-shaped result instead of JSON', async () => {
|
||||
// Use an ephemeral driver registered onto the controller's bag.
|
||||
const streamPayload = Buffer.from('hello-world');
|
||||
|
||||
@@ -276,8 +276,10 @@ export class DriverController extends PuterController {
|
||||
interface: ifaceName,
|
||||
method,
|
||||
driver: driverName,
|
||||
args = {},
|
||||
args: rawArgs,
|
||||
} = (req.body ?? {}) as Record<string, unknown>;
|
||||
// Drivers read fields off `args`, so a null one counts as absent.
|
||||
const args = rawArgs ?? {};
|
||||
|
||||
if (!ifaceName || typeof ifaceName !== 'string') {
|
||||
throw new HttpError(400, 'Missing or invalid `interface`', {
|
||||
|
||||
@@ -36,9 +36,9 @@ import type {
|
||||
|
||||
/**
|
||||
* GUI popups a first-party page can show in a frame at `/embed/<action>`,
|
||||
* instead of opening `/action/<action>` in a window, plus the upgrade dialog,
|
||||
* which it would otherwise open in a dashboard tab, and the email confirmation,
|
||||
* which it otherwise can't show.
|
||||
* instead of opening `/action/<action>` in a window, plus the upgrade and
|
||||
* top-up dialogs, which it would otherwise open in a dashboard tab, and the
|
||||
* email confirmation, which it otherwise can't show.
|
||||
*/
|
||||
export const FRAMED_POPUP_ACTIONS = [
|
||||
'sign-in',
|
||||
@@ -46,7 +46,9 @@ export const FRAMED_POPUP_ACTIONS = [
|
||||
'show-save-file-picker',
|
||||
'show-directory-picker',
|
||||
'upgrade',
|
||||
'top-up',
|
||||
'request-email-confirmation',
|
||||
'attach-custom-domain',
|
||||
] as const;
|
||||
|
||||
/** Longest description/og:description/twitter:description on `/app/<name>`. */
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import {
|
||||
setupPuterTestEnv,
|
||||
TEST_USER_CREDENTIALS,
|
||||
type PuterTestEnv,
|
||||
} from '../../testUtil.js';
|
||||
|
||||
/** A PUT body is the file, whatever content type the client labels it with. */
|
||||
describe('PUT stores the body as sent', () => {
|
||||
let env: PuterTestEnv;
|
||||
|
||||
beforeAll(async () => {
|
||||
env = await setupPuterTestEnv();
|
||||
}, 60_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await env?.shutdown();
|
||||
});
|
||||
|
||||
const dav = (path: string, init: RequestInit) => {
|
||||
const port = new URL(env.apiOrigin).port;
|
||||
const auth = Buffer.from(
|
||||
`${TEST_USER_CREDENTIALS.username}:${TEST_USER_CREDENTIALS.password}`,
|
||||
).toString('base64');
|
||||
return fetch(`http://dav.puter.localhost:${port}${encodeURI(path)}`, {
|
||||
...init,
|
||||
headers: { Authorization: `Basic ${auth}`, ...init.headers },
|
||||
});
|
||||
};
|
||||
|
||||
it.each([
|
||||
['application/json', '{"name":"report","rows":[1,2,3]}'],
|
||||
// Not JSON at all: the label alone must not get the body rejected.
|
||||
['application/json', 'not json'],
|
||||
['text/plain;actually=json', '{"a":1}'],
|
||||
['application/x-www-form-urlencoded', 'a=1&b=two'],
|
||||
['application/octet-stream', 'plain bytes'],
|
||||
])(
|
||||
'with Content-Type %s',
|
||||
async (contentType, content) => {
|
||||
const path = `/${env.users.user.username}/Documents/put-${randomUUID().slice(0, 8)}.bin`;
|
||||
const put = await dav(path, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': contentType },
|
||||
body: content,
|
||||
});
|
||||
expect(put.status).toBe(201);
|
||||
|
||||
const get = await dav(path, { method: 'GET' });
|
||||
expect(get.status).toBe(200);
|
||||
expect(await get.text()).toBe(content);
|
||||
},
|
||||
30_000,
|
||||
);
|
||||
|
||||
it('with a form body over the form parser limit', async () => {
|
||||
const path = `/${env.users.user.username}/Documents/put-${randomUUID().slice(0, 8)}.bin`;
|
||||
const content = `a=${'x'.repeat(200 * 1024)}`;
|
||||
const put = await dav(path, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: content,
|
||||
});
|
||||
expect(put.status).toBe(201);
|
||||
|
||||
const get = await dav(path, { method: 'GET' });
|
||||
expect(await get.text()).toBe(content);
|
||||
}, 30_000);
|
||||
});
|
||||
@@ -224,7 +224,7 @@ const extractToken = (
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Query string (used by e.g. QR login, asset URLs).
|
||||
// 5. Query string (used by e.g. asset URLs).
|
||||
const queryToken = (req.query as { auth_token?: unknown } | undefined)
|
||||
?.auth_token;
|
||||
if (typeof queryToken === 'string' && queryToken.length > 0) {
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import type { Server } from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { brotliCompressSync, deflateSync, gzipSync } from 'node:zlib';
|
||||
import express, {
|
||||
type ErrorRequestHandler,
|
||||
type RequestHandler,
|
||||
} from 'express';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { SLICE_BYTES } from '../../../util/slicedJson';
|
||||
import { createJsonBodyParser } from './jsonBody';
|
||||
|
||||
const LIMIT = 4 * 1024 * 1024;
|
||||
const TEXT_AS_JSON = 'text/plain;actually=json';
|
||||
|
||||
type Verify = NonNullable<Parameters<typeof express.json>[0]>['verify'];
|
||||
const captureRawBody: Verify = (req, _res, buf) => {
|
||||
(req as { rawBody?: Buffer }).rawBody = buf;
|
||||
};
|
||||
|
||||
/** An app that answers with what its parsers left on the request. */
|
||||
const listen = (parsers: RequestHandler[]): Promise<Server> => {
|
||||
const app = express();
|
||||
app.use(...parsers);
|
||||
app.post('/', (req, res) => {
|
||||
const rawBody = (req as { rawBody?: Buffer }).rawBody;
|
||||
res.json({
|
||||
body: req.body,
|
||||
hasBody: req.body !== undefined,
|
||||
rawBody: rawBody?.toString('base64'),
|
||||
});
|
||||
});
|
||||
const onError: ErrorRequestHandler = (err, _req, res, _next) => {
|
||||
res.status(err.statusCode ?? 500).json({ type: err.type });
|
||||
};
|
||||
app.use(onError);
|
||||
return new Promise((resolve) => {
|
||||
const server = app.listen(0, '127.0.0.1', () => resolve(server));
|
||||
});
|
||||
};
|
||||
|
||||
describe('createJsonBodyParser', () => {
|
||||
let sliced: Server;
|
||||
let framework: Server;
|
||||
|
||||
beforeAll(async () => {
|
||||
sliced = await listen([
|
||||
createJsonBodyParser({ limit: LIMIT, verify: captureRawBody }),
|
||||
]);
|
||||
// What the server ran before: one parser per content type.
|
||||
framework = await listen([
|
||||
express.json({ limit: LIMIT, verify: captureRawBody }),
|
||||
express.json({
|
||||
limit: LIMIT,
|
||||
type: (req) => req.headers['content-type'] === TEXT_AS_JSON,
|
||||
verify: captureRawBody,
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
sliced?.close();
|
||||
framework?.close();
|
||||
});
|
||||
|
||||
const post = async (
|
||||
server: Server,
|
||||
body: string | Buffer | undefined,
|
||||
headers: Record<string, string>,
|
||||
) => {
|
||||
const { port } = server.address() as AddressInfo;
|
||||
const response = await fetch(`http://127.0.0.1:${port}/`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body,
|
||||
});
|
||||
return { status: response.status, answer: await response.json() };
|
||||
};
|
||||
|
||||
const large = `${JSON.stringify({
|
||||
text: 'é😀 "quoted" \\ line\n'.repeat(SLICE_BYTES / 8),
|
||||
list: Array.from({ length: 20_000 }, (_, i) => ({
|
||||
i,
|
||||
on: i % 2 === 0,
|
||||
})),
|
||||
}).slice(0, -1)},"__proto__":{"nested":true}}`;
|
||||
|
||||
it.each<[string, string | Buffer | undefined, Record<string, string>]>([
|
||||
['an object', '{"a":1}', { 'Content-Type': 'application/json' }],
|
||||
['an array', '[1,2]', { 'Content-Type': 'application/json' }],
|
||||
[
|
||||
'a body sent as text',
|
||||
'{"interface":"x","auth_token":"t"}',
|
||||
{ 'Content-Type': TEXT_AS_JSON },
|
||||
],
|
||||
['a large body', large, { 'Content-Type': 'application/json' }],
|
||||
['a large body sent as text', large, { 'Content-Type': TEXT_AS_JSON }],
|
||||
[
|
||||
'a charset parameter',
|
||||
large,
|
||||
{ 'Content-Type': 'application/json; charset=UTF-8' },
|
||||
],
|
||||
[
|
||||
'a quoted charset parameter',
|
||||
'{"a":"é"}',
|
||||
{ 'Content-Type': 'application/json;charset="utf-8"' },
|
||||
],
|
||||
[
|
||||
'another parameter',
|
||||
'{"a":1}',
|
||||
{ 'Content-Type': 'application/json; profile=x' },
|
||||
],
|
||||
['an empty body', '', { 'Content-Type': 'application/json' }],
|
||||
['no body', undefined, { 'Content-Type': 'application/json' }],
|
||||
[
|
||||
'a byte order mark',
|
||||
`\ufeff${large}`,
|
||||
{ 'Content-Type': 'application/json' },
|
||||
],
|
||||
[
|
||||
'only a byte order mark',
|
||||
'\ufeff',
|
||||
{ 'Content-Type': 'application/json' },
|
||||
],
|
||||
['only whitespace', ' \n', { 'Content-Type': 'application/json' }],
|
||||
['a bare string', '"text"', { 'Content-Type': 'application/json' }],
|
||||
['a bare number', ' 12', { 'Content-Type': 'application/json' }],
|
||||
['null', 'null', { 'Content-Type': 'application/json' }],
|
||||
['malformed JSON', '{"a":', { 'Content-Type': 'application/json' }],
|
||||
[
|
||||
'malformed large JSON',
|
||||
`${large.slice(0, -1)},]`,
|
||||
{ 'Content-Type': 'application/json' },
|
||||
],
|
||||
[
|
||||
'a large bare string',
|
||||
JSON.stringify('x'.repeat(4 * SLICE_BYTES)),
|
||||
{ 'Content-Type': 'application/json' },
|
||||
],
|
||||
[
|
||||
'invalid UTF-8',
|
||||
Buffer.concat([
|
||||
Buffer.from('{"a":"'),
|
||||
Buffer.from([0xff, 0xe2, 0x82]),
|
||||
Buffer.from('"}'),
|
||||
]),
|
||||
{ 'Content-Type': 'application/json' },
|
||||
],
|
||||
[
|
||||
'a body over the limit',
|
||||
`["${'x'.repeat(LIMIT)}"]`,
|
||||
{ 'Content-Type': 'application/json' },
|
||||
],
|
||||
[
|
||||
'a gzipped body',
|
||||
gzipSync(large),
|
||||
{ 'Content-Type': 'application/json', 'Content-Encoding': 'gzip' },
|
||||
],
|
||||
[
|
||||
'a deflated body',
|
||||
deflateSync(large),
|
||||
{
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Encoding': 'deflate',
|
||||
},
|
||||
],
|
||||
[
|
||||
'a brotli body',
|
||||
brotliCompressSync(large),
|
||||
{ 'Content-Type': 'application/json', 'Content-Encoding': 'br' },
|
||||
],
|
||||
[
|
||||
'a body that inflates past the limit',
|
||||
gzipSync(`["${'x'.repeat(LIMIT)}"]`),
|
||||
{ 'Content-Type': 'application/json', 'Content-Encoding': 'gzip' },
|
||||
],
|
||||
[
|
||||
'an unknown content encoding',
|
||||
'{"a":1}',
|
||||
{ 'Content-Type': 'application/json', 'Content-Encoding': 'lzw' },
|
||||
],
|
||||
['plain text', '{"a":1}', { 'Content-Type': 'text/plain' }],
|
||||
[
|
||||
'text with the marker and a charset',
|
||||
'{"a":1}',
|
||||
{ 'Content-Type': `${TEXT_AS_JSON}; charset=utf-8` },
|
||||
],
|
||||
[
|
||||
'a JSON-suffixed type',
|
||||
'{"a":1}',
|
||||
{ 'Content-Type': 'application/vnd.api+json' },
|
||||
],
|
||||
[
|
||||
'form data',
|
||||
'a=1',
|
||||
{ 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
],
|
||||
['no content type', '{"a":1}', { 'Content-Type': '' }],
|
||||
])('answers %s the way express.json does', async (_name, body, headers) => {
|
||||
const got = await post(sliced, body, headers);
|
||||
const want = await post(framework, body, headers);
|
||||
expect(got).toEqual(want);
|
||||
});
|
||||
|
||||
it('leaves a body in another charset unread', async () => {
|
||||
for (const charset of ['utf-16', 'utf8', 'latin1']) {
|
||||
const { status, answer } = await post(
|
||||
sliced,
|
||||
Buffer.from('{"a":1}', 'utf16le'),
|
||||
{ 'Content-Type': `application/json; charset=${charset}` },
|
||||
);
|
||||
expect(status).toBe(200);
|
||||
expect(answer.hasBody).toBe(false);
|
||||
}
|
||||
// The last charset named is the one that counts.
|
||||
const { answer } = await post(sliced, '{"a":1}', {
|
||||
'Content-Type': 'application/json; charset=utf-8; charset=utf-16',
|
||||
});
|
||||
expect(answer.hasBody).toBe(false);
|
||||
});
|
||||
|
||||
it('parses bodies that arrive together, each to its own result', async () => {
|
||||
const bodies = Array.from({ length: 6 }, (_, n) =>
|
||||
JSON.stringify({ n, pad: 'x'.repeat((n + 1) * SLICE_BYTES) }),
|
||||
);
|
||||
const answers = await Promise.all(
|
||||
bodies.map((body) =>
|
||||
post(sliced, body, { 'Content-Type': 'application/json' }),
|
||||
),
|
||||
);
|
||||
answers.forEach(({ status, answer }, n) => {
|
||||
expect(status).toBe(200);
|
||||
expect(answer.body).toEqual(JSON.parse(bodies[n]!));
|
||||
});
|
||||
// A failed parse hands its turn on like a finished one.
|
||||
const mixed = await Promise.all([
|
||||
post(sliced, `${bodies[5]!},`, {
|
||||
'Content-Type': 'application/json',
|
||||
}),
|
||||
post(sliced, bodies[4], { 'Content-Type': 'application/json' }),
|
||||
post(sliced, bodies[3], { 'Content-Type': 'application/json' }),
|
||||
]);
|
||||
expect(mixed.map(({ status }) => status)).toEqual([400, 200, 200]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import express, { type Request, type RequestHandler } from 'express';
|
||||
import { parseJsonInSlices, SLICE_BYTES } from '../../../util/slicedJson';
|
||||
|
||||
/** What puter.js labels a JSON driver call, to keep it a simple CORS request. */
|
||||
const TEXT_AS_JSON = 'text/plain;actually=json';
|
||||
|
||||
const UTF8_CHARSET = /;\s*charset=("?)utf-8\1\s*(?:;|$)/i;
|
||||
|
||||
/** No charset, or exactly UTF-8. Anything else is left to `express.json`. */
|
||||
const declaresUtf8 = (contentType: string): boolean => {
|
||||
const mentions = contentType.match(/charset/gi)?.length ?? 0;
|
||||
return mentions === 0 || (mentions === 1 && UTF8_CHARSET.test(contentType));
|
||||
};
|
||||
|
||||
const isUtf8Json = (req: Request): boolean => {
|
||||
const contentType = req.headers['content-type'];
|
||||
if (contentType === TEXT_AS_JSON) return true;
|
||||
return (
|
||||
typeof contentType === 'string' &&
|
||||
Boolean(req.is('application/json')) &&
|
||||
declaresUtf8(contentType)
|
||||
);
|
||||
};
|
||||
|
||||
/** The error `express.json` raises, which the error handler answers with a 400. */
|
||||
const parseFailed = (message: string): Error =>
|
||||
Object.assign(new SyntaxError(message), {
|
||||
status: 400,
|
||||
statusCode: 400,
|
||||
expose: true,
|
||||
type: 'entity.parse.failed',
|
||||
});
|
||||
|
||||
const waiting: Array<() => void> = [];
|
||||
let parsing = false;
|
||||
|
||||
/**
|
||||
* Bodies too large for one `JSON.parse` call parse one at a time, so a single
|
||||
* tree is under construction however many arrive together.
|
||||
*/
|
||||
const parseInTurn = async (body: Buffer): Promise<unknown> => {
|
||||
if (body.length <= SLICE_BYTES) return parseJsonInSlices(body);
|
||||
if (parsing) await new Promise<void>((resolve) => waiting.push(resolve));
|
||||
parsing = true;
|
||||
try {
|
||||
return await parseJsonInSlices(body);
|
||||
} finally {
|
||||
// Handing over keeps `parsing` set, so a new arrival can't cut in.
|
||||
const next = waiting.shift();
|
||||
if (next) next();
|
||||
else parsing = false;
|
||||
}
|
||||
};
|
||||
|
||||
interface JsonBodyOptions {
|
||||
limit: number;
|
||||
verify?: NonNullable<Parameters<typeof express.raw>[0]>['verify'];
|
||||
}
|
||||
|
||||
/**
|
||||
* `express.json` for UTF-8 bodies, with the parse done in slices so a large
|
||||
* body can't hold the event loop. Reading, limits, decompression and `verify`
|
||||
* are the framework's; the result and the errors match `express.json`.
|
||||
*/
|
||||
export const createJsonBodyParser = ({
|
||||
limit,
|
||||
verify,
|
||||
}: JsonBodyOptions): RequestHandler => {
|
||||
const read = express.raw({
|
||||
limit,
|
||||
verify,
|
||||
type: (req) => isUtf8Json(req as Request),
|
||||
});
|
||||
|
||||
return (req, res, next) => {
|
||||
read(req, res, async (err?: unknown) => {
|
||||
// Not a Buffer: the reader skipped this request.
|
||||
if (err || !Buffer.isBuffer(req.body)) {
|
||||
next(err);
|
||||
return;
|
||||
}
|
||||
let body: Buffer = req.body;
|
||||
req.body = undefined;
|
||||
// The framework's decoder drops a byte order mark.
|
||||
if (body[0] === 0xef && body[1] === 0xbb && body[2] === 0xbf) {
|
||||
body = body.subarray(3);
|
||||
}
|
||||
if (body.length === 0) {
|
||||
req.body = {};
|
||||
next();
|
||||
return;
|
||||
}
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = await parseInTurn(body);
|
||||
} catch (e) {
|
||||
next(parseFailed((e as Error).message));
|
||||
return;
|
||||
}
|
||||
if (typeof parsed !== 'object' || parsed === null) {
|
||||
next(parseFailed('JSON body must be an object or an array'));
|
||||
return;
|
||||
}
|
||||
req.body = parsed;
|
||||
next();
|
||||
});
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,184 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { request, type Server } from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { setImmediate as nextTurn } from 'node:timers/promises';
|
||||
import express, {
|
||||
type ErrorRequestHandler,
|
||||
type RequestHandler,
|
||||
} from 'express';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { createJsonBodyParser } from './jsonBody';
|
||||
import {
|
||||
createLargeJsonBodyParser,
|
||||
DEFAULT_JSON_LIMIT_BYTES,
|
||||
} from './largeJsonBody';
|
||||
|
||||
const MiB = 1024 * 1024;
|
||||
const TOKEN = 'valid-token';
|
||||
const PAD = 'x'.repeat(DEFAULT_JSON_LIMIT_BYTES);
|
||||
|
||||
/** Stands in for the auth probe: one token is valid, wherever it is sent. */
|
||||
const authProbe: RequestHandler = (req, _res, next) => {
|
||||
const token =
|
||||
(req.body as { auth_token?: string } | undefined)?.auth_token ??
|
||||
req.headers.authorization;
|
||||
if (!req.actor && token === TOKEN) {
|
||||
req.actor = { user: { uuid: 'u1' } } as typeof req.actor;
|
||||
}
|
||||
next();
|
||||
};
|
||||
|
||||
describe('a JSON body over the default limit', () => {
|
||||
let server: Server;
|
||||
|
||||
beforeAll(async () => {
|
||||
const app = express();
|
||||
app.post(
|
||||
'/call',
|
||||
createLargeJsonBodyParser({
|
||||
authProbe,
|
||||
limitBytes: 128 * MiB,
|
||||
budgetBytes: 256 * MiB,
|
||||
perUserBytes: 128 * MiB,
|
||||
}),
|
||||
);
|
||||
app.use(createJsonBodyParser({ limit: DEFAULT_JSON_LIMIT_BYTES }));
|
||||
app.use(authProbe);
|
||||
app.post('/call', (req, res) => {
|
||||
const body = req.body as { auth_token?: string; pad: string };
|
||||
res.json({
|
||||
user: req.actor?.user.uuid ?? null,
|
||||
token: body.auth_token ?? null,
|
||||
padLength: body.pad.length,
|
||||
});
|
||||
});
|
||||
const onError: ErrorRequestHandler = (err, _req, res, _next) => {
|
||||
res.status(err.statusCode ?? 500).json({});
|
||||
};
|
||||
app.use(onError);
|
||||
await new Promise<void>((resolve) => {
|
||||
server = app.listen(0, '127.0.0.1', resolve);
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
server?.close();
|
||||
});
|
||||
|
||||
/** Sends `chunks` one write at a time, so the server sees them apart. */
|
||||
const post = (chunks: string[], headers: Record<string, string> = {}) =>
|
||||
new Promise<{ status: number; answer: Record<string, unknown> }>(
|
||||
(resolve, reject) => {
|
||||
const { port } = server.address() as AddressInfo;
|
||||
const req = request(
|
||||
{
|
||||
host: '127.0.0.1',
|
||||
port,
|
||||
path: '/call',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'text/plain;actually=json',
|
||||
'Content-Length': chunks.reduce(
|
||||
(total, chunk) =>
|
||||
total + Buffer.byteLength(chunk),
|
||||
0,
|
||||
),
|
||||
...headers,
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
const parts: Buffer[] = [];
|
||||
res.on('data', (part: Buffer) => parts.push(part));
|
||||
res.on('end', () =>
|
||||
resolve({
|
||||
status: res.statusCode!,
|
||||
answer: JSON.parse(
|
||||
Buffer.concat(parts).toString(),
|
||||
),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
req.on('error', reject);
|
||||
void (async () => {
|
||||
for (const chunk of chunks) {
|
||||
req.write(chunk);
|
||||
await nextTurn();
|
||||
}
|
||||
req.end();
|
||||
})();
|
||||
},
|
||||
);
|
||||
|
||||
it('is accepted when it opens with a valid auth_token', async () => {
|
||||
const { status, answer } = await post([
|
||||
`{"auth_token":"${TOKEN}","pad":"${PAD}"}`,
|
||||
]);
|
||||
expect(status).toBe(200);
|
||||
expect(answer).toEqual({
|
||||
user: 'u1',
|
||||
token: TOKEN,
|
||||
padLength: PAD.length,
|
||||
});
|
||||
}, 60_000);
|
||||
|
||||
it('is accepted when the token arrives in pieces, with spacing', async () => {
|
||||
const opening = ` {\n "auth_token" : "${TOKEN}" ,`;
|
||||
const { status, answer } = await post([...opening, `"pad":"${PAD}"}`]);
|
||||
expect(status).toBe(200);
|
||||
expect(answer.user).toBe('u1');
|
||||
}, 60_000);
|
||||
|
||||
it('is accepted with a header credential, as before', async () => {
|
||||
const { status, answer } = await post([`{"pad":"${PAD}"}`], {
|
||||
Authorization: TOKEN,
|
||||
});
|
||||
expect(status).toBe(200);
|
||||
expect(answer).toEqual({
|
||||
user: 'u1',
|
||||
token: null,
|
||||
padLength: PAD.length,
|
||||
});
|
||||
}, 60_000);
|
||||
|
||||
it.each([
|
||||
[
|
||||
'its token comes after other fields',
|
||||
`{"pad":"${PAD}","auth_token":"${TOKEN}"}`,
|
||||
],
|
||||
['its token is not valid', `{"auth_token":"expired","pad":"${PAD}"}`],
|
||||
['it has no token', `{"pad":"${PAD}"}`],
|
||||
[
|
||||
'a later field replaces the token it opens with',
|
||||
`{"auth_token":"${TOKEN}","pad":"${PAD}","auth_token":"other"}`,
|
||||
],
|
||||
[
|
||||
'the token it opens with is nested',
|
||||
`{"args":{"auth_token":"${TOKEN}"},"pad":"${PAD}"}`,
|
||||
],
|
||||
])(
|
||||
'is refused with 413 when %s',
|
||||
async (_name, body) => {
|
||||
expect((await post([body])).status).toBe(413);
|
||||
},
|
||||
60_000,
|
||||
);
|
||||
});
|
||||
@@ -18,6 +18,7 @@
|
||||
*/
|
||||
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { Readable } from 'node:stream';
|
||||
import type { NextFunction, Request, RequestHandler, Response } from 'express';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { isHttpError } from '../HttpError';
|
||||
@@ -35,7 +36,7 @@ const makeReq = (
|
||||
user: string | null = 'u1',
|
||||
body?: unknown,
|
||||
) =>
|
||||
({
|
||||
Object.assign(Readable.from([]), {
|
||||
complete: true,
|
||||
body,
|
||||
headers: {
|
||||
|
||||
@@ -17,13 +17,54 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import express, { type Request, type RequestHandler } from 'express';
|
||||
import type { Request, RequestHandler, Response } from 'express';
|
||||
import { actorUid } from '../../actor';
|
||||
import { HttpError } from '../HttpError';
|
||||
import { createJsonBodyParser } from './jsonBody';
|
||||
|
||||
/** The global JSON parser's limit, which applies before auth. */
|
||||
export const DEFAULT_JSON_LIMIT_BYTES = 50 * 1024 * 1024;
|
||||
|
||||
/** How much of a body is read to find a token it opens with. */
|
||||
const LEADING_TOKEN_BYTES = 8 * 1024;
|
||||
const LEADING_TOKEN =
|
||||
/^[ \t\n\r]*\{[ \t\n\r]*"auth_token"[ \t\n\r]*:[ \t\n\r]*"([^"\\]+)"/;
|
||||
|
||||
/**
|
||||
* The first `bytes` of the body, put back for the parser to read. Empty when
|
||||
* the body ends or fails before that many arrive.
|
||||
*/
|
||||
const peekBody = (req: Request, bytes: number): Promise<Buffer> =>
|
||||
new Promise((resolve) => {
|
||||
const settle = (head: Buffer | null) => {
|
||||
req.off('readable', onReadable);
|
||||
req.off('end', onGone);
|
||||
req.off('close', onGone);
|
||||
req.off('error', onGone);
|
||||
if (head) req.unshift(head);
|
||||
resolve(head ?? Buffer.alloc(0));
|
||||
};
|
||||
const onReadable = () => {
|
||||
// Null until `bytes` are buffered.
|
||||
const head = req.read(bytes) as Buffer | null;
|
||||
if (head) settle(head);
|
||||
};
|
||||
const onGone = () => settle(null);
|
||||
req.on('readable', onReadable);
|
||||
req.on('end', onGone);
|
||||
req.on('close', onGone);
|
||||
req.on('error', onGone);
|
||||
});
|
||||
|
||||
/**
|
||||
* The `auth_token` a JSON body opens with, which puter.js sends first so it can
|
||||
* be read ahead of the body.
|
||||
*/
|
||||
const leadingBodyToken = async (req: Request): Promise<string | undefined> => {
|
||||
const head = await peekBody(req, LEADING_TOKEN_BYTES);
|
||||
return LEADING_TOKEN.exec(head.toString('latin1'))?.[1];
|
||||
};
|
||||
|
||||
interface LargeJsonBodyOptions {
|
||||
/** The global auth probe; it skips requests that already carry an actor. */
|
||||
authProbe: RequestHandler;
|
||||
@@ -38,9 +79,9 @@ interface LargeJsonBodyOptions {
|
||||
|
||||
/**
|
||||
* Parses JSON bodies over the default limit, up to `limitBytes`, once the
|
||||
* caller's header or cookie credential resolves. Unauthenticated requests and
|
||||
* requests without a Content-Length fall through to the global parser and its
|
||||
* limit.
|
||||
* caller's credential resolves: a header, a cookie, or an `auth_token` the body
|
||||
* opens with. Unauthenticated requests and requests without a Content-Length
|
||||
* fall through to the global parser and its limit.
|
||||
*
|
||||
* The parsed body lives as long as the request, so a body's bytes count against
|
||||
* both budgets until its response closes. Over the user's budget gets a 429,
|
||||
@@ -53,82 +94,91 @@ export const createLargeJsonBodyParser = ({
|
||||
perUserBytes,
|
||||
accepts,
|
||||
}: LargeJsonBodyOptions): RequestHandler => {
|
||||
const json = express.json({ limit: limitBytes });
|
||||
const textAsJson = express.json({
|
||||
limit: limitBytes,
|
||||
type: (req) =>
|
||||
req.headers['content-type'] === 'text/plain;actually=json',
|
||||
});
|
||||
const json = createJsonBodyParser({ limit: limitBytes });
|
||||
let inFlightBytes = 0;
|
||||
const inFlightByUser = new Map<string, number>();
|
||||
|
||||
return (req, res, next) => {
|
||||
const probe = (req: Request, res: Response) =>
|
||||
new Promise<void>((resolve) => {
|
||||
void authProbe(req, res, () => resolve());
|
||||
});
|
||||
|
||||
return async (req, res, next) => {
|
||||
const declared = Number(req.headers['content-length']);
|
||||
if (!(declared > DEFAULT_JSON_LIMIT_BYTES && declared <= limitBytes)) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
void authProbe(req, res, () => {
|
||||
// `res.closed`: the client left during the probe, so `close` has
|
||||
// already fired and would never release a charge.
|
||||
if (!req.actor || res.closed) {
|
||||
next();
|
||||
await probe(req, res);
|
||||
let bodyToken: string | undefined;
|
||||
if (!req.actor && !res.closed) {
|
||||
bodyToken = await leadingBodyToken(req);
|
||||
if (bodyToken) {
|
||||
// Where the probe looks for a body token.
|
||||
req.body = { auth_token: bodyToken };
|
||||
await probe(req, res);
|
||||
req.body = undefined;
|
||||
}
|
||||
}
|
||||
// `res.closed`: the client left during the probe, so `close` has
|
||||
// already fired and would never release a charge.
|
||||
if (!req.actor || res.closed) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
const user = req.actor.user.uuid ?? actorUid(req.actor);
|
||||
const userBytes = inFlightByUser.get(user) ?? 0;
|
||||
if (userBytes + declared > perUserBytes) {
|
||||
res.setHeader('Retry-After', '5');
|
||||
next(
|
||||
new HttpError(
|
||||
429,
|
||||
'Too many large requests in progress for this account',
|
||||
{ legacyCode: 'too_many_requests' },
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (inFlightBytes + declared > budgetBytes) {
|
||||
res.setHeader('Retry-After', '5');
|
||||
next(
|
||||
new HttpError(503, 'Too many large requests in progress', {
|
||||
code: 'large_body_capacity',
|
||||
// Load shedding, not a fault: record it, don't page.
|
||||
alarmSeverity: 'info',
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
inFlightBytes += declared;
|
||||
inFlightByUser.set(user, userBytes + declared);
|
||||
res.once('close', () => {
|
||||
inFlightBytes -= declared;
|
||||
const left = (inFlightByUser.get(user) ?? 0) - declared;
|
||||
if (left > 0) inFlightByUser.set(user, left);
|
||||
else inFlightByUser.delete(user);
|
||||
});
|
||||
json(req, res, (err?: unknown) => {
|
||||
if (err) {
|
||||
next(err);
|
||||
return;
|
||||
}
|
||||
const user = req.actor.user.uuid ?? actorUid(req.actor);
|
||||
const userBytes = inFlightByUser.get(user) ?? 0;
|
||||
if (userBytes + declared > perUserBytes) {
|
||||
res.setHeader('Retry-After', '5');
|
||||
// The caller was resolved from the token the body opens with,
|
||||
// so the parsed body has to name the same one.
|
||||
const tokenMoved =
|
||||
bodyToken !== undefined &&
|
||||
(req.body as { auth_token?: unknown } | undefined)
|
||||
?.auth_token !== bodyToken;
|
||||
if (tokenMoved || (accepts && !accepts(req))) {
|
||||
// The same answer the default limit gives.
|
||||
next(
|
||||
new HttpError(
|
||||
429,
|
||||
'Too many large requests in progress for this account',
|
||||
{ legacyCode: 'too_many_requests' },
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (inFlightBytes + declared > budgetBytes) {
|
||||
res.setHeader('Retry-After', '5');
|
||||
next(
|
||||
new HttpError(503, 'Too many large requests in progress', {
|
||||
code: 'large_body_capacity',
|
||||
// Load shedding, not a fault: record it, don't page.
|
||||
alarmSeverity: 'info',
|
||||
new HttpError(413, 'request entity too large', {
|
||||
legacyCode: 'client_bad_request',
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
inFlightBytes += declared;
|
||||
inFlightByUser.set(user, userBytes + declared);
|
||||
res.once('close', () => {
|
||||
inFlightBytes -= declared;
|
||||
const left = (inFlightByUser.get(user) ?? 0) - declared;
|
||||
if (left > 0) inFlightByUser.set(user, left);
|
||||
else inFlightByUser.delete(user);
|
||||
});
|
||||
json(req, res, (err?: unknown) => {
|
||||
if (err) {
|
||||
next(err);
|
||||
return;
|
||||
}
|
||||
textAsJson(req, res, (err?: unknown) => {
|
||||
if (err) {
|
||||
next(err);
|
||||
return;
|
||||
}
|
||||
if (accepts && !accepts(req)) {
|
||||
// The same answer the default limit gives.
|
||||
next(
|
||||
new HttpError(413, 'request entity too large', {
|
||||
legacyCode: 'client_bad_request',
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
next();
|
||||
});
|
||||
});
|
||||
next();
|
||||
});
|
||||
};
|
||||
};
|
||||
@@ -355,6 +355,17 @@ describe('ChatCompletionDriver.complete auth and model resolution', () => {
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
|
||||
it('rejects a model that is not a string with 400', async () => {
|
||||
await expect(
|
||||
withTestActor(() =>
|
||||
driver.complete({
|
||||
messages: [{ role: 'user', content: 'hi' }],
|
||||
model: { id: 'gpt' },
|
||||
} as unknown as ICompleteArguments),
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
|
||||
it('routes by alias when a provider exposes one (puterId is auto-aliased on the bucket)', async () => {
|
||||
// Inject a model that carries a `puterId` so we can verify the
|
||||
// alias bucket resolves back to the canonical id. Spy on
|
||||
|
||||
@@ -79,6 +79,7 @@ import type {
|
||||
} from './types.js';
|
||||
import { normalize_tools_object } from './utils/FunctionCalling.js';
|
||||
import {
|
||||
requestedServiceSpeed,
|
||||
selectServiceSpeed,
|
||||
lowerServiceSpeed,
|
||||
isServiceSpeedUnavailable,
|
||||
@@ -909,18 +910,16 @@ export class ChatCompletionDriver extends PuterDriver {
|
||||
attemptProvider: IChatProvider,
|
||||
baseModel: IChatModel,
|
||||
) => {
|
||||
let requestedSpeed = requestedServiceSpeed(
|
||||
args,
|
||||
baseModel.provider,
|
||||
);
|
||||
const offers =
|
||||
args.serviceSpeed !== undefined &&
|
||||
args.serviceSpeed !== 'standard'
|
||||
requestedSpeed !== undefined && requestedSpeed !== 'standard'
|
||||
? ((await attemptProvider.serviceSpeedModels?.(
|
||||
baseModel,
|
||||
)) ?? {})
|
||||
: {};
|
||||
let requestedSpeed =
|
||||
args.serviceSpeed ??
|
||||
(baseModel.provider === 'claude' && args.speed === 'fast'
|
||||
? 'fast'
|
||||
: undefined);
|
||||
for (;;) {
|
||||
const selection = selectServiceSpeed(
|
||||
baseModel,
|
||||
@@ -2130,7 +2129,9 @@ export class ChatCompletionDriver extends PuterDriver {
|
||||
}
|
||||
|
||||
#resolveModel(modelId: string, provider?: string): IChatModel | null {
|
||||
const models = this.#modelIdMap[normalizeModelKey(modelId ?? '')];
|
||||
// `model` comes straight from the caller and may not be a string.
|
||||
if (typeof modelId !== 'string') return null;
|
||||
const models = this.#modelIdMap[normalizeModelKey(modelId)];
|
||||
if (!models || models.length === 0) return null;
|
||||
// An explicitly requested provider is honoured even if its route is
|
||||
// marked — the caller asked for that one, not for the cheapest hop.
|
||||
|
||||
@@ -44,7 +44,9 @@ import {
|
||||
type MockInstance,
|
||||
} from 'vitest';
|
||||
|
||||
import { SYSTEM_ACTOR } from '../../../../core/actor.js';
|
||||
import { SYSTEM_ACTOR, type Actor } from '../../../../core/actor.js';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { ChatCompletionDriver } from '../../ChatCompletionDriver.js';
|
||||
import type { MeteringService } from '../../../../services/metering/MeteringService.js';
|
||||
import { PuterServer } from '../../../../server.js';
|
||||
import { setupTestServer } from '../../../../testUtil.js';
|
||||
@@ -1580,3 +1582,117 @@ describe('OpenAiResponsesChatProvider.complete error mapping', () => {
|
||||
expect(recordSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ChatCompletionDriver OpenAI billing', () => {
|
||||
const makeBillingUser = async () => {
|
||||
const user = await server.stores.user.create({
|
||||
username: `billing-${uuidv4().slice(0, 8)}`,
|
||||
uuid: uuidv4(),
|
||||
password: null,
|
||||
email: null,
|
||||
free_storage: 1000000,
|
||||
requires_email_confirmation: false,
|
||||
});
|
||||
return { user: { ...user, email_confirmed: true } } as Actor;
|
||||
};
|
||||
const makeBillingDriver = async () => {
|
||||
const driver = new ChatCompletionDriver(
|
||||
{
|
||||
providers: {
|
||||
ollama: { enabled: false },
|
||||
'openai-completion': { apiKey: 'test-key' },
|
||||
},
|
||||
} as never,
|
||||
server.clients,
|
||||
server.stores,
|
||||
server.services,
|
||||
);
|
||||
await driver.onServerStart();
|
||||
return driver;
|
||||
};
|
||||
it('meters an empty Responses completion before returning its error', async () => {
|
||||
const actor = await makeBillingUser();
|
||||
const driver = await makeBillingDriver();
|
||||
const before = await server.services.metering.getRemainingUsage(actor);
|
||||
responsesCreateMock.mockResolvedValueOnce({
|
||||
status: 'incomplete',
|
||||
incomplete_details: { reason: 'max_output_tokens' },
|
||||
output: [],
|
||||
output_text: '',
|
||||
usage: {
|
||||
input_tokens: 1200,
|
||||
output_tokens: 2000,
|
||||
output_tokens_details: { reasoning_tokens: 2000 },
|
||||
},
|
||||
});
|
||||
await expect(
|
||||
withTestActor(
|
||||
() =>
|
||||
driver.complete({
|
||||
model: 'gpt-5.4-mini',
|
||||
provider: 'openai-responses',
|
||||
messages: [{ role: 'user', content: 'hello' }],
|
||||
max_tokens: 1,
|
||||
fallback: false,
|
||||
}),
|
||||
actor,
|
||||
),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
expect(responsesCreateMock).toHaveBeenCalledTimes(1);
|
||||
expect(recordSpy).toHaveBeenCalledTimes(1);
|
||||
expect(recordSpy.mock.calls[0][0]).toMatchObject({
|
||||
prompt_tokens: 1200,
|
||||
completion_tokens: 2000,
|
||||
});
|
||||
await Promise.all(recordSpy.mock.results.map((result) => result.value));
|
||||
expect(
|
||||
await server.services.metering.getRemainingUsage(actor),
|
||||
).toBeLessThan(before);
|
||||
});
|
||||
it('prices a raw priority tier with the same rate card as fast service', async () => {
|
||||
const actor = await makeBillingUser();
|
||||
const driver = await makeBillingDriver();
|
||||
const charges: number[] = [];
|
||||
for (const extra of [
|
||||
{},
|
||||
{ service_tier: 'priority' },
|
||||
{ serviceSpeed: 'fast' },
|
||||
]) {
|
||||
responsesCreateMock.mockResolvedValueOnce({
|
||||
output: [],
|
||||
output_text: 'hi',
|
||||
service_tier: Object.keys(extra).length
|
||||
? 'priority'
|
||||
: 'default',
|
||||
usage: { input_tokens: 100, output_tokens: 100 },
|
||||
});
|
||||
const before =
|
||||
await server.services.metering.getRemainingUsage(actor);
|
||||
await withTestActor(
|
||||
() =>
|
||||
driver.complete({
|
||||
model: 'gpt-6.1-terra',
|
||||
provider: 'openai-responses',
|
||||
messages: [{ role: 'user', content: 'hello' }],
|
||||
max_tokens: 100,
|
||||
fallback: false,
|
||||
...extra,
|
||||
} as never),
|
||||
actor,
|
||||
);
|
||||
await Promise.all(
|
||||
recordSpy.mock.results.map((result) => result.value),
|
||||
);
|
||||
charges.push(
|
||||
before -
|
||||
(await server.services.metering.getRemainingUsage(actor)),
|
||||
);
|
||||
}
|
||||
expect(responsesCreateMock.mock.calls[1][0].service_tier).toBe(
|
||||
'priority',
|
||||
);
|
||||
expect(charges[0]).toBeGreaterThan(0);
|
||||
expect(charges[1]).toBe(charges[2]);
|
||||
expect(charges[2]).toBe(charges[0] * 2);
|
||||
});
|
||||
});
|
||||
@@ -1122,16 +1122,6 @@ export const handle_completion_output_responses_api = async ({
|
||||
// Inline-compaction artifact, if the upstream compacted this turn.
|
||||
const compactionItem = output.find((item) => item?.type === 'compaction');
|
||||
|
||||
const is_empty = completion.output_text.trim() === '';
|
||||
if (is_empty && responseToolCalls.length < 1 && !compactionItem) {
|
||||
// GPT refuses to generate an empty response if you ask it to,
|
||||
// so this will probably only happen on an error condition.
|
||||
// A compaction-only output is legitimate, so don't reject it.
|
||||
throw new HttpError(400, 'an empty response was generated', {
|
||||
legacyCode: 'bad_response',
|
||||
});
|
||||
}
|
||||
|
||||
// Reasoning models return `reasoning` output items; their human-readable
|
||||
// text only exists when the caller requested summaries via
|
||||
// `reasoning: { summary: ... }` (raw chain-of-thought is never returned).
|
||||
@@ -1234,6 +1224,14 @@ export const handle_completion_output_responses_api = async ({
|
||||
if (usageDetails) ret.usageDetails = usageDetails;
|
||||
}
|
||||
|
||||
// Empty output can still include paid reasoning and input tokens.
|
||||
const isEmpty = completion.output_text.trim() === '';
|
||||
if (isEmpty && responseToolCalls.length < 1 && !compactionItem) {
|
||||
throw new HttpError(400, 'an empty response was generated', {
|
||||
legacyCode: 'bad_response',
|
||||
});
|
||||
}
|
||||
|
||||
const mod_text = completion.output_text;
|
||||
if (moderate && mod_text !== null) {
|
||||
await applyModeration(moderate, mod_text);
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
} from './OpenAIUtil.js';
|
||||
import type { IChatModel, ServiceSpeed } from '../types.js';
|
||||
import {
|
||||
requestedServiceSpeed,
|
||||
selectServiceSpeed,
|
||||
servedServiceSpeed,
|
||||
serviceSpeedBillingModel,
|
||||
@@ -83,6 +84,31 @@ describe('service speed selection', () => {
|
||||
expect(selected.model).toBe(entry);
|
||||
expect(selected.args).toBe(args);
|
||||
});
|
||||
it.each([
|
||||
[{ service_tier: 'priority' }, 'openai-responses', 'fast'],
|
||||
[{ service_tier: 'ultrafast' }, 'openai-responses', 'ultrafast'],
|
||||
[{ service_tier: 'auto' }, 'mistral', 'fast'],
|
||||
[{ speed: 'fast' }, 'claude', 'fast'],
|
||||
[{ service_tier: 'auto' }, 'openai-responses', undefined],
|
||||
[{ service_tier: 'flex' }, 'openai-responses', undefined],
|
||||
[{ speed: 'fast' }, 'openai-responses', undefined],
|
||||
[{ serviceSpeed: 'standard', service_tier: 'priority' }, 'openai-responses', 'standard'],
|
||||
] as const)('reads %j on %s as speed %s', (args, provider, speed) => {
|
||||
expect(requestedServiceSpeed(args, provider)).toBe(speed);
|
||||
});
|
||||
it('prices a native priority tier like fast service', () => {
|
||||
const entry = model('openai-responses', 'gpt-6.1-sol');
|
||||
const args = { ...request(), service_tier: 'priority' as const };
|
||||
const selected = selectServiceSpeed(
|
||||
entry,
|
||||
{ ...args, serviceSpeed: requestedServiceSpeed(args, entry.provider) },
|
||||
noVariant,
|
||||
);
|
||||
const explicit = selectServiceSpeed(entry, request('fast'), noVariant);
|
||||
expect(selected.speed).toBe('fast');
|
||||
expect(selected.model).toEqual(explicit.model);
|
||||
expect(selected.args.service_tier).toBe('priority');
|
||||
});
|
||||
it.each([
|
||||
'deepseek',
|
||||
'zai',
|
||||
@@ -248,6 +274,33 @@ describe('served speed billing', () => {
|
||||
expect(recorded).toEqual([result.costs]);
|
||||
},
|
||||
);
|
||||
it.each([
|
||||
['fast', 2],
|
||||
['ultrafast', 6],
|
||||
] as const)(
|
||||
'bills a served %s tier at its catalog rate without a selection snapshot',
|
||||
(speed, multiplier) => {
|
||||
const entry = model('openai-responses', 'gpt-6.1-sol');
|
||||
entry.pricingOverrides = [
|
||||
{
|
||||
minPromptTokens: 100,
|
||||
costs: { prompt_tokens: 400, completion_tokens: 1500 },
|
||||
},
|
||||
];
|
||||
const billed = serviceSpeedBillingModel(entry, speed);
|
||||
expect(billed.costs.prompt_tokens).toBe(200 * multiplier);
|
||||
expect(billed.pricingOverrides?.[0]?.costs.prompt_tokens).toBe(
|
||||
400 * multiplier,
|
||||
);
|
||||
expect(serviceSpeedBillingModel(entry, 'standard')).toBe(entry);
|
||||
},
|
||||
);
|
||||
it('bills a served premium tier as standard when the catalog has no rate for it', () => {
|
||||
const entry = model('groq', 'some-model');
|
||||
expect(serviceSpeedBillingModel(entry, 'fast').costs).toEqual(
|
||||
entry.costs,
|
||||
);
|
||||
});
|
||||
it('restores standard scheduled and long-context rates after a downgrade', () => {
|
||||
const entry = model('openai-responses', 'gpt-6.1-sol');
|
||||
entry.pricingOverrides = [
|
||||
|
||||
@@ -59,6 +59,26 @@ export interface ServiceSpeedSelection {
|
||||
speed: ServiceSpeed;
|
||||
}
|
||||
|
||||
/**
|
||||
* The speed a request asks for. Native premium tier parameters count as the
|
||||
* matching `serviceSpeed`, so they are priced like it; `serviceSpeed` wins.
|
||||
*/
|
||||
export const requestedServiceSpeed = (
|
||||
args: Pick<ICompleteArguments, 'serviceSpeed' | 'service_tier' | 'speed'>,
|
||||
provider: string | undefined,
|
||||
): ServiceSpeed | undefined => {
|
||||
if (args.serviceSpeed !== undefined) return args.serviceSpeed;
|
||||
if (args.service_tier === 'ultrafast') return 'ultrafast';
|
||||
if (
|
||||
args.service_tier === 'priority' ||
|
||||
(provider === 'claude' && args.speed === 'fast') ||
|
||||
// Mistral's `auto` tier is its priority tier.
|
||||
(provider === 'mistral' && args.service_tier === 'auto')
|
||||
)
|
||||
return 'fast';
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/** Select only an equivalent model from the same provider's loaded catalog. */
|
||||
export const selectServiceSpeed = (
|
||||
model: IChatModel,
|
||||
@@ -201,16 +221,27 @@ export const servedServiceSpeed = (
|
||||
: 'standard';
|
||||
};
|
||||
|
||||
/**
|
||||
* The model priced at the speed the provider served. Without a selection
|
||||
* snapshot the catalog's rates for that speed apply, so a premium tier reached
|
||||
* some other way is never billed as standard.
|
||||
*/
|
||||
export const serviceSpeedBillingModel = (
|
||||
model: IChatModel,
|
||||
speed: ServiceSpeed,
|
||||
): IChatModel => {
|
||||
const pricing = model.serviceSpeedPricing;
|
||||
if (!pricing || pricing.speed === speed) return model;
|
||||
const pricing = model.serviceSpeedPricing ?? {
|
||||
speed: 'standard',
|
||||
standardCosts: model.costs,
|
||||
standardOverrides: model.pricingOverrides,
|
||||
fastCosts: serviceSpeedCosts(model, 'fast'),
|
||||
ultrafastCosts: serviceSpeedCosts(model, 'ultrafast'),
|
||||
};
|
||||
if (pricing.speed === speed) return model;
|
||||
const costs =
|
||||
speed === 'fast'
|
||||
? (pricing.fastCosts ?? pricing.standardCosts)
|
||||
: pricing.standardCosts;
|
||||
(speed === 'ultrafast' ? pricing.ultrafastCosts : undefined) ??
|
||||
(speed !== 'standard' ? pricing.fastCosts : undefined) ??
|
||||
pricing.standardCosts;
|
||||
return {
|
||||
...model,
|
||||
costs,
|
||||
|
||||
@@ -190,6 +190,39 @@ describe('VoiceChangerDriver.convert argument validation', () => {
|
||||
withActor(actor, () => driver.convert({ audio: undefined })),
|
||||
).rejects.toMatchObject({ statusCode: 400 });
|
||||
});
|
||||
|
||||
it.each([
|
||||
['an unpriced', 'eleven_multilingual_sts_v1'],
|
||||
['a malformed', 'eleven_english_sts_v2&x=1'],
|
||||
])(
|
||||
'rejects %s model before loading audio or calling ElevenLabs',
|
||||
async (_label, model) => {
|
||||
const { actor } = await makeUser();
|
||||
await expect(
|
||||
withActor(actor, () =>
|
||||
driver.convert({
|
||||
audio: 'https://audio.example/sample.wav',
|
||||
model,
|
||||
}),
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
statusCode: 400,
|
||||
legacyCode: 'field_invalid',
|
||||
fields: {
|
||||
key: 'model',
|
||||
expected: [
|
||||
'eleven_multilingual_sts_v2',
|
||||
'eleven_english_sts_v2',
|
||||
],
|
||||
got: model,
|
||||
},
|
||||
});
|
||||
expect(webFetchMock).not.toHaveBeenCalled();
|
||||
expect(fetchSpy).not.toHaveBeenCalled();
|
||||
expect(admitSpy).not.toHaveBeenCalled();
|
||||
expect(incrementUsageSpy).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
// ── Credit gate ─────────────────────────────────────────────────────
|
||||
|
||||
@@ -51,6 +51,10 @@ const MAX_AUDIO_FILE_SIZE = 25 * 1024 * 1024;
|
||||
// Covers the upload as well as the conversion.
|
||||
const CONVERT_TIMEOUT_MS = 10 * 60 * 1000;
|
||||
|
||||
const SUPPORTED_MODELS = Object.keys(VOICE_CHANGER_COSTS).map(
|
||||
(key) => key.split(':')[1]!,
|
||||
);
|
||||
|
||||
const VOICE_CHANGER_CATALOG: ProviderCatalog = {
|
||||
label: 'Speech-to-speech',
|
||||
ids: ['elevenlabs'],
|
||||
@@ -165,14 +169,6 @@ export class VoiceChangerDriver extends PuterDriver {
|
||||
});
|
||||
}
|
||||
|
||||
const loaded = await loadFileInput(
|
||||
this.stores,
|
||||
this.services.fs,
|
||||
actor,
|
||||
args.audio,
|
||||
{ maxBytes: MAX_AUDIO_FILE_SIZE, acceptWebInput: true },
|
||||
);
|
||||
|
||||
const modelId =
|
||||
args.model_id || args.model || elevenlabs.defaultModelId;
|
||||
const voiceId =
|
||||
@@ -184,21 +180,41 @@ export class VoiceChangerDriver extends PuterDriver {
|
||||
throw new HttpError(400, '`voice` is required', {
|
||||
legacyCode: 'bad_request',
|
||||
});
|
||||
// `voiceId` lands in the request URL path; `modelId` lands in a
|
||||
// multipart field. Both are forwarded to ElevenLabs with our
|
||||
// long-lived API key, so anything other than a strict alphanumeric
|
||||
// shape lets a caller steer the request at a different endpoint or
|
||||
// inject parameters. ElevenLabs voice/model IDs are always
|
||||
// `[A-Za-z0-9_-]+` in practice.
|
||||
const ID_REGEX = /^[A-Za-z0-9_-]+$/;
|
||||
if (!ID_REGEX.test(voiceId))
|
||||
// `voiceId` lands in the request URL path, which carries our API key,
|
||||
// so anything outside ElevenLabs' `[A-Za-z0-9_-]+` id shape could
|
||||
// steer the request at a different endpoint.
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(voiceId))
|
||||
throw new HttpError(400, '`voice` must be alphanumeric', {
|
||||
legacyCode: 'bad_request',
|
||||
});
|
||||
if (!ID_REGEX.test(modelId))
|
||||
throw new HttpError(400, '`model` must be alphanumeric', {
|
||||
legacyCode: 'bad_request',
|
||||
});
|
||||
|
||||
// Gate on the cost table: an id we can't price is one we can't bill
|
||||
// for, and ElevenLabs bills us for it either way. This also keeps
|
||||
// anything but a known id out of the multipart `model_id` field.
|
||||
const usageKey = `elevenlabs:${modelId}:second`;
|
||||
if (!Object.hasOwn(VOICE_CHANGER_COSTS, usageKey)) {
|
||||
throw new HttpError(
|
||||
400,
|
||||
`Invalid model: ${modelId}. Expected: ${SUPPORTED_MODELS.join(', ')}`,
|
||||
{
|
||||
legacyCode: 'field_invalid',
|
||||
fields: {
|
||||
key: 'model',
|
||||
expected: SUPPORTED_MODELS,
|
||||
got: modelId,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
const ucentsPerSecond = VOICE_CHANGER_COSTS[usageKey]!;
|
||||
|
||||
const loaded = await loadFileInput(
|
||||
this.stores,
|
||||
this.services.fs,
|
||||
actor,
|
||||
args.audio,
|
||||
{ maxBytes: MAX_AUDIO_FILE_SIZE, acceptWebInput: true },
|
||||
);
|
||||
|
||||
// The hold estimates seconds from the input at 128 kbps: compact audio
|
||||
// is under-held rather than refused. Usage is metered from the length
|
||||
@@ -207,8 +223,6 @@ export class VoiceChangerDriver extends PuterDriver {
|
||||
1,
|
||||
Math.ceil(loaded.buffer.byteLength / 16000),
|
||||
);
|
||||
const usageKey = `elevenlabs:${modelId}:second`;
|
||||
const ucentsPerSecond = VOICE_CHANGER_COSTS[usageKey] ?? 0;
|
||||
const estimatedCost = ucentsPerSecond * estimatedSeconds;
|
||||
|
||||
const formData = new FormData();
|
||||
|
||||
@@ -37,7 +37,7 @@ import {
|
||||
postGeminiJson,
|
||||
geminiTokenCount as tokenCount,
|
||||
} from '../../../util/geminiRest.js';
|
||||
import { decodeStrictBase64 } from '../../../../util/mediaSniff.js';
|
||||
import { decodeStrictBase64InSlices } from '../../../../util/mediaSniff.js';
|
||||
import { isUpstreamTimeoutError } from '../../../util/upstreamErrors.js';
|
||||
import { SAMPLE_AUDIO_URL } from '../../../util/testMode.js';
|
||||
import type {
|
||||
@@ -456,7 +456,8 @@ export class GeminiTTSProvider implements ITTSProvider {
|
||||
},
|
||||
);
|
||||
}
|
||||
const { body, contentType } = this.#decodeAudio(audio);
|
||||
const { body, contentType } =
|
||||
await this.#decodeAudio(audio);
|
||||
|
||||
outputTokens = usageTokens(
|
||||
usage?.output_tokens_by_modality,
|
||||
@@ -474,7 +475,7 @@ export class GeminiTTSProvider implements ITTSProvider {
|
||||
dataType: 'stream',
|
||||
content_type: contentType,
|
||||
chunked: true,
|
||||
stream: Readable.from(body),
|
||||
stream: Readable.from(body, { objectMode: false }),
|
||||
};
|
||||
} finally {
|
||||
// Every outcome pays once for the counts it reports.
|
||||
@@ -519,13 +520,15 @@ export class GeminiTTSProvider implements ITTSProvider {
|
||||
}
|
||||
|
||||
/** WAV passes through byte for byte; raw PCM is wrapped in a WAV header. */
|
||||
#decodeAudio(audio: InteractionContent): {
|
||||
body: Buffer;
|
||||
async #decodeAudio(audio: InteractionContent): Promise<{
|
||||
body: Buffer[];
|
||||
contentType: string;
|
||||
} {
|
||||
}> {
|
||||
const { data, mime_type: mimeType } = audio;
|
||||
const bytes =
|
||||
typeof data === 'string' ? decodeStrictBase64(data) : null;
|
||||
typeof data === 'string'
|
||||
? await decodeStrictBase64InSlices(data)
|
||||
: null;
|
||||
if (!bytes || typeof mimeType !== 'string') {
|
||||
throw upstreamFailure('Gemini TTS returned invalid audio data');
|
||||
}
|
||||
@@ -541,7 +544,7 @@ export class GeminiTTSProvider implements ITTSProvider {
|
||||
) {
|
||||
throw upstreamFailure('Gemini TTS returned invalid audio data');
|
||||
}
|
||||
return { body: bytes, contentType: 'audio/wav' };
|
||||
return { body: [bytes], contentType: 'audio/wav' };
|
||||
}
|
||||
if (PCM_MIME_TYPES.has(essence) && bytes.length > 0) {
|
||||
const rate = Number(
|
||||
@@ -551,8 +554,9 @@ export class GeminiTTSProvider implements ITTSProvider {
|
||||
Number.isSafeInteger(rate) && rate > 0
|
||||
? rate
|
||||
: DEFAULT_PCM_SAMPLE_RATE;
|
||||
// Sent ahead of the samples, which are never copied behind it.
|
||||
return {
|
||||
body: this.#wrapPcmInWav(bytes, sampleRate, 1, 16),
|
||||
body: [this.#wavHeader(bytes.length, sampleRate, 1, 16), bytes],
|
||||
contentType: 'audio/wav',
|
||||
};
|
||||
}
|
||||
@@ -560,17 +564,15 @@ export class GeminiTTSProvider implements ITTSProvider {
|
||||
}
|
||||
|
||||
/** Wrap raw PCM samples in a WAV container so browsers can play it. */
|
||||
#wrapPcmInWav(
|
||||
pcm: Buffer,
|
||||
#wavHeader(
|
||||
dataSize: number,
|
||||
sampleRate: number,
|
||||
channels: number,
|
||||
bitsPerSample: number,
|
||||
): Buffer {
|
||||
const byteRate = (sampleRate * channels * bitsPerSample) / 8;
|
||||
const blockAlign = (channels * bitsPerSample) / 8;
|
||||
const dataSize = pcm.length;
|
||||
const headerSize = 44;
|
||||
const buffer = Buffer.alloc(headerSize + dataSize);
|
||||
const buffer = Buffer.alloc(44);
|
||||
|
||||
// RIFF header
|
||||
buffer.write('RIFF', 0);
|
||||
@@ -590,7 +592,6 @@ export class GeminiTTSProvider implements ITTSProvider {
|
||||
// data sub-chunk
|
||||
buffer.write('data', 36);
|
||||
buffer.writeUInt32LE(dataSize, 40);
|
||||
pcm.copy(buffer, headerSize);
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ import { insufficientCreditsError } from '../../../../services/metering/enforcem
|
||||
import type { UsageInput } from '../../../../services/metering/types.js';
|
||||
import { normalizeRawBase64ImageString } from '../../../../util/appIcon.js';
|
||||
import {
|
||||
decodeStrictBase64,
|
||||
decodeStrictBase64InSlices,
|
||||
sniffImageMime,
|
||||
sniffVideoMime,
|
||||
} from '../../../../util/mediaSniff.js';
|
||||
@@ -405,7 +405,7 @@ export class GeminiVideoProvider extends VideoProvider {
|
||||
'Gemini video generation did not complete the request',
|
||||
);
|
||||
}
|
||||
const video = this.#readVideo(videoBlock);
|
||||
const video = await this.#readVideo(videoBlock);
|
||||
if (!billed) {
|
||||
throw geminiUpstreamFailure(
|
||||
'Gemini video generation returned unusable usage',
|
||||
@@ -722,7 +722,7 @@ export class GeminiVideoProvider extends VideoProvider {
|
||||
}
|
||||
|
||||
/** The base64 MP4 held by the video block. */
|
||||
#readVideo(video: InteractionContent | undefined): string {
|
||||
async #readVideo(video: InteractionContent | undefined): Promise<string> {
|
||||
if (!video) {
|
||||
throw new HttpError(400, 'Gemini did not return a video', {
|
||||
legacyCode: 'upstream_bad_request',
|
||||
@@ -731,7 +731,7 @@ export class GeminiVideoProvider extends VideoProvider {
|
||||
}
|
||||
const bytes =
|
||||
video.mime_type === 'video/mp4' && typeof video.data === 'string'
|
||||
? decodeStrictBase64(video.data)
|
||||
? await decodeStrictBase64InSlices(video.data)
|
||||
: null;
|
||||
if (!bytes || sniffVideoMime(bytes) !== 'video/mp4') {
|
||||
throw geminiUpstreamFailure(
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
*/
|
||||
|
||||
import { HttpError } from '../../core/http/HttpError.js';
|
||||
import { parseJsonInSlices } from '../../util/slicedJson.js';
|
||||
import { readBoundedBody } from './fileInput.js';
|
||||
import { upstreamFetch } from './upstreamErrors.js';
|
||||
|
||||
@@ -39,8 +40,8 @@ export const geminiUpstreamFailure = (message: string): HttpError =>
|
||||
/**
|
||||
* POSTs `body` to a Gemini REST `path` and parses the JSON object it answers
|
||||
* with. `timeoutMs` covers the body read, and a reply over `maxBytes` fails as
|
||||
* an upstream error unless `tooLarge` supplies another. `T` is the documented reply shape; callers check every
|
||||
* field before use.
|
||||
* an upstream error unless `tooLarge` supplies another. `T` is the documented
|
||||
* reply shape; callers check every field before use.
|
||||
*/
|
||||
export async function postGeminiJson<T extends object>(
|
||||
apiKey: string,
|
||||
@@ -87,7 +88,8 @@ export async function postGeminiJson<T extends object>(
|
||||
const raw = await readBoundedBody(response, maxBytes, tooLarge);
|
||||
let parsed: unknown = null;
|
||||
try {
|
||||
parsed = JSON.parse(raw.toString('utf8'));
|
||||
// Media replies run to tens of megabytes of base64.
|
||||
parsed = await parseJsonInSlices(raw);
|
||||
} catch {
|
||||
// Handled with the non-object case below.
|
||||
}
|
||||
|
||||
@@ -414,7 +414,9 @@ describe('PuterServer host header validation', () => {
|
||||
'show-save-file-picker',
|
||||
'show-directory-picker',
|
||||
'upgrade',
|
||||
'top-up',
|
||||
'request-email-confirmation',
|
||||
'attach-custom-domain',
|
||||
])('lets a deployment subdomain frame the %s popup and names it to the GUI', async (action) => {
|
||||
const parent = `http://spreadsheet.puter.localhost:${port}`;
|
||||
const guiParams = (body: string) =>
|
||||
@@ -447,7 +449,7 @@ describe('PuterServer host header validation', () => {
|
||||
expect(redirected.headers['x-frame-options']).toBe('SAMEORIGIN');
|
||||
});
|
||||
|
||||
it.each(['/embed/SIGN-IN', '/embed/Show-Open-File-Picker', '/embed/sign-in/', '/embed/Upgrade', '/embed/upgrade/', '/embed/Request-Email-Confirmation'])(
|
||||
it.each(['/embed/SIGN-IN', '/embed/Show-Open-File-Picker', '/embed/sign-in/', '/embed/Upgrade', '/embed/upgrade/', '/embed/Top-Up', '/embed/top-up/', '/embed/Request-Email-Confirmation'])(
|
||||
'lets a first-party page frame only the exact spelling of %s',
|
||||
async (spelling) => {
|
||||
const res = await request(spelling, {
|
||||
@@ -792,6 +794,26 @@ describe('PuterServer request parsing', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('parses a chat call above 50 MiB whose body opens with its token', async () => {
|
||||
const fields = `"interface":"puter-chat-completion","method":"no-such-method","pad":"${'x'.repeat(51 * MiB)}"`;
|
||||
const asText = { 'content-type': 'text/plain;actually=json' };
|
||||
const first = await postJson(
|
||||
'/drivers/call',
|
||||
`{"auth_token":"${token}",${fields}}`,
|
||||
asText,
|
||||
);
|
||||
expect(first.status).toBe(404);
|
||||
expect(first.body).toContain('no-such-method');
|
||||
|
||||
// A token after other fields can't be read ahead of the body.
|
||||
const last = await postJson(
|
||||
'/drivers/call',
|
||||
`{${fields},"auth_token":"${token}"}`,
|
||||
asText,
|
||||
);
|
||||
expect(last.status).toBe(413);
|
||||
});
|
||||
|
||||
it('keeps the default JSON limit for other drivers', async () => {
|
||||
const payload = JSON.stringify({
|
||||
interface: 'puter-kvstore',
|
||||
|
||||
+30
-11
@@ -36,6 +36,7 @@ import { createAuthProbe } from './core/http/middleware/authProbe';
|
||||
import { createRequestContextMiddleware } from './core/http/middleware/requestContext';
|
||||
import { createFingerprintMiddleware } from './core/http/middleware/fingerprint';
|
||||
import { createErrorHandler } from './core/http/middleware/errorHandler';
|
||||
import { createJsonBodyParser } from './core/http/middleware/jsonBody';
|
||||
import {
|
||||
createLargeJsonBodyParser,
|
||||
DEFAULT_JSON_LIMIT_BYTES,
|
||||
@@ -144,6 +145,8 @@ const LARGE_JSON_ROUTES = [
|
||||
const LARGE_JSON_LIMIT_BYTES = 128 * 1024 * 1024;
|
||||
/** Two max-size bodies per process. */
|
||||
const LARGE_JSON_BUDGET_BYTES = 2 * LARGE_JSON_LIMIT_BYTES;
|
||||
/** These parse in one go, so they stay small enough for that to be quick. */
|
||||
const NON_UTF8_JSON_LIMIT_BYTES = 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Through `/drivers/call`, only chat takes a large body; other drivers keep the
|
||||
@@ -575,26 +578,42 @@ export class PuterServer {
|
||||
}),
|
||||
);
|
||||
}
|
||||
// A WebDAV body is the file being stored, whatever content type the
|
||||
// client labels it with, so the controller reads it off the stream.
|
||||
const exceptDav =
|
||||
(parser: RequestHandler): RequestHandler =>
|
||||
(req, res, next) => {
|
||||
if (activeSubdomain(req) === 'dav') {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
return parser(req, res, next);
|
||||
};
|
||||
this.#app.use(
|
||||
express.json({
|
||||
limit: DEFAULT_JSON_LIMIT_BYTES,
|
||||
verify: captureRawBody,
|
||||
}),
|
||||
exceptDav(
|
||||
createJsonBodyParser({
|
||||
limit: DEFAULT_JSON_LIMIT_BYTES,
|
||||
verify: captureRawBody,
|
||||
}),
|
||||
),
|
||||
);
|
||||
// JSON in another charset, which the parser above leaves alone.
|
||||
this.#app.use(
|
||||
express.json({
|
||||
limit: DEFAULT_JSON_LIMIT_BYTES,
|
||||
type: (req) =>
|
||||
req.headers['content-type'] === 'text/plain;actually=json',
|
||||
verify: captureRawBody,
|
||||
}),
|
||||
exceptDav(
|
||||
express.json({
|
||||
limit: NON_UTF8_JSON_LIMIT_BYTES,
|
||||
verify: captureRawBody,
|
||||
}),
|
||||
),
|
||||
);
|
||||
// Form-encoded bodies (e.g. `/down` from the GUI's iframe-triggered
|
||||
// download form). Needs to run before the auth probe so
|
||||
// `req.body.auth_token` is populated for urlencoded POSTs the same
|
||||
// way it is for JSON POSTs. Small cap — this parser is only here to
|
||||
// cover the auth_token / anti_csrf field shape, not file uploads.
|
||||
this.#app.use(express.urlencoded({ extended: true, limit: '100kb' }));
|
||||
this.#app.use(
|
||||
exceptDav(express.urlencoded({ extended: true, limit: '100kb' })),
|
||||
);
|
||||
|
||||
// -- Auth probe ----------------------------------------------
|
||||
if (authProbe) {
|
||||
|
||||
@@ -31,24 +31,13 @@ export const RECOMMENDED_APP_NAMES = [
|
||||
'spreadsheet',
|
||||
'presentation',
|
||||
'whiteboard',
|
||||
'notes',
|
||||
'pdf-editor',
|
||||
'contacts',
|
||||
'calendar',
|
||||
'meetings',
|
||||
'teamchat',
|
||||
'email',
|
||||
'dev-center',
|
||||
'cap-table',
|
||||
'invoices',
|
||||
'crm',
|
||||
'signatures',
|
||||
'projects',
|
||||
'point-of-sale',
|
||||
'inventory',
|
||||
'hiring',
|
||||
'time-tracking',
|
||||
'shift-planner',
|
||||
'equipment',
|
||||
'chess',
|
||||
'checkers',
|
||||
'backgammon',
|
||||
|
||||
@@ -2864,7 +2864,7 @@ export class AuthService extends PuterService {
|
||||
|
||||
#actorUserFromRow(user: UserRow) {
|
||||
// Strip the password hash; pass everything else through so callers
|
||||
// can read metadata, desktop_bg_*, otp_enabled, etc. without
|
||||
// can read metadata, otp_enabled, etc. without
|
||||
// re-fetching the user. Mirrors what /whoami exposes off of UserRow.
|
||||
const { password: _password, ...rest } = user;
|
||||
return {
|
||||
|
||||
@@ -43,7 +43,7 @@ export type TokenType = 'session' | 'gui' | 'app-under-user' | 'access-token';
|
||||
|
||||
/**
|
||||
* Browser session token. `'session'` is the HTTP-only-cookie flavor, `'gui'`
|
||||
* the same shape served in a response body (e.g. QR login).
|
||||
* the same shape served in a response body (e.g. the login response).
|
||||
*/
|
||||
export interface SessionTokenPayload extends TokenPayloadBase {
|
||||
type: 'session' | 'gui';
|
||||
@@ -109,9 +109,7 @@ export interface AccessTokenPayload extends TokenPayloadBase {
|
||||
}
|
||||
|
||||
export type AnyTokenPayload =
|
||||
| SessionTokenPayload
|
||||
| AppUnderUserTokenPayload
|
||||
| AccessTokenPayload;
|
||||
SessionTokenPayload | AppUnderUserTokenPayload | AccessTokenPayload;
|
||||
|
||||
// -- Session row (from `sessions` table) ----------------------------
|
||||
|
||||
|
||||
@@ -647,6 +647,22 @@ describe('FSService overwrite and dedupe resolution', () => {
|
||||
expect(await readBack(second)).toBe('second');
|
||||
});
|
||||
|
||||
it('leaves one readable file when two overwrites create the same path at once', async () => {
|
||||
const path = `${user.home}/Documents/raced.txt`;
|
||||
const written = await Promise.all([
|
||||
writeFile(user, path, 'short', { overwrite: true }),
|
||||
writeFile(user, path, 'a much longer body', { overwrite: true }),
|
||||
]);
|
||||
|
||||
// Both started before the row existed, so each uploaded under its own
|
||||
// key; the row has to end up describing bytes that are really there.
|
||||
expect(written[0].uuid).toBe(written[1].uuid);
|
||||
const stored = (await entryAt(user, '/Documents/raced.txt'))!;
|
||||
const body = await readBack(stored);
|
||||
expect(['short', 'a much longer body']).toContain(body);
|
||||
expect(stored.size).toBe(Buffer.byteLength(body));
|
||||
});
|
||||
|
||||
it('dedupes into an unused " (n)" name, skipping names already taken', async () => {
|
||||
await writeFile(user, `${user.home}/Documents/d.txt`, 'a');
|
||||
await writeFile(user, `${user.home}/Documents/d (1).txt`, 'a');
|
||||
|
||||
@@ -2073,10 +2073,7 @@ export class FSService extends PuterService {
|
||||
);
|
||||
});
|
||||
|
||||
const fsEntries = await this.stores.fsEntry.batchCreateEntries(
|
||||
createInputs,
|
||||
true,
|
||||
);
|
||||
const fsEntries = await this.#createUploadedEntries(createInputs);
|
||||
return preparedBatch.items.map((item, index) => {
|
||||
const fsEntry = fsEntries[index];
|
||||
if (!fsEntry) {
|
||||
@@ -3001,30 +2998,97 @@ export class FSService extends PuterService {
|
||||
legacyCode: 'conflict',
|
||||
});
|
||||
}
|
||||
await this.#moveObjectOntoKey(
|
||||
session.objectKey,
|
||||
liveKey,
|
||||
{ bucket, region, size },
|
||||
session.contentType,
|
||||
);
|
||||
}
|
||||
|
||||
async #moveObjectOntoKey(
|
||||
fromKey: string,
|
||||
toKey: string,
|
||||
at: { bucket: string; region: string; size: number },
|
||||
contentType?: string | null,
|
||||
): Promise<void> {
|
||||
await this.stores.s3Object.copyObjectOfAnySize(
|
||||
{
|
||||
sourceBucket: bucket,
|
||||
sourceKey: session.objectKey,
|
||||
destinationBucket: bucket,
|
||||
destinationKey: liveKey,
|
||||
contentType: session.contentType,
|
||||
sourceBucket: at.bucket,
|
||||
sourceKey: fromKey,
|
||||
destinationBucket: at.bucket,
|
||||
destinationKey: toKey,
|
||||
...(contentType ? { contentType } : {}),
|
||||
metadataDirective: 'REPLACE',
|
||||
},
|
||||
region,
|
||||
size,
|
||||
at.region,
|
||||
at.size,
|
||||
);
|
||||
try {
|
||||
await this.stores.s3Object.deleteObject(
|
||||
bucket,
|
||||
session.objectKey,
|
||||
region,
|
||||
at.bucket,
|
||||
fromKey,
|
||||
at.region,
|
||||
);
|
||||
} catch (e) {
|
||||
// The live object is already right; the staged one is only litter.
|
||||
console.warn('[fs] staged overwrite left behind:', e);
|
||||
// The destination is already right; the source is only litter.
|
||||
console.warn('[fs] moved object left behind:', e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the rows for objects already uploaded. A row another writer
|
||||
* created first keeps its uuid, so those bytes move onto that key.
|
||||
*/
|
||||
async #createUploadedEntries(
|
||||
inputs: FSEntryCreateInput[],
|
||||
): Promise<FSEntry[]> {
|
||||
const entries = await this.stores.fsEntry.batchCreateEntries(
|
||||
inputs,
|
||||
true,
|
||||
);
|
||||
const raced = inputs.flatMap((input, index) => {
|
||||
const liveKey = entries[index]?.uuid;
|
||||
return liveKey && liveKey !== input.uuid
|
||||
? [{ input, index, liveKey }]
|
||||
: [];
|
||||
});
|
||||
if (raced.length === 0) return entries;
|
||||
|
||||
await Promise.all(
|
||||
raced.map(({ input, liveKey }) =>
|
||||
this.#moveObjectOntoKey(
|
||||
input.uuid,
|
||||
liveKey,
|
||||
{
|
||||
bucket: this.stores.s3Object.resolveBucket(
|
||||
input.bucket,
|
||||
),
|
||||
region: this.stores.s3Object.resolveRegion(
|
||||
input.bucketRegion,
|
||||
),
|
||||
size: input.size,
|
||||
},
|
||||
input.contentType,
|
||||
),
|
||||
),
|
||||
);
|
||||
const adopted = await this.stores.fsEntry.batchCreateEntries(
|
||||
raced.map(({ input, liveKey }) => ({ ...input, uuid: liveKey })),
|
||||
true,
|
||||
);
|
||||
raced.forEach(({ index, liveKey }, i) => {
|
||||
const entry = adopted[i];
|
||||
if (entry?.uuid !== liveKey) {
|
||||
throw new HttpError(409, 'Write target changed mid-write', {
|
||||
legacyCode: 'conflict',
|
||||
});
|
||||
}
|
||||
entries[index] = entry;
|
||||
});
|
||||
return entries;
|
||||
}
|
||||
|
||||
async completeUrlWrite(
|
||||
userId: number,
|
||||
completeWriteRequest: CompleteWriteRequest,
|
||||
@@ -3581,10 +3645,10 @@ export class FSService extends PuterService {
|
||||
: uploadBody.contentHashSha256;
|
||||
|
||||
const createInput = this.#toCreateInput(normalizedInput, objectKey);
|
||||
const fsEntry = await this.stores.fsEntry.createEntry(
|
||||
createInput,
|
||||
normalizedInput.createMissingParents,
|
||||
);
|
||||
const [fsEntry] = await this.#createUploadedEntries([createInput]);
|
||||
if (!fsEntry) {
|
||||
throw new Error('Failed to create entry');
|
||||
}
|
||||
|
||||
this.#emitFsEvent(
|
||||
existingEntry ? 'fs.write.file' : 'fs.create.file',
|
||||
@@ -3682,17 +3746,18 @@ export class FSService extends PuterService {
|
||||
updates.filter(isValid),
|
||||
);
|
||||
let next = 0;
|
||||
return updates.map((update): PromiseSettledResult<FSEntry> =>
|
||||
isValid(update)
|
||||
? stored[next++]
|
||||
: {
|
||||
status: 'rejected',
|
||||
reason: new HttpError(
|
||||
400,
|
||||
'Invalid file entry identifier for thumbnail update',
|
||||
{ legacyCode: 'bad_request' },
|
||||
),
|
||||
},
|
||||
return updates.map(
|
||||
(update): PromiseSettledResult<FSEntry> =>
|
||||
isValid(update)
|
||||
? stored[next++]
|
||||
: {
|
||||
status: 'rejected',
|
||||
reason: new HttpError(
|
||||
400,
|
||||
'Invalid file entry identifier for thumbnail update',
|
||||
{ legacyCode: 'bad_request' },
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -517,8 +517,6 @@ export class PuterHomepageService extends PuterService {
|
||||
<meta name="theme-color" content="#ffffff">
|
||||
${bundled ? `<link rel="stylesheet" href="${guiCss}">` : ''}
|
||||
|
||||
<link rel="preload" as="image" href="https://puter-assets.b-cdn.net/wallpaper.webp">
|
||||
|
||||
<script>
|
||||
if ( ! window.service_script ) {
|
||||
window.service_script_api_promise = (() => {
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
*/
|
||||
|
||||
import { Writable } from 'node:stream';
|
||||
import v8 from 'node:v8';
|
||||
import type { Request, Response } from 'express';
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
@@ -229,6 +230,37 @@ describe('ProfileService', () => {
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
// V8 stops optimizing regexps once a process holds enough compiled code,
|
||||
// as long-running servers do, and an unoptimized one overflows on this.
|
||||
it('answers a picture of several megabytes with 413', () => {
|
||||
const picture = `data:image/png;base64,${'A'.repeat(6 * 1024 * 1024)}`;
|
||||
v8.setFlagsFromString('--no-regexp-optimization');
|
||||
try {
|
||||
expect(() => service.validatePatch({ picture })).toThrow(
|
||||
expect.objectContaining({
|
||||
statusCode: 413,
|
||||
code: 'profile_picture_too_large',
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
v8.setFlagsFromString('--regexp-optimization');
|
||||
}
|
||||
});
|
||||
|
||||
it('accepts a picture of the largest size, with or without padding', () => {
|
||||
const prefix = 'data:image/png;base64,';
|
||||
const full = `${prefix}${'A'.repeat(PROFILE_PICTURE_MAX_BYTES - prefix.length)}`;
|
||||
expect(service.validatePatch({ picture: full })).toEqual({
|
||||
picture: full,
|
||||
});
|
||||
expect(service.validatePatch({ picture: `${prefix}QQ` })).toEqual({
|
||||
picture: `${prefix}QQ`,
|
||||
});
|
||||
expect(() => service.validatePatch({ picture: `${full}A` })).toThrow(
|
||||
expect.objectContaining({ code: 'profile_picture_too_large' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps what validates from a legacy profile and names the rest', () => {
|
||||
expect(
|
||||
service.normalizeLegacyProfile({
|
||||
|
||||
@@ -83,6 +83,14 @@ const validateField = (field: ProfileField, value: unknown): string | null => {
|
||||
);
|
||||
}
|
||||
if (field === 'picture') {
|
||||
// Sized before the pattern runs, which fails outright on megabytes of
|
||||
// text. Only ASCII passes the pattern, so the length is the byte count.
|
||||
if (value.length > PROFILE_PICTURE_MAX_BYTES) {
|
||||
throw new HttpError(413, 'picture is too large', {
|
||||
code: 'profile_picture_too_large',
|
||||
fields: { field, maxBytes: PROFILE_PICTURE_MAX_BYTES },
|
||||
});
|
||||
}
|
||||
if (!PICTURE_DATA_URL.test(value)) {
|
||||
throw invalid(
|
||||
field,
|
||||
@@ -90,12 +98,6 @@ const validateField = (field: ProfileField, value: unknown): string | null => {
|
||||
'profile_picture_invalid',
|
||||
);
|
||||
}
|
||||
if (Buffer.byteLength(value) > PROFILE_PICTURE_MAX_BYTES) {
|
||||
throw new HttpError(413, 'picture is too large', {
|
||||
code: 'profile_picture_too_large',
|
||||
fields: { field, maxBytes: PROFILE_PICTURE_MAX_BYTES },
|
||||
});
|
||||
}
|
||||
return value;
|
||||
}
|
||||
const maxLength =
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
PuterStore,
|
||||
} from '../types';
|
||||
import { HttpError } from '../../core/http/HttpError.js';
|
||||
import { runWithConcurrencyLimit } from '../../util/concurrency.js';
|
||||
import { isUniqueViolation } from '../../util/dbError.js';
|
||||
import {
|
||||
validateUrl,
|
||||
@@ -89,6 +90,8 @@ const STATS_CACHE_TTL_SECONDS = 30 * 60;
|
||||
// `app-` + a UUID. ClickHouse's `app_opens.app_uid` is FixedString(40) and
|
||||
// fails the whole query on a longer value.
|
||||
const APP_UID_MAX_BYTES = 40;
|
||||
// ClickHouse caps the size of one query parameter, and the uid list is one.
|
||||
const CLICKHOUSE_UIDS_PER_QUERY = 1000;
|
||||
|
||||
// Period helpers for detailed/grouped stats. Ported from v1
|
||||
// AppInformationService — queries go straight to ClickHouse/MySQL on demand
|
||||
@@ -1727,20 +1730,30 @@ export class AppStore extends PuterStore {
|
||||
|
||||
const clickhouse = this.clients.clickhouse;
|
||||
if (clickhouse) {
|
||||
const res = await clickhouse.query({
|
||||
query: `
|
||||
SELECT app_uid,
|
||||
uniqExact((user_id, intDiv(ts, ${APP_OPEN_COUNT_PERIOD_SECONDS}))) AS open_count,
|
||||
count(DISTINCT user_id) AS user_count
|
||||
FROM app_opens
|
||||
WHERE app_uid IN {uids:Array(String)}
|
||||
GROUP BY app_uid
|
||||
`,
|
||||
query_params: { uids: uids.map((u) => String(u)) },
|
||||
format: 'JSONEachRow',
|
||||
});
|
||||
const rows = await res.json();
|
||||
for (const row of rows) {
|
||||
const chunks = [];
|
||||
for (let i = 0; i < uids.length; i += CLICKHOUSE_UIDS_PER_QUERY) {
|
||||
chunks.push(uids.slice(i, i + CLICKHOUSE_UIDS_PER_QUERY));
|
||||
}
|
||||
const results = await runWithConcurrencyLimit(
|
||||
chunks,
|
||||
4,
|
||||
async (chunk) => {
|
||||
const res = await clickhouse.query({
|
||||
query: `
|
||||
SELECT app_uid,
|
||||
uniqExact((user_id, intDiv(ts, ${APP_OPEN_COUNT_PERIOD_SECONDS}))) AS open_count,
|
||||
count(DISTINCT user_id) AS user_count
|
||||
FROM app_opens
|
||||
WHERE app_uid IN {uids:Array(String)}
|
||||
GROUP BY app_uid
|
||||
`,
|
||||
query_params: { uids: chunk.map((u) => String(u)) },
|
||||
format: 'JSONEachRow',
|
||||
});
|
||||
return res.json();
|
||||
},
|
||||
);
|
||||
for (const row of results.flat()) {
|
||||
out.set(row.app_uid, {
|
||||
open_count: parseInt(row.open_count, 10) || 0,
|
||||
user_count: parseInt(row.user_count, 10) || 0,
|
||||
|
||||
@@ -200,6 +200,37 @@ describe('AppStore app stats (cache-on-read)', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('splits a long uid list across ClickHouse queries', async () => {
|
||||
const uids = Array.from({ length: 2500 }, () => freshUid());
|
||||
const queried = [];
|
||||
|
||||
server.clients.clickhouse = {
|
||||
query: async ({ query_params }) => {
|
||||
queried.push(query_params.uids.length);
|
||||
return {
|
||||
json: async () =>
|
||||
query_params.uids.map((u) => ({
|
||||
app_uid: u,
|
||||
open_count: '2',
|
||||
user_count: '1',
|
||||
})),
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
try {
|
||||
const stats = await appStore.getAppsStats(uids);
|
||||
expect(queried.sort((a, b) => b - a)).toEqual([1000, 1000, 500]);
|
||||
expect(stats.size).toBe(2500);
|
||||
expect(stats.get(uids[2499])).toMatchObject({
|
||||
open_count: 2,
|
||||
user_count: 1,
|
||||
});
|
||||
} finally {
|
||||
delete server.clients.clickhouse;
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps ids longer than an app uid out of the ClickHouse query', async () => {
|
||||
const uid = freshUid();
|
||||
const longId = `iap-${'a'.repeat(36)}-extra`;
|
||||
|
||||
@@ -444,7 +444,7 @@ describe('FSEntryStore cache invalidation', () => {
|
||||
store.batchCreateEntries([
|
||||
{
|
||||
userId: user.userId,
|
||||
uuid: uuidv4(),
|
||||
uuid: file.uuid,
|
||||
path: file.path,
|
||||
size: 7,
|
||||
overwrite: true,
|
||||
@@ -1185,7 +1185,7 @@ describe('FSEntryStore entry creation', () => {
|
||||
const [updated] = await store.batchCreateEntries([
|
||||
{
|
||||
userId: user.userId,
|
||||
uuid: uuidv4(),
|
||||
uuid: original.uuid,
|
||||
path: `${user.home}/Documents/ow.txt`,
|
||||
size: 42,
|
||||
overwrite: true,
|
||||
@@ -1204,6 +1204,33 @@ describe('FSEntryStore entry creation', () => {
|
||||
expect(updated?.thumbnail).toBe('data:image/png;base64,AA');
|
||||
});
|
||||
|
||||
it('leaves the row alone when an overwrite brings a different object key', async () => {
|
||||
const user = await makeUser();
|
||||
const original = await createFile(
|
||||
user,
|
||||
`${user.home}/Documents/otherkey.txt`,
|
||||
{ size: 1 },
|
||||
);
|
||||
|
||||
// The bytes for this write sit under a key the row doesn't name, so
|
||||
// repointing bucket or size would describe an object that isn't there.
|
||||
const returned = await createFile(user, original.path, {
|
||||
size: 42,
|
||||
overwrite: true,
|
||||
bucket: 'elsewhere',
|
||||
bucketRegion: 'eu-central-1',
|
||||
});
|
||||
|
||||
expect(returned.uuid).toBe(original.uuid);
|
||||
await expect(
|
||||
store.getEntryByPath(original.path),
|
||||
).resolves.toMatchObject({
|
||||
uuid: original.uuid,
|
||||
size: 1,
|
||||
bucket: 'puter-local',
|
||||
});
|
||||
});
|
||||
|
||||
it('refuses to clobber an existing entry without overwrite, or a directory with it', async () => {
|
||||
const user = await makeUser();
|
||||
await createFile(user, `${user.home}/Documents/keep.txt`);
|
||||
@@ -1227,7 +1254,10 @@ describe('FSEntryStore entry creation', () => {
|
||||
|
||||
it('propagates the underlying failure when an overwrite update fails', async () => {
|
||||
const user = await makeUser();
|
||||
await createFile(user, `${user.home}/Documents/upfail.txt`);
|
||||
const existing = await createFile(
|
||||
user,
|
||||
`${user.home}/Documents/upfail.txt`,
|
||||
);
|
||||
|
||||
const db = server.clients.db;
|
||||
const originalWrite = (Object.getPrototypeOf(db) as typeof db).write;
|
||||
@@ -1243,6 +1273,7 @@ describe('FSEntryStore entry creation', () => {
|
||||
await expect(
|
||||
createFile(user, `${user.home}/Documents/upfail.txt`, {
|
||||
overwrite: true,
|
||||
uuid: existing.uuid,
|
||||
}),
|
||||
).rejects.toThrow('update rejected');
|
||||
|
||||
@@ -3801,7 +3832,7 @@ describe('FSEntryStore lost-insert recovery', () => {
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('updates the race winner in place when overwrite was requested', async () => {
|
||||
it('hands back the race winner untouched when overwrite was requested', async () => {
|
||||
const user = await makeUser();
|
||||
const uuid = uuidv4();
|
||||
const spy = loseInsertRace(uuid, () =>
|
||||
@@ -3827,13 +3858,14 @@ describe('FSEntryStore lost-insert recovery', () => {
|
||||
]);
|
||||
spy.mockRestore();
|
||||
|
||||
// The winner's row survived; our payload was written onto it.
|
||||
// Our object is under `uuid`, not the winner's key, so the winner's
|
||||
// row is returned as it stands for the caller to move the bytes onto.
|
||||
expect(entry?.uuid).not.toBe(uuid);
|
||||
expect(entry?.size).toBe(77);
|
||||
expect(entry?.thumbnail).toBe('thumb');
|
||||
expect(entry?.size).not.toBe(77);
|
||||
expect(entry?.thumbnail).not.toBe('thumb');
|
||||
await expect(
|
||||
store.getEntryByPath(`${user.home}/Documents/recovered.txt`),
|
||||
).resolves.toMatchObject({ size: 77, uuid: entry?.uuid });
|
||||
).resolves.toMatchObject({ size: entry?.size, uuid: entry?.uuid });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1941,6 +1941,11 @@ export class FSEntryStore extends PuterStore {
|
||||
return entry;
|
||||
}
|
||||
|
||||
/**
|
||||
* An overwrite whose `uuid` is not the existing row's leaves that row
|
||||
* untouched and returns it: the caller's object is under another key, so
|
||||
* the row can't describe it until the caller moves the bytes.
|
||||
*/
|
||||
async batchCreateEntries(
|
||||
entries: FSEntryCreateInput[],
|
||||
createPaths = true,
|
||||
@@ -2074,6 +2079,10 @@ export class FSEntryStore extends PuterStore {
|
||||
{ legacyCode: 'cannot_overwrite_a_directory' },
|
||||
);
|
||||
}
|
||||
if (existingEntry.uuid !== entry.input.uuid) {
|
||||
updatedResultsByIndex.set(entry.index, existingEntry);
|
||||
continue;
|
||||
}
|
||||
|
||||
const updatedEntry = {
|
||||
...existingEntry,
|
||||
@@ -2398,6 +2407,10 @@ export class FSEntryStore extends PuterStore {
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (existing.uuid !== entry.input.uuid) {
|
||||
updatedResultsByIndex.set(entry.index, existing);
|
||||
continue;
|
||||
}
|
||||
|
||||
const updatedEntry: FSEntry = {
|
||||
...existing,
|
||||
|
||||
@@ -18,7 +18,10 @@
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { decodeStrictBase64 } from './mediaSniff.ts';
|
||||
import {
|
||||
decodeStrictBase64,
|
||||
decodeStrictBase64InSlices,
|
||||
} from './mediaSniff.ts';
|
||||
|
||||
describe('decodeStrictBase64', () => {
|
||||
it.each([
|
||||
@@ -50,3 +53,52 @@ describe('decodeStrictBase64', () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('decodeStrictBase64InSlices', () => {
|
||||
// Several slices, with a last one that is partial and padded.
|
||||
const bytes = Buffer.alloc(5 * 1024 * 1024 + 2);
|
||||
for (let i = 0; i < bytes.length; i += 4099) bytes[i] = i % 251;
|
||||
const valid = bytes.toString('base64');
|
||||
|
||||
it('decodes a multi-MB payload to the same bytes', async () => {
|
||||
expect(valid.endsWith('==')).toBe(true);
|
||||
expect((await decodeStrictBase64InSlices(valid))?.equals(bytes)).toBe(
|
||||
true,
|
||||
);
|
||||
const short = Buffer.from('abcd').toString('base64');
|
||||
expect(await decodeStrictBase64InSlices(short)).toEqual(
|
||||
Buffer.from('abcd'),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['empty input', ''],
|
||||
['unpadded input', valid.slice(0, -2)],
|
||||
[
|
||||
'a character outside the alphabet in the first slice',
|
||||
`*${valid.slice(1)}`,
|
||||
],
|
||||
[
|
||||
'a character outside the alphabet in the last slice',
|
||||
`${valid.slice(0, -5)}*${valid.slice(-4)}`,
|
||||
],
|
||||
[
|
||||
'the URL-safe alphabet',
|
||||
`${valid.slice(0, 3_000_000)}-${valid.slice(3_000_001)}`,
|
||||
],
|
||||
[
|
||||
'a non-ASCII character',
|
||||
`${valid.slice(0, 3_000_000)}ī${valid.slice(3_000_001)}`,
|
||||
],
|
||||
[
|
||||
'padding where a slice ends',
|
||||
`${valid.slice(0, 1024 * 1024 - 1)}=${valid.slice(1024 * 1024)}`,
|
||||
],
|
||||
[
|
||||
'padding inside a slice',
|
||||
`${valid.slice(0, 2_000_002)}==${valid.slice(2_000_004)}`,
|
||||
],
|
||||
])('rejects %s', async (_label, value) => {
|
||||
expect(await decodeStrictBase64InSlices(value)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -17,6 +17,8 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { setImmediate as nextTurn } from 'node:timers/promises';
|
||||
|
||||
// Identify uploaded media by its bytes. A caller-supplied MIME type or file
|
||||
// extension is never trusted.
|
||||
|
||||
@@ -69,6 +71,33 @@ export function decodeStrictBase64(value: string): Buffer | null {
|
||||
return bytes.length === (value.length / 4) * 3 - padding ? bytes : null;
|
||||
}
|
||||
|
||||
/** Base64 characters decoded per turn; a multiple of four. */
|
||||
const BASE64_SLICE_CHARS = 1024 * 1024;
|
||||
|
||||
/**
|
||||
* `decodeStrictBase64` for payloads of many megabytes: decodes a slice per turn
|
||||
* of the event loop, so the whole string never holds it.
|
||||
*/
|
||||
export async function decodeStrictBase64InSlices(
|
||||
value: string,
|
||||
): Promise<Buffer | null> {
|
||||
if (value.length <= BASE64_SLICE_CHARS) return decodeStrictBase64(value);
|
||||
if (value.length % 4 !== 0) return null;
|
||||
const padding = value.endsWith('==') ? 2 : value.endsWith('=') ? 1 : 0;
|
||||
const bytes = Buffer.allocUnsafe((value.length / 4) * 3 - padding);
|
||||
let written = 0;
|
||||
for (let at = 0; at < value.length; at += BASE64_SLICE_CHARS) {
|
||||
const slice = decodeStrictBase64(
|
||||
value.slice(at, at + BASE64_SLICE_CHARS),
|
||||
);
|
||||
// Padding inside the string leaves a slice short, and the total with it.
|
||||
if (!slice || written + slice.length > bytes.length) return null;
|
||||
written += slice.copy(bytes, written);
|
||||
await nextTurn();
|
||||
}
|
||||
return written === bytes.length ? bytes : null;
|
||||
}
|
||||
|
||||
function looksLikeSvg(bytes: Buffer): boolean {
|
||||
let head = bytes.subarray(0, SVG_SNIFF_WINDOW).toString('utf8');
|
||||
if (head.charCodeAt(0) === 0xfeff) head = head.slice(1);
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
MAX_DEPTH,
|
||||
parseJsonInSlices,
|
||||
SLICE_BYTES,
|
||||
STRING_PIECE_BYTES,
|
||||
} from './slicedJson.js';
|
||||
|
||||
type Outcome = { value: unknown } | { error: string };
|
||||
|
||||
const native = (body: Buffer): Outcome => {
|
||||
try {
|
||||
return { value: JSON.parse(body.toString('utf8')) };
|
||||
} catch (e) {
|
||||
return { error: (e as Error).name };
|
||||
}
|
||||
};
|
||||
|
||||
const sliced = async (body: Buffer): Promise<Outcome> => {
|
||||
try {
|
||||
return { value: await parseJsonInSlices(body) };
|
||||
} catch (e) {
|
||||
return { error: (e as Error).name };
|
||||
}
|
||||
};
|
||||
|
||||
/** Key order, own `__proto__` keys and lone surrogates all show in the text. */
|
||||
const shown = (outcome: Outcome): string =>
|
||||
'error' in outcome ? outcome.error : JSON.stringify(outcome.value);
|
||||
|
||||
const expectSameAsNative = async (body: Buffer | string): Promise<void> => {
|
||||
const buffer = typeof body === 'string' ? Buffer.from(body) : body;
|
||||
expect(shown(await sliced(buffer))).toBe(shown(native(buffer)));
|
||||
};
|
||||
|
||||
/** Whitespace that pushes `text` onto the sliced path without changing it. */
|
||||
const padded = (text: string): string => `${' '.repeat(SLICE_BYTES)}${text}`;
|
||||
|
||||
// mulberry32: the cases must be the same on every run.
|
||||
const seeded = (seed: number) => () => {
|
||||
seed = (seed + 0x6d2b79f5) | 0;
|
||||
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
|
||||
const STRING_PARTS = [
|
||||
'a',
|
||||
'word ',
|
||||
'"',
|
||||
'\\',
|
||||
'\\\\"',
|
||||
'\n',
|
||||
'\u0001',
|
||||
'é',
|
||||
'日本',
|
||||
'😀',
|
||||
'\ud83d',
|
||||
'\u2028',
|
||||
'/',
|
||||
'\\u00e9',
|
||||
];
|
||||
const KEYS = ['id', 'name', '__proto__', '7', '3', 'constructor', 'a b', ''];
|
||||
// No key holds a backslash: with one in a key seen earlier, some V8 versions
|
||||
// misread a later escaped key, in `JSON.parse` itself.
|
||||
const KEY_PARTS = STRING_PARTS.filter((part) => !part.includes('\\'));
|
||||
const SCALARS = [
|
||||
'0',
|
||||
'-0',
|
||||
'1.5e300',
|
||||
'-12.25',
|
||||
'1e-7',
|
||||
'9007199254740993',
|
||||
'true',
|
||||
'false',
|
||||
'null',
|
||||
];
|
||||
const GAPS = ['', '', '', ' ', '\n\t', '\r\n '];
|
||||
|
||||
/** A random JSON document, written as text so spacing and escapes vary. */
|
||||
const randomDocument = (
|
||||
random: () => number,
|
||||
targetBytes: number,
|
||||
{ plainKeys = false } = {},
|
||||
): string => {
|
||||
const pick = <T>(items: readonly T[]): T =>
|
||||
items[Math.floor(random() * items.length)]!;
|
||||
const gap = () => pick(GAPS);
|
||||
const string = (maxParts: number, from = STRING_PARTS): string => {
|
||||
let text = '';
|
||||
const parts = Math.floor(random() * maxParts);
|
||||
for (let i = 0; i < parts; i++) text += pick(from);
|
||||
return JSON.stringify(text);
|
||||
};
|
||||
let written = 0;
|
||||
const value = (depth: number): string => {
|
||||
const roll = random();
|
||||
let text: string;
|
||||
if (depth > 0 && roll < 0.25) {
|
||||
const count = Math.floor(random() * 12);
|
||||
const items: string[] = [];
|
||||
for (let i = 0; i < count; i++) items.push(value(depth - 1));
|
||||
text = `[${gap()}${items.join(`${gap()},${gap()}`)}${gap()}]`;
|
||||
} else if (depth > 0 && roll < 0.5) {
|
||||
const count = Math.floor(random() * 12);
|
||||
const members: string[] = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
const key =
|
||||
plainKeys || random() < 0.7
|
||||
? JSON.stringify(pick(KEYS))
|
||||
: string(6, KEY_PARTS);
|
||||
members.push(`${key}${gap()}:${gap()}${value(depth - 1)}`);
|
||||
}
|
||||
text = `{${gap()}${members.join(`${gap()},${gap()}`)}${gap()}}`;
|
||||
} else if (roll < 0.75) {
|
||||
// Now and then one long enough to be read in pieces.
|
||||
text = string(random() < 0.002 ? 3 * SLICE_BYTES : 20);
|
||||
} else {
|
||||
text = pick(SCALARS);
|
||||
}
|
||||
written += text.length;
|
||||
return text;
|
||||
};
|
||||
const items: string[] = [];
|
||||
while (written < targetBytes) items.push(value(6));
|
||||
return random() < 0.5
|
||||
? `[${items.join(',')}]`
|
||||
: `{${items.map((item, i) => `"k${i % 50}":${item}`).join(',')}}`;
|
||||
};
|
||||
|
||||
describe('parseJsonInSlices', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('parses what JSON.parse parses, the same way', async () => {
|
||||
const random = seeded(1);
|
||||
for (let i = 0; i < 60; i++) {
|
||||
const size = SLICE_BYTES * (1 + Math.floor(random() * 12));
|
||||
await expectSameAsNative(randomDocument(random, size));
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it('parses the same when every clock read ends the turn', async () => {
|
||||
let now = 0;
|
||||
vi.spyOn(performance, 'now').mockImplementation(() => (now += 1000));
|
||||
const random = seeded(3);
|
||||
for (let i = 0; i < 30; i++) {
|
||||
await expectSameAsNative(randomDocument(random, 6 * SLICE_BYTES));
|
||||
}
|
||||
// Strings long enough for a turn to end inside them.
|
||||
await expectSameAsNative(
|
||||
`["${'ab\\n'.repeat(SLICE_BYTES)}",{"k":"${'\\\\'.repeat(SLICE_BYTES)}"},${'1234567890'.repeat(SLICE_BYTES / 2)}]`,
|
||||
);
|
||||
}, 60_000);
|
||||
|
||||
it('rejects what JSON.parse rejects', async () => {
|
||||
const random = seeded(2);
|
||||
const replacements = Buffer.from('[]{},:"\\ 0a\néx-.e');
|
||||
for (let i = 0; i < 40; i++) {
|
||||
// Plain keys, so no edit can leave a backslash in one.
|
||||
const valid = Buffer.from(
|
||||
randomDocument(random, 2 * SLICE_BYTES, { plainKeys: true }),
|
||||
);
|
||||
for (let edit = 0; edit < 12; edit++) {
|
||||
const body = Buffer.from(valid);
|
||||
const at = Math.floor(random() * body.length);
|
||||
const roll = random();
|
||||
if (roll < 0.4) {
|
||||
body[at] =
|
||||
replacements[
|
||||
Math.floor(random() * replacements.length)
|
||||
]!;
|
||||
await expectSameAsNative(body);
|
||||
} else if (roll < 0.7) {
|
||||
await expectSameAsNative(
|
||||
Buffer.concat([
|
||||
body.subarray(0, at),
|
||||
body.subarray(at + 1),
|
||||
]),
|
||||
);
|
||||
} else {
|
||||
await expectSameAsNative(body.subarray(0, at));
|
||||
}
|
||||
}
|
||||
}
|
||||
}, 120_000);
|
||||
|
||||
it.each([
|
||||
['an empty body', ''],
|
||||
['only whitespace', ' \n '],
|
||||
['two values', '[1] [2]'],
|
||||
['a trailing comma in an array', '[1,2,]'],
|
||||
['a trailing comma in an object', '{"a":1,}'],
|
||||
['a leading comma', '[,1]'],
|
||||
['a doubled comma', '[1,,2]'],
|
||||
['a missing colon', '{"a" 1}'],
|
||||
['a missing value', '{"a":}'],
|
||||
['a bare key', '{a:1}'],
|
||||
['a colon in an array', '[1:2]'],
|
||||
['mismatched brackets', '[1}'],
|
||||
['an extra close', '[1]]'],
|
||||
['an unterminated string', '["abc'],
|
||||
['an unterminated array', '[1,2'],
|
||||
['a byte order mark', '\ufeff[1]'],
|
||||
['a comment', '[1/* x */]'],
|
||||
['a bad literal', '[tru]'],
|
||||
['a bad number', '[01]'],
|
||||
['a bad escape', '["\\x"]'],
|
||||
['a raw control character in a string', '["a\tb"]'],
|
||||
['a wide space between values', '[1,\u00a02]'],
|
||||
])('rejects %s', async (_name, text) => {
|
||||
await expectSameAsNative(text);
|
||||
// Short input takes the native path, so check the sliced one too.
|
||||
await expectSameAsNative(padded(text));
|
||||
await expectSameAsNative(
|
||||
`[${'1,'.repeat(SLICE_BYTES)}${text},${'2,'.repeat(SLICE_BYTES)}3]`,
|
||||
);
|
||||
});
|
||||
|
||||
it('reads a string longer than one piece, wherever a piece ends', async () => {
|
||||
const units = [
|
||||
'\\u00e9',
|
||||
'\\n',
|
||||
'\\\\',
|
||||
'\\"',
|
||||
'é',
|
||||
'日',
|
||||
'😀',
|
||||
'\\ud83d\\ude00',
|
||||
];
|
||||
for (const unit of units) {
|
||||
for (let shift = 0; shift < 9; shift++) {
|
||||
const lead = 'a'.repeat(STRING_PIECE_BYTES - 12 + shift);
|
||||
const text = `{"text":"${lead}${unit.repeat(8)}${lead}","n":1}`;
|
||||
await expectSameAsNative(text);
|
||||
}
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it('reads long runs of escapes and stray UTF-8 bytes', async () => {
|
||||
const length = STRING_PIECE_BYTES + SLICE_BYTES;
|
||||
await expectSameAsNative(`["${'\\\\'.repeat(length)}"]`);
|
||||
await expectSameAsNative(`["${'\\"'.repeat(length)}"]`);
|
||||
await expectSameAsNative(`["${'\\'.repeat(2 * length + 1)}"]`);
|
||||
await expectSameAsNative(
|
||||
Buffer.concat([
|
||||
Buffer.from('["'),
|
||||
Buffer.alloc(2 * length, 0x80),
|
||||
Buffer.from([0xe2, 0x82]),
|
||||
Buffer.from('"]'),
|
||||
]),
|
||||
);
|
||||
}, 60_000);
|
||||
|
||||
it('reads a long key', async () => {
|
||||
const key = 'k'.repeat(2 * SLICE_BYTES);
|
||||
await expectSameAsNative(`{"a":1,"${key}":{"b":[2]},"${key}x":"v"}`);
|
||||
await expectSameAsNative(`{"${key}\\n":2,"z":3}`);
|
||||
});
|
||||
|
||||
it('reads long gaps of whitespace', async () => {
|
||||
const gap = ' '.repeat(2 * SLICE_BYTES);
|
||||
await expectSameAsNative(
|
||||
`${gap}{${gap}"a"${gap}:${gap}1${gap},${gap}"b":[${gap}2${gap},3${gap}]${gap}}${gap}`,
|
||||
);
|
||||
await expectSameAsNative(`[1,${gap}2${gap}]`);
|
||||
});
|
||||
|
||||
it('reads a scalar or a string at the top level', async () => {
|
||||
await expectSameAsNative(padded('12.5'));
|
||||
await expectSameAsNative(padded('null'));
|
||||
await expectSameAsNative(`"${'x'.repeat(4 * SLICE_BYTES)}"`);
|
||||
});
|
||||
|
||||
it('keeps the last of a repeated key, in its first position', async () => {
|
||||
const filler = `"f":"${'x'.repeat(SLICE_BYTES)}"`;
|
||||
await expectSameAsNative(`{"a":1,"b":2,${filler},"a":3,"7":4,"3":5}`);
|
||||
const value = (await parseJsonInSlices(
|
||||
Buffer.from(`{"a":1,"b":2,${filler},"a":3}`),
|
||||
)) as Record<string, unknown>;
|
||||
expect(Object.keys(value)).toEqual(['a', 'b', 'f']);
|
||||
expect(value.a).toBe(3);
|
||||
});
|
||||
|
||||
it('keeps __proto__ as a plain own property', async () => {
|
||||
const filler = `"f":"${'x'.repeat(SLICE_BYTES)}"`;
|
||||
const bodies = [
|
||||
// In a batch of members, as a container of its own, and alone.
|
||||
`{${filler},"__proto__":{"polluted":true},"z":1}`,
|
||||
`{"__proto__":{"polluted":true,${filler}}}`,
|
||||
`{"__proto__":"${'y'.repeat(2 * SLICE_BYTES)}"}`,
|
||||
];
|
||||
for (const body of bodies) {
|
||||
const value = (await parseJsonInSlices(
|
||||
Buffer.from(body),
|
||||
)) as Record<string, unknown>;
|
||||
expect(Object.getPrototypeOf(value)).toBe(Object.prototype);
|
||||
expect(Object.hasOwn(value, '__proto__')).toBe(true);
|
||||
expect(({} as { polluted?: boolean }).polluted).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the sign of negative zero', async () => {
|
||||
const value = (await parseJsonInSlices(
|
||||
Buffer.from(`[${'0,'.repeat(SLICE_BYTES)}-0]`),
|
||||
)) as number[];
|
||||
expect(Object.is(value.at(-1), -0)).toBe(true);
|
||||
});
|
||||
|
||||
it('reads nesting up to the depth limit and refuses more', async () => {
|
||||
const nested = (depth: number) =>
|
||||
padded(`${'['.repeat(depth)}${']'.repeat(depth)}`);
|
||||
// The root is not a level of nesting.
|
||||
let value = await parseJsonInSlices(Buffer.from(nested(MAX_DEPTH)));
|
||||
let depth = 0;
|
||||
while (Array.isArray(value)) {
|
||||
depth++;
|
||||
value = value[0];
|
||||
}
|
||||
expect(depth).toBe(MAX_DEPTH);
|
||||
|
||||
await expect(
|
||||
parseJsonInSlices(Buffer.from(nested(MAX_DEPTH + 1))),
|
||||
).rejects.toThrow(SyntaxError);
|
||||
});
|
||||
|
||||
it('reads members spread thinly across many levels', async () => {
|
||||
// No level holds a slice of members, but together they hold many.
|
||||
const members = '1,'.repeat(SLICE_BYTES / 8);
|
||||
const depth = 200;
|
||||
await expectSameAsNative(
|
||||
`${`[${members}`.repeat(depth)}0${']'.repeat(depth)}`,
|
||||
);
|
||||
await expectSameAsNative(
|
||||
`${`{"a":[${members}0],"b":`.repeat(depth)}0${'}'.repeat(depth)}`,
|
||||
);
|
||||
});
|
||||
|
||||
it('lets the event loop run while it parses', async () => {
|
||||
// Dense input: the slowest kind to parse for its size.
|
||||
const body = Buffer.from(`[${'[],'.repeat(1_000_000)}[]]`);
|
||||
let turns = 0;
|
||||
let running = true;
|
||||
const tick = () => {
|
||||
turns++;
|
||||
if (running) setImmediate(tick);
|
||||
};
|
||||
setImmediate(tick);
|
||||
const value = (await parseJsonInSlices(body)) as unknown[];
|
||||
running = false;
|
||||
expect(value).toHaveLength(1_000_001);
|
||||
expect(turns).toBeGreaterThan(5);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,581 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { setImmediate as nextTurn } from 'node:timers/promises';
|
||||
|
||||
/**
|
||||
* Text handed to one native `JSON.parse` call stays within a few multiples of
|
||||
* this, which bounds how long the call can run. Shorter input parses whole.
|
||||
*/
|
||||
export const SLICE_BYTES = 32 * 1024;
|
||||
/** Bytes of a long string decoded per turn. */
|
||||
export const STRING_PIECE_BYTES = 512 * 1024;
|
||||
/** Deeper nesting is refused. No mainstream serializer writes this deep. */
|
||||
export const MAX_DEPTH = 10_000;
|
||||
/** How long a parse runs before the event loop gets a turn. */
|
||||
const TURN_BUDGET_MS = 3;
|
||||
/** Bytes scanned between clock reads. */
|
||||
const CLOCK_INTERVAL_BYTES = 16 * 1024;
|
||||
/** Bytes of a string scanned one at a time before a native search takes over. */
|
||||
const BYTEWISE_BYTES = 64;
|
||||
/** Rounds of a string scan between clock reads. */
|
||||
const CLOCK_INTERVAL_ROUNDS = 64;
|
||||
|
||||
const QUOTE = 0x22;
|
||||
const BACKSLASH = 0x5c;
|
||||
|
||||
// Byte classes. Anything unlisted is part of a number or literal.
|
||||
const C_SCALAR = 0;
|
||||
const C_SPACE = 1;
|
||||
const C_QUOTE = 2;
|
||||
const C_OPEN_ARRAY = 3;
|
||||
const C_OPEN_OBJECT = 4;
|
||||
const C_CLOSE_ARRAY = 5;
|
||||
const C_CLOSE_OBJECT = 6;
|
||||
const C_COMMA = 7;
|
||||
const C_COLON = 8;
|
||||
const BYTE_CLASS = new Uint8Array(256);
|
||||
for (const byte of [0x20, 0x09, 0x0a, 0x0d]) BYTE_CLASS[byte] = C_SPACE;
|
||||
BYTE_CLASS[QUOTE] = C_QUOTE;
|
||||
BYTE_CLASS[0x5b] = C_OPEN_ARRAY;
|
||||
BYTE_CLASS[0x7b] = C_OPEN_OBJECT;
|
||||
BYTE_CLASS[0x5d] = C_CLOSE_ARRAY;
|
||||
BYTE_CLASS[0x7d] = C_CLOSE_OBJECT;
|
||||
BYTE_CLASS[0x2c] = C_COMMA;
|
||||
BYTE_CLASS[0x3a] = C_COLON;
|
||||
|
||||
const ROOT = 0;
|
||||
const ARRAY = 1;
|
||||
const OBJECT = 2;
|
||||
|
||||
/** Just opened: a member or the close. */
|
||||
const S_FIRST = 0;
|
||||
/** After a comma: a member. */
|
||||
const S_MEMBER = 1;
|
||||
/** After an object key. */
|
||||
const S_COLON = 2;
|
||||
/** After a colon, and the root before its value. */
|
||||
const S_VALUE = 3;
|
||||
/** After a value: a comma or the close. The root is done. */
|
||||
const S_AFTER = 4;
|
||||
|
||||
const DONE = 0;
|
||||
const TURN = 1;
|
||||
const LONG_STRING = 2;
|
||||
|
||||
/**
|
||||
* One open container, or the root. Members are scanned, not parsed: `pending`
|
||||
* marks text handed to `JSON.parse` once enough of it has built up, and a
|
||||
* container too large for one call gets its `out` filled a batch at a time.
|
||||
*/
|
||||
class Frame {
|
||||
kind = ROOT;
|
||||
state = S_VALUE;
|
||||
/** Offset of the opening bracket. */
|
||||
start = 0;
|
||||
/** The container under construction, once it is known to be large. */
|
||||
out: unknown[] | Record<string, unknown> | null = null;
|
||||
/** Where the members not yet parsed start, or -1. */
|
||||
pending = -1;
|
||||
/** Where the last complete member ended. */
|
||||
lastEnd = -1;
|
||||
/** Bounds of the member being scanned. */
|
||||
memberStart = -1;
|
||||
keyStart = -1;
|
||||
keyEnd = -1;
|
||||
valueStart = -1;
|
||||
/** The current member's key, when the member is parsed apart from `pending`. */
|
||||
ownKey: string | null = null;
|
||||
/** Bytes of the parent's `pending` waiting behind this container. */
|
||||
backlog = 0;
|
||||
|
||||
open(kind: number, start: number): void {
|
||||
this.kind = kind;
|
||||
this.state = kind === ROOT ? S_VALUE : S_FIRST;
|
||||
this.start = start;
|
||||
this.out = null;
|
||||
this.pending = -1;
|
||||
this.lastEnd = -1;
|
||||
this.memberStart = -1;
|
||||
this.keyStart = -1;
|
||||
this.keyEnd = -1;
|
||||
this.valueStart = -1;
|
||||
this.ownKey = null;
|
||||
this.backlog = 0;
|
||||
}
|
||||
}
|
||||
|
||||
const unexpected = (at: number): SyntaxError =>
|
||||
new SyntaxError(`Unexpected token in JSON at position ${at}`);
|
||||
|
||||
/** `JSON.parse` keeps `__proto__` as an own property; assignment would not. */
|
||||
const setOwn = (
|
||||
target: Record<string, unknown>,
|
||||
key: string,
|
||||
value: unknown,
|
||||
): void => {
|
||||
if (key === '__proto__') {
|
||||
Object.defineProperty(target, key, {
|
||||
value,
|
||||
writable: true,
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
});
|
||||
} else {
|
||||
target[key] = value;
|
||||
}
|
||||
};
|
||||
|
||||
class SlicedJsonParser {
|
||||
result: unknown;
|
||||
/** Bounds of the string `run` stopped at, quotes included. */
|
||||
longStart = -1;
|
||||
longEnd = -1;
|
||||
|
||||
readonly #body: Buffer;
|
||||
readonly #end: number;
|
||||
#pos = 0;
|
||||
#frames = [new Frame()];
|
||||
#depth = 0;
|
||||
/** Frames below this depth have an `out`; the root counts as one. */
|
||||
#filling = 1;
|
||||
/** Bytes of `pending` in frames below the top one. */
|
||||
#backlog = 0;
|
||||
#inScalar = false;
|
||||
/** The string being scanned, and where its scan resumes. */
|
||||
#stringStart = -1;
|
||||
#stringPos = 0;
|
||||
/** Next quote and backslash at or after the last search origin. */
|
||||
#quoteAt = -1;
|
||||
#backslashAt = -1;
|
||||
#longIsKey = false;
|
||||
|
||||
constructor(body: Buffer) {
|
||||
this.#body = body;
|
||||
this.#end = body.length;
|
||||
}
|
||||
|
||||
/** Scans until the input ends, `deadline` passes, or a long string starts. */
|
||||
run(deadline: number): number {
|
||||
const body = this.#body;
|
||||
const end = this.#end;
|
||||
let i = this.#pos;
|
||||
let frame = this.#frames[this.#depth]!;
|
||||
let clockAt = i + CLOCK_INTERVAL_BYTES;
|
||||
|
||||
for (;;) {
|
||||
if (this.#stringStart !== -1) {
|
||||
const close = this.#stringEnd(deadline);
|
||||
if (close === -1) return TURN;
|
||||
const start = this.#stringStart;
|
||||
this.#stringStart = -1;
|
||||
i = close + 1;
|
||||
if (this.#string(frame, start, close)) {
|
||||
this.#pos = i;
|
||||
return LONG_STRING;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (i >= clockAt) {
|
||||
clockAt = i + CLOCK_INTERVAL_BYTES;
|
||||
if (performance.now() >= deadline) {
|
||||
this.#pos = i;
|
||||
return TURN;
|
||||
}
|
||||
}
|
||||
if (i >= end) break;
|
||||
|
||||
const byteClass = BYTE_CLASS[body[i]!]!;
|
||||
if (byteClass === C_SCALAR) {
|
||||
if (!this.#inScalar) {
|
||||
this.#valueStart(frame, i);
|
||||
this.#inScalar = true;
|
||||
}
|
||||
const stop = Math.min(end, clockAt);
|
||||
i++;
|
||||
while (i < stop && BYTE_CLASS[body[i]!] === C_SCALAR) i++;
|
||||
continue;
|
||||
}
|
||||
if (this.#inScalar) {
|
||||
this.#inScalar = false;
|
||||
this.#valueEnd(frame, i);
|
||||
}
|
||||
|
||||
switch (byteClass) {
|
||||
case C_SPACE: {
|
||||
const stop = Math.min(end, clockAt);
|
||||
i++;
|
||||
while (i < stop && BYTE_CLASS[body[i]!] === C_SPACE) i++;
|
||||
break;
|
||||
}
|
||||
case C_QUOTE:
|
||||
this.#stringStart = i;
|
||||
this.#stringPos = i + 1;
|
||||
break;
|
||||
case C_OPEN_ARRAY:
|
||||
case C_OPEN_OBJECT: {
|
||||
this.#valueStart(frame, i);
|
||||
if (this.#depth === MAX_DEPTH) {
|
||||
throw new SyntaxError('JSON is nested too deeply');
|
||||
}
|
||||
const parent = frame;
|
||||
// Members before this one wait until it closes or grows.
|
||||
const before =
|
||||
parent.pending !== -1 &&
|
||||
parent.pending !== parent.memberStart
|
||||
? parent.lastEnd - parent.pending
|
||||
: 0;
|
||||
this.#depth++;
|
||||
frame = this.#frames[this.#depth] ??= new Frame();
|
||||
frame.open(byteClass === C_OPEN_ARRAY ? ARRAY : OBJECT, i);
|
||||
frame.backlog = before;
|
||||
this.#backlog += before;
|
||||
// Parsed now, so deep nesting can't save it all up.
|
||||
if (this.#backlog >= SLICE_BYTES) this.#fill();
|
||||
i++;
|
||||
break;
|
||||
}
|
||||
case C_CLOSE_ARRAY:
|
||||
case C_CLOSE_OBJECT: {
|
||||
if (
|
||||
frame.kind !==
|
||||
(byteClass === C_CLOSE_ARRAY ? ARRAY : OBJECT) ||
|
||||
(frame.state !== S_FIRST && frame.state !== S_AFTER)
|
||||
) {
|
||||
throw unexpected(i);
|
||||
}
|
||||
let filled = this.#depth < this.#filling;
|
||||
if (!filled && i + 1 - frame.start > SLICE_BYTES) {
|
||||
this.#fill();
|
||||
filled = true;
|
||||
}
|
||||
if (filled) {
|
||||
if (frame.pending !== -1) {
|
||||
this.#parsePending(frame);
|
||||
}
|
||||
frame.out = null;
|
||||
this.#filling = this.#depth;
|
||||
}
|
||||
this.#backlog -= frame.backlog;
|
||||
this.#depth--;
|
||||
frame = this.#frames[this.#depth]!;
|
||||
i++;
|
||||
if (filled) {
|
||||
frame.state = S_AFTER;
|
||||
frame.lastEnd = i;
|
||||
} else {
|
||||
this.#valueEnd(frame, i);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case C_COMMA:
|
||||
if (frame.kind === ROOT || frame.state !== S_AFTER) {
|
||||
throw unexpected(i);
|
||||
}
|
||||
frame.state = S_MEMBER;
|
||||
i++;
|
||||
break;
|
||||
default:
|
||||
if (frame.kind !== OBJECT || frame.state !== S_COLON) {
|
||||
throw unexpected(i);
|
||||
}
|
||||
frame.state = S_VALUE;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.#inScalar) {
|
||||
this.#inScalar = false;
|
||||
this.#valueEnd(frame, end);
|
||||
}
|
||||
if (this.#depth !== 0 || frame.state !== S_AFTER) {
|
||||
throw new SyntaxError('Unexpected end of JSON input');
|
||||
}
|
||||
if (frame.pending !== -1) this.#parsePending(frame);
|
||||
return DONE;
|
||||
}
|
||||
|
||||
/** Supplies the string `run` stopped at. */
|
||||
resolveLongString(value: string): void {
|
||||
const frame = this.#frames[this.#depth]!;
|
||||
if (this.#longIsKey) {
|
||||
frame.ownKey = value;
|
||||
return;
|
||||
}
|
||||
this.#attach(frame, frame.ownKey, value);
|
||||
frame.ownKey = null;
|
||||
frame.lastEnd = this.longEnd + 1;
|
||||
frame.state = S_AFTER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Offset of the quote closing the string being scanned, or -1 when
|
||||
* `deadline` passed first.
|
||||
*/
|
||||
#stringEnd(deadline: number): number {
|
||||
const body = this.#body;
|
||||
const end = this.#end;
|
||||
let at = this.#stringPos;
|
||||
|
||||
for (let round = 1; ; round++) {
|
||||
// Bytewise through a short string or a stretch of escapes.
|
||||
const near = Math.min(at + BYTEWISE_BYTES, end);
|
||||
while (at < near) {
|
||||
const byte = body[at]!;
|
||||
if (byte === QUOTE) return at;
|
||||
at += byte === BACKSLASH ? 2 : 1;
|
||||
}
|
||||
if (at >= end) throw new SyntaxError('Unterminated string in JSON');
|
||||
|
||||
// Then a native search across text that holds neither.
|
||||
if (this.#quoteAt < at) {
|
||||
this.#quoteAt = body.indexOf(QUOTE, at);
|
||||
if (this.#quoteAt === -1) {
|
||||
throw new SyntaxError('Unterminated string in JSON');
|
||||
}
|
||||
}
|
||||
if (this.#backslashAt < at) {
|
||||
const found = body.indexOf(BACKSLASH, at);
|
||||
this.#backslashAt = found === -1 ? end : found;
|
||||
}
|
||||
if (this.#backslashAt > this.#quoteAt) return this.#quoteAt;
|
||||
at = this.#backslashAt;
|
||||
|
||||
if (round % CLOCK_INTERVAL_ROUNDS === 0) {
|
||||
if (performance.now() >= deadline) {
|
||||
this.#stringPos = at;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Handles a scanned string; true when `run` must stop for a long one. */
|
||||
#string(frame: Frame, start: number, close: number): boolean {
|
||||
const long = close - start > SLICE_BYTES;
|
||||
if (
|
||||
frame.kind === OBJECT &&
|
||||
(frame.state === S_FIRST || frame.state === S_MEMBER)
|
||||
) {
|
||||
this.#memberStart(frame, start);
|
||||
frame.keyStart = start;
|
||||
frame.keyEnd = close;
|
||||
frame.state = S_COLON;
|
||||
if (!long) return false;
|
||||
this.#detachMember(frame);
|
||||
this.#longIsKey = true;
|
||||
} else {
|
||||
this.#valueStart(frame, start);
|
||||
if (!long) {
|
||||
this.#valueEnd(frame, close + 1);
|
||||
return false;
|
||||
}
|
||||
if (frame.ownKey === null) {
|
||||
this.#detachMember(frame);
|
||||
if (frame.kind === OBJECT) frame.ownKey = this.#key(frame);
|
||||
}
|
||||
this.#longIsKey = false;
|
||||
}
|
||||
this.longStart = start;
|
||||
this.longEnd = close;
|
||||
return true;
|
||||
}
|
||||
|
||||
#memberStart(frame: Frame, at: number): void {
|
||||
if (frame.pending !== -1 && at - frame.pending >= SLICE_BYTES) {
|
||||
this.#fill();
|
||||
this.#parsePending(frame);
|
||||
}
|
||||
frame.memberStart = at;
|
||||
if (frame.pending === -1) frame.pending = at;
|
||||
}
|
||||
|
||||
#valueStart(frame: Frame, at: number): void {
|
||||
if (frame.kind === OBJECT) {
|
||||
if (frame.state !== S_VALUE) throw unexpected(at);
|
||||
// A long gap after the key would reach `JSON.parse` with it.
|
||||
if (frame.ownKey === null && at - frame.memberStart > SLICE_BYTES) {
|
||||
this.#detachMember(frame);
|
||||
frame.ownKey = this.#key(frame);
|
||||
}
|
||||
} else {
|
||||
if (
|
||||
frame.kind === ROOT
|
||||
? frame.state !== S_VALUE
|
||||
: frame.state > S_MEMBER
|
||||
) {
|
||||
throw unexpected(at);
|
||||
}
|
||||
this.#memberStart(frame, at);
|
||||
}
|
||||
frame.valueStart = at;
|
||||
}
|
||||
|
||||
#valueEnd(frame: Frame, at: number): void {
|
||||
frame.lastEnd = at;
|
||||
frame.state = S_AFTER;
|
||||
if (frame.ownKey !== null) {
|
||||
this.#attach(
|
||||
frame,
|
||||
frame.ownKey,
|
||||
JSON.parse(this.#text(frame.valueStart, at)),
|
||||
);
|
||||
frame.ownKey = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Takes the current member out of `pending`; its value is attached alone. */
|
||||
#detachMember(frame: Frame): void {
|
||||
this.#fill();
|
||||
if (frame.pending !== -1 && frame.pending !== frame.memberStart) {
|
||||
this.#parsePending(frame);
|
||||
}
|
||||
frame.pending = -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives every open container an `out`, attached to its parent after the
|
||||
* members that precede it.
|
||||
*/
|
||||
#fill(): void {
|
||||
const frames = this.#frames;
|
||||
for (let level = this.#filling; level <= this.#depth; level++) {
|
||||
const parent = frames[level - 1]!;
|
||||
const child = frames[level]!;
|
||||
if (
|
||||
parent.pending !== -1 &&
|
||||
parent.pending !== parent.memberStart
|
||||
) {
|
||||
this.#parsePending(parent);
|
||||
}
|
||||
parent.pending = -1;
|
||||
const key =
|
||||
parent.kind === OBJECT
|
||||
? (parent.ownKey ?? this.#key(parent))
|
||||
: null;
|
||||
parent.ownKey = null;
|
||||
child.out = child.kind === ARRAY ? [] : {};
|
||||
child.backlog = 0;
|
||||
this.#attach(parent, key, child.out);
|
||||
}
|
||||
this.#filling = this.#depth + 1;
|
||||
this.#backlog = 0;
|
||||
}
|
||||
|
||||
/** Parses the complete members in `pending` into the frame's container. */
|
||||
#parsePending(frame: Frame): void {
|
||||
const text = this.#text(frame.pending, frame.lastEnd);
|
||||
frame.pending = -1;
|
||||
if (frame.kind === ROOT) {
|
||||
this.result = JSON.parse(text);
|
||||
} else if (frame.kind === ARRAY) {
|
||||
const out = frame.out as unknown[];
|
||||
const items = JSON.parse(`[${text}]`) as unknown[];
|
||||
for (let k = 0; k < items.length; k++) out.push(items[k]);
|
||||
} else {
|
||||
const out = frame.out as Record<string, unknown>;
|
||||
const members = JSON.parse(`{${text}}`) as Record<string, unknown>;
|
||||
for (const key of Object.keys(members)) {
|
||||
setOwn(out, key, members[key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#attach(frame: Frame, key: string | null, value: unknown): void {
|
||||
if (frame.kind === ROOT) this.result = value;
|
||||
else if (frame.kind === ARRAY) (frame.out as unknown[]).push(value);
|
||||
else setOwn(frame.out as Record<string, unknown>, key!, value);
|
||||
}
|
||||
|
||||
#key(frame: Frame): string {
|
||||
return JSON.parse(
|
||||
this.#text(frame.keyStart, frame.keyEnd + 1),
|
||||
) as string;
|
||||
}
|
||||
|
||||
#text(from: number, to: number): string {
|
||||
return this.#body.toString('utf8', from, to);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a string's content can be cut at or before `target` without splitting
|
||||
* an escape or a UTF-8 sequence. `from` starts a character or an escape.
|
||||
*/
|
||||
const pieceEnd = (body: Buffer, from: number, target: number): number => {
|
||||
// Far enough back that a `\uXXXX` reaching `target` starts after it.
|
||||
let at = Math.max(from, target - 8);
|
||||
// An odd run of backslashes before `at` means `at` is an escaped byte.
|
||||
let run = 0;
|
||||
while (at - run > from && body[at - run - 1] === BACKSLASH) run++;
|
||||
at -= run % 2;
|
||||
for (;;) {
|
||||
const length =
|
||||
body[at] !== BACKSLASH ? 1 : body[at + 1] === 0x75 ? 6 : 2;
|
||||
if (at + length > target) break;
|
||||
at += length;
|
||||
}
|
||||
// A sequence has at most three continuation bytes; more are stray.
|
||||
for (let back = 0; back < 3 && (body[at]! & 0xc0) === 0x80; back++) at--;
|
||||
return at;
|
||||
};
|
||||
|
||||
/** The string literal at `[start, close]`, decoded a piece per turn. */
|
||||
const readLongString = async (
|
||||
body: Buffer,
|
||||
start: number,
|
||||
close: number,
|
||||
): Promise<string> => {
|
||||
const pieces: string[] = [];
|
||||
let at = start + 1;
|
||||
while (at < close) {
|
||||
const end =
|
||||
close - at <= STRING_PIECE_BYTES
|
||||
? close
|
||||
: pieceEnd(body, at, at + STRING_PIECE_BYTES);
|
||||
pieces.push(
|
||||
JSON.parse(`"${body.toString('utf8', at, end)}"`) as string,
|
||||
);
|
||||
at = end;
|
||||
await nextTurn();
|
||||
}
|
||||
return pieces.join('');
|
||||
};
|
||||
|
||||
/**
|
||||
* `JSON.parse` of UTF-8 `body`, done in slices with the event loop running
|
||||
* between them, so no input holds it for long. Throws a `SyntaxError` for
|
||||
* malformed JSON, and for nesting deeper than `MAX_DEPTH`.
|
||||
*/
|
||||
export async function parseJsonInSlices(body: Buffer): Promise<unknown> {
|
||||
if (body.length <= SLICE_BYTES) return JSON.parse(body.toString('utf8'));
|
||||
|
||||
const parser = new SlicedJsonParser(body);
|
||||
for (;;) {
|
||||
const signal = parser.run(performance.now() + TURN_BUDGET_MS);
|
||||
if (signal === DONE) return parser.result;
|
||||
if (signal === LONG_STRING) {
|
||||
parser.resolveLongString(
|
||||
await readLongString(body, parser.longStart, parser.longEnd),
|
||||
);
|
||||
} else {
|
||||
await nextTurn();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -170,9 +170,6 @@ export async function buildUserDetails(
|
||||
cardFallbackDepsFrom(clients),
|
||||
)
|
||||
: false,
|
||||
desktop_bg_url: user.desktop_bg_url,
|
||||
desktop_bg_color: user.desktop_bg_color,
|
||||
desktop_bg_fit: user.desktop_bg_fit,
|
||||
is_temp: user.password === null && user.email === null,
|
||||
is_user_token: true,
|
||||
// Null until the account asks for a code; never minted here.
|
||||
|
||||
@@ -385,6 +385,10 @@ The `usageDetails.serviceSpeed` field reports the served speed. Billing uses the
|
||||
|
||||
### OpenAI models
|
||||
|
||||
Passing `service_tier: "priority"` selects fast service, and `service_tier: "ultrafast"` selects ultrafast service. These requests use the same prices and supported-speed selection as `serviceSpeed`. An explicit `serviceSpeed` takes precedence.
|
||||
|
||||
Input and reasoning tokens reported by a non-streaming Responses API call are billed even when its output is empty. These charges apply whether the request fails or retries another provider.
|
||||
|
||||
Fast service is available on models with a published Fast rate card. Ultrafast is available for GPT-6.1 Sol and GPT-6 Astra. Other models fall back to fast or standard. Cache and long-context rates apply to the served tier.
|
||||
|
||||
#### `temperature`
|
||||
@@ -588,6 +592,8 @@ MiniMax M3 uses Priority admission for fast service. Earlier models with an equi
|
||||
|
||||
Fast service requests Priority when the account and model are eligible. The provider can serve the request at standard speed.
|
||||
|
||||
Passing `service_tier: "auto"` selects fast service, with the same prices as `serviceSpeed: "fast"`. An explicit `serviceSpeed` takes precedence.
|
||||
|
||||
### Alibaba Cloud models
|
||||
|
||||
Models with an equivalent Prime or Fast variant select that variant for fast service. Other models use standard service.
|
||||
|
||||
@@ -32,7 +32,7 @@ Fine-tune the conversion:
|
||||
| Option | Type | Description |
|
||||
|--------|------|-------------|
|
||||
| `voice` | `String` | Target ElevenLabs voice ID. Defaults to `21m00Tcm4TlvDq8ikWAM`. |
|
||||
| `model` | `String` | Voice-changer model. Defaults to `eleven_multilingual_sts_v2`. You can also use `eleven_english_sts_v2` for English-only inputs. |
|
||||
| `model` | `String` | Voice-changer model, either `eleven_multilingual_sts_v2` or `eleven_english_sts_v2` (English-only inputs). Defaults to `eleven_multilingual_sts_v2`. Any other value fails with a `field_invalid` error. |
|
||||
| `output_format` | `String` | Desired output codec and bitrate, e.g. `mp3_44100_128`, `opus_48000_64`, or `pcm_48000`. Defaults to `mp3_44100_128`. |
|
||||
| `voice_settings` | `Object \| String` | ElevenLabs voice settings payload (e.g. `{"stability":0.5,"similarity_boost":0.75}`). |
|
||||
| `remove_background_noise` | `Boolean` | Apply background noise removal. |
|
||||
|
||||
@@ -12,7 +12,7 @@ When the user adds a new domain, the dialog shows the DNS records to set at thei
|
||||
|
||||
Your app doesn't need any permission to call this method. The user makes the choice in the dialog, and your app only receives the domain they chose. Custom domains are billed to the user's Puter account, and the dialog shows the price before the user adds one.
|
||||
|
||||
Inside Puter, the dialog is rendered by the desktop environment. On a website, a puter.com popup hosts the dialog and signs the user in first if needed.
|
||||
Inside Puter, the dialog is rendered by the desktop environment. On a website, a puter.com popup hosts the dialog and signs the user in first if needed. Puter's own apps on puter.com subdomains show it in a frame over the page instead, when the user is signed in to both.
|
||||
|
||||
## Syntax
|
||||
|
||||
|
||||
@@ -13,6 +13,20 @@ puter.ui.showColorPicker(defaultColor)
|
||||
puter.ui.showColorPicker(options)
|
||||
```
|
||||
|
||||
## Parameters
|
||||
#### `defaultColor` (String)
|
||||
The color to select when the color picker is opened, as a hex string such as `#3b82f6` or `#38f`.
|
||||
|
||||
#### `options` (Object)
|
||||
An object with the following properties:
|
||||
|
||||
| Option | Type | Description |
|
||||
|--------|------|-------------|
|
||||
| `defaultColor` | `String` | The color to select when the color picker is opened, as a hex string. The picker has no alpha, so the alpha in an 8-digit hex such as `#3b82f680` is ignored. If the value isn't a valid hex color, the picker opens on `#3b82f6`. The `defaultValue` and `default` options are accepted as aliases. If more than one is given, `defaultValue` is used, then `defaultColor`, then `default`. |
|
||||
|
||||
## Return value
|
||||
A `Promise` that resolves to the selected color as a lowercase 6-digit hex string, such as `#ff0000`. If the user closes the picker without selecting a color, the promise resolves to `null`.
|
||||
|
||||
## Examples
|
||||
|
||||
### Change the background to the picked color
|
||||
@@ -23,7 +37,9 @@ puter.ui.showColorPicker(options)
|
||||
<script src="https://js.puter.com/v2/"></script>
|
||||
<script>
|
||||
puter.ui.showColorPicker().then((color)=>{
|
||||
document.body.style.backgroundColor = color;
|
||||
if (color) {
|
||||
document.body.style.backgroundColor = color;
|
||||
}
|
||||
})
|
||||
</script>
|
||||
</body>
|
||||
|
||||
@@ -6,8 +6,10 @@
|
||||
<script>
|
||||
document.getElementById('pick-color').addEventListener('click', () => {
|
||||
puter.ui.showColorPicker().then((color) => {
|
||||
document.body.style.backgroundColor = color;
|
||||
puter.print('Selected color: ' + color);
|
||||
if (color) {
|
||||
document.body.style.backgroundColor = color;
|
||||
puter.print('Selected color: ' + color);
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -159,7 +159,7 @@ The [`puter.ai.realtime()`](/AI/realtime/) SDK also applies these limits before
|
||||
|
||||
`/puterai/anthropic/v1/messages/count_tokens` has its own budget of 120 requests per minute per user, with no concurrency limit, and is not charged.
|
||||
|
||||
Chat requests accept JSON bodies up to 128 MiB (134,217,728 bytes), including `text/plain;actually=json` bodies. That covers `puter-chat-completion` calls through `/drivers/call`, which `puter.ai.chat()` uses, and POSTs to `/puterai/openai/v1/*`, `/puterai/anthropic/v1/messages` and `/puterai/anthropic/v1/messages/count_tokens`. A body over 50 MiB needs a `Content-Length` header and a token in the `Authorization` or `x-api-key` header (or a session cookie); an `auth_token` inside the body isn't read until the body is, so it only works up to 50 MiB. Larger bodies, and bodies over 50 MiB for other drivers, return HTTP 413. One account can have up to 128 MiB of these large bodies in flight at once; past that, requests get `429` with `Retry-After`. A server handling too many large bodies at once returns `503` with `Retry-After`. Retry either after the given number of seconds. Other routes accept JSON bodies up to 50 MiB.
|
||||
Chat requests accept JSON bodies up to 128 MiB (134,217,728 bytes), including `text/plain;actually=json` bodies. That covers `puter-chat-completion` calls through `/drivers/call`, which `puter.ai.chat()` uses, and POSTs to `/puterai/openai/v1/*`, `/puterai/anthropic/v1/messages` and `/puterai/anthropic/v1/messages/count_tokens`. A body over 50 MiB needs a `Content-Length` header and a credential that can be read before the rest of the body. That is a token in the `Authorization` or `x-api-key` header, a session cookie, or an `auth_token` that is the first field of the body, which is where Puter.js sends it. An `auth_token` after other fields isn't read until the body is, so it only works up to 50 MiB. Larger bodies, and bodies over 50 MiB for other drivers, return HTTP 413. One account can have up to 128 MiB of these large bodies in flight at once; past that, requests get `429` with `Retry-After`. A server handling too many large bodies at once returns `503` with `Retry-After`. Retry either after the given number of seconds. Other routes accept JSON bodies up to 50 MiB. A JSON body in a charset other than UTF-8 is accepted up to 1 MiB. A JSON body over 32 KiB can nest arrays and objects up to 10,000 levels deep, and deeper nesting returns HTTP 400.
|
||||
|
||||
Claude's server-executed tools are clamped so a request can't reserve an unbounded amount of credit:
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
## Credits
|
||||
|
||||
The default wallpaper is created by [Milad Fakurian](https://unsplash.com/photos/blue-orange-and-yellow-wallpaper-E8Ufcyxz514) and published on [Unsplash](https://unsplash.com/).
|
||||
|
||||
Icons by [Papirus](https://github.com/PapirusDevelopmentTeam/papirus-icon-theme) under GPL-3.0 license.
|
||||
|
||||
Icons by [Iconoir](https://iconoir.com/) under MIT license.
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
"/lib/jquery.dragster.js",
|
||||
"/lib/html-entities.js",
|
||||
"/lib/timeago.min.js",
|
||||
"/lib/iro.min.js",
|
||||
"/lib/isMobile.min.js",
|
||||
"/lib/fflate-0.8.2.min.js"
|
||||
],
|
||||
|
||||
@@ -40,7 +40,6 @@ vi.mock('./UI/UIPopover.js', stub);
|
||||
vi.mock('./UI/UIPrompt.js', stub);
|
||||
vi.mock('./UI/UIWindow.js', stub);
|
||||
vi.mock('./UI/UIWindowAppFeedback.js', stub);
|
||||
vi.mock('./UI/UIWindowColorPicker.js', stub);
|
||||
vi.mock('./UI/UIWindowEmailConfirmationRequired.js', stub);
|
||||
vi.mock('./UI/UIWindowFontPicker.js', stub);
|
||||
vi.mock('./UI/UIPermissionDialog.js', () => ({ default: permissionDialog }));
|
||||
|
||||
@@ -18,7 +18,6 @@ vi.mock('./UI/UIPopover.js', stub);
|
||||
vi.mock('./UI/UIPrompt.js', stub);
|
||||
vi.mock('./UI/UIWindow.js', stub);
|
||||
vi.mock('./UI/UIWindowAppFeedback.js', stub);
|
||||
vi.mock('./UI/UIWindowColorPicker.js', stub);
|
||||
vi.mock('./UI/UIWindowEmailConfirmationRequired.js', stub);
|
||||
vi.mock('./UI/UIWindowFontPicker.js', stub);
|
||||
vi.mock('./UI/UIPermissionDialog.js', stub);
|
||||
|
||||
+24
-17
@@ -32,7 +32,6 @@ import UIPrompt from './UI/UIPrompt.js';
|
||||
import UIWindow from './UI/UIWindow.js';
|
||||
import UIWindowAppFeedback from './UI/UIWindowAppFeedback.js';
|
||||
import UIWindowAttachCustomDomain from './UI/UIWindowAttachCustomDomain.js';
|
||||
import UIWindowColorPicker from './UI/UIWindowColorPicker.js';
|
||||
import UIWindowFontPicker from './UI/UIWindowFontPicker.js';
|
||||
import UIPermissionDialog from './UI/UIPermissionDialog.js';
|
||||
import UIEnablePushDialog from './UI/UIEnablePushDialog.js';
|
||||
@@ -1625,26 +1624,34 @@ const ipc_listener = async (event, handled) => {
|
||||
return;
|
||||
}
|
||||
|
||||
// set options
|
||||
if ( typeof event.data.options === 'string' ) {
|
||||
event.data.options = { defaultColor: event.data.options };
|
||||
}
|
||||
event.data.options = event.data.options ?? {};
|
||||
const options = typeof event.data.options === 'string'
|
||||
? { defaultColor: event.data.options }
|
||||
: (event.data.options ?? {});
|
||||
const requested_color = options.defaultValue ?? options.defaultColor ?? options.default;
|
||||
// The picker has no alpha, so an 8-digit hex loses its last two digits.
|
||||
// Anything still not a 3- or 6-digit hex is left out: older builds of
|
||||
// the picker fail to open on it.
|
||||
const default_color = typeof requested_color === 'string'
|
||||
? requested_color.trim().replace(/^(#?[0-9a-f]{6})[0-9a-f]{2}$/i, '$1')
|
||||
: '';
|
||||
|
||||
// Clear window_options for security reasons
|
||||
event.data.options.window_options = {};
|
||||
// The same picker puter.js shows outside Puter, so an app gets one
|
||||
// answer shape everywhere: a 6-digit hex string, or null on cancel.
|
||||
const picker = document.createElement('puter-color-picker');
|
||||
if ( /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.test(default_color) ) picker.setAttribute('default-color', default_color);
|
||||
const selected_color = await new Promise((resolve) => {
|
||||
picker.addEventListener('response', (e) => resolve(e.detail ?? null), { once: true });
|
||||
document.body.appendChild(picker);
|
||||
picker.open();
|
||||
});
|
||||
// Older builds leave the element behind when Escape closes it.
|
||||
picker.remove();
|
||||
|
||||
// Set app as parent window of the font picker window
|
||||
event.data.options.window_options.parent_uuid = event.data.appInstanceID;
|
||||
|
||||
// Open color picker
|
||||
let selected_color = await UIWindowColorPicker(event.data.options);
|
||||
|
||||
// Send selected color to requester window
|
||||
target_iframe.contentWindow.postMessage({
|
||||
// The app may have closed while the picker was up.
|
||||
target_iframe.contentWindow?.postMessage({
|
||||
msg: 'colorPicked',
|
||||
original_msg_id: msg_id,
|
||||
color: selected_color ? selected_color.color : undefined,
|
||||
color: selected_color,
|
||||
}, '*');
|
||||
$(target_iframe).get(0).focus({ preventScroll: true });
|
||||
}
|
||||
|
||||
@@ -41,7 +41,6 @@ vi.mock('./UI/UIPopover.js', stub);
|
||||
vi.mock('./UI/UIPrompt.js', stub);
|
||||
vi.mock('./UI/UIWindow.js', stub);
|
||||
vi.mock('./UI/UIWindowAppFeedback.js', stub);
|
||||
vi.mock('./UI/UIWindowColorPicker.js', stub);
|
||||
vi.mock('./UI/UIWindowEmailConfirmationRequired.js', () => ({ default: confirmEmail }));
|
||||
vi.mock('./UI/UIWindowFontPicker.js', stub);
|
||||
vi.mock('./UI/UIPermissionDialog.js', stub);
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
// @vitest-environment jsdom
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import jQuery from './lib/jquery-3.6.1/jquery-3.6.1.min.js';
|
||||
|
||||
globalThis.def = globalThis.def ?? ((cls) => cls);
|
||||
globalThis.use = globalThis.use ?? (() => ({}));
|
||||
globalThis.$ = globalThis.jQuery = jQuery;
|
||||
globalThis.i18n = (key) => key;
|
||||
|
||||
const { stub } = vi.hoisted(() => ({ stub: () => ({ default: () => {} }) }));
|
||||
vi.mock('./helpers/download.js', stub);
|
||||
vi.mock('./helpers/itemIcon.js', stub);
|
||||
vi.mock('./helpers/socialLink.js', stub);
|
||||
vi.mock('./helpers/updateMousePosition.js', stub);
|
||||
vi.mock('./UI/UIAlert.js', stub);
|
||||
vi.mock('./UI/UIContextMenu.js', stub);
|
||||
vi.mock('./UI/UIItem.js', stub);
|
||||
vi.mock('./UI/UIPopover.js', stub);
|
||||
vi.mock('./UI/UIPrompt.js', stub);
|
||||
vi.mock('./UI/UIWindow.js', stub);
|
||||
vi.mock('./UI/UIWindowAppFeedback.js', stub);
|
||||
vi.mock('./UI/UIWindowEmailConfirmationRequired.js', stub);
|
||||
vi.mock('./UI/UIWindowFontPicker.js', stub);
|
||||
vi.mock('./UI/UIPermissionDialog.js', stub);
|
||||
vi.mock('./UI/UIEnablePushDialog.js', stub);
|
||||
vi.mock('./UI/UIWindowSaveAccount.js', stub);
|
||||
vi.mock('./UI/Auth/UIAuthSignup.js', stub);
|
||||
vi.mock('./UI/UINotification.js', stub);
|
||||
vi.mock('./helpers/godmodeTokens.js', () => ({ renewGodmodeToken: vi.fn() }));
|
||||
vi.mock('./helpers/watchItems.js', () => ({ addItemWatcher: vi.fn() }));
|
||||
vi.mock('./helpers/verification_gates.js', () => ({
|
||||
openVerificationGateWindow: vi.fn(),
|
||||
}));
|
||||
|
||||
// Stands in for puter.js's <puter-color-picker>, which the GUI page gets from
|
||||
// the SDK: it records how it was opened, and the test answers for the user.
|
||||
const opened = [];
|
||||
class FakeColorPicker extends HTMLElement {
|
||||
open () {
|
||||
opened.push(this);
|
||||
}
|
||||
answer (color) {
|
||||
this.dispatchEvent(new CustomEvent('response', { detail: color }));
|
||||
}
|
||||
}
|
||||
customElements.define('puter-color-picker', FakeColorPicker);
|
||||
|
||||
let iframe;
|
||||
let posted;
|
||||
|
||||
beforeAll(async () => {
|
||||
window.when_puter_happens = [];
|
||||
window.appCallbackFunctions = {};
|
||||
await import('./IPC.js');
|
||||
globalThis.puter = { services: undefined, util: { rpc: { send: vi.fn() } } };
|
||||
for (const fn of window.when_puter_happens) await fn();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
opened.length = 0;
|
||||
document.body.innerHTML = '';
|
||||
const win = document.createElement('div');
|
||||
win.setAttribute('data-app_uuid', 'app-1');
|
||||
iframe = document.createElement('iframe');
|
||||
iframe.setAttribute('data-app', 'notes');
|
||||
win.append(iframe);
|
||||
document.body.append(win);
|
||||
posted = vi.spyOn(iframe.contentWindow, 'postMessage').mockImplementation(() => {});
|
||||
window.app_instance_ids = new Set(['inst-1']);
|
||||
window.iframe_for_app_instance = (id) => (id === 'inst-1' ? iframe : null);
|
||||
window.window_for_app_instance = () => win;
|
||||
window.is_auth = () => true;
|
||||
window.ipc_handlers = {};
|
||||
globalThis.services = { get: () => ({ get_by_uuid: () => ({ name: 'caller', uuid: 'inst-1' }) }) };
|
||||
});
|
||||
|
||||
const request = (options) =>
|
||||
window.dispatchEvent(
|
||||
new MessageEvent('message', {
|
||||
data: { appInstanceID: 'inst-1', env: 'app', msg: 'showColorPicker', uuid: 'cb-1', options },
|
||||
source: iframe.contentWindow,
|
||||
origin: 'https://app.example',
|
||||
}),
|
||||
);
|
||||
|
||||
const settle = () => new Promise((r) => setTimeout(r, 20));
|
||||
|
||||
const replies = () => posted.mock.calls
|
||||
.map(([data]) => data)
|
||||
.filter((data) => data.msg === 'colorPicked');
|
||||
|
||||
describe('showColorPicker', () => {
|
||||
it.each([
|
||||
['a string', '#abcdef'],
|
||||
['defaultColor', { defaultColor: '#abcdef' }],
|
||||
['the legacy default alias', { default: '#abcdef' }],
|
||||
['the legacy defaultValue alias', { defaultValue: '#abcdef' }],
|
||||
['an 8-digit hex, without its alpha', '#abcdef80'],
|
||||
])('opens the picker on the color given as %s', async (_, options) => {
|
||||
request(options);
|
||||
await settle();
|
||||
expect(opened).toHaveLength(1);
|
||||
expect(opened[0].getAttribute('default-color')).toBe('#abcdef');
|
||||
expect(opened[0].isConnected).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['no color', undefined],
|
||||
['a color that isn\'t hex', 'red'],
|
||||
['a malformed hex', '#abcd'],
|
||||
])('leaves the picker\'s own default when the app gives %s', async (_, options) => {
|
||||
request(options);
|
||||
await settle();
|
||||
expect(opened[0].hasAttribute('default-color')).toBe(false);
|
||||
});
|
||||
|
||||
it('replies with the picked color', async () => {
|
||||
request('#abcdef');
|
||||
await settle();
|
||||
opened[0].answer('#123456');
|
||||
await settle();
|
||||
expect(replies()).toEqual([{ msg: 'colorPicked', original_msg_id: 'cb-1', color: '#123456' }]);
|
||||
expect(opened[0].isConnected).toBe(false);
|
||||
});
|
||||
|
||||
it('replies null when the user cancels', async () => {
|
||||
request();
|
||||
await settle();
|
||||
opened[0].answer(null);
|
||||
await settle();
|
||||
expect(replies()).toEqual([{ msg: 'colorPicked', original_msg_id: 'cb-1', color: null }]);
|
||||
expect(opened[0].isConnected).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -69,6 +69,7 @@ beforeAll(async () => {
|
||||
[sessionToken]: { uuid: sessionUser, username: 'session-user' },
|
||||
'app-token-session-user': { uuid: sessionUser, username: 'session-user' },
|
||||
'app-token-other-user': { uuid: otherUser, username: 'other-user' },
|
||||
'app-token-subscriber': { uuid: sessionUser, username: 'session-user', subscribed: true },
|
||||
};
|
||||
// The SDK on a sibling subdomain sends credentialed cross-origin requests.
|
||||
app.use(['/whoami', '/profile', '/rao'], (req, res, next) => {
|
||||
@@ -513,6 +514,81 @@ describe('embedded app browser', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('offers Add credits to an account with a plan, and frames the top-up over the page', async () => {
|
||||
const context = await menuContext('app-token-subscriber');
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`http://spreadsheet.puter.localhost:${port}/menu-host`);
|
||||
await page.locator('puter-user-menu .avatar').click();
|
||||
const item = page.locator('puter-user-menu .add-credits');
|
||||
await item.waitFor();
|
||||
expect(await item.textContent()).toBe('Add credits');
|
||||
// Under Usage, in the same row style as the links around it.
|
||||
expect(await page.locator('puter-user-menu .usage + .add-credits').count()).toBe(1);
|
||||
expect(await item.evaluate(el => getComputedStyle(el).height))
|
||||
.toBe(await page.locator('puter-user-menu .feedback').evaluate(el => getComputedStyle(el).height));
|
||||
|
||||
await item.click();
|
||||
const frame = page.locator('dialog.puter-popup-frame iframe');
|
||||
await frame.waitFor({ state: 'attached' });
|
||||
expect(await frame.getAttribute('src')).toBe(`${origin}/embed/top-up#user=${sessionUser}`);
|
||||
expect(await frame.getAttribute('allow')).toBe('payment; otp-credentials');
|
||||
expect(await page.locator('puter-user-menu .menu').isHidden()).toBe(true);
|
||||
} finally {
|
||||
guestApps = [];
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('returns keyboard focus to the account button when Add credits is chosen', async () => {
|
||||
const context = await menuContext('app-token-subscriber');
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`http://spreadsheet.puter.localhost:${port}/menu-host`);
|
||||
await page.locator('puter-user-menu .avatar').focus();
|
||||
await page.keyboard.press('Enter');
|
||||
await page.locator('puter-user-menu .add-credits').waitFor();
|
||||
await page.locator('puter-user-menu .add-credits').focus();
|
||||
await page.keyboard.press('Enter');
|
||||
await page.locator('dialog.puter-popup-frame iframe').waitFor({ state: 'attached' });
|
||||
const focused = () => page.evaluate(() => document.activeElement.shadowRoot?.activeElement?.className ?? document.activeElement.tagName);
|
||||
expect(await focused()).toBe('avatar');
|
||||
|
||||
// The dialog hands the focus back when it closes.
|
||||
const fromFrame = (state) => page.evaluate(([guiOrigin, frameState]) => {
|
||||
const source = document.querySelector('dialog.puter-popup-frame iframe').contentWindow;
|
||||
window.dispatchEvent(new MessageEvent('message', {
|
||||
data: { msg: 'puterPopupFrame', state: frameState }, origin: guiOrigin, source,
|
||||
}));
|
||||
}, [origin, state]);
|
||||
await fromFrame('ready');
|
||||
expect(await page.locator('dialog.puter-popup-frame').evaluate(el => el.open)).toBe(true);
|
||||
await fromFrame('closed');
|
||||
await page.locator('dialog.puter-popup-frame').waitFor({ state: 'detached' });
|
||||
expect(await focused()).toBe('avatar');
|
||||
} finally {
|
||||
guestApps = [];
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('leaves Add credits out of the menu of an account without a plan', async () => {
|
||||
const context = await menuContext('app-token-session-user');
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
await page.goto(`http://spreadsheet.puter.localhost:${port}/menu-host`);
|
||||
await page.locator('puter-user-menu .avatar').click();
|
||||
await page.locator('puter-user-menu .usage').waitFor();
|
||||
expect(await page.locator('puter-user-menu .add-credits').isHidden()).toBe(true);
|
||||
} finally {
|
||||
guestApps = [];
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('closes the account menu when Tab leaves it', async () => {
|
||||
const context = await menuContext('app-token-session-user');
|
||||
try {
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
import UIWindow from '../UIWindow.js';
|
||||
import {
|
||||
openChangeEmailDialog,
|
||||
openChangeLanguageDialog,
|
||||
openChangePasswordDialog,
|
||||
openChangeUsernameDialog,
|
||||
openCreateTokenDialog,
|
||||
@@ -141,6 +142,21 @@ const TabAccount = {
|
||||
h += '</div>';
|
||||
}
|
||||
|
||||
// Language card
|
||||
const language = window.listSupportedLanguages().find((lang) => lang.code === window.locale);
|
||||
h += '<div class="dashboard-card dashboard-settings-card">';
|
||||
h += '<div class="dashboard-settings-card-content">';
|
||||
h += '<div class="dashboard-settings-card-icon">';
|
||||
h += '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M2 12h20"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>';
|
||||
h += '</div>';
|
||||
h += '<div class="dashboard-settings-card-info">';
|
||||
h += `<strong>${i18n('language')}</strong>`;
|
||||
h += `<span>${html_encode(language?.name ?? window.locale)}</span>`;
|
||||
h += '</div>';
|
||||
h += '</div>';
|
||||
h += `<button class="button change-language">${i18n('change_language')}</button>`;
|
||||
h += '</div>';
|
||||
|
||||
// API token card
|
||||
h += '<div class="dashboard-card dashboard-settings-card">';
|
||||
h += '<div class="dashboard-settings-card-content">';
|
||||
@@ -213,6 +229,9 @@ const TabAccount = {
|
||||
$el_window.find('.dashboard-section-account .change-email').on('click', function () {
|
||||
openChangeEmailDialog(dialogOptions(this));
|
||||
});
|
||||
$el_window.find('.dashboard-section-account .change-language').on('click', function () {
|
||||
openChangeLanguageDialog(dialogOptions(this));
|
||||
});
|
||||
$el_window.find('.dashboard-section-account .copy-auth-token').on('click', function () {
|
||||
openCreateTokenDialog({ ...dialogOptions(this), $sessionsParent: $el_window });
|
||||
});
|
||||
@@ -251,8 +270,6 @@ const TabAccount = {
|
||||
function showProfilePicture (picture) {
|
||||
const url = picture ?? window.icons['profile.svg'];
|
||||
$('.profile-pic').css('background-image', `url(${ html_encode(url) })`);
|
||||
$('.profile-image').css('background-image', `url(${ html_encode(url) })`);
|
||||
$('.profile-image').toggleClass('profile-image-has-picture', !! picture);
|
||||
}
|
||||
// A save started after another one owns the avatar and the hint; the
|
||||
// earlier one's answer must not put its picture (or a failure) back.
|
||||
|
||||
@@ -296,25 +296,6 @@ const TabHome = {
|
||||
h += '</div>';
|
||||
h += '</div>';
|
||||
|
||||
// Open Desktop card (spans full width, links to the desktop interface)
|
||||
h +=
|
||||
'<a href="/desktop" target="_blank" rel="noopener" class="bento-card bento-desktop allow-native-ctxmenu">';
|
||||
h +=
|
||||
'<div class="bento-card-fancy-icon bento-card-fancy-icon-desktop">';
|
||||
h +=
|
||||
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>';
|
||||
h += '</div>';
|
||||
h += '<div class="bento-card-fancy-text">';
|
||||
h += `<h2>${i18n('open_desktop')}</h2>`;
|
||||
h += '<span class="bento-card-fancy-subtitle">';
|
||||
h +=
|
||||
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>';
|
||||
h += i18n('open_desktop_hint');
|
||||
h += '</span>';
|
||||
h += '</div>';
|
||||
h += '<span class="bento-desktop-arrow">›</span>';
|
||||
h += '</a>';
|
||||
|
||||
h += '</div>';
|
||||
return h;
|
||||
},
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
|
||||
import { formatCount, formatCredits, formatDollarsFromMicrocents, usageIsCredits } from './credits.js';
|
||||
import { isOrgSeat } from './orgSeat.js';
|
||||
import { addonCreditsRemaining, meterPercent, monthlyUsageOrThrow, usageBudget } from './usageBudget.js';
|
||||
import { addonCreditsBudget, addonCreditsRemaining, meterPercent, monthlyUsageOrThrow, usageBudget } from './usageBudget.js';
|
||||
import { getMonthlyUsage, getStorageSpace } from './usageRequests.js';
|
||||
|
||||
// Whether the server reported credits — decides whether the usage surfaces
|
||||
@@ -67,7 +67,7 @@ const TabUsage = {
|
||||
</div>
|
||||
<div class="driver-usage-container" style="margin-top: 30px;">
|
||||
<div class="driver-usage-header">
|
||||
<h3 style="margin:0; font-size: 14px; flex-grow: 1; font-weight: 500;">${i18n('Resources')}</h3>
|
||||
<h3 style="margin:0; font-size: 14px; flex-grow: 1; font-weight: 500;">${i18n('monthly_credits_title')}</h3>
|
||||
<div style="font-size: 13px; margin-bottom: 3px; opacity:0.85;">
|
||||
<span class="usage-progbar-percent">--%</span>
|
||||
<span> · </span>
|
||||
@@ -77,10 +77,22 @@ const TabUsage = {
|
||||
<div class="usage-progbar-wrapper">
|
||||
<div class="usage-progbar" style="width: 0;"></div>
|
||||
</div>
|
||||
<p class="usage-addon-credits" style="display: none;">
|
||||
<span class="usage-addon-left"></span>
|
||||
<span class="usage-addon-note">· ${i18n('addon_credits_note')}</span>
|
||||
</p>
|
||||
<div class="usage-addon" style="display: none;">
|
||||
<div class="driver-usage-header">
|
||||
<h3 id="usage-addon-title" style="margin:0; font-size: 14px; flex-grow: 1; font-weight: 500;">${i18n('addon_credits')}</h3>
|
||||
<div style="font-size: 13px; margin-bottom: 3px; opacity:0.85;">
|
||||
<span class="usage-addon-percent">--%</span>
|
||||
<span> · </span>
|
||||
${i18n('used_of', { used: '<span class="usage-addon-used">--</span>', available: '<span class="usage-addon-capacity">--</span>' }, false)}
|
||||
</div>
|
||||
</div>
|
||||
<div class="usage-progbar-wrapper" role="progressbar" aria-labelledby="usage-addon-title" aria-valuemin="0" aria-valuemax="100">
|
||||
<div class="usage-addon-bar" style="width: 0;"></div>
|
||||
</div>
|
||||
<p class="usage-addon-credits">
|
||||
<span class="usage-addon-note">${i18n('addon_credits_note')}</span>
|
||||
</p>
|
||||
</div>
|
||||
<h3 style="margin:15px 0 10px 0; font-size: 14px; font-weight: 500;">${i18n('usage_details')}</h3>
|
||||
<div class="driver-usage-details-content visible">
|
||||
</div>
|
||||
@@ -330,9 +342,20 @@ async function update_usage_details ($el_window) {
|
||||
'background-color': window.usage_bar_color(budget.barPercent),
|
||||
});
|
||||
|
||||
$('.usage-addon-credits').toggle(addonLeft !== null);
|
||||
if ( addonLeft !== null ) {
|
||||
$('.usage-addon-left').html(i18n('addon_credits_available', { amount: amount(addonLeft) }));
|
||||
// Its own meter under the monthly one, for an account that has ever had any.
|
||||
const addon = addonCreditsBudget(res.allowanceInfo);
|
||||
$('.usage-addon').toggle(addon !== null);
|
||||
if ( addon !== null ) {
|
||||
$('.usage-addon-used').html(amount(addon.used));
|
||||
$('.usage-addon-capacity').html(amount(addon.capacity));
|
||||
$('.usage-addon-percent').html(`${addon.percent}%`);
|
||||
$('.usage-addon-bar').css({
|
||||
width: `${addon.barPercent}%`,
|
||||
'background-color': window.usage_bar_color(addon.barPercent),
|
||||
}).parent().attr({
|
||||
'aria-valuenow': addon.percent,
|
||||
'aria-valuetext': `${addon.percent}%`,
|
||||
});
|
||||
}
|
||||
|
||||
// Store raw data for sorting
|
||||
|
||||
@@ -25,6 +25,7 @@ import check_password_strength from '../../helpers/checkPasswordStrength.js';
|
||||
import create_access_token from '../../helpers/createAccessToken.js';
|
||||
import postUserProtected from '../../helpers/postUserProtected.js';
|
||||
import update_username_in_gui from '../../helpers/updateUsernameInGui.js';
|
||||
import changeLanguage from '../../i18n/i18nChangeLanguage.js';
|
||||
import UIWindowManageSessions from '../UIWindowManageSessions.js';
|
||||
import UIDashboardFormDialog, { copyRowHtml } from './UIDashboardFormDialog.js';
|
||||
|
||||
@@ -119,6 +120,42 @@ export function openEditProfileDialog ({ onSave, ...opts } = {}) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the language Puter is shown in, then reloads the page in it.
|
||||
*
|
||||
* @param {AccountDialogOptions} [opts]
|
||||
*/
|
||||
export function openChangeLanguageDialog (opts = {}) {
|
||||
return UIDashboardFormDialog({
|
||||
...opts,
|
||||
title: t('change_language'),
|
||||
submitLabel: t('save'),
|
||||
fields: [
|
||||
{
|
||||
name: 'language',
|
||||
type: 'select',
|
||||
label: i18n('language'),
|
||||
value: window.locale,
|
||||
options: window.listSupportedLanguages().map((lang) => ({
|
||||
value: lang.code,
|
||||
label: html_encode(lang.name),
|
||||
})),
|
||||
},
|
||||
],
|
||||
async onSubmit (dialog) {
|
||||
const { language } = dialog.values();
|
||||
if ( language === window.locale ) {
|
||||
dialog.close();
|
||||
return;
|
||||
}
|
||||
// On success the page reloads, so the dialog stays in progress.
|
||||
if ( ! await changeLanguage(language) ) {
|
||||
dialog.setStatus(t('language_save_failed'), { field: 'language' });
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the signed-in user's username.
|
||||
*
|
||||
|
||||
@@ -293,6 +293,57 @@ describe('create API token', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('change language', () => {
|
||||
beforeEach(() => {
|
||||
window.locale = 'en';
|
||||
window.listSupportedLanguages = () => [
|
||||
{ code: 'en', name: 'English' },
|
||||
{ code: 'de', name: 'Deutsch' },
|
||||
{ code: 'ja', name: '日本語' },
|
||||
];
|
||||
window.mutate_user_preferences = vi.fn();
|
||||
globalThis.puter.kv = { set: vi.fn(async () => true) };
|
||||
});
|
||||
|
||||
it('lists every language by its own name, with the current one selected', () => {
|
||||
dialogs.openChangeLanguageDialog();
|
||||
const options = field('language').find('option').map((_, el) => [[el.value, el.textContent]]).get();
|
||||
expect(options).toEqual([['en', 'English'], ['de', 'Deutsch'], ['ja', '日本語']]);
|
||||
expect(field('language').val()).toBe('en');
|
||||
});
|
||||
|
||||
it('closes without saving when the language is unchanged', async () => {
|
||||
dialogs.openChangeLanguageDialog();
|
||||
|
||||
await submitWith({ language: 'en' });
|
||||
|
||||
expect(puter.kv.set).not.toHaveBeenCalled();
|
||||
expect(isOpen()).toBe(false);
|
||||
});
|
||||
|
||||
it('saves the picked language to the account', async () => {
|
||||
dialogs.openChangeLanguageDialog();
|
||||
|
||||
await submitWith({ language: 'de' });
|
||||
|
||||
expect(puter.kv.set).toHaveBeenCalledWith('user_preferences.language', 'de');
|
||||
expect(window.mutate_user_preferences).toHaveBeenCalledWith({ language: 'de' });
|
||||
expect(status()).toBe('');
|
||||
});
|
||||
|
||||
it('stays open with an error when the save fails', async () => {
|
||||
puter.kv.set.mockRejectedValue(new Error('offline'));
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
dialogs.openChangeLanguageDialog();
|
||||
|
||||
await submitWith({ language: 'de' });
|
||||
|
||||
expect(window.mutate_user_preferences).not.toHaveBeenCalled();
|
||||
expect(status()).toBe('language_save_failed');
|
||||
expect(isOpen()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete account', () => {
|
||||
it('asks a temporary account to type confirm', async () => {
|
||||
// What the server sends for a temporary account: no password, so `oidc_only` too.
|
||||
|
||||
@@ -109,10 +109,9 @@ const count_label = (count) => (count === 1
|
||||
: i18n('items_count_other', { count }));
|
||||
|
||||
/**
|
||||
* A responsive, from-scratch sharing modal for the Dashboard's Files tab.
|
||||
* Unlike UIWindowShare (which spawns a desktop UIWindow), this renders a
|
||||
* self-contained overlay that behaves as a centered card on desktop and a
|
||||
* bottom sheet on mobile, styled with the dashboard's design tokens.
|
||||
* A responsive sharing modal for the Dashboard's Files tab: a self-contained
|
||||
* overlay that behaves as a centered card on desktop and a bottom sheet on
|
||||
* mobile, styled with the dashboard's design tokens.
|
||||
*
|
||||
* Shares one item or a whole selection. With several items the access list is
|
||||
* one row per person folded across them ({@link aggregateShares}), so every
|
||||
@@ -120,10 +119,9 @@ const count_label = (count) => (count === 1
|
||||
* rather than a chore repeated per file. A person who holds only some of the
|
||||
* selection says so, and can be extended to the rest in one click.
|
||||
*
|
||||
* Feature-equivalent to UIWindowShare: grant access by email or username,
|
||||
* list who has access (owner, direct grants, grants inherited from an
|
||||
* ancestor folder), change a grant's mode, and revoke — with the revoke
|
||||
* confirmation inlined into the row instead of a stacked alert window.
|
||||
* Grants access by email or username, lists who has access (owner, direct
|
||||
* grants, grants inherited from an ancestor folder), changes a grant's mode,
|
||||
* and revokes, with the revoke confirmation inlined into the row.
|
||||
*
|
||||
* @param {Object} opts
|
||||
* @param {Array<Object>} [opts.items] - The items to share, each
|
||||
|
||||
@@ -221,7 +221,7 @@ describe('aggregateShares', () => {
|
||||
|
||||
it('falls back to the handle, then the uid, for an unnamed team', () => {
|
||||
// Whatever team_label says, so a team reads the same here as it does
|
||||
// in the desktop dialog's access list.
|
||||
// in the recipient suggestions.
|
||||
const named = (team) => aggregateShares(['/me/a'], new Map([
|
||||
['/me/a', [grant(null, 'read', { holderTeam: team })]],
|
||||
]))[0].name;
|
||||
|
||||
@@ -30,8 +30,8 @@ export const meterPercent = (share) => (share < 100 ? Math.min(99, Math.round(sh
|
||||
|
||||
/**
|
||||
* @typedef {Object} UsageBudget
|
||||
* @property {number} used - Allowance-charged spend, in the server's units.
|
||||
* @property {number} capacity - The monthly plan allowance.
|
||||
* @property {number} used - Spend charged to it, in the server's units.
|
||||
* @property {number} capacity - What the meter is out of: the monthly plan allowance, or the add-on credit bought.
|
||||
* @property {number} percent - `used` as a whole-number share of `capacity`.
|
||||
* @property {number} barPercent - The share clamped to 0-100, for a bar width.
|
||||
*/
|
||||
@@ -83,6 +83,28 @@ export const addonCreditsRemaining = (allowanceInfo) => {
|
||||
return Math.max(0, purchased - nonNegative(addons.consumedPurchaseCredits));
|
||||
};
|
||||
|
||||
/**
|
||||
* The add-on credit meter: what has been spent of all the add-on credit the
|
||||
* account ever bought. Null when it has never had any, as there is no pool
|
||||
* to meter.
|
||||
*
|
||||
* @param {Object | null | undefined} allowanceInfo
|
||||
* @returns {UsageBudget | null}
|
||||
*/
|
||||
export const addonCreditsBudget = (allowanceInfo) => {
|
||||
const left = addonCreditsRemaining(allowanceInfo);
|
||||
if ( left === null ) return null;
|
||||
const capacity = nonNegative(allowanceInfo.addons.purchasedCredits);
|
||||
const used = capacity - left;
|
||||
const share = (used / capacity) * 100;
|
||||
return {
|
||||
used,
|
||||
capacity,
|
||||
percent: meterPercent(share),
|
||||
barPercent: Math.max(0, Math.min(100, share)),
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* `getMonthlyUsage()` resolves with whatever body the server answered, an
|
||||
* error included. Throws unless that body is a usage report, so a failed
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { addonCreditsRemaining, meterPercent, monthlyUsageOrThrow, usageBudget } from './usageBudget.js';
|
||||
import { addonCreditsBudget, addonCreditsRemaining, meterPercent, monthlyUsageOrThrow, usageBudget } from './usageBudget.js';
|
||||
|
||||
const info = (allowance, addons = {}) => ({
|
||||
monthUsageAllowance: allowance,
|
||||
@@ -148,6 +148,41 @@ describe('addonCreditsRemaining', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('addonCreditsBudget', () => {
|
||||
it('has no meter for an account that never had add-on credit', () => {
|
||||
expect(addonCreditsBudget(info(900_000_000))).toBeNull();
|
||||
expect(addonCreditsBudget(info(900_000_000, { purchasedCredits: 0 }))).toBeNull();
|
||||
expect(addonCreditsBudget(undefined)).toBeNull();
|
||||
});
|
||||
|
||||
it('meters what was spent of the credit bought', () => {
|
||||
expect(addonCreditsBudget(info(900_000_000, {
|
||||
purchasedCredits: 2_500,
|
||||
consumedPurchaseCredits: 850,
|
||||
}))).toEqual({ used: 850, capacity: 2_500, percent: 34, barPercent: 34 });
|
||||
});
|
||||
|
||||
it('starts empty when nothing has been spent, or the spend is unreadable', () => {
|
||||
expect(addonCreditsBudget(info(0, { purchasedCredits: 1_000 })))
|
||||
.toEqual({ used: 0, capacity: 1_000, percent: 0, barPercent: 0 });
|
||||
expect(addonCreditsBudget(info(0, { purchasedCredits: 1_000, consumedPurchaseCredits: NaN })).used).toBe(0);
|
||||
});
|
||||
|
||||
it('reads full, never past it, once the pool is spent', () => {
|
||||
expect(addonCreditsBudget(info(0, {
|
||||
purchasedCredits: 1_000,
|
||||
consumedPurchaseCredits: 1_200,
|
||||
}))).toEqual({ used: 1_000, capacity: 1_000, percent: 100, barPercent: 100 });
|
||||
});
|
||||
|
||||
it('holds at 99% while any credit is left', () => {
|
||||
expect(addonCreditsBudget(info(0, {
|
||||
purchasedCredits: 100_000,
|
||||
consumedPurchaseCredits: 99_999,
|
||||
})).percent).toBe(99);
|
||||
});
|
||||
});
|
||||
|
||||
describe('monthlyUsageOrThrow', () => {
|
||||
it('passes a usage report through', () => {
|
||||
const res = { usage: { total: 0 }, allowanceInfo: null };
|
||||
|
||||
@@ -1,243 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a reusable color picker widget using iro.ColorPicker
|
||||
* @param {HTMLElement|jQuery} container - Container element for the color picker
|
||||
* @param {Object} options - Configuration options
|
||||
* @param {string} options.default - Default color in hex format (e.g., "#f00" or "#ff0000ff")
|
||||
* @param {Object} options.layout - Custom layout configuration for iro.ColorPicker
|
||||
* @param {Function} options.onColorChange - Callback function called when color changes
|
||||
* @returns {Object} Color picker instance with methods to interact with it
|
||||
*/
|
||||
export function UIColorPickerWidget (container, options = {}) {
|
||||
// Get the DOM element if it's a jQuery object
|
||||
const domElement = container instanceof HTMLElement
|
||||
? container
|
||||
: $(container).get(0);
|
||||
|
||||
if ( ! domElement ) {
|
||||
throw new Error('Container element is required');
|
||||
}
|
||||
|
||||
// Default layout configuration
|
||||
const defaultLayout = [
|
||||
{
|
||||
component: iro.ui.Box,
|
||||
options: {
|
||||
layoutDirection: 'horizontal',
|
||||
width: 265,
|
||||
height: 265,
|
||||
},
|
||||
},
|
||||
{
|
||||
component: iro.ui.Slider,
|
||||
options: {
|
||||
sliderType: 'alpha',
|
||||
layoutDirection: 'horizontal',
|
||||
height: 265,
|
||||
width: 265,
|
||||
},
|
||||
},
|
||||
{
|
||||
component: iro.ui.Slider,
|
||||
options: {
|
||||
sliderType: 'hue',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
// Initialize the color picker
|
||||
const colorPicker = new iro.ColorPicker(domElement, {
|
||||
layout: options.layout ?? defaultLayout,
|
||||
color: options.default ?? '#f00',
|
||||
});
|
||||
|
||||
// Set up color change callback if provided
|
||||
if ( options.onColorChange ) {
|
||||
colorPicker.on('color:change', (color) => {
|
||||
options.onColorChange(color);
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
/**
|
||||
* Get the current color
|
||||
* @returns {Object} iro.Color object
|
||||
*/
|
||||
getColor: () => colorPicker.color,
|
||||
|
||||
/**
|
||||
* Get the current color as hex8 string (includes alpha)
|
||||
* @returns {string} Color in hex8 format (e.g., "#ff0000ff")
|
||||
*/
|
||||
getHex8String: () => colorPicker.color.hex8String,
|
||||
|
||||
/**
|
||||
* Get the current color as hex string (no alpha)
|
||||
* @returns {string} Color in hex format (e.g., "#ff0000")
|
||||
*/
|
||||
getHexString: () => colorPicker.color.hexString,
|
||||
|
||||
/**
|
||||
* Get the current color as HSLA object
|
||||
* @returns {Object} Object with h, s, l, a properties
|
||||
*/
|
||||
getHSLA: () => {
|
||||
const color = colorPicker.color;
|
||||
return color.hsla;
|
||||
},
|
||||
|
||||
/**
|
||||
* Set the color
|
||||
* @param {string|Object} color - Color in hex format (e.g., "#f00" or "#ff0000ff") or HSLA object
|
||||
*/
|
||||
setColor: (color) => {
|
||||
if ( typeof color === 'string' ) {
|
||||
// Remove # if present for matching
|
||||
const hexValue = color.startsWith('#') ? color.substring(1) : color;
|
||||
|
||||
// Check if it's a hex8 string (8 hex digits)
|
||||
if ( /^[0-9a-fA-F]{8}$/.test(hexValue) ) {
|
||||
// It's a hex8 string, set both hex and alpha
|
||||
const hex6 = `#${ hexValue.substring(0, 6)}`; // Get first 6 hex digits
|
||||
const alphaHex = hexValue.substring(6, 8); // Get last 2 hex digits (alpha)
|
||||
colorPicker.color.hexString = hex6;
|
||||
colorPicker.color.alpha = parseInt(alphaHex, 16) / 255;
|
||||
} else {
|
||||
// Regular hex string (with or without #)
|
||||
colorPicker.color.hexString = color.startsWith('#') ? color : `#${ color}`;
|
||||
}
|
||||
} else if ( typeof color === 'object' && color.h !== undefined ) {
|
||||
// HSLA object - set properties directly
|
||||
colorPicker.color.hue = color.h;
|
||||
colorPicker.color.saturation = color.s;
|
||||
colorPicker.color.lightness = color.l;
|
||||
colorPicker.color.alpha = color.a !== undefined ? color.a : 1;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Add an event listener
|
||||
* @param {string} event - Event name (e.g., 'color:change')
|
||||
* @param {Function} callback - Callback function
|
||||
*/
|
||||
on: (event, callback) => {
|
||||
colorPicker.on(event, callback);
|
||||
},
|
||||
|
||||
/**
|
||||
* Remove an event listener
|
||||
* @param {string} event - Event name
|
||||
* @param {Function} callback - Callback function
|
||||
*/
|
||||
off: (event, callback) => {
|
||||
colorPicker.off(event, callback);
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the underlying iro.ColorPicker instance
|
||||
* @returns {iro.ColorPicker} The iro.ColorPicker instance
|
||||
*/
|
||||
getPicker: () => colorPicker,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts HSLA values to hex8 string
|
||||
* @param {number} h - Hue (0-360)
|
||||
* @param {number} s - Saturation (0-100)
|
||||
* @param {number} l - Lightness (0-100)
|
||||
* @param {number} a - Alpha (0-1)
|
||||
* @returns {string} Color in hex8 format
|
||||
*/
|
||||
export function hslaToHex8 (h, s, l, a) {
|
||||
// Convert HSL to RGB
|
||||
s /= 100;
|
||||
l /= 100;
|
||||
const c = (1 - Math.abs(2 * l - 1)) * s;
|
||||
const x = c * (1 - Math.abs((h / 60) % 2 - 1));
|
||||
const m = l - c / 2;
|
||||
let r = 0, g = 0, b = 0;
|
||||
|
||||
if ( h >= 0 && h < 60 ) {
|
||||
r = c; g = x; b = 0;
|
||||
} else if ( h >= 60 && h < 120 ) {
|
||||
r = x; g = c; b = 0;
|
||||
} else if ( h >= 120 && h < 180 ) {
|
||||
r = 0; g = c; b = x;
|
||||
} else if ( h >= 180 && h < 240 ) {
|
||||
r = 0; g = x; b = c;
|
||||
} else if ( h >= 240 && h < 300 ) {
|
||||
r = x; g = 0; b = c;
|
||||
} else if ( h >= 300 && h < 360 ) {
|
||||
r = c; g = 0; b = x;
|
||||
}
|
||||
|
||||
r = Math.round((r + m) * 255);
|
||||
g = Math.round((g + m) * 255);
|
||||
b = Math.round((b + m) * 255);
|
||||
const alpha = Math.round(a * 255);
|
||||
|
||||
return `#${[r, g, b, alpha].map(x => {
|
||||
const hex = x.toString(16);
|
||||
return hex.length === 1 ? `0${ hex}` : hex;
|
||||
}).join('')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts hex8 string to HSLA object
|
||||
* @param {string} hex8 - Color in hex8 format (e.g., "#ff0000ff")
|
||||
* @returns {Object} Object with h, s, l, a properties
|
||||
*/
|
||||
export function hex8ToHSLA (hex8) {
|
||||
// Remove # if present
|
||||
hex8 = hex8.replace('#', '');
|
||||
|
||||
// Parse hex values
|
||||
const r = parseInt(hex8.substring(0, 2), 16) / 255;
|
||||
const g = parseInt(hex8.substring(2, 4), 16) / 255;
|
||||
const b = parseInt(hex8.substring(4, 6), 16) / 255;
|
||||
const a = parseInt(hex8.substring(6, 8), 16) / 255;
|
||||
|
||||
// Convert RGB to HSL
|
||||
const max = Math.max(r, g, b);
|
||||
const min = Math.min(r, g, b);
|
||||
let h, s, l = (max + min) / 2;
|
||||
|
||||
if ( max === min ) {
|
||||
h = s = 0; // achromatic
|
||||
} else {
|
||||
const d = max - min;
|
||||
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
||||
|
||||
switch ( max ) {
|
||||
case r: h = ((g - b) / d + (g < b ? 6 : 0)) / 6; break;
|
||||
case g: h = ((b - r) / d + 2) / 6; break;
|
||||
case b: h = ((r - g) / d + 4) / 6; break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
h: Math.round(h * 360),
|
||||
s: Math.round(s * 100),
|
||||
l: Math.round(l * 100),
|
||||
a: a,
|
||||
};
|
||||
}
|
||||
@@ -24,22 +24,15 @@ import UIItem from './UIItem.js';
|
||||
import UIAlert from './UIAlert.js';
|
||||
import UIWindow from './UIWindow.js';
|
||||
import UIWindowSaveAccount from './UIWindowSaveAccount.js';
|
||||
import UIWindowDesktopBGSettings from './UIWindowDesktopBGSettings.js';
|
||||
import UIWindowMyWebsites from './UIWindowMyWebsites.js';
|
||||
import UIWindowFeedback from './UIWindowFeedback.js';
|
||||
import UIAuthLogin from './Auth/UIAuthLogin.js';
|
||||
import UIWindowQR from './UIWindowQR.js';
|
||||
|
||||
import UIWindowProgress from './UIWindowProgress.js';
|
||||
import UITaskbar from './UITaskbar.js';
|
||||
import new_context_menu_item from '../helpers/newContextMenuItem.js';
|
||||
import refresh_item_container from '../helpers/refreshItemContainer.js';
|
||||
import { atPath, retargetNavHistory, retargetPaths, underPath } from '../helpers/pathElements.js';
|
||||
import changeLanguage from '../i18n/i18nChangeLanguage.js';
|
||||
import UIWindowTaskManager from './UIWindowTaskManager.js';
|
||||
import truncate_filename from '../helpers/truncateFilename.js';
|
||||
import UINotification from './UINotification.js';
|
||||
import UIWindowWelcome from './UIWindowWelcome.js';
|
||||
import launch_app from '../helpers/launchApp.js';
|
||||
import { urlFileLaunchOptions } from '../helpers/confirmUrlFileAccess.js';
|
||||
import item_icon from '../helpers/itemIcon.js';
|
||||
@@ -68,7 +61,6 @@ import { get_app_by_uid } from '../helpers/getAppByUid.js';
|
||||
import { httpsIconFor, notificationTarget, senderNameFor } from './Dashboard/notificationCenter.js';
|
||||
import apply_item_added_to_containers from '../helpers/applyItemAddedToContainers.js';
|
||||
import parse_item_metadata from '../helpers/parseItemMetadata.js';
|
||||
import UIWindowSearch from './UIWindowSearch.js';
|
||||
import { resolve_default_app } from '../helpers/defaultApp.js';
|
||||
|
||||
async function UIDesktop (options) {
|
||||
@@ -90,18 +82,6 @@ async function UIDesktop (options) {
|
||||
// Add this near the very beginning of the UIDesktop function
|
||||
window.desktop_icons_hidden = false; // Set default value immediately
|
||||
|
||||
// Initialize toolbar auto-hide preference
|
||||
window.toolbar_auto_hide_enabled = true; // Set default value
|
||||
|
||||
// Load the toolbar auto-hide preference
|
||||
// Preferences are best-effort: a KV read that fails (offline, rate
|
||||
// limited, no usage left on the account) leaves the default in place
|
||||
// rather than stopping the desktop from rendering.
|
||||
let toolbar_auto_hide_enabled_val = await puter.kv.get('toolbar_auto_hide_enabled').catch(() => null);
|
||||
if ( toolbar_auto_hide_enabled_val === 'false' || toolbar_auto_hide_enabled_val === false ) {
|
||||
window.toolbar_auto_hide_enabled = false;
|
||||
}
|
||||
|
||||
// Give Camera and Recorder write permissions to Desktop
|
||||
puter.kv.get('has_set_default_app_user_permissions').then(async (user_permissions) => {
|
||||
if ( ! user_permissions ) {
|
||||
@@ -391,23 +371,6 @@ async function UIDesktop (options) {
|
||||
update_tab_notif_count_badge();
|
||||
});
|
||||
|
||||
window.socket.on('app.opened', async (app) => {
|
||||
// don't update if this is the original client that initiated the action
|
||||
if ( app.original_client_socket_id === window.socket.id )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// add the app to the beginning of the array
|
||||
window.launch_apps.recent.unshift(app);
|
||||
|
||||
// dedupe the array by uuid, uid, and id
|
||||
window.launch_apps.recent = [...new Map(window.launch_apps.recent.map(v => [v.name, v])).values()];
|
||||
|
||||
// limit to 5
|
||||
window.launch_apps.recent = window.launch_apps.recent.slice(0, window.launch_recent_apps_count);
|
||||
});
|
||||
|
||||
window.socket.on('item.removed', async (item) => {
|
||||
// don't update if this is the original client that initiated the action
|
||||
if ( item.original_client_socket_id === window.socket.id )
|
||||
@@ -545,8 +508,6 @@ async function UIDesktop (options) {
|
||||
if ( dest_path === window.trash_path ) {
|
||||
// if trashing dir...
|
||||
if ( fsentry.is_dir ) {
|
||||
// remove website badge
|
||||
$(`.mywebsites-dir-path[data-uuid="${fsentry.uid}"]`).remove();
|
||||
// remove the website badge from all instances of the dir
|
||||
$(`.item[data-uid="${fsentry.uid}"]`).find('.item-has-website-badge').fadeOut(300);
|
||||
|
||||
@@ -1111,20 +1072,6 @@ async function UIDesktop (options) {
|
||||
window.init_upload_using_dialog(el_desktop);
|
||||
},
|
||||
},
|
||||
// -------------------------------------------
|
||||
// -
|
||||
// -------------------------------------------
|
||||
'-',
|
||||
// -------------------------------------------
|
||||
// Change Desktop Background…
|
||||
// -------------------------------------------
|
||||
{
|
||||
html: i18n('change_desktop_background'),
|
||||
onClick: function () {
|
||||
UIWindowDesktopBGSettings();
|
||||
},
|
||||
},
|
||||
|
||||
],
|
||||
});
|
||||
}
|
||||
@@ -1148,22 +1095,6 @@ async function UIDesktop (options) {
|
||||
|
||||
// home directory
|
||||
puter.fs.readdir({ path: window.home_path, consistency: 'strong' });
|
||||
|
||||
// Show welcome window if user hasn't already seen it and hasn't directly navigated to an app
|
||||
if ( !window.url_paths[0]?.toLocaleLowerCase() === 'app' || !window.url_paths[1] ) {
|
||||
if ( !isMobile.phone && !isMobile.tablet ) {
|
||||
setTimeout(() => {
|
||||
// The catch goes on the end of the chain, not on the read:
|
||||
// falling back to null would read as "never seen it" and
|
||||
// show the window to someone who has.
|
||||
puter.kv.get('has_seen_welcome_window').then(async (val) => {
|
||||
if ( val === null ) {
|
||||
await UIWindowWelcome();
|
||||
}
|
||||
}).catch(err => console.warn('Could not check has_seen_welcome_window:', err));
|
||||
}, 1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------
|
||||
@@ -1246,67 +1177,6 @@ async function UIDesktop (options) {
|
||||
$('.desktop').removeClass('desktop-selectable-active');
|
||||
});
|
||||
}
|
||||
// ----------------------------------------------------
|
||||
// Toolbar
|
||||
// ----------------------------------------------------
|
||||
// Has user seen the toolbar animation?
|
||||
window.has_seen_toolbar_animation = await puter.kv.get('has_seen_toolbar_animation').catch(() => null) ?? false;
|
||||
|
||||
let ht = '';
|
||||
let style = '';
|
||||
let class_name = '';
|
||||
if ( window.has_seen_toolbar_animation && !isMobile.phone && !isMobile.tablet ) {
|
||||
style = 'top: -20px; width: 40px;';
|
||||
class_name = 'toolbar-hidden';
|
||||
} else {
|
||||
style = 'height:30px; min-height:30px; max-height:30px;';
|
||||
}
|
||||
|
||||
ht += `<div class="toolbar hide-scrollbar ${class_name}" style="${style}">`;
|
||||
// logo
|
||||
ht += `<div class="toolbar-btn toolbar-puter-logo" title="Puter" style="margin-left: 10px;"><img src="${window.icons['logo-white.svg']}" draggable="false" style="display:block; width:17px; height:17px"></div>`;
|
||||
|
||||
// spacer to push items to the right
|
||||
ht += '<div class="toolbar-spacer"></div>';
|
||||
|
||||
// create account button
|
||||
ht += `<div class="toolbar-btn user-options-create-account-btn ${window.user.is_temp ? '' : 'hidden'}" style="padding:0; opacity:1;" title="${i18n('toolbar.save_account')}">`;
|
||||
ht += '<svg style="width: 17px; height: 17px;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="48px" height="48px" viewBox="0 0 48 48"><g transform="translate(0, 0)"><path d="M45.521,39.04L27.527,5.134c-1.021-1.948-3.427-2.699-5.375-1.679-.717,.376-1.303,.961-1.679,1.679L2.479,39.04c-.676,1.264-.635,2.791,.108,4.017,.716,1.207,2.017,1.946,3.42,1.943H41.993c1.403,.003,2.704-.736,3.42-1.943,.743-1.226,.784-2.753,.108-4.017ZM23.032,15h1.937c.565,0,1.017,.467,1,1.031l-.438,14c-.017,.54-.459,.969-1,.969h-1.062c-.54,0-.983-.429-1-.969l-.438-14c-.018-.564,.435-1.031,1-1.031Zm.968,25c-1.657,0-3-1.343-3-3s1.343-3,3-3,3,1.343,3,3-1.343,3-3,3Z" fill="#ffbb00"></path></g></svg>';
|
||||
ht += '</div>';
|
||||
|
||||
|
||||
|
||||
// qr code button -- only show if not embedded
|
||||
if ( ! window.is_embedded )
|
||||
{
|
||||
ht += `<div class="toolbar-btn qr-btn" title="${i18n('toolbar.qrcode')}" style="background-image:url(${window.icons['qr.svg']})"></div>`;
|
||||
}
|
||||
|
||||
// search button
|
||||
ht += `<div class="toolbar-btn search-btn" title="${i18n('toolbar.search')}" style="background-image:url('${window.icons['search.svg']}')"></div>`;
|
||||
|
||||
// user options menu
|
||||
ht += '<div class="toolbar-btn user-options-menu-btn profile-pic" style="display:block;">';
|
||||
ht += `<div class="profile-image ${window.user?.profile?.picture && 'profile-image-has-picture'}" style="border-radius: 50%; background-image:url(${window.user?.profile?.picture || window.icons['profile.svg']}); box-sizing: border-box; width: 17px !important; height: 17px !important; background-size: contain; background-repeat: no-repeat; background-position: center; background-position: center; background-size: cover;"></div>`;
|
||||
ht += '</div>';
|
||||
ht += '</div>';
|
||||
|
||||
// prepend toolbar to desktop
|
||||
$(ht).insertBefore(el_desktop);
|
||||
|
||||
// If auto-hide is disabled, ensure toolbar is visible on load
|
||||
if ( ! window.toolbar_auto_hide_enabled ) {
|
||||
// Make sure toolbar is visible when auto-hide is disabled
|
||||
setTimeout(() => {
|
||||
if ( $('.toolbar').hasClass('toolbar-hidden') ) {
|
||||
window.show_toolbar();
|
||||
}
|
||||
}, 100); // Small delay to ensure DOM is ready
|
||||
}
|
||||
|
||||
// send event
|
||||
window.dispatchEvent(new CustomEvent('toolbar:ready'));
|
||||
|
||||
// notification container
|
||||
$('body').append(`<div class="notification-container"><div class="notifications-close-all">${i18n('close_all')}</div></div>`);
|
||||
|
||||
@@ -1429,328 +1299,6 @@ async function UIDesktop (options) {
|
||||
$('.window-menubar-global').hide();
|
||||
});
|
||||
|
||||
window.hide_toolbar = (animate = true) => {
|
||||
// Always show toolbar on mobile and tablet devices
|
||||
if ( isMobile.phone || isMobile.tablet ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't hide toolbar if auto-hide is disabled
|
||||
if ( ! window.toolbar_auto_hide_enabled ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( $('.toolbar').hasClass('toolbar-hidden') ) return;
|
||||
|
||||
// attach hidden class to toolbar
|
||||
$('.toolbar').addClass('toolbar-hidden');
|
||||
|
||||
// animate the toolbar to top = -20px;
|
||||
// animate width to 40px;
|
||||
if ( animate ) {
|
||||
$('.toolbar').animate({
|
||||
top: '-20px',
|
||||
width: '40px',
|
||||
}, 100);
|
||||
} else {
|
||||
$('.toolbar').css({
|
||||
top: '-20px',
|
||||
width: '40px',
|
||||
});
|
||||
}
|
||||
// animate hide toolbar buttons
|
||||
if ( animate ) {
|
||||
$('.toolbar-btn, .user-options-menu-btn').animate({
|
||||
opacity: 0,
|
||||
}, 10);
|
||||
} else {
|
||||
$('.toolbar-btn, .user-options-menu-btn').css({
|
||||
opacity: 0,
|
||||
});
|
||||
}
|
||||
|
||||
if ( ! window.has_seen_toolbar_animation ) {
|
||||
puter.kv.set({
|
||||
key: 'has_seen_toolbar_animation',
|
||||
value: true,
|
||||
}).catch(err => console.warn('Could not save has_seen_toolbar_animation:', err));
|
||||
|
||||
window.has_seen_toolbar_animation = true;
|
||||
}
|
||||
};
|
||||
|
||||
window.show_toolbar = () => {
|
||||
if ( ! $('.toolbar').hasClass('toolbar-hidden') ) return;
|
||||
|
||||
// remove hidden class from toolbar
|
||||
$('.toolbar').removeClass('toolbar-hidden');
|
||||
|
||||
$('.toolbar').animate({
|
||||
top: 0,
|
||||
}, 100).css('width', 'max-content');
|
||||
|
||||
// animate show toolbar buttons
|
||||
$('.toolbar-btn, .user-options-menu-btn').animate({
|
||||
opacity: 0.8,
|
||||
}, 50);
|
||||
};
|
||||
|
||||
// Toolbar hide/show logic with improved UX
|
||||
window.toolbarHideTimeout = null;
|
||||
let isMouseNearToolbar = false;
|
||||
|
||||
// Define safe zone around toolbar (in pixels)
|
||||
const TOOLBAR_SAFE_ZONE = 30;
|
||||
const TOOLBAR_HIDE_DELAY = 100; // Base delay before hiding
|
||||
const TOOLBAR_QUICK_HIDE_DELAY = 200; // Quicker hide when mouse moves far away
|
||||
|
||||
// Function to check if mouse is in the safe zone around toolbar
|
||||
window.isMouseInToolbarSafeZone = (mouseX, mouseY) => {
|
||||
const toolbar = $('.toolbar')[0];
|
||||
if ( ! toolbar ) return false;
|
||||
|
||||
const rect = toolbar.getBoundingClientRect();
|
||||
|
||||
// Expand the toolbar bounds by the safe zone
|
||||
const safeZone = {
|
||||
top: rect.top - TOOLBAR_SAFE_ZONE,
|
||||
bottom: rect.bottom + TOOLBAR_SAFE_ZONE,
|
||||
left: rect.left - TOOLBAR_SAFE_ZONE,
|
||||
right: rect.right + TOOLBAR_SAFE_ZONE,
|
||||
};
|
||||
|
||||
return mouseX >= safeZone.left &&
|
||||
mouseX <= safeZone.right &&
|
||||
mouseY >= safeZone.top &&
|
||||
mouseY <= safeZone.bottom;
|
||||
};
|
||||
|
||||
// Function to handle toolbar hiding with improved logic
|
||||
window.handleToolbarHiding = (mouseX, mouseY) => {
|
||||
// Always show toolbar on mobile and tablet devices
|
||||
if ( isMobile.phone || isMobile.tablet ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't hide toolbar if auto-hide is disabled
|
||||
if ( ! window.toolbar_auto_hide_enabled ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear any existing timeout
|
||||
if ( window.toolbarHideTimeout ) {
|
||||
clearTimeout(window.toolbarHideTimeout);
|
||||
window.toolbarHideTimeout = null;
|
||||
}
|
||||
|
||||
// Don't hide if toolbar is already hidden
|
||||
if ( $('.toolbar').hasClass('toolbar-hidden') ) return;
|
||||
|
||||
const wasNearToolbar = isMouseNearToolbar;
|
||||
isMouseNearToolbar = window.isMouseInToolbarSafeZone(mouseX, mouseY);
|
||||
|
||||
// If mouse is in safe zone, don't hide
|
||||
if ( isMouseNearToolbar ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Determine hide delay based on mouse movement pattern
|
||||
let hideDelay = TOOLBAR_HIDE_DELAY;
|
||||
|
||||
// If mouse was previously near toolbar and now moved far away, hide quicker
|
||||
if ( wasNearToolbar && !isMouseNearToolbar ) {
|
||||
// Check if mouse moved significantly away
|
||||
const toolbar = $('.toolbar')[0];
|
||||
if ( toolbar ) {
|
||||
const rect = toolbar.getBoundingClientRect();
|
||||
const distanceFromToolbar = Math.min(
|
||||
Math.abs(mouseY - rect.bottom),
|
||||
Math.abs(mouseY - rect.top),
|
||||
);
|
||||
|
||||
// If mouse is far from toolbar, hide quicker
|
||||
if ( distanceFromToolbar > TOOLBAR_SAFE_ZONE * 2 ) {
|
||||
hideDelay = TOOLBAR_QUICK_HIDE_DELAY;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Set timeout to hide toolbar
|
||||
window.toolbarHideTimeout = setTimeout(() => {
|
||||
// Double-check mouse position before hiding
|
||||
if ( ! window.isMouseInToolbarSafeZone(window.mouseX, window.mouseY) ) {
|
||||
window.hide_toolbar();
|
||||
}
|
||||
window.toolbarHideTimeout = null;
|
||||
}, hideDelay);
|
||||
};
|
||||
|
||||
// debounce timer to prevent toolbar showing immediately after drag ends
|
||||
window.drag_release_debounce_timer = null;
|
||||
const DRAG_RELEASE_DEBOUNCE_MS = 300;
|
||||
|
||||
// track when drag operations end to enable debounce
|
||||
$(document).on('dragend', function () {
|
||||
window.drag_release_debounce_timer = setTimeout(() => {
|
||||
window.drag_release_debounce_timer = null;
|
||||
}, DRAG_RELEASE_DEBOUNCE_MS);
|
||||
});
|
||||
|
||||
// also debounce when mouseup occurs while in drag state
|
||||
$(document).on('mouseup', function () {
|
||||
if ( window.a_window_is_being_dragged || window.an_item_is_being_dragged ) {
|
||||
window.drag_release_debounce_timer = setTimeout(() => {
|
||||
window.drag_release_debounce_timer = null;
|
||||
}, DRAG_RELEASE_DEBOUNCE_MS);
|
||||
}
|
||||
});
|
||||
|
||||
// hovering over a hidden toolbar will show it
|
||||
$(document).on('mouseenter', '.toolbar-hidden', function () {
|
||||
// if a window is being dragged or currently in drag release debounce period, don't show the toolbar
|
||||
if ( window.a_window_is_being_dragged || window.drag_release_debounce_timer !== null )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// if selectable is active , don't show the toolbar
|
||||
if ( window.desktop_selectable_is_active )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// if an item is being dragged, don't show the toolbar
|
||||
if ( window.an_item_is_being_dragged )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if ( window.is_fullpage_mode )
|
||||
{
|
||||
$('.window-app-iframe').css('pointer-events', 'none');
|
||||
}
|
||||
|
||||
window.show_toolbar();
|
||||
// Clear any pending hide timeout
|
||||
if ( window.toolbarHideTimeout ) {
|
||||
clearTimeout(window.toolbarHideTimeout);
|
||||
window.toolbarHideTimeout = null;
|
||||
}
|
||||
});
|
||||
|
||||
// hovering over a visible toolbar will show it and cancel hiding
|
||||
$(document).on('mouseenter', '.toolbar:not(.toolbar-hidden)', function () {
|
||||
// if a window is being dragged, don't show the toolbar
|
||||
if ( window.a_window_is_being_dragged )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear any pending hide timeout when entering toolbar
|
||||
if ( window.toolbarHideTimeout ) {
|
||||
clearTimeout(window.toolbarHideTimeout);
|
||||
window.toolbarHideTimeout = null;
|
||||
}
|
||||
isMouseNearToolbar = true;
|
||||
});
|
||||
|
||||
$(document).on('mouseenter', '.toolbar', function () {
|
||||
if ( window.is_fullpage_mode )
|
||||
{
|
||||
$('.toolbar').focus();
|
||||
}
|
||||
});
|
||||
|
||||
// any click will hide the toolbar, unless:
|
||||
// - it's on the toolbar
|
||||
// - it's the user options menu button
|
||||
// - the user options menu is open
|
||||
$(document).on('click', function (e) {
|
||||
// Always show toolbar on mobile and tablet devices
|
||||
if ( isMobile.phone || isMobile.tablet ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't hide toolbar if auto-hide is disabled
|
||||
if ( ! window.toolbar_auto_hide_enabled ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// if the user has not seen the toolbar animation, don't hide the toolbar
|
||||
if ( ! window.has_seen_toolbar_animation )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
!$(e.target).hasClass('toolbar') &&
|
||||
!$(e.target).hasClass('user-options-menu-btn') &&
|
||||
$('.context-menu[data-id="user-options-menu"]').length === 0 &&
|
||||
true
|
||||
) {
|
||||
window.hide_toolbar(false);
|
||||
}
|
||||
});
|
||||
|
||||
// Handle mouse leaving the toolbar
|
||||
$(document).on('mouseleave', '.toolbar', function () {
|
||||
// Always show toolbar on mobile and tablet devices
|
||||
if ( isMobile.phone || isMobile.tablet ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't hide toolbar if auto-hide is disabled
|
||||
if ( ! window.toolbar_auto_hide_enabled ) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.has_left_toolbar_at_least_once = true;
|
||||
// if the user options menu is open, don't hide the toolbar
|
||||
if ( $('.context-menu[data-id="user-options-menu"]').length > 0 )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Start the hiding logic with current mouse position
|
||||
window.handleToolbarHiding(window.mouseX, window.mouseY);
|
||||
});
|
||||
|
||||
// Track mouse movement globally to update toolbar hiding logic
|
||||
$(document).on('mousemove', function (e) {
|
||||
// Always show toolbar on mobile and tablet devices
|
||||
if ( isMobile.phone || isMobile.tablet ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't hide toolbar if auto-hide is disabled
|
||||
if ( ! window.toolbar_auto_hide_enabled ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// if the user has not seen the toolbar animation, don't hide the toolbar
|
||||
if ( !window.has_seen_toolbar_animation && !window.has_left_toolbar_at_least_once )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// if the user options menu is open, don't hide the toolbar
|
||||
if ( $('.context-menu[data-id="user-options-menu"]').length > 0 )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Only handle toolbar hiding if toolbar is visible and mouse moved significantly
|
||||
if ( ! $('.toolbar').hasClass('toolbar-hidden') ) {
|
||||
// Use throttling to avoid excessive calls
|
||||
if ( ! window.mouseMoveThrottle ) {
|
||||
window.mouseMoveThrottle = setTimeout(() => {
|
||||
window.handleToolbarHiding(window.mouseX, window.mouseY);
|
||||
window.mouseMoveThrottle = null;
|
||||
}, 100); // Throttle to every 100ms
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
//--------------------------------------------------------------------------------------
|
||||
// Trying to view a user's public folder?
|
||||
// i.e. https://puter.com/@<username>
|
||||
@@ -2103,410 +1651,6 @@ $(document).on('contextmenu taphold', '.taskbar', function (event) {
|
||||
return false;
|
||||
});
|
||||
|
||||
// Toolbar context menu
|
||||
$(document).on('contextmenu taphold', '.toolbar', function (event) {
|
||||
// dismiss taphold on regular devices
|
||||
if ( event.type === 'taphold' && !isMobile.phone && !isMobile.tablet )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't show context menu on mobile devices since toolbar auto-hide is disabled there
|
||||
if ( isMobile.phone || isMobile.tablet )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
UIContextMenu({
|
||||
parent_element: $('.toolbar'),
|
||||
items: [
|
||||
//--------------------------------------------------
|
||||
// Enable/Disable Auto-hide
|
||||
//--------------------------------------------------
|
||||
{
|
||||
html: window.toolbar_auto_hide_enabled ? i18n('Disable Auto-hide') : i18n('Enable Auto-hide'),
|
||||
onClick: function () {
|
||||
// Toggle the preference
|
||||
window.toolbar_auto_hide_enabled = !window.toolbar_auto_hide_enabled;
|
||||
|
||||
// Save the preference
|
||||
puter.kv.set('toolbar_auto_hide_enabled', window.toolbar_auto_hide_enabled.toString())
|
||||
.catch(err => console.warn('Could not save toolbar_auto_hide_enabled:', err));
|
||||
|
||||
// If auto-hide was just disabled and toolbar is currently hidden, show it
|
||||
if ( !window.toolbar_auto_hide_enabled && $('.toolbar').hasClass('toolbar-hidden') ) {
|
||||
window.show_toolbar();
|
||||
}
|
||||
|
||||
// Clear any pending hide timeout
|
||||
if ( window.toolbarHideTimeout ) {
|
||||
clearTimeout(window.toolbarHideTimeout);
|
||||
window.toolbarHideTimeout = null;
|
||||
}
|
||||
|
||||
// hide toolbar
|
||||
window.hide_toolbar();
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
return false;
|
||||
});
|
||||
|
||||
$(document).on('click', '.qr-btn', async function (e) {
|
||||
UIWindowQR({
|
||||
message_i18n_key: 'scan_qr_c2a',
|
||||
text: `${window.gui_origin }/desktop?auth_token=${ window.auth_token}`,
|
||||
});
|
||||
});
|
||||
|
||||
$(document).on('click', '.user-options-menu-btn', async function (e) {
|
||||
const pos = this.getBoundingClientRect();
|
||||
if ( $('.context-menu[data-id="user-options-menu"]').length > 0 )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let items = [];
|
||||
let parent_element = this;
|
||||
//--------------------------------------------------
|
||||
// Save Session
|
||||
//--------------------------------------------------
|
||||
if ( window.user.is_temp ) {
|
||||
items.push({
|
||||
html: i18n('save_session'),
|
||||
icon: '<svg style="margin-bottom: -4px; width: 16px; height: 16px;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="48px" height="48px" viewBox="0 0 48 48"><g transform="translate(0, 0)"><path d="M45.521,39.04L27.527,5.134c-1.021-1.948-3.427-2.699-5.375-1.679-.717,.376-1.303,.961-1.679,1.679L2.479,39.04c-.676,1.264-.635,2.791,.108,4.017,.716,1.207,2.017,1.946,3.42,1.943H41.993c1.403,.003,2.704-.736,3.42-1.943,.743-1.226,.784-2.753,.108-4.017ZM23.032,15h1.937c.565,0,1.017,.467,1,1.031l-.438,14c-.017,.54-.459,.969-1,.969h-1.062c-.54,0-.983-.429-1-.969l-.438-14c-.018-.564,.435-1.031,1-1.031Zm.968,25c-1.657,0-3-1.343-3-3s1.343-3,3-3,3,1.343,3,3-1.343,3-3,3Z" fill="#ffbb00"></path></g></svg>',
|
||||
icon_active: '<svg style="margin-bottom: -4px; width: 16px; height: 16px;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="48px" height="48px" viewBox="0 0 48 48"><g transform="translate(0, 0)"><path d="M45.521,39.04L27.527,5.134c-1.021-1.948-3.427-2.699-5.375-1.679-.717,.376-1.303,.961-1.679,1.679L2.479,39.04c-.676,1.264-.635,2.791,.108,4.017,.716,1.207,2.017,1.946,3.42,1.943H41.993c1.403,.003,2.704-.736,3.42-1.943,.743-1.226,.784-2.753,.108-4.017ZM23.032,15h1.937c.565,0,1.017,.467,1,1.031l-.438,14c-.017,.54-.459,.969-1,.969h-1.062c-.54,0-.983-.429-1-.969l-.438-14c-.018-.564,.435-1.031,1-1.031Zm.968,25c-1.657,0-3-1.343-3-3s1.343-3,3-3,3,1.343,3,3-1.343,3-3,3Z" fill="#ffbb00"></path></g></svg>',
|
||||
onClick: async function () {
|
||||
UIWindowSaveAccount({
|
||||
send_confirmation_code: false,
|
||||
default_username: window.user.username,
|
||||
});
|
||||
},
|
||||
});
|
||||
// -------------------------------------------
|
||||
// -
|
||||
// -------------------------------------------
|
||||
items.push('-');
|
||||
}
|
||||
|
||||
// -------------------------------------------
|
||||
// Logged in users
|
||||
// -------------------------------------------
|
||||
if ( window.logged_in_users.length > 0 ) {
|
||||
let users_arr = window.logged_in_users;
|
||||
|
||||
// bring logged in user's item to top
|
||||
users_arr.sort(function (x, y) {
|
||||
return x.uuid === window.user.uuid ? -1 : y.uuid == window.user.uuid ? 1 : 0;
|
||||
});
|
||||
|
||||
// create menu items
|
||||
users_arr.forEach(l_user => {
|
||||
items.push({
|
||||
html: l_user.username,
|
||||
icon: l_user.username === window.user.username ? '✓' : '',
|
||||
onClick: async function (val) {
|
||||
// don't reload everything if clicked on already-logged-in user
|
||||
if ( l_user.username === window.user.username )
|
||||
{
|
||||
return;
|
||||
}
|
||||
// update auth data
|
||||
await window.update_auth_data(l_user.auth_token, l_user);
|
||||
// refresh
|
||||
location.reload();
|
||||
},
|
||||
|
||||
});
|
||||
});
|
||||
// -------------------------------------------
|
||||
// -
|
||||
// -------------------------------------------
|
||||
items.push('-');
|
||||
|
||||
items.push({
|
||||
html: i18n('add_another_account'),
|
||||
// icon: l_user.username === user.username ? '✓' : '',
|
||||
onClick: async function (val) {
|
||||
await UIAuthLogin({
|
||||
reload_on_success: true,
|
||||
send_confirmation_code: false,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
// -------------------------------------------
|
||||
// -
|
||||
// -------------------------------------------
|
||||
items.push('-');
|
||||
|
||||
}
|
||||
|
||||
// -------------------------------------------
|
||||
// Load available languages
|
||||
// -------------------------------------------
|
||||
const supportedLanguagesItems = window.listSupportedLanguages()
|
||||
.slice()
|
||||
.sort((a, b) => a.english_name.localeCompare(b.english_name, 'en'))
|
||||
.map(lang => {
|
||||
return {
|
||||
html: lang.name,
|
||||
icon: window.locale === lang.code ? '✓' : '',
|
||||
onClick: async function () {
|
||||
await changeLanguage(lang.code);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
UIContextMenu({
|
||||
id: 'user-options-menu',
|
||||
parent_element: parent_element,
|
||||
position: { top: pos.top + 28, left: pos.left + pos.width - 15 },
|
||||
items: [
|
||||
...items,
|
||||
//--------------------------------------------------
|
||||
// Change Language
|
||||
//--------------------------------------------------
|
||||
{
|
||||
html: i18n('change_language'),
|
||||
items: supportedLanguagesItems,
|
||||
},
|
||||
//--------------------------------------------------
|
||||
// Settings
|
||||
//--------------------------------------------------
|
||||
{
|
||||
html: i18n('settings'),
|
||||
id: 'settings',
|
||||
onClick: async function () {
|
||||
window.open('/dashboard/#home', '_blank');
|
||||
},
|
||||
},
|
||||
//--------------------------------------------------
|
||||
// My Websites
|
||||
//--------------------------------------------------
|
||||
{
|
||||
html: i18n('my_websites'),
|
||||
id: 'my_websites',
|
||||
onClick: async function () {
|
||||
UIWindowMyWebsites();
|
||||
},
|
||||
},
|
||||
//--------------------------------------------------
|
||||
// Task Manager
|
||||
//--------------------------------------------------
|
||||
{
|
||||
html: i18n('task_manager'),
|
||||
id: 'task_manager',
|
||||
onClick: async function () {
|
||||
UIWindowTaskManager();
|
||||
},
|
||||
},
|
||||
//--------------------------------------------------
|
||||
// Contact Us
|
||||
//--------------------------------------------------
|
||||
{
|
||||
html: i18n('contact_us'),
|
||||
id: 'contact_us',
|
||||
onClick: async function () {
|
||||
UIWindowFeedback();
|
||||
},
|
||||
},
|
||||
// -------------------------------------------
|
||||
// -
|
||||
// -------------------------------------------
|
||||
'-',
|
||||
|
||||
//--------------------------------------------------
|
||||
// Log Out
|
||||
//--------------------------------------------------
|
||||
{
|
||||
html: i18n('log_out'),
|
||||
onClick: async function () {
|
||||
// see if there are any open windows, if yes notify user
|
||||
if ( $('.window-app').length > 0 ) {
|
||||
const alert_resp = await UIAlert({
|
||||
message: `<p>${i18n('confirm_open_apps_log_out')}</p>`,
|
||||
buttons: [
|
||||
{
|
||||
label: i18n('close_all_windows_and_log_out'),
|
||||
value: 'close_and_log_out',
|
||||
type: 'primary',
|
||||
},
|
||||
{
|
||||
label: i18n('cancel'),
|
||||
},
|
||||
],
|
||||
});
|
||||
if ( alert_resp === 'close_and_log_out' )
|
||||
{
|
||||
window.logout();
|
||||
}
|
||||
}
|
||||
// no open windows
|
||||
else
|
||||
{
|
||||
window.logout();
|
||||
}
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
$(document).on('click', '.close-launch-popover', function () {
|
||||
$('.launch-popover').closest('.popover').fadeOut(200, function () {
|
||||
$('.launch-popover').closest('.popover').remove();
|
||||
});
|
||||
});
|
||||
|
||||
$(document).on('click', '.search-btn', function () {
|
||||
UIWindowSearch();
|
||||
});
|
||||
|
||||
$(document).on('click', '.toolbar-puter-logo', function () {
|
||||
window.open('/dashboard/#home', '_blank');
|
||||
});
|
||||
|
||||
$(document).on('click', '.user-options-create-account-btn', async function (e) {
|
||||
UIWindowSaveAccount({
|
||||
send_confirmation_code: false,
|
||||
default_username: window.user.username,
|
||||
});
|
||||
});
|
||||
|
||||
$(document).on('click', '.start-app', async function (e) {
|
||||
launch_app({
|
||||
name: $(this).attr('data-app-name'),
|
||||
});
|
||||
// close popovers
|
||||
$('.popover').fadeOut(200, function () {
|
||||
$('.popover').remove();
|
||||
});
|
||||
$('.context-menu').fadeOut(200, function () {
|
||||
$(this).remove();
|
||||
});
|
||||
});
|
||||
|
||||
$(document).on('click', '.user-options-login-btn', async function (e) {
|
||||
const alert_resp = await UIAlert({
|
||||
message: '<strong>Save session before exiting!</strong><p>You are in a temporary session and logging into another account will erase all data in your current session.</p>',
|
||||
buttons: [
|
||||
{
|
||||
label: i18n('save_session'),
|
||||
value: 'save-session',
|
||||
type: 'primary',
|
||||
},
|
||||
{
|
||||
label: i18n('log_into_another_account_anyway'),
|
||||
value: 'login',
|
||||
},
|
||||
{
|
||||
label: i18n('cancel'),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
if ( alert_resp === 'save-session' ) {
|
||||
let saved = await UIWindowSaveAccount({
|
||||
send_confirmation_code: false,
|
||||
});
|
||||
if ( saved )
|
||||
{
|
||||
UIAuthLogin({ show_signup_button: false, reload_on_success: true });
|
||||
}
|
||||
} else if ( alert_resp === 'login' ) {
|
||||
UIAuthLogin({
|
||||
show_signup_button: false,
|
||||
reload_on_success: true,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
$(document).on('click mousedown', '.launch-search, .launch-popover', function (e) {
|
||||
$(this).focus();
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
// don't let click bubble up to window
|
||||
e.stopImmediatePropagation();
|
||||
});
|
||||
|
||||
$(document).on('focus', '.launch-search', function (e) {
|
||||
// remove all selected items in start menu
|
||||
$('.launch-app-selected').removeClass('launch-app-selected');
|
||||
// scroll popover to top
|
||||
$('.launch-popover').scrollTop(0);
|
||||
});
|
||||
|
||||
$(document).on('change keyup keypress keydown paste', '.launch-search', function (e) {
|
||||
// search window.launch_apps.recommended for query
|
||||
const query = $(this).val().toLowerCase();
|
||||
if ( query === '' ) {
|
||||
$('.launch-search-clear').hide();
|
||||
$('.start-app-card').show();
|
||||
$('.launch-apps-recent').show();
|
||||
$('.start-section-heading').show();
|
||||
} else {
|
||||
$('.launch-apps-recent').hide();
|
||||
$('.start-section-heading').hide();
|
||||
$('.launch-search-clear').show();
|
||||
window.launch_apps.recommended.forEach((app) => {
|
||||
if ( app.title.toLowerCase().includes(query.toLowerCase()) ) {
|
||||
$(`.start-app-card[data-name="${app.name}"]`).show();
|
||||
} else {
|
||||
$(`.start-app-card[data-name="${app.name}"]`).hide();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
$(document).on('click', '.launch-search-clear', function (e) {
|
||||
$('.launch-search').val('');
|
||||
$('.launch-search').trigger('change');
|
||||
$('.launch-search').focus();
|
||||
});
|
||||
|
||||
|
||||
window.set_desktop_background = function (options) {
|
||||
if ( options.fit ) {
|
||||
let fit = options.fit;
|
||||
if ( fit === 'cover' || fit === 'contain' ) {
|
||||
$('body').css('background-size', fit);
|
||||
$('body').css('background-repeat', 'no-repeat');
|
||||
$('body').css('background-position', 'center center');
|
||||
}
|
||||
else if ( fit === 'center' ) {
|
||||
$('body').css('background-size', 'auto');
|
||||
$('body').css('background-repeat', 'no-repeat');
|
||||
$('body').css('background-position', 'center center');
|
||||
}
|
||||
|
||||
else if ( fit === 'repeat' ) {
|
||||
$('body').css('background-size', 'auto');
|
||||
$('body').css('background-repeat', 'repeat');
|
||||
}
|
||||
window.desktop_bg_fit = fit;
|
||||
}
|
||||
|
||||
if ( options.url ) {
|
||||
$('body').css('background-image', `url(${options.url})`);
|
||||
window.desktop_bg_url = options.url;
|
||||
window.desktop_bg_color = undefined;
|
||||
}
|
||||
else if ( options.color ) {
|
||||
$('body').css({
|
||||
'background-image': 'none',
|
||||
'background-color': options.color,
|
||||
});
|
||||
window.desktop_bg_color = options.color;
|
||||
window.desktop_bg_url = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
window.update_taskbar = function () {
|
||||
let items = [];
|
||||
$('.taskbar-item-sortable[data-keep-in-taskbar="true"]').each(function (index) {
|
||||
@@ -2580,9 +1724,6 @@ window.exit_fullpage_mode = (el_window) => {
|
||||
|
||||
// reset dektop height to take into account the taskbar height
|
||||
$('.desktop').css('height', `calc(100vh - ${window.taskbar_height + window.toolbar_height}px)`);
|
||||
|
||||
// refresh desktop background
|
||||
window.refresh_desktop_background();
|
||||
};
|
||||
|
||||
window.reset_window_size_and_position = (el_window) => {
|
||||
|
||||
@@ -18,21 +18,17 @@
|
||||
*/
|
||||
|
||||
import UIWindowItemProperties from './UIWindowItemProperties.js';
|
||||
import ensureConfirmedEmail from '../helpers/ensureConfirmedEmail.js';
|
||||
import UIPopover from './UIPopover.js';
|
||||
import UIContextMenu from './UIContextMenu.js';
|
||||
import UIAlert from './UIAlert.js';
|
||||
import UIWindowPublishWorker from './UIWindowPublishWorker.js';
|
||||
import UIWindowShare from './UIWindowShare.js';
|
||||
import path from '../lib/path.js';
|
||||
import truncate_filename from '../helpers/truncateFilename.js';
|
||||
import launch_app from '../helpers/launchApp.js';
|
||||
import open_item from '../helpers/openItem.js';
|
||||
import publish_as_website from '../helpers/publishAsWebsite.js';
|
||||
import mime from '../lib/mime.js';
|
||||
import { isWeblinkName, weblinkChangeIconMenuItem } from '../helpers/weblink.js';
|
||||
import { is_owned_by_me } from '../helpers/pathOwner.js';
|
||||
import { can_rename, can_restructure, invalidate_shared_roots, shared_mode_for } from '../helpers/sharedAccess.js';
|
||||
import { can_rename, can_restructure, invalidate_shared_roots } from '../helpers/sharedAccess.js';
|
||||
import { is_default_app } from '../helpers/defaultApp.js';
|
||||
import openWithAI from '../helpers/openWithAI.js';
|
||||
import refresh_item_container from '../helpers/refreshItemContainer.js';
|
||||
@@ -329,7 +325,6 @@ async function UIItem (options) {
|
||||
last_window_dragged_over = null;
|
||||
|
||||
window.an_item_is_being_dragged = true;
|
||||
$('.toolbar').css('pointer-events', 'none');
|
||||
},
|
||||
drag: function (event, ui) {
|
||||
// Constrain item within desktop bounds
|
||||
@@ -442,7 +437,6 @@ async function UIItem (options) {
|
||||
clearTimeout(longer_hover_timeout);
|
||||
last_window_dragged_over = null;
|
||||
window.an_item_is_being_dragged = false;
|
||||
$('.toolbar').css('pointer-events', 'auto');
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1099,11 +1093,6 @@ async function UIItem (options) {
|
||||
// Someone else's, however we got here — including items reached by
|
||||
// opening a shared folder, which carry no share markers.
|
||||
const is_not_mine = !is_owned_by_me($(el_item).attr('data-path'));
|
||||
// `manage` inherits downwards, so a file inside a folder you manage
|
||||
// counts too — the row itself only carries a mode at a shared root.
|
||||
const can_manage_share =
|
||||
$(el_item).attr('data-share_mode') === 'manage'
|
||||
|| (await shared_mode_for($(el_item).attr('data-path'))) === 'manage';
|
||||
// Moving and deleting go by the holding folder, not by the item.
|
||||
const may_restructure = !is_not_mine
|
||||
|| await can_restructure($(el_item).attr('data-path'));
|
||||
@@ -1269,19 +1258,6 @@ async function UIItem (options) {
|
||||
});
|
||||
|
||||
}
|
||||
//-------------------------------------------
|
||||
// Publish as Worker
|
||||
// -------------------------------------------
|
||||
// The backend refuses deploys from a file someone else owns.
|
||||
if ( !is_trashed && !is_trash && !is_not_mine && !options.is_dir && $(el_item).attr('data-name').toLowerCase().endsWith('.js') ) {
|
||||
menu_items.push({
|
||||
html: i18n('publish_as_serverless_worker'),
|
||||
onClick: async function () {
|
||||
if ( ! await ensureConfirmedEmail(i18n('save_account_to_publish')) ) return;
|
||||
UIWindowPublishWorker(options.uid, $(el_item).attr('data-name'), $(el_item).attr('data-path'));
|
||||
},
|
||||
});
|
||||
}
|
||||
// -------------------------------------------
|
||||
// Deploy As App
|
||||
// -------------------------------------------
|
||||
@@ -1315,20 +1291,6 @@ async function UIItem (options) {
|
||||
});
|
||||
}
|
||||
// -------------------------------------------
|
||||
// Share
|
||||
// -------------------------------------------
|
||||
if ( !is_trash && !is_trashed && (!is_not_mine || can_manage_share) ) {
|
||||
menu_items.push({
|
||||
html: i18n('share_ellipsis'),
|
||||
onClick: async function () {
|
||||
UIWindowShare({
|
||||
path: $(el_item).attr('data-path'),
|
||||
name: $(el_item).attr('data-name'),
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
// -------------------------------------------
|
||||
// Download
|
||||
// -------------------------------------------
|
||||
if ( !is_trash && !is_trashed && (options.associated_app_name === null || options.associated_app_name === undefined) ) {
|
||||
@@ -1348,48 +1310,6 @@ async function UIItem (options) {
|
||||
});
|
||||
}
|
||||
// -------------------------------------------
|
||||
// Set as Wallpaper
|
||||
// -------------------------------------------
|
||||
const mime_type = mime.getType($(el_item).attr('data-name')) ??
|
||||
'application/octet-stream';
|
||||
if ( !is_trashed && !is_trash && !options.is_dir && mime_type.startsWith('image/') ) {
|
||||
menu_items.push({
|
||||
html: i18n('set_as_background'),
|
||||
onClick: async function () {
|
||||
const read_url = await puter.fs.sign(undefined, { uid: $(el_item).attr('data-uid'), action: 'read' });
|
||||
window.set_desktop_background({
|
||||
url: read_url.items.read_url,
|
||||
fit: window.desktop_bg_fit,
|
||||
});
|
||||
try {
|
||||
$.ajax({
|
||||
url: `${window.api_origin }/set-desktop-bg`,
|
||||
type: 'POST',
|
||||
data: JSON.stringify({
|
||||
url: window.desktop_bg_url,
|
||||
color: window.desktop_bg_color,
|
||||
fit: window.desktop_bg_fit,
|
||||
}),
|
||||
async: true,
|
||||
contentType: 'application/json',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${window.auth_token}`,
|
||||
},
|
||||
statusCode: {
|
||||
401: function (xhr) {
|
||||
window.handle401(xhr);
|
||||
},
|
||||
},
|
||||
});
|
||||
$(el_window).close();
|
||||
resolve(true);
|
||||
} catch ( err ) {
|
||||
// Ignore
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
// -------------------------------------------
|
||||
// Zip
|
||||
// -------------------------------------------
|
||||
if ( !is_trash && !is_trashed && !$(el_item).attr('data-path').endsWith('.zip') ) {
|
||||
|
||||
@@ -27,8 +27,6 @@ vi.mock('./UIPopover.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./UIWindowEmailConfirmationRequired.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./UIContextMenu.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./UIAlert.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./UIWindowPublishWorker.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./UIWindowShare.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('../helpers/launchApp.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('../helpers/openItem.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('../helpers/publishAsWebsite.js', () => ({ default: vi.fn() }));
|
||||
@@ -139,3 +137,41 @@ describe('UIItem Remove from Shared', () => {
|
||||
expect(refresh_item_container.mock.calls[0][0][0]).toBe($('.item-container')[0]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('UIItem Share', () => {
|
||||
beforeEach(() => {
|
||||
window.user = { username: 'alice' };
|
||||
window.trash_path = '/alice/Trash';
|
||||
});
|
||||
|
||||
it('is not offered, even on an item the user owns', async () => {
|
||||
const labels = await menuLabels({
|
||||
path: '/alice/Photos',
|
||||
owner: 'alice',
|
||||
shared_with_me: false,
|
||||
share_mode: undefined,
|
||||
shared_by: undefined,
|
||||
});
|
||||
expect(labels).not.toContain('share_ellipsis');
|
||||
});
|
||||
});
|
||||
|
||||
describe('UIItem Publish as Worker', () => {
|
||||
beforeEach(() => {
|
||||
window.user = { username: 'alice' };
|
||||
window.trash_path = '/alice/Trash';
|
||||
});
|
||||
|
||||
it('is not offered, even on a .js file the user owns', async () => {
|
||||
const labels = await menuLabels({
|
||||
path: '/alice/worker.js',
|
||||
name: 'worker.js',
|
||||
is_dir: false,
|
||||
owner: 'alice',
|
||||
shared_with_me: false,
|
||||
share_mode: undefined,
|
||||
shared_by: undefined,
|
||||
});
|
||||
expect(labels).not.toContain('publish_as_serverless_worker');
|
||||
});
|
||||
});
|
||||
+3
-304
@@ -17,13 +17,9 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { createUploadThumbnailGenerator } from '../services/pdfThumbnails/index.js';
|
||||
import UITaskbarItem from './UITaskbarItem.js';
|
||||
import UIPopover from './UIPopover.js';
|
||||
import launch_app from '../helpers/launchApp.js';
|
||||
import UIContextMenu from './UIContextMenu.js';
|
||||
import { appIconAttrs, appIconSrc } from '../helpers/appIcon.js';
|
||||
import { filterLaunchableApps } from '../helpers/launchAppsList.js';
|
||||
import { appIconSrc } from '../helpers/appIcon.js';
|
||||
|
||||
const TASKBAR_POSITIONS = ['left', 'bottom', 'right'];
|
||||
|
||||
@@ -58,27 +54,6 @@ async function UITaskbar (options) {
|
||||
// Set global taskbar position
|
||||
window.taskbar_position = taskbar_position;
|
||||
|
||||
let launchAppsRequest = 0;
|
||||
let pendingLaunchApps;
|
||||
const fetchLaunchApps = () => {
|
||||
pendingLaunchApps?.abort();
|
||||
pendingLaunchApps = $.ajax({
|
||||
url: `${window.api_origin}/get-launch-apps?icon_size=64`,
|
||||
type: 'GET',
|
||||
contentType: 'application/json',
|
||||
timeout: 30000,
|
||||
headers: { 'Authorization': `Bearer ${window.auth_token}` },
|
||||
});
|
||||
return pendingLaunchApps;
|
||||
};
|
||||
const logRefreshFailure = (xhr, status) => {
|
||||
if ( status !== 'abort' ) console.error('Failed to refresh launch apps:', status);
|
||||
};
|
||||
|
||||
fetchLaunchApps().done(apps => {
|
||||
if ( launchAppsRequest === 0 ) window.launch_apps = apps;
|
||||
}).fail(logRefreshFailure);
|
||||
|
||||
let h = '';
|
||||
h += `<div id="ui-taskbar_${window.global_element_id}" class="taskbar taskbar-position-${taskbar_position}" style="height:${window.taskbar_height}px;">`;
|
||||
h += '<div class="taskbar-sortable" style="display: flex; justify-content: center; z-index: 99999;"></div>';
|
||||
@@ -90,240 +65,6 @@ async function UITaskbar (options) {
|
||||
|
||||
$('.desktop').append(h);
|
||||
|
||||
//---------------------------------------------
|
||||
// add `Start` to taskbar
|
||||
//---------------------------------------------
|
||||
UITaskbarItem({
|
||||
icon: window.icons['start.svg'],
|
||||
name: i18n('start'),
|
||||
sortable: false,
|
||||
keep_in_taskbar: true,
|
||||
disable_context_menu: true,
|
||||
onClick: async function (item) {
|
||||
// skip if popover already open
|
||||
if ( $(item).hasClass('has-open-popover') )
|
||||
{
|
||||
$('.popover-launcher').remove();
|
||||
return;
|
||||
}
|
||||
|
||||
// show popover
|
||||
let popover = UIPopover({
|
||||
content: '<div class="launch-popover hide-scrollbar"></div>',
|
||||
snapToElement: item,
|
||||
parent_element: item,
|
||||
width: 500,
|
||||
height: 500,
|
||||
class: 'popover-launcher',
|
||||
center_horizontally: true,
|
||||
});
|
||||
|
||||
$(popover).on('remove', () => pendingLaunchApps?.abort());
|
||||
const request = ++launchAppsRequest;
|
||||
if ( ! window.launch_apps?.recent ) {
|
||||
window.launch_apps = { recent: [], recommended: [] };
|
||||
}
|
||||
$(popover).find('.launch-popover').append(`
|
||||
<div class="launch-search-wrapper">
|
||||
<input style="background-image:url('${window.icons['magnifier-outline.svg']}');" class="launch-search">
|
||||
<img class="launch-search-clear" src="${window.icons['close.svg']}">
|
||||
</div>
|
||||
`);
|
||||
|
||||
const renderApps = () => {
|
||||
const recentApps = filterLaunchableApps(window.launch_apps.recent);
|
||||
const recommendedApps = filterLaunchableApps(window.launch_apps.recommended);
|
||||
let apps_str = '';
|
||||
|
||||
// -------------------------------------------
|
||||
// Recent apps
|
||||
// -------------------------------------------
|
||||
if ( recentApps.length > 0 ) {
|
||||
// heading
|
||||
apps_str += `<h1 class="start-section-heading start-section-heading-recent">${i18n('recent')}</h1>`;
|
||||
|
||||
// apps
|
||||
apps_str += '<div class="launch-apps-recent">';
|
||||
for ( let index = 0; index < window.launch_recent_apps_count && index < recentApps.length; index++ ) {
|
||||
const app_info = recentApps[index];
|
||||
apps_str += `<div title="${html_encode(app_info.title)}" data-name="${html_encode(app_info.name)}" class="start-app-card">`;
|
||||
const icon = appIconSrc(app_info);
|
||||
apps_str += `<div class="start-app" data-app-name="${html_encode(app_info.name)}" data-app-uuid="${html_encode(app_info.uuid)}" data-app-icon="${html_encode(icon.src)}" data-app-icon-fallback="${html_encode(icon.fallback)}" data-app-title="${html_encode(app_info.title)}">`;
|
||||
apps_str += `<img class="start-app-icon" ${appIconAttrs(app_info, window.icons['app.svg'])}>`;
|
||||
apps_str += `<span class="start-app-title">${html_encode(app_info.title)}</span>`;
|
||||
apps_str += '</div>';
|
||||
apps_str += '</div>';
|
||||
}
|
||||
apps_str += '</div>';
|
||||
}
|
||||
// -------------------------------------------
|
||||
// Recommended apps
|
||||
// -------------------------------------------
|
||||
if ( recommendedApps.length > 0 ) {
|
||||
// heading
|
||||
apps_str += `<h1 class="start-section-heading start-section-heading-recommended" style="${recentApps.length > 0 ? 'padding-top: 30px;' : ''}">${i18n('recommended')}</h1>`;
|
||||
// apps
|
||||
apps_str += '<div class="launch-apps-recommended">';
|
||||
for ( let index = 0; index < recommendedApps.length; index++ ) {
|
||||
const app_info = recommendedApps[index];
|
||||
apps_str += `<div title="${html_encode(app_info.title)}" data-name="${html_encode(app_info.name)}" class="start-app-card">`;
|
||||
const icon = appIconSrc(app_info);
|
||||
apps_str += `<div class="start-app" data-app-name="${html_encode(app_info.name)}" data-app-uuid="${html_encode(app_info.uuid)}" data-app-icon="${html_encode(icon.src)}" data-app-icon-fallback="${html_encode(icon.fallback)}" data-app-title="${html_encode(app_info.title)}">`;
|
||||
apps_str += `<img class="start-app-icon" ${appIconAttrs(app_info, window.icons['app.svg'])}>`;
|
||||
apps_str += `<span class="start-app-title">${html_encode(app_info.title)}</span>`;
|
||||
apps_str += '</div>';
|
||||
apps_str += '</div>';
|
||||
}
|
||||
apps_str += '</div>';
|
||||
}
|
||||
|
||||
// Replace tiles only, so the search input keeps its text and focus.
|
||||
$(popover).find('.start-section-heading, .launch-apps-recent, .launch-apps-recommended').remove();
|
||||
$(popover).find('.launch-popover').append(apps_str);
|
||||
|
||||
// make apps draggable
|
||||
$(popover).find('.start-app').draggable({
|
||||
appendTo: 'body',
|
||||
revert: 'invalid',
|
||||
connectToSortable: '.taskbar-sortable',
|
||||
zIndex: parseInt($(popover).css('z-index')) + 1,
|
||||
scroll: false,
|
||||
distance: 5,
|
||||
revertDuration: 100,
|
||||
helper: 'clone',
|
||||
cursorAt: { left: 18, top: 20 },
|
||||
start: function (event, ui) {
|
||||
},
|
||||
drag: function (event, ui) {
|
||||
},
|
||||
stop: function () {
|
||||
},
|
||||
});
|
||||
};
|
||||
renderApps();
|
||||
if ( ! isMobile.phone ) $(popover).find('.launch-search').focus();
|
||||
|
||||
fetchLaunchApps().done(apps => {
|
||||
if ( request !== launchAppsRequest || !popover.isConnected ) return;
|
||||
window.launch_apps = apps;
|
||||
renderApps();
|
||||
$(popover).find('.launch-search').trigger('change');
|
||||
}).fail(logRefreshFailure);
|
||||
|
||||
$(popover).on('click', function () {
|
||||
// close other context menus
|
||||
$('.context-menu').fadeOut(200, function () {
|
||||
$(this).remove();
|
||||
$('.launch-app-selected').removeClass('launch-app-selected');
|
||||
});
|
||||
});
|
||||
|
||||
$(popover).on('contextmenu taphold', function (e) {
|
||||
if ( ! e.target.closest('.launch-search') ) {
|
||||
e.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
$(document).on('contextmenu taphold', '.start-app', function (e) {
|
||||
if ( e.type === 'taphold' && !isMobile.phone && !isMobile.tablet )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
e.stopImmediatePropagation();
|
||||
e.preventDefault();
|
||||
|
||||
// close other context menus
|
||||
$('.context-menu').fadeOut(200, function () {
|
||||
$(this).remove();
|
||||
});
|
||||
|
||||
let items = [{
|
||||
html: i18n('open'),
|
||||
onClick: function () {
|
||||
$(e.currentTarget).trigger('click');
|
||||
},
|
||||
}];
|
||||
|
||||
$('.launch-app-selected').removeClass('launch-app-selected');
|
||||
$(e.currentTarget).parent().addClass('launch-app-selected');
|
||||
|
||||
// Determine pin state
|
||||
const $existingTaskbarItem = $(`.taskbar-item[data-app="${e.currentTarget.dataset.appName}"]`);
|
||||
const isPinned = $existingTaskbarItem.length > 0 && $existingTaskbarItem.attr('data-keep-in-taskbar') === 'true';
|
||||
|
||||
items.push({
|
||||
html: i18n('add_to_desktop'),
|
||||
onClick: async function () {
|
||||
try {
|
||||
const fileName = `${e.currentTarget.dataset.appTitle}.app`;
|
||||
const content = JSON.stringify({
|
||||
app: e.currentTarget.dataset.appName,
|
||||
title: e.currentTarget.dataset.appTitle,
|
||||
icon: e.currentTarget.dataset.appIcon,
|
||||
});
|
||||
await puter.fs.upload(new File([content], fileName), window.desktop_path, {
|
||||
generateThumbnails: true,
|
||||
thumbnailGenerator: createUploadThumbnailGenerator(),
|
||||
});
|
||||
} catch ( err ) {
|
||||
console.error('Failed to add shortcut to desktop:', err);
|
||||
// Consider showing a user-facing error notification
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
if ( ! isPinned ) {
|
||||
items.push({
|
||||
html: i18n('keep_in_taskbar'),
|
||||
onClick: function () {
|
||||
const $taskbarItem = $(`.taskbar-item[data-app="${e.currentTarget.dataset.appName}"]`);
|
||||
if ( $taskbarItem.length === 0 ) {
|
||||
// No taskbar item yet: create a new pinned one
|
||||
UITaskbarItem({
|
||||
icon: e.currentTarget.dataset.appIcon,
|
||||
iconFallback: e.currentTarget.dataset.appIconFallback,
|
||||
app: e.currentTarget.dataset.appName,
|
||||
name: e.currentTarget.dataset.appTitle,
|
||||
keep_in_taskbar: true,
|
||||
});
|
||||
} else if ( $taskbarItem.attr('data-keep-in-taskbar') !== 'true' ) {
|
||||
// mark as pinned
|
||||
$taskbarItem.attr('data-keep-in-taskbar', 'true');
|
||||
}
|
||||
// Persist
|
||||
window.update_taskbar();
|
||||
},
|
||||
});
|
||||
} else {
|
||||
items.push({
|
||||
html: i18n('remove_from_taskbar'),
|
||||
onClick: function () {
|
||||
const $taskbarItem = $(`.taskbar-item[data-app="${e.currentTarget.dataset.appName}"]`);
|
||||
if ( $taskbarItem.length === 0 ) return; // nothing to do
|
||||
// Unpin
|
||||
$taskbarItem.attr('data-keep-in-taskbar', 'false');
|
||||
// If no open windows for this app, remove the item
|
||||
if ( $taskbarItem.attr('data-open-windows') === '0' ) {
|
||||
if ( window.remove_taskbar_item ) {
|
||||
window.remove_taskbar_item($taskbarItem.get(0));
|
||||
} else {
|
||||
$taskbarItem.remove();
|
||||
}
|
||||
}
|
||||
window.update_taskbar();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
UIContextMenu({
|
||||
items: items,
|
||||
});
|
||||
return false;
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
//---------------------------------------------
|
||||
// add `Explorer` to the taskbar
|
||||
//---------------------------------------------
|
||||
@@ -454,51 +195,9 @@ window.make_taskbar_sortable = function () {
|
||||
helper: 'clone',
|
||||
distance: 5,
|
||||
revert: 10,
|
||||
receive: function (event, ui) {
|
||||
if ( ! $(ui.item).hasClass('taskbar-item') ) {
|
||||
// if app is already in taskbar, cancel
|
||||
if ( $(`.taskbar-item[data-app="${$(ui.item).attr('data-app-name')}"]`).length !== 0 ) {
|
||||
$(this).sortable('cancel');
|
||||
$('.taskbar .start-app').remove();
|
||||
return;
|
||||
}
|
||||
}
|
||||
},
|
||||
update: function (event, ui) {
|
||||
if ( ! $(ui.item).hasClass('taskbar-item') ) {
|
||||
// if app is already in taskbar, cancel
|
||||
if ( $(`.taskbar-item[data-app="${$(ui.item).attr('data-app-name')}"]`).length !== 0 ) {
|
||||
$(this).sortable('cancel');
|
||||
$('.taskbar .start-app').remove();
|
||||
return;
|
||||
}
|
||||
|
||||
let item = UITaskbarItem({
|
||||
icon: $(ui.item).attr('data-app-icon'),
|
||||
iconFallback: $(ui.item).attr('data-app-icon-fallback'),
|
||||
app: $(ui.item).attr('data-app-name'),
|
||||
name: $(ui.item).attr('data-app-title'),
|
||||
append_to_taskbar: false,
|
||||
keep_in_taskbar: true,
|
||||
onClick: function () {
|
||||
let open_window_count = parseInt($(`.taskbar-item[data-app="${$(ui.item).attr('data-app-name')}"]`).attr('data-open-windows'));
|
||||
if ( open_window_count === 0 ) {
|
||||
launch_app({
|
||||
name: $(ui.item).attr('data-app-name'),
|
||||
});
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
});
|
||||
let el = ($(item).detach());
|
||||
$(el).insertAfter(ui.item);
|
||||
$(el).show();
|
||||
$(ui.item).removeItems();
|
||||
window.update_taskbar();
|
||||
}
|
||||
// only proceed to update DB if the item sorted was a pinned item otherwise no point in updating the taskbar in DB
|
||||
else if ( $(ui.item).attr('data-keep-in-taskbar') === 'true' ) {
|
||||
// only update the DB if the sorted item is pinned
|
||||
if ( $(ui.item).attr('data-keep-in-taskbar') === 'true' ) {
|
||||
window.update_taskbar();
|
||||
}
|
||||
},
|
||||
|
||||
@@ -22,28 +22,22 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest';
|
||||
import jQuery from '../lib/jquery-3.6.1/jquery-3.6.1.min.js';
|
||||
|
||||
vi.mock('../helpers/launchApp.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./UIContextMenu.js', () => ({ default: vi.fn() }));
|
||||
|
||||
globalThis.$ = globalThis.jQuery = jQuery;
|
||||
globalThis.i18n = (key) => (key === 'start' ? 'Start' : key);
|
||||
globalThis.i18n = (key) => key;
|
||||
globalThis.html_encode = (value) => String(value ?? '');
|
||||
globalThis.isMobile = { phone: false, tablet: false };
|
||||
await import('../lib/jquery-ui-1.13.2/jquery-ui.js');
|
||||
const { default: UITaskbar } = await import('./UITaskbar.js');
|
||||
|
||||
const app = { name: 'test-app', uuid: 'test-uid', title: 'Test app' };
|
||||
let launchApps;
|
||||
let start;
|
||||
let requests;
|
||||
|
||||
afterEach(() => {
|
||||
$('.popover-launcher, .taskbar').remove();
|
||||
$('.taskbar').remove();
|
||||
$(document).off();
|
||||
$(window).off();
|
||||
document.body.innerHTML = '';
|
||||
delete window.launch_apps;
|
||||
vi.unstubAllGlobals();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
@@ -56,126 +50,26 @@ beforeEach(async () => {
|
||||
api_origin: 'http://api.test',
|
||||
auth_token: 'test-token',
|
||||
icons: {},
|
||||
user: {},
|
||||
launch_recent_apps_count: 10,
|
||||
user: { taskbar_items: [{ name: 'notes', title: 'Notes' }] },
|
||||
trash_path: '/test/Trash',
|
||||
});
|
||||
vi.stubGlobal('puter', {
|
||||
kv: { get: async () => 'bottom' },
|
||||
fs: { stat: async () => ({ is_empty: true }) },
|
||||
});
|
||||
launchApps = { recent: [app], recommended: [] };
|
||||
requests = [];
|
||||
$.ajaxTransport('+*', () => {
|
||||
let complete;
|
||||
const request = {
|
||||
send(headers, done) {
|
||||
complete = done;
|
||||
},
|
||||
abort: vi.fn(),
|
||||
resolve(data) {
|
||||
complete(
|
||||
200,
|
||||
'OK',
|
||||
{ text: JSON.stringify(data) },
|
||||
'Content-Type: application/json',
|
||||
);
|
||||
},
|
||||
};
|
||||
requests.push(request);
|
||||
return request;
|
||||
$.ajaxTransport('+*', (options) => {
|
||||
requests.push(options.url);
|
||||
return { send () {}, abort () {} };
|
||||
});
|
||||
await UITaskbar();
|
||||
requests[0].resolve(launchApps);
|
||||
start = $('.taskbar-item[data-name="Start"]');
|
||||
});
|
||||
|
||||
it.each([true, false])(
|
||||
'keeps cached search usable after a timeout, cached=%s',
|
||||
async (cached) => {
|
||||
if (!cached) window.launch_apps = [];
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
vi.useFakeTimers();
|
||||
start.trigger('click');
|
||||
await vi.advanceTimersByTimeAsync(30000);
|
||||
expect(requests.at(-1).abort).toHaveBeenCalledOnce();
|
||||
expect($('.launch-search')).toHaveLength(1);
|
||||
expect($('.start-app')).toHaveLength(cached ? 1 : 0);
|
||||
},
|
||||
);
|
||||
|
||||
function deferRefresh() {
|
||||
return (data) => requests.at(-1).resolve(data);
|
||||
}
|
||||
|
||||
it('refreshes reopened Start without losing cached tiles or search input', async () => {
|
||||
const survivor = {
|
||||
name: 'survivor',
|
||||
uuid: 'survivor-uid',
|
||||
title: 'Survivor',
|
||||
};
|
||||
launchApps.recent.push(survivor);
|
||||
start.trigger('click');
|
||||
requests.at(-1).resolve(launchApps);
|
||||
start.trigger('click');
|
||||
const resolve = deferRefresh();
|
||||
start.trigger('click');
|
||||
const input = $('.launch-search').get(0);
|
||||
expect(input).toBeDefined();
|
||||
expect($('.start-app[data-app-name="test-app"]')).toHaveLength(1);
|
||||
input.value = 'notes';
|
||||
const onChange = vi.fn();
|
||||
$(input).on('change', onChange);
|
||||
resolve({
|
||||
recent: [survivor],
|
||||
recommended: [{ name: 'notes', uuid: 'notes-uid', title: 'Notes' }],
|
||||
});
|
||||
await vi.waitFor(() =>
|
||||
expect($('.start-app[data-app-name="notes"]')).toHaveLength(1),
|
||||
);
|
||||
expect($('.launch-search').get(0)).toBe(input);
|
||||
expect(input.value).toBe('notes');
|
||||
expect(document.activeElement).toBe(input);
|
||||
expect(onChange).toHaveBeenCalledOnce();
|
||||
expect($('.start-app[data-app-name="survivor"]')).toHaveLength(1);
|
||||
expect($('.start-app[data-app-name="test-app"]')).toHaveLength(0);
|
||||
it('starts the taskbar at Explorer, followed by pinned apps and Trash', () => {
|
||||
const apps = $('.taskbar .taskbar-item').map((_, el) => el.dataset.app).get();
|
||||
expect(apps).toEqual(['explorer', 'separator', 'notes', 'separator', 'trash']);
|
||||
});
|
||||
|
||||
it('cancels closed menus and ignores their late responses', () => {
|
||||
start.trigger('click');
|
||||
const old = requests.at(-1);
|
||||
start.trigger('click');
|
||||
expect(old.abort).toHaveBeenCalledOnce();
|
||||
start.trigger('click');
|
||||
requests.at(-1).resolve({ recent: [], recommended: [] });
|
||||
old.resolve({ recent: [app], recommended: [] });
|
||||
expect(window.launch_apps.recent).toHaveLength(0);
|
||||
expect($('.start-app')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('cancels the startup request when Start opens', async () => {
|
||||
requests = [];
|
||||
document.body.innerHTML = '<div class="desktop"></div>';
|
||||
await UITaskbar();
|
||||
const startup = requests[0];
|
||||
$('.taskbar-item[data-name="Start"]').trigger('click');
|
||||
expect(startup.abort).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('hides apps the backend marks unlaunchable', () => {
|
||||
start.trigger('click');
|
||||
requests.at(-1).resolve({
|
||||
recent: [
|
||||
app,
|
||||
{
|
||||
name: 'reclaimed',
|
||||
uuid: 'reclaimed-uid',
|
||||
title: 'Reclaimed',
|
||||
index_url: null,
|
||||
privateAccess: { hasAccess: false },
|
||||
},
|
||||
],
|
||||
recommended: [],
|
||||
});
|
||||
expect($('.start-app[data-app-name="test-app"]')).toHaveLength(1);
|
||||
expect($('.start-app[data-app-name="reclaimed"]')).toHaveLength(0);
|
||||
it('does not fetch launch apps when the taskbar loads', () => {
|
||||
expect(requests.filter(url => url.includes('/get-launch-apps'))).toEqual([]);
|
||||
});
|
||||
@@ -31,7 +31,6 @@ function UITaskbarItem (options) {
|
||||
options.sortable = options.sortable ?? true;
|
||||
options.open_windows_count = options.open_windows_count ?? 0;
|
||||
options.lock_keep_in_taskbar = options.lock_keep_in_taskbar ?? false;
|
||||
options.append_to_taskbar = options.append_to_taskbar ?? true;
|
||||
options.before_trash = options.before_trash ?? false;
|
||||
|
||||
// The windows this item stands for: the user's own. An instance another
|
||||
@@ -78,28 +77,24 @@ function UITaskbarItem (options) {
|
||||
}
|
||||
h += '</div>';
|
||||
|
||||
if ( options.append_to_taskbar ) {
|
||||
if ( options.before_trash ) {
|
||||
if ( options.before_trash ) {
|
||||
$('.taskbar-sortable').append(h);
|
||||
} else {
|
||||
if ( options.sortable )
|
||||
{
|
||||
$('.taskbar-sortable').append(h);
|
||||
} else {
|
||||
if ( options.sortable )
|
||||
}
|
||||
else {
|
||||
// if taskbar-sortable is empty then append before it
|
||||
if ( $('.taskbar-sortable').children().length === 0 )
|
||||
{
|
||||
$('.taskbar-sortable').append(h);
|
||||
$('.taskbar').find('.taskbar-sortable').before(h);
|
||||
}
|
||||
else {
|
||||
// if taskbar-sortable is empty then append before it
|
||||
if ( $('.taskbar-sortable').children().length === 0 )
|
||||
{
|
||||
$('.taskbar').find('.taskbar-sortable').before(h);
|
||||
}
|
||||
else
|
||||
{
|
||||
$('.taskbar').find('.taskbar-sortable').after(h);
|
||||
}
|
||||
else
|
||||
{
|
||||
$('.taskbar').find('.taskbar-sortable').after(h);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$('body').prepend(h);
|
||||
}
|
||||
|
||||
const el_taskbar_item = document.querySelector(`#taskbar-item-${tray_item_id}`);
|
||||
@@ -123,13 +118,6 @@ function UITaskbarItem (options) {
|
||||
return;
|
||||
}
|
||||
|
||||
// if this is for the launcher popover, and it's mobile, and has-open-popover, close the popover
|
||||
if ( $(el_taskbar_item).attr('data-name') === 'Start'
|
||||
&& (isMobile.phone || isMobile.tablet) && $(el_taskbar_item).hasClass('has-open-popover') ) {
|
||||
$('.popover').remove();
|
||||
return;
|
||||
}
|
||||
|
||||
// If this item has an open context menu, don't do anything
|
||||
if ( $(el_taskbar_item).hasClass('has-open-contextmenu') )
|
||||
{
|
||||
|
||||
@@ -551,12 +551,6 @@ async function UIWindow (options) {
|
||||
backdrop_zindex = taskbar_zindex > zindex ? taskbar_zindex : zindex;
|
||||
}
|
||||
|
||||
// dominant backdrop will cover over toolbar as well
|
||||
if ( options.backdrop_covers_toolbar )
|
||||
{
|
||||
backdrop_zindex = 999999;
|
||||
}
|
||||
|
||||
h = `<div class="window-backdrop" style="z-index:${backdrop_zindex};">${ h }</div>`;
|
||||
}
|
||||
|
||||
@@ -1952,7 +1946,6 @@ async function UIWindow (options) {
|
||||
snap_trigger_timeout = undefined;
|
||||
}
|
||||
hideSnapPlaceholder();
|
||||
$('.toolbar').css('pointer-events', 'none');
|
||||
// if window is snapped, unsnap it and reset its position to where it was before snapping
|
||||
if ( options.is_resizable && window_is_snapped ) {
|
||||
window_is_snapped = false;
|
||||
@@ -2047,7 +2040,6 @@ async function UIWindow (options) {
|
||||
|
||||
$(el_window_app_iframe).css('pointer-events', 'all');
|
||||
$('.window').css('pointer-events', 'initial');
|
||||
$('.toolbar').css('pointer-events', 'auto');
|
||||
|
||||
if ( options.is_resizable && snap_placeholder_active && !window_is_snapped ) {
|
||||
window_will_snap = true;
|
||||
@@ -3846,11 +3838,6 @@ window.scale_window = (el_window) => {
|
||||
|
||||
// Use taskbar position-aware window positioning
|
||||
window.update_maximized_window_for_taskbar(el_window);
|
||||
|
||||
// hide toolbar
|
||||
if ( !isMobile.phone && !isMobile.tablet ) {
|
||||
window.hide_toolbar();
|
||||
}
|
||||
}
|
||||
//shrink
|
||||
else {
|
||||
|
||||
@@ -1,103 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { UIColorPickerWidget } from './UIColorPickerWidget.js';
|
||||
import UIWindow from './UIWindow.js';
|
||||
|
||||
async function UIWindowColorPicker (options) {
|
||||
// set sensible defaults
|
||||
if ( arguments.length > 0 ) {
|
||||
// if first argument is a string, then assume it is the default color
|
||||
if ( window.isString(arguments[0]) ) {
|
||||
options = {};
|
||||
options.default = arguments[0];
|
||||
}
|
||||
}
|
||||
options = options ?? {};
|
||||
|
||||
return new Promise(async (resolve) => {
|
||||
let colorPickerWidget;
|
||||
|
||||
let h = '';
|
||||
h += '<div>';
|
||||
h += '<div style="padding: 20px; border-bottom: 1px solid #ced7e1; width: 100%; box-sizing: border-box;">';
|
||||
// picker
|
||||
h += '<div style="padding: 0; margin-bottom: 20px;">';
|
||||
h += '<div class="picker"></div>';
|
||||
h += '</div>';
|
||||
|
||||
// Select button
|
||||
h += `<button class="select-btn button button-primary button-block button-normal">${i18n('select')}</button>`;
|
||||
h += '</form>';
|
||||
h += '</div>';
|
||||
h += '</div>';
|
||||
|
||||
const el_window = await UIWindow({
|
||||
title: i18n('select_color'),
|
||||
app: 'color-picker',
|
||||
single_instance: true,
|
||||
icon: null,
|
||||
uid: null,
|
||||
is_dir: false,
|
||||
body_content: h,
|
||||
has_head: true,
|
||||
selectable_body: false,
|
||||
draggable_body: false,
|
||||
allow_context_menu: false,
|
||||
is_draggable: true,
|
||||
is_droppable: false,
|
||||
is_resizable: false,
|
||||
stay_on_top: false,
|
||||
allow_native_ctxmenu: true,
|
||||
allow_user_select: true,
|
||||
...options.window_options,
|
||||
width: 350,
|
||||
dominant: true,
|
||||
on_close: async () => {
|
||||
resolve(false);
|
||||
},
|
||||
onAppend: function (window) {
|
||||
colorPickerWidget = UIColorPickerWidget($(window).find('.picker'), {
|
||||
default: options.defaultValue ?? options.defaultColor ?? options.default ?? '#f00',
|
||||
});
|
||||
},
|
||||
window_class: 'window-login',
|
||||
window_css: {
|
||||
height: 'initial',
|
||||
},
|
||||
body_css: {
|
||||
width: 'initial',
|
||||
padding: '0',
|
||||
'background-color': 'rgba(231, 238, 245, .95)',
|
||||
'backdrop-filter': 'blur(3px)',
|
||||
},
|
||||
});
|
||||
|
||||
$(el_window).find('.select-btn').on('click', function (e) {
|
||||
resolve({ color: colorPickerWidget.getHex8String() });
|
||||
$(el_window).close();
|
||||
});
|
||||
$(el_window).find('.font-selector').on('click', function (e) {
|
||||
$(el_window).find('.font-selector').removeClass('font-selector-active');
|
||||
$(this).addClass('font-selector-active');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export default UIWindowColorPicker;
|
||||
@@ -1,217 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import UIWindow from './UIWindow.js';
|
||||
|
||||
async function UIWindowDesktopBGSettings (options) {
|
||||
options = options ?? {};
|
||||
|
||||
return new Promise(async (resolve) => {
|
||||
let h = '';
|
||||
const original_background_css = $('body').attr('style');
|
||||
let bg_url = window.desktop_bg_url,
|
||||
bg_color = window.desktop_bg_color,
|
||||
bg_fit = window.desktop_bg_fit;
|
||||
|
||||
h += '<div style="padding: 10px; border-bottom: 1px solid #ced7e1;">';
|
||||
|
||||
// type
|
||||
h += `<label>${i18n('background')}:</label>`;
|
||||
h += '<select class="desktop-bg-type" style="width: 150px; margin-bottom: 20px;">';
|
||||
h += `<option value="default">${i18n('default')}</option>`;
|
||||
h += `<option value="picture">${i18n('picture')}</option>`;
|
||||
h += `<option value="color">${i18n('color')}</option>`;
|
||||
h += '</select>';
|
||||
|
||||
// Picture
|
||||
h += '<div class="desktop-bg-settings-wrapper desktop-bg-settings-picture">';
|
||||
h += `<label>${i18n('image')}:</label>`;
|
||||
h += `<button class="button button-default button-small browse">${i18n('browse')}</button>`;
|
||||
h += `<label style="margin-top: 20px;">${i18n('fit')}:</label>`;
|
||||
h += '<select class="desktop-bg-fit" style="width: 150px;">';
|
||||
h += `<option value="cover">${i18n('cover')}</option>`;
|
||||
h += `<option value="center">${i18n('center')}</option>`;
|
||||
h += `<option value="contain">${i18n('contain')}</option>`;
|
||||
h += `<option value="repeat">${i18n('repeat')}</option>`;
|
||||
h += '</select>';
|
||||
h += '</div>';
|
||||
|
||||
// Color
|
||||
h += '<div class="desktop-bg-settings-wrapper desktop-bg-settings-color">';
|
||||
h += `<label>${i18n('color')}:</label>`;
|
||||
h += '<div class="desktop-bg-color-blocks">';
|
||||
h += '<div class="desktop-bg-color-block" data-color="#4F7BB5" style="background-color: #4F7BB5"></div>';
|
||||
h += '<div class="desktop-bg-color-block" data-color="#545554" style="background-color: #545554"></div>';
|
||||
h += '<div class="desktop-bg-color-block" data-color="#F5D3CE" style="background-color: #F5D3CE"></div>';
|
||||
h += '<div class="desktop-bg-color-block" data-color="#52A758" style="background-color: #52A758"></div>';
|
||||
h += '<div class="desktop-bg-color-block" data-color="#ad3983" style="background-color: #ad3983"></div>';
|
||||
h += '<div class="desktop-bg-color-block" data-color="#ffffff" style="background-color: #ffffff"></div>';
|
||||
h += '<div class="desktop-bg-color-block" data-color="#000000" style="background-color: #000000"></div>';
|
||||
h += '<div class="desktop-bg-color-block" data-color="#454545" style="background-color: #454545"></div>';
|
||||
h += `<div class="desktop-bg-color-block desktop-bg-color-block-palette" data-color="" style="background-image: url(${window.icons['palette.svg']});
|
||||
background-repeat: no-repeat;
|
||||
background-size: contain;
|
||||
background-position: center;"><input type="color" style="width:25px; height: 25px; opacity:0;"></div>`;
|
||||
h += '</div>';
|
||||
h += '</div>';
|
||||
|
||||
h += '<div style="padding-top: 5px; overflow:hidden; margin-top: 25px; border-top: 1px solid #CCC;">';
|
||||
h += `<button class="button button-primary apply" style="float:right;">${i18n('apply')}</button>`;
|
||||
h += `<button class="button button-default cancel" style="float:right; margin-right: 10px;">${i18n('cancel')}</button>`;
|
||||
h += '</div>';
|
||||
|
||||
h += '</div>';
|
||||
|
||||
const el_window = await UIWindow({
|
||||
title: i18n('change_desktop_background'),
|
||||
icon: null,
|
||||
uid: null,
|
||||
is_dir: false,
|
||||
body_content: h,
|
||||
has_head: true,
|
||||
selectable_body: false,
|
||||
draggable_body: false,
|
||||
allow_context_menu: false,
|
||||
is_resizable: false,
|
||||
is_droppable: false,
|
||||
init_center: true,
|
||||
allow_native_ctxmenu: true,
|
||||
allow_user_select: true,
|
||||
onAppend: function (this_window) {
|
||||
$(this_window).find('.access-recipient').focus();
|
||||
},
|
||||
window_class: 'window-give-access',
|
||||
width: 350,
|
||||
window_css: {
|
||||
height: 'initial',
|
||||
},
|
||||
body_css: {
|
||||
width: 'initial',
|
||||
height: '100%',
|
||||
'background-color': 'rgb(245 247 249)',
|
||||
'backdrop-filter': 'blur(3px)',
|
||||
},
|
||||
...options.window_options,
|
||||
});
|
||||
|
||||
const default_wallpaper = (window.gui_env === 'prod') ? 'https://puter-assets.b-cdn.net/wallpaper.webp' : '/images/wallpaper.webp';
|
||||
$(el_window).find('.desktop-bg-settings-wrapper').hide();
|
||||
|
||||
if ( window.desktop_bg_url === default_wallpaper ) {
|
||||
$(el_window).find('.desktop-bg-type').val('default');
|
||||
} else if ( window.desktop_bg_url !== undefined && window.desktop_bg_url !== null ) {
|
||||
$(el_window).find('.desktop-bg-settings-picture').show();
|
||||
$(el_window).find('.desktop-bg-type').val('picture');
|
||||
} else if ( window.desktop_bg_color !== undefined && window.desktop_bg_color !== null ) {
|
||||
$(el_window).find('.desktop-bg-settings-color').show();
|
||||
$(el_window).find('.desktop-bg-type').val('color');
|
||||
} else {
|
||||
// Default fallback if no specific wallpaper settings are detected
|
||||
$(el_window).find('.desktop-bg-type').val('default');
|
||||
}
|
||||
|
||||
$(el_window).find('.desktop-bg-color-block:not(.desktop-bg-color-block-palette').on('click', async function (e) {
|
||||
window.set_desktop_background({ color: $(this).attr('data-color') });
|
||||
});
|
||||
$(el_window).find('.desktop-bg-color-block-palette input').on('change', async function (e) {
|
||||
window.set_desktop_background({ color: $(this).val() });
|
||||
});
|
||||
$(el_window).on('file_opened', function (e) {
|
||||
let selected_file = Array.isArray(e.detail) ? e.detail[0] : e.detail;
|
||||
const fit = $(el_window).find('.desktop-bg-fit').val();
|
||||
bg_url = selected_file.read_url;
|
||||
bg_fit = fit;
|
||||
bg_color = undefined;
|
||||
window.set_desktop_background({ url: bg_url, fit: bg_fit });
|
||||
});
|
||||
|
||||
$(el_window).find('.desktop-bg-fit').on('change', function (e) {
|
||||
const fit = $(this).val();
|
||||
bg_fit = fit;
|
||||
window.set_desktop_background({ fit: fit });
|
||||
});
|
||||
|
||||
$(el_window).find('.desktop-bg-type').on('change', function (e) {
|
||||
const type = $(this).val();
|
||||
$(el_window).find('.desktop-bg-settings-wrapper').hide();
|
||||
if ( type === 'picture' ) {
|
||||
$(el_window).find('.desktop-bg-settings-picture').show();
|
||||
} else if ( type === 'color' ) {
|
||||
$(el_window).find('.desktop-bg-settings-color').show();
|
||||
} else if ( type === 'default' ) {
|
||||
bg_color = undefined;
|
||||
bg_fit = 'cover';
|
||||
window.set_desktop_background({ url: default_wallpaper, fit: bg_fit });
|
||||
}
|
||||
});
|
||||
|
||||
$(el_window).find('.apply').on('click', async function (e) {
|
||||
// /set-desktop-bg
|
||||
try {
|
||||
$.ajax({
|
||||
url: `${window.api_origin }/set-desktop-bg`,
|
||||
type: 'POST',
|
||||
data: JSON.stringify({
|
||||
url: window.desktop_bg_url,
|
||||
color: window.desktop_bg_color,
|
||||
fit: window.desktop_bg_fit,
|
||||
}),
|
||||
async: true,
|
||||
contentType: 'application/json',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${window.auth_token}`,
|
||||
},
|
||||
statusCode: {
|
||||
401: function (xhr) {
|
||||
window.handle401(xhr);
|
||||
},
|
||||
},
|
||||
});
|
||||
$(el_window).close();
|
||||
resolve(true);
|
||||
} catch ( err ) {
|
||||
// Ignore
|
||||
}
|
||||
});
|
||||
|
||||
$(el_window).find('.browse').on('click', function () {
|
||||
// open dialog
|
||||
UIWindow({
|
||||
path: `/${ window.user.username }/Desktop`,
|
||||
// this is the uuid of the window to which this dialog will return
|
||||
parent_uuid: $(el_window).attr('data-element_uuid'),
|
||||
allowed_file_types: ['image/*'],
|
||||
show_maximize_button: false,
|
||||
show_minimize_button: false,
|
||||
title: i18n('window_title_open'),
|
||||
is_dir: true,
|
||||
is_openFileDialog: true,
|
||||
selectable_body: false,
|
||||
});
|
||||
});
|
||||
|
||||
$(el_window).find('.cancel').on('click', function () {
|
||||
$('body').attr('style', original_background_css);
|
||||
$(el_window).close();
|
||||
resolve(true);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export default UIWindowDesktopBGSettings;
|
||||
@@ -1,233 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import {
|
||||
ATTACHMENT_ACCEPT_ATTRIBUTE,
|
||||
MAX_ATTACHMENTS,
|
||||
MAX_ATTACHMENT_BYTES,
|
||||
MAX_TOTAL_ATTACHMENT_BYTES,
|
||||
checkAttachment,
|
||||
} from '../helpers/contact_attachments.js';
|
||||
import UIWindow from './UIWindow.js';
|
||||
|
||||
const MB = 1024 * 1024;
|
||||
|
||||
// Numbers interpolated into each error message, taken from the enforced limits.
|
||||
const ERROR_VALUES = {
|
||||
contact_us_attachment_too_many: [MAX_ATTACHMENTS],
|
||||
contact_us_attachment_too_large: [MAX_ATTACHMENT_BYTES / MB],
|
||||
contact_us_attachment_total_too_large: [MAX_TOTAL_ATTACHMENT_BYTES / MB],
|
||||
};
|
||||
|
||||
/**
|
||||
* Puter's own Contact Us form, delivered to support (UIWindowAppFeedback is the
|
||||
* one for third-party apps). Attachments are posted as multipart form data; the
|
||||
* client-side checks only fail fast, the server enforces the limits.
|
||||
*/
|
||||
async function UIWindowFeedback (options) {
|
||||
return new Promise(async (resolve) => {
|
||||
options = options ?? {};
|
||||
|
||||
// Staged files; kept out of the DOM so re-rendering chips keeps them.
|
||||
let attachments = [];
|
||||
let sending = false;
|
||||
|
||||
let h = '';
|
||||
h += '<div style="padding: 20px; margin-top: 0;">';
|
||||
// success
|
||||
h += '<div class="feedback-sent-success">';
|
||||
h += `<img src="${html_encode(window.icons['c-check.svg'])}" style="width:50px; height:50px; display: block; margin:10px auto;">`;
|
||||
h += `<p style="text-align:center; margin-bottom:10px; color: #005300; padding: 10px;">${i18n('feedback_sent_confirmation')}</p>`;
|
||||
h += '</div>';
|
||||
// form
|
||||
h += '<div class="feedback-form">';
|
||||
h += `<p style="margin-top:0; font-size: 15px; -webkit-font-smoothing: antialiased;">${i18n('feedback_c2a')}</p>`;
|
||||
h += '<textarea class="feedback-message" style="width:100%; height: 200px; padding: 10px; box-sizing: border-box;"></textarea>';
|
||||
// attachments
|
||||
h += '<div class="feedback-attachments">';
|
||||
h += `<input type="file" class="feedback-attach-input" accept="${html_encode(ATTACHMENT_ACCEPT_ATTRIBUTE)}" multiple style="display:none;">`;
|
||||
h += `<button type="button" class="button button-small feedback-attach-btn">${i18n('contact_us_attach')}</button>`;
|
||||
h += `<span class="feedback-attach-hint">${i18n('contact_us_attach_hint', [MAX_ATTACHMENTS, MAX_ATTACHMENT_BYTES / MB])}</span>`;
|
||||
h += '<ul class="feedback-attachment-list"></ul>';
|
||||
h += '</div>';
|
||||
h += '<p class="feedback-error" role="alert" style="display:none;"></p>';
|
||||
h += `<button class="button button-primary send-feedback-btn" style="float: right; margin-bottom: 15px; margin-top: 10px;">${i18n('send')}</button>`;
|
||||
h += '</div>';
|
||||
h += '</div>';
|
||||
|
||||
const el_window = await UIWindow({
|
||||
title: i18n('contact_us'),
|
||||
app: 'feedback',
|
||||
single_instance: true,
|
||||
icon: null,
|
||||
uid: null,
|
||||
is_dir: false,
|
||||
body_content: h,
|
||||
has_head: true,
|
||||
selectable_body: false,
|
||||
draggable_body: false,
|
||||
allow_context_menu: false,
|
||||
is_resizable: false,
|
||||
is_droppable: false,
|
||||
init_center: true,
|
||||
allow_native_ctxmenu: false,
|
||||
allow_user_select: false,
|
||||
width: 380,
|
||||
height: 'auto',
|
||||
dominant: true,
|
||||
show_in_taskbar: false,
|
||||
...options.window_options,
|
||||
onAppend: function (this_window) {
|
||||
$(this_window).find('.feedback-message').get(0).focus({ preventScroll: true });
|
||||
},
|
||||
window_class: 'window-feedback',
|
||||
body_css: {
|
||||
width: 'initial',
|
||||
height: '100%',
|
||||
'background-color': 'rgb(245 247 249)',
|
||||
'backdrop-filter': 'blur(3px)',
|
||||
},
|
||||
});
|
||||
|
||||
const $error = $(el_window).find('.feedback-error');
|
||||
// `.html()` rather than `.text()`: i18n() html-encodes what it returns,
|
||||
// so text() would render the entities literally.
|
||||
const showError = (key) => $error.html(i18n(key, ERROR_VALUES[key] ?? [])).show();
|
||||
const clearError = () => $error.hide().empty();
|
||||
|
||||
// -- Attachments -------------------------------------------------
|
||||
|
||||
const renderAttachments = () => {
|
||||
const $list = $(el_window).find('.feedback-attachment-list').empty();
|
||||
attachments.forEach((file, index) => {
|
||||
const removeLabel = i18n('contact_us_attachment_remove');
|
||||
const $item = $(
|
||||
'<li class="feedback-attachment">' +
|
||||
`<span class="feedback-attachment-name" title="${html_encode(file.name)}">${html_encode(file.name)}</span>` +
|
||||
`<span class="feedback-attachment-size">${html_encode(window.byte_format(file.size))}</span>` +
|
||||
`<button type="button" class="feedback-attachment-remove" aria-label="${removeLabel}" title="${removeLabel}">×</button>` +
|
||||
'</li>',
|
||||
);
|
||||
$item.find('.feedback-attachment-remove').on('click', () => {
|
||||
if ( sending ) return;
|
||||
attachments.splice(index, 1);
|
||||
clearError();
|
||||
renderAttachments();
|
||||
});
|
||||
$list.append($item);
|
||||
});
|
||||
// Nothing left to add once the count cap is reached.
|
||||
$(el_window).find('.feedback-attach-btn')
|
||||
.prop('disabled', sending || attachments.length >= MAX_ATTACHMENTS);
|
||||
};
|
||||
|
||||
const addFiles = (files) => {
|
||||
if ( sending ) return;
|
||||
let rejection = null;
|
||||
for ( const file of files ) {
|
||||
const verdict = checkAttachment(file, attachments);
|
||||
if ( ! verdict.ok ) {
|
||||
// Report the first rejection but keep the files that fit.
|
||||
rejection = rejection ?? verdict.error;
|
||||
continue;
|
||||
}
|
||||
attachments.push(file);
|
||||
}
|
||||
if ( rejection ) showError(rejection);
|
||||
else clearError();
|
||||
renderAttachments();
|
||||
};
|
||||
|
||||
const $fileInput = $(el_window).find('.feedback-attach-input');
|
||||
$(el_window).find('.feedback-attach-btn').on('click', () => $fileInput.trigger('click'));
|
||||
$fileInput.on('change', function () {
|
||||
addFiles(Array.from(this.files ?? []));
|
||||
// Reset so re-picking the same file fires `change` again.
|
||||
this.value = '';
|
||||
});
|
||||
|
||||
// Caught here before UIWindow's body-level drop handler sees it.
|
||||
const $form = $(el_window).find('.feedback-form');
|
||||
$form.on('dragover dragenter', (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if ( ! sending ) $form.addClass('feedback-form-dragover');
|
||||
});
|
||||
$form.on('dragleave dragend', () => $form.removeClass('feedback-form-dragover'));
|
||||
$form.on('drop', (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
$form.removeClass('feedback-form-dragover');
|
||||
addFiles(Array.from(e.originalEvent?.dataTransfer?.files ?? []));
|
||||
});
|
||||
|
||||
// -- Submit --------------------------------------------------------
|
||||
|
||||
const setSending = (value) => {
|
||||
sending = value;
|
||||
$(el_window).find('.send-feedback-btn').prop('disabled', value);
|
||||
$(el_window).find('.feedback-attachment-remove').prop('disabled', value);
|
||||
renderAttachments();
|
||||
};
|
||||
|
||||
$(el_window).find('.send-feedback-btn').on('click', async function () {
|
||||
if ( sending ) return;
|
||||
const message = $(el_window).find('.feedback-message').val();
|
||||
if ( ! message || ! message.trim() ) {
|
||||
showError('contact_us_message_required');
|
||||
return;
|
||||
}
|
||||
|
||||
clearError();
|
||||
setSending(true);
|
||||
try {
|
||||
const body = new FormData();
|
||||
body.append('message', message);
|
||||
for ( const file of attachments ) {
|
||||
body.append('attachments', file, file.name);
|
||||
}
|
||||
|
||||
// No Content-Type: the browser sets it with the boundary.
|
||||
const resp = await fetch(`${window.api_origin}/contactUs`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${window.auth_token}`,
|
||||
},
|
||||
body,
|
||||
});
|
||||
if ( ! resp.ok ) {
|
||||
showError(resp.status === 429 ? 'contact_us_rate_limited' : 'contact_us_error');
|
||||
return;
|
||||
}
|
||||
$(el_window).find('.feedback-form').hide();
|
||||
$(el_window).find('.feedback-sent-success').show(100);
|
||||
} catch ( e ) {
|
||||
console.error('contact-us: submit failed', e);
|
||||
showError('contact_us_error');
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
});
|
||||
|
||||
renderAttachments();
|
||||
resolve(el_window);
|
||||
});
|
||||
}
|
||||
|
||||
export default UIWindowFeedback;
|
||||
@@ -1,192 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import UIWindow from './UIWindow.js';
|
||||
import UIContextMenu from './UIContextMenu.js';
|
||||
import UIAlert from './UIAlert.js';
|
||||
|
||||
async function UIWindowMyWebsites (options) {
|
||||
let h = '';
|
||||
h += '<div>';
|
||||
h += '</div>';
|
||||
|
||||
const el_window = await UIWindow({
|
||||
title: 'My Websites',
|
||||
app: 'my-websites',
|
||||
single_instance: true,
|
||||
icon: null,
|
||||
uid: null,
|
||||
is_dir: false,
|
||||
body_content: h,
|
||||
has_head: true,
|
||||
selectable_body: false,
|
||||
draggable_body: false,
|
||||
allow_context_menu: false,
|
||||
is_resizable: false,
|
||||
is_droppable: false,
|
||||
init_center: true,
|
||||
allow_native_ctxmenu: true,
|
||||
allow_user_select: true,
|
||||
width: 400,
|
||||
dominant: false,
|
||||
body_css: {
|
||||
padding: '10px',
|
||||
width: 'initial',
|
||||
'background-color': 'rgba(231, 238, 245)',
|
||||
'backdrop-filter': 'blur(3px)',
|
||||
'padding-bottom': 0,
|
||||
'height': '351px',
|
||||
'box-sizing': 'border-box',
|
||||
},
|
||||
});
|
||||
|
||||
// /sites
|
||||
let init_ts = Date.now();
|
||||
let loading = setTimeout(function () {
|
||||
$(el_window).find('.window-body').html(`<p style="text-align: center;
|
||||
margin-top: 40px;
|
||||
margin-bottom: 50px;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
color: #596c7c;">${i18n('loading')}...</p>`);
|
||||
}, 1000);
|
||||
|
||||
puter.hosting.list().then(function (sites) {
|
||||
setTimeout(function () {
|
||||
// clear loading
|
||||
clearTimeout(loading);
|
||||
// user has sites
|
||||
if ( sites.length > 0 ) {
|
||||
let h = '';
|
||||
for ( let i = 0; i < sites.length; i++ ) {
|
||||
h += `<div class="mywebsites-card" data-uuid="${sites[i].uid}">`;
|
||||
h += `<a class="mywebsites-address-link" href="https://${sites[i].subdomain}.puter.site" target="_blank">${sites[i].subdomain}.puter.site</a>`;
|
||||
h += `<img class="mywebsites-site-setting" data-site-uuid="${sites[i].uid}" src="${html_encode(window.icons['cog.svg'])}">`;
|
||||
// there is a directory associated with this site
|
||||
if ( sites[i].root_dir ) {
|
||||
h += `<p class="mywebsites-dir-path" data-path="${html_encode(sites[i].root_dir.path)}" data-name="${html_encode(sites[i].root_dir.name)}" data-uuid="${sites[i].root_dir.id}">`;
|
||||
h += `<img src="${html_encode(window.icons['folder.svg'])}">`;
|
||||
h += `${html_encode(sites[i].root_dir.path)}`;
|
||||
h += '</p>';
|
||||
h += '<p style="margin-bottom:0; margin-top: 20px; font-size: 13px;">';
|
||||
h += `<span class="mywebsites-dis-dir" data-dir-uuid="${html_encode(sites[i].root_dir.id)}" data-site-subdomain="${html_encode(sites[i].subdomain)}" data-site-uuid="${html_encode(sites[i].uid)}">`;
|
||||
h += `<img style="width: 16px; margin-bottom: -2px; margin-right: 4px;" src="${html_encode(window.icons['plug.svg'])}">${i18n('disassociate_dir')}</span>`;
|
||||
h += '</p>';
|
||||
}
|
||||
h += `<p class="mywebsites-no-dir-notice" data-site-uuid="${html_encode(sites[i].uid)}" style="${sites[i].root_dir ? 'display:none;' : 'display:block;'}">${i18n('no_dir_associated_with_site')}</p>`;
|
||||
h += '</div>';
|
||||
}
|
||||
$(el_window).find('.window-body').html(h);
|
||||
}
|
||||
// has no sites
|
||||
else {
|
||||
$(el_window).find('.window-body').html(`<p style="text-align: center;
|
||||
margin-top: 40px;
|
||||
margin-bottom: 50px;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
color: #596c7c;">${i18n('no_websites_published')}</p>`);
|
||||
}
|
||||
}, Date.now() - init_ts < 1000 ? 0 : 2000);
|
||||
});
|
||||
}
|
||||
|
||||
$(document).on('click', '.mywebsites-dir-path', function (e) {
|
||||
e = e.target;
|
||||
UIWindow({
|
||||
path: $(e).attr('data-path'),
|
||||
title: $(e).attr('data-name'),
|
||||
icon: window.icons['folder.svg'],
|
||||
uid: $(e).attr('data-uuid'),
|
||||
is_dir: true,
|
||||
app: 'explorer',
|
||||
});
|
||||
});
|
||||
|
||||
$(document).on('click', '.mywebsites-site-setting', function (e) {
|
||||
const pos = e.target.getBoundingClientRect();
|
||||
UIContextMenu({
|
||||
parent_element: e.target,
|
||||
position: { top: pos.top + 25, left: pos.left - 193 },
|
||||
items: [
|
||||
//--------------------------------------------------
|
||||
// Release Address
|
||||
//--------------------------------------------------
|
||||
{
|
||||
html: 'Release Address',
|
||||
onClick: async function () {
|
||||
const alert_resp = await UIAlert({
|
||||
message: i18n('release_address_confirmation'),
|
||||
buttons: [
|
||||
{
|
||||
label: i18n('yes_release_it'),
|
||||
value: 'yes',
|
||||
type: 'primary',
|
||||
},
|
||||
{
|
||||
label: i18n('cancel'),
|
||||
},
|
||||
],
|
||||
});
|
||||
if ( alert_resp !== 'yes' ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
url: `${window.api_origin }/delete-site`,
|
||||
type: 'POST',
|
||||
data: JSON.stringify({
|
||||
site_uuid: $(e.target).attr('data-site-uuid'),
|
||||
}),
|
||||
async: false,
|
||||
contentType: 'application/json',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${window.auth_token}`,
|
||||
},
|
||||
statusCode: {
|
||||
401: function (xhr) {
|
||||
window.handle401(xhr);
|
||||
},
|
||||
},
|
||||
success: function () {
|
||||
$(`.mywebsites-card[data-uuid="${$(e.target).attr('data-site-uuid')}"]`).fadeOut();
|
||||
},
|
||||
});
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
$(document).on('click', '.mywebsites-dis-dir', function (e) {
|
||||
puter.hosting.delete(
|
||||
// dir
|
||||
$(e.target).attr('data-dir-uuid'),
|
||||
// hostname
|
||||
$(e.target).attr('data-site-subdomain'),
|
||||
// success
|
||||
function () {
|
||||
$(`.mywebsites-no-dir-notice[data-site-uuid="${$(e.target).attr('data-site-uuid')}"]`).show();
|
||||
$(`.mywebsites-dir-path[data-uuid="${$(e.target).attr('data-dir-uuid')}"]`).remove();
|
||||
// remove the website badge from all instances of the dir
|
||||
$(`.item[data-uid="${$(e.target).attr('data-dir-uuid')}"]`).find('.item-has-website-badge').fadeOut(300);
|
||||
$(e.target).hide();
|
||||
});
|
||||
});
|
||||
export default UIWindowMyWebsites;
|
||||
@@ -18,7 +18,6 @@
|
||||
*/
|
||||
|
||||
import UIWindow from './UIWindow.js';
|
||||
import UIWindowMyWebsites from './UIWindowMyWebsites.js';
|
||||
import { underPath } from '../helpers/pathElements.js';
|
||||
|
||||
async function UIWindowPublishWebsite (target_dir_uid, target_dir_name, target_dir_path) {
|
||||
@@ -122,12 +121,7 @@ async function UIWindowPublishWebsite (target_dir_uid, target_dir_name, target_d
|
||||
|
||||
} catch ( err ) {
|
||||
const errorMessage = err.message || (err.error && err.error.message) || 'An error occurred while publishing';
|
||||
$(el_window).find('.publish-website-error-msg').html(
|
||||
errorMessage + (
|
||||
err.error && err.error.code === 'subdomain_limit_reached' ?
|
||||
` <span class="manage-your-websites-link">${ i18n('manage_your_subdomains') }</span>` : ''
|
||||
),
|
||||
);
|
||||
$(el_window).find('.publish-website-error-msg').html(errorMessage);
|
||||
$(el_window).find('.publish-website-error-msg').fadeIn();
|
||||
// re-enable 'Publish' button
|
||||
$(el_window).find('.publish-btn').prop('disabled', false);
|
||||
@@ -139,8 +133,4 @@ async function UIWindowPublishWebsite (target_dir_uid, target_dir_name, target_d
|
||||
});
|
||||
}
|
||||
|
||||
$(document).on('click', '.manage-your-websites-link', async function (e) {
|
||||
UIWindowMyWebsites();
|
||||
});
|
||||
|
||||
export default UIWindowPublishWebsite;
|
||||
@@ -1,157 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import UIWindow from './UIWindow.js';
|
||||
import UIWindowMyWebsites from './UIWindowMyWebsites.js';
|
||||
import { underPath } from '../helpers/pathElements.js';
|
||||
|
||||
async function UIWindowPublishWorker (target_dir_uid, target_dir_name, target_dir_path) {
|
||||
let h = '';
|
||||
h += '<div class="window-publishWorker-content" style="padding: 20px; border-bottom: 1px solid #ced7e1;">';
|
||||
// success
|
||||
h += '<div class="window-publishWorker-success">';
|
||||
h += `<img src="${html_encode(window.icons['c-check.svg'])}" style="width:80px; height:80px; display: block; margin:10px auto;">`;
|
||||
h += `<p style="text-align:center;">${i18n('dir_published_as_website', `<strong>${html_encode(target_dir_name)}</strong>`, false)}<p>`;
|
||||
h += `<p style="text-align:center;"><a class="publishWorker-published-link" target="_blank"></a><img class="publishWorker-published-link-icon" src="${html_encode(window.icons['launch.svg'])}"></p>`;
|
||||
h += `<button class="button button-normal button-block button-primary publish-window-ok-btn" style="margin-top:20px;">${i18n('ok')}</button>`;
|
||||
h += '</div>';
|
||||
// form
|
||||
h += '<form class="window-publishWorker-form">';
|
||||
// error msg
|
||||
h += '<div class="publish-worker-error-msg"></div>';
|
||||
// worker name
|
||||
h += '<div style="overflow: hidden;">';
|
||||
h += `<label style="margin-bottom: 10px;">${i18n('pick_name_for_worker')}</label>`;
|
||||
h += `<div style="font-family: monospace;">${html_encode(window.extractProtocol(window.url))}://<input class="publish-worker-name" style="width:235px;" type="text" autocomplete="subdomain" spellcheck="false" autocorrect="off" autocapitalize="off" data-gramm_editor="false"/>${html_encode('.puter.work')}</div>`;
|
||||
h += '</div>';
|
||||
// uid
|
||||
h += `<input class="publishWebsiteTargetDirUID" type="hidden" value="${html_encode(target_dir_uid)}"/>`;
|
||||
// Advanced (collapsed by default)
|
||||
h += '<details class="publish-worker-advanced" style="margin: 16px 0;">';
|
||||
h += '<summary style="cursor: pointer; font-size: 13px; color: #5c6b7a; user-select: none;">Advanced</summary>';
|
||||
h += '<div style="margin-top: 12px; padding-left: 2px;">';
|
||||
h += '<label style="display: flex; align-items: center; gap: 8px; cursor: pointer; font-size: 13px;">';
|
||||
h += '<input type="checkbox" class="publish-worker-sandboxed" checked>';
|
||||
h += 'Sandboxed</label>';
|
||||
h += '</div>';
|
||||
h += '</details>';
|
||||
// Publish
|
||||
h += `<button class="publish-btn button button-action button-block button-normal">${i18n('publish')}</button>`;
|
||||
h += '</form>';
|
||||
h += '</div>';
|
||||
|
||||
const el_window = await UIWindow({
|
||||
title: i18n('window_title_publish_worker'),
|
||||
icon: null,
|
||||
uid: null,
|
||||
is_dir: false,
|
||||
body_content: h,
|
||||
has_head: true,
|
||||
selectable_body: false,
|
||||
draggable_body: false,
|
||||
allow_context_menu: false,
|
||||
is_resizable: false,
|
||||
is_droppable: false,
|
||||
init_center: true,
|
||||
allow_native_ctxmenu: true,
|
||||
allow_user_select: true,
|
||||
width: 450,
|
||||
dominant: true,
|
||||
onAppend: function (this_window) {
|
||||
$(this_window).find('.publish-worker-name').val(window.generate_identifier());
|
||||
$(this_window).find('.publish-worker-name').get(0).focus({ preventScroll: true });
|
||||
},
|
||||
window_class: 'window-publishWorker',
|
||||
window_css: {
|
||||
height: 'initial',
|
||||
},
|
||||
body_css: {
|
||||
width: 'initial',
|
||||
height: '100%',
|
||||
'background-color': 'rgb(245 247 249)',
|
||||
'backdrop-filter': 'blur(3px)',
|
||||
},
|
||||
});
|
||||
|
||||
$(el_window).find('.publish-btn').on('click', function (e) {
|
||||
// todo do some basic validation client-side
|
||||
|
||||
//Worker name
|
||||
let worker_name = $(el_window).find('.publish-worker-name').val();
|
||||
|
||||
// Store original text and replace with spinner
|
||||
const originalText = $(el_window).find('.publish-btn').text();
|
||||
$(el_window).find('.publish-btn').prop('disabled', true).html(`
|
||||
<div style="display: inline-block; margin-top: 10px; width: 16px; height: 16px; border: 2px solid #ffffff; border-radius: 50%; border-top: 2px solid transparent; animation: spin 1s linear infinite;"></div>
|
||||
`);
|
||||
|
||||
const sandboxed = $(el_window).find('.publish-worker-sandboxed').is(':checked');
|
||||
const createOptions = sandboxed ? { sandbox: true } : { sandbox: false };
|
||||
|
||||
puter.workers.create(
|
||||
worker_name,
|
||||
target_dir_path,
|
||||
createOptions,
|
||||
).then((res) => {
|
||||
let url = `https://${ worker_name }.puter.work`;
|
||||
$(el_window).find('.window-publishWorker-form').hide(100, function () {
|
||||
$(el_window).find('.publishWorker-published-link').attr('href', url);
|
||||
$(el_window).find('.publishWorker-published-link').text(url);
|
||||
$(el_window).find('.window-publishWorker-success').show(100);
|
||||
// $(`.item[data-uid="${target_dir_uid}"] .item-has-website-badge`).show();
|
||||
});
|
||||
|
||||
// find all items whose path starts with target_dir_path
|
||||
underPath('.item', target_dir_path).each(function () {
|
||||
// show the link badge
|
||||
// $(this).find('.item-has-website-url-badge').show();
|
||||
// update item's website_url attribute
|
||||
// $(this).attr('data-website_url', url + $(this).attr('data-path').substring(target_dir_path.length));
|
||||
});
|
||||
}).catch((err) => {
|
||||
let errorHtml;
|
||||
// Handle worker service errors (result.success === false)
|
||||
if ( ! (err instanceof Error) ) {
|
||||
// Handle regular API errors
|
||||
const error = err.error || err;
|
||||
errorHtml = error.message + (
|
||||
error.code === 'subdomain_limit_reached' ?
|
||||
` <span class="manage-your-websites-link">${ i18n('manage_your_subdomains') }</span>` : ''
|
||||
);
|
||||
} else {
|
||||
errorHtml = `<pre style="white-space: pre-wrap; font-family: monospace; font-size: 12px; margin: 0; text-align: left; font-family: monospace;">${html_encode(err.message)}</pre>`;
|
||||
}
|
||||
|
||||
$(el_window).find('.publish-worker-error-msg').html(errorHtml);
|
||||
$(el_window).find('.publish-worker-error-msg').fadeIn();
|
||||
// re-enable 'Publish' button and restore original text
|
||||
$(el_window).find('.publish-btn').prop('disabled', false).text(originalText);
|
||||
});
|
||||
});
|
||||
|
||||
$(el_window).find('.publish-window-ok-btn').on('click', function () {
|
||||
$(el_window).close();
|
||||
});
|
||||
}
|
||||
|
||||
$(document).on('click', '.manage-your-websites-link', async function (e) {
|
||||
UIWindowMyWebsites();
|
||||
});
|
||||
|
||||
export default UIWindowPublishWorker;
|
||||
@@ -1,88 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import Placeholder from '../util/Placeholder.js';
|
||||
import Flexer from './Components/Flexer.js';
|
||||
import UIQRCode from './UIQRCode.js';
|
||||
import UIWindow from './UIWindow.js';
|
||||
|
||||
async function UIWindowQR (options) {
|
||||
|
||||
options = options ?? {};
|
||||
|
||||
const placeholder_qr = Placeholder();
|
||||
|
||||
let h = '';
|
||||
// close button containing the multiplication sign
|
||||
h += '<div class="qr-code-window-close-btn generic-close-window-button"> × </div>';
|
||||
h += '<div class="otp-qr-code">';
|
||||
h += `<h1 style="text-align: center; font-size: 16px; padding: 10px; font-weight: 400; margin: -10px 10px 20px 10px; -webkit-font-smoothing: antialiased; color: #5f626d;">${
|
||||
i18n(options.message_i18n_key || 'scan_qr_generic')
|
||||
}</h1>`;
|
||||
h += '</div>';
|
||||
|
||||
h += placeholder_qr.html;
|
||||
|
||||
const el_window = await UIWindow({
|
||||
title: i18n('window_title_instant_login'),
|
||||
app: 'instant-login',
|
||||
single_instance: true,
|
||||
icon: null,
|
||||
uid: null,
|
||||
is_dir: false,
|
||||
body_content: h,
|
||||
has_head: false,
|
||||
selectable_body: false,
|
||||
allow_context_menu: false,
|
||||
is_resizable: false,
|
||||
is_droppable: false,
|
||||
init_center: true,
|
||||
allow_native_ctxmenu: false,
|
||||
allow_user_select: false,
|
||||
backdrop: true,
|
||||
width: 450,
|
||||
height: 'auto',
|
||||
dominant: true,
|
||||
show_in_taskbar: false,
|
||||
draggable_body: true,
|
||||
window_class: 'window-qr',
|
||||
body_css: {
|
||||
width: 'initial',
|
||||
height: '100%',
|
||||
'background-color': 'rgb(245 247 249)',
|
||||
'backdrop-filter': 'blur(3px)',
|
||||
padding: '50px 20px',
|
||||
},
|
||||
});
|
||||
|
||||
const el_qr = UIQRCode({
|
||||
value: options.text,
|
||||
size: 250,
|
||||
});
|
||||
|
||||
const component_flexer = new Flexer({
|
||||
children: [
|
||||
el_qr,
|
||||
],
|
||||
});
|
||||
|
||||
component_flexer.attach(placeholder_qr);
|
||||
}
|
||||
|
||||
export default UIWindowQR;
|
||||
@@ -1,308 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import UIWindow from './UIWindow.js';
|
||||
import path from '../lib/path.js';
|
||||
import UIAlert from './UIAlert.js';
|
||||
import launch_app from '../helpers/launchApp.js';
|
||||
import item_icon from '../helpers/itemIcon.js';
|
||||
import UIContextMenu from './UIContextMenu.js';
|
||||
|
||||
async function UIWindowSearch (options) {
|
||||
let h = '';
|
||||
|
||||
h += '<div class="search-input-wrapper">';
|
||||
h += `<input type="text" class="search-input" placeholder="Search" style="background-image:url('${window.icons['magnifier-outline.svg']}');">`;
|
||||
h += '</div>';
|
||||
h += '<div class="search-results" style="overflow-y: auto; max-height: 300px;">';
|
||||
|
||||
const el_window = await UIWindow({
|
||||
icon: null,
|
||||
single_instance: true,
|
||||
app: 'search',
|
||||
uid: null,
|
||||
is_dir: false,
|
||||
body_content: h,
|
||||
has_head: false,
|
||||
selectable_body: false,
|
||||
draggable_body: true,
|
||||
allow_context_menu: false,
|
||||
is_draggable: false,
|
||||
is_resizable: false,
|
||||
is_droppable: false,
|
||||
init_center: true,
|
||||
allow_native_ctxmenu: true,
|
||||
allow_user_select: true,
|
||||
window_class: 'window-search',
|
||||
backdrop: true,
|
||||
center: isMobile.phone,
|
||||
width: 500,
|
||||
dominant: true,
|
||||
|
||||
window_css: {
|
||||
height: 'initial',
|
||||
padding: '0',
|
||||
},
|
||||
body_css: {
|
||||
width: 'initial',
|
||||
'max-height': 'calc(100vh - 200px)',
|
||||
'background-color': 'rgb(241 246 251)',
|
||||
'backdrop-filter': 'blur(3px)',
|
||||
'padding': '0',
|
||||
'height': 'initial',
|
||||
'overflow': 'hidden',
|
||||
'min-height': '65px',
|
||||
'padding-bottom': '10px',
|
||||
},
|
||||
});
|
||||
|
||||
$(el_window).find('.search-input').focus();
|
||||
|
||||
// Debounce function to limit rate of API calls
|
||||
function debounce (func, wait) {
|
||||
let timeout;
|
||||
return function (...args) {
|
||||
const context = this;
|
||||
clearTimeout(timeout);
|
||||
timeout = setTimeout(() => {
|
||||
func.apply(context, args);
|
||||
}, wait);
|
||||
};
|
||||
}
|
||||
|
||||
// State for managing loading indicator
|
||||
let isSearching = false;
|
||||
|
||||
// Debounced search function
|
||||
const performSearch = debounce(async function (searchInput, resultsContainer) {
|
||||
// Don't search if input is empty
|
||||
if ( searchInput.val() === '' ) {
|
||||
resultsContainer.html('');
|
||||
resultsContainer.hide();
|
||||
return;
|
||||
}
|
||||
|
||||
// Set loading state
|
||||
if ( ! isSearching ) {
|
||||
isSearching = true;
|
||||
}
|
||||
|
||||
try {
|
||||
// Perform the search
|
||||
let results = await fetch(`${window.api_origin }/search`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${puter.authToken}`,
|
||||
},
|
||||
body: JSON.stringify({ text: searchInput.val() }),
|
||||
});
|
||||
|
||||
results = await results.json();
|
||||
|
||||
// Hide results if there are none
|
||||
if ( results.length === 0 )
|
||||
{
|
||||
resultsContainer.hide();
|
||||
}
|
||||
else
|
||||
{
|
||||
resultsContainer.show();
|
||||
}
|
||||
|
||||
// Build results HTML
|
||||
let h = '';
|
||||
|
||||
for ( let i = 0; i < results.length; i++ ) {
|
||||
const result = results[i];
|
||||
h += `<div
|
||||
class="search-result"
|
||||
data-path="${html_encode(result.path)}"
|
||||
data-uid="${html_encode(result.uid)}"
|
||||
data-is_dir="${html_encode(result.is_dir)}"
|
||||
>`;
|
||||
// icon
|
||||
h += `<img src="${html_encode((await item_icon(result)).image)}" style="width: 20px; height: 20px; margin-right: 6px;">`;
|
||||
h += html_encode(result.name);
|
||||
h += '</div>';
|
||||
}
|
||||
resultsContainer.html(h);
|
||||
} catch ( error ) {
|
||||
resultsContainer.html('<div class="search-error">Search failed. Please try again.</div>');
|
||||
console.error('Search error:', error);
|
||||
} finally {
|
||||
isSearching = false;
|
||||
}
|
||||
}, 300); // Wait 300ms after last keystroke before searching
|
||||
|
||||
// Event binding
|
||||
$(el_window).find('.search-input').on('input', function (e) {
|
||||
const searchInput = $(this);
|
||||
const resultsContainer = $(el_window).find('.search-results');
|
||||
performSearch(searchInput, resultsContainer);
|
||||
});
|
||||
}
|
||||
|
||||
$(document).on('click', '.search-result', async function (e) {
|
||||
const fspath = $(this).data('path');
|
||||
const fsuid = $(this).data('uid');
|
||||
const is_dir = $(this).attr('data-is_dir') === 'true' || $(this).data('is_dir') === '1';
|
||||
let open_item_meta;
|
||||
|
||||
if ( is_dir ) {
|
||||
UIWindow({
|
||||
path: fspath,
|
||||
title: path.basename(fspath),
|
||||
icon: await item_icon({ is_dir: true, path: fspath }),
|
||||
uid: fsuid,
|
||||
is_dir: is_dir,
|
||||
app: 'explorer',
|
||||
});
|
||||
|
||||
// close search window
|
||||
$(this).closest('.window').close();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// get all info needed to open an item
|
||||
try {
|
||||
open_item_meta = await $.ajax({
|
||||
url: `${window.api_origin }/open_item`,
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify({
|
||||
uid: fsuid ?? undefined,
|
||||
path: fspath ?? undefined,
|
||||
}),
|
||||
headers: {
|
||||
'Authorization': `Bearer ${window.auth_token}`,
|
||||
},
|
||||
statusCode: {
|
||||
401: function (xhr) {
|
||||
window.handle401(xhr);
|
||||
},
|
||||
},
|
||||
});
|
||||
} catch ( err ) {
|
||||
// Ignored
|
||||
}
|
||||
|
||||
// get a list of suggested apps for this file type.
|
||||
let suggested_apps = open_item_meta?.suggested_apps ?? await window.suggest_apps_for_fsentry({ uid: fsuid, path: fspath });
|
||||
|
||||
//---------------------------------------------
|
||||
// No suitable apps, ask if user would like to
|
||||
// download
|
||||
//---------------------------------------------
|
||||
if ( suggested_apps.length === 0 ) {
|
||||
//---------------------------------------------
|
||||
// If .zip file, unzip it
|
||||
//---------------------------------------------
|
||||
if ( path.extname(fspath) === '.zip' ) {
|
||||
window.unzipItem(fspath);
|
||||
return;
|
||||
}
|
||||
const alert_resp = await UIAlert('Found no suitable apps to open this file with. Would you like to download it instead?',
|
||||
[
|
||||
{
|
||||
label: i18n('download_file'),
|
||||
value: 'download_file',
|
||||
type: 'primary',
|
||||
|
||||
},
|
||||
{
|
||||
label: i18n('cancel'),
|
||||
},
|
||||
]);
|
||||
if ( alert_resp === 'download_file' ) {
|
||||
window.trigger_download([fspath]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
//---------------------------------------------
|
||||
// First suggested app is default app to open this item
|
||||
//---------------------------------------------
|
||||
else {
|
||||
launch_app({
|
||||
name: suggested_apps[0].name,
|
||||
token: open_item_meta.token,
|
||||
file_path: fspath,
|
||||
app_obj: suggested_apps[0],
|
||||
window_title: path.basename(fspath),
|
||||
file_uid: fsuid,
|
||||
// maximized: options.maximized,
|
||||
file_signature: open_item_meta.signature,
|
||||
});
|
||||
}
|
||||
|
||||
// close
|
||||
$(this).closest('.window').close();
|
||||
});
|
||||
|
||||
// Context menu for search results
|
||||
$(document).on('contextmenu', '.search-result', async function (e) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
const fspath = $(this).data('path');
|
||||
const fsuid = $(this).data('uid');
|
||||
const is_dir = $(this).attr('data-is_dir') === 'true' || $(this).data('is_dir') === '1';
|
||||
|
||||
// Get the parent directory path
|
||||
const parent_path = path.dirname(fspath);
|
||||
|
||||
// Build context menu items
|
||||
const menuItems = [
|
||||
{
|
||||
html: i18n('open'),
|
||||
onClick: async function () {
|
||||
// Trigger the same logic as clicking on the search result
|
||||
$(e.target).trigger('click');
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
// Only add "Open enclosing folder" if we're not already at root
|
||||
if ( parent_path && parent_path !== fspath && parent_path !== '/' ) {
|
||||
menuItems.push('-'); // divider
|
||||
menuItems.push({
|
||||
html: i18n('open_containing_folder'),
|
||||
onClick: async function () {
|
||||
// Open the enclosing folder
|
||||
UIWindow({
|
||||
path: parent_path,
|
||||
title: path.basename(parent_path) || window.root_dirname,
|
||||
icon: window.icons['folder.svg'],
|
||||
is_dir: true,
|
||||
app: 'explorer',
|
||||
});
|
||||
|
||||
// Close search window
|
||||
$(e.target).closest('.window').close();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
UIContextMenu({
|
||||
items: menuItems,
|
||||
});
|
||||
});
|
||||
|
||||
export default UIWindowSearch;
|
||||
@@ -1,454 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import UIWindow from './UIWindow.js';
|
||||
import UIAlert from './UIAlert.js';
|
||||
import path from '../lib/path.js';
|
||||
import { is_owned_by_me, owner_of_path } from '../helpers/pathOwner.js';
|
||||
import { invalidate_shared_roots } from '../helpers/sharedAccess.js';
|
||||
import { icons } from '../helpers/actionIcons.js';
|
||||
import { mode_label, options_for } from '../helpers/shareModes.js';
|
||||
import { has_direct_share, mark_item_shared } from '../helpers/sharedBadge.js';
|
||||
import { share_outcome } from '../helpers/shareOutcome.js';
|
||||
import shareRecipientPicker from '../helpers/shareRecipientPicker.js';
|
||||
import { share_key } from '../helpers/shareSuggest.js';
|
||||
import {
|
||||
team_for_share, team_label, teams_for_sharing,
|
||||
} from '../helpers/shareTeams.js';
|
||||
import { share_link_for } from '../helpers/sharePaths.js';
|
||||
import { is_plan_gate_error, open_upgrade_flow } from '../helpers/planGate.js';
|
||||
import { with_verification_gate } from '../helpers/verification_gates.js';
|
||||
|
||||
/** What each outcome of a share call is called on screen. */
|
||||
const SHARE_MESSAGE = {
|
||||
invited: 'share_invited',
|
||||
shared: 'share_shared_with',
|
||||
updated: 'share_access_updated',
|
||||
unchanged: 'share_already_shared_with',
|
||||
};
|
||||
|
||||
/**
|
||||
* Sharing dialog for one file or directory.
|
||||
*
|
||||
* @param {object} options
|
||||
* @param {string} options.path Item to share.
|
||||
* @param {string} [options.name] Display name; defaults to the path's basename.
|
||||
* @param {string} [options.owner] Owner's username; defaults to the first path
|
||||
* segment, which is not the current user when a `manage` recipient opens this.
|
||||
* @param {string} [options.uid] The item's uid, when the caller has it; saves
|
||||
* the lookup the "copy link" button otherwise makes.
|
||||
*/
|
||||
async function UIWindowShare (options) {
|
||||
options = options ?? {};
|
||||
const item_path = options.path;
|
||||
const item_name = options.name ?? path.basename(item_path);
|
||||
const item_owner =
|
||||
options.owner ?? owner_of_path(item_path) ?? window.user.username;
|
||||
// A delegate passes on access, never the authority to pass it on.
|
||||
const allow_manage = is_owned_by_me(item_path);
|
||||
|
||||
let h = '';
|
||||
h += '<div class="share-dialog">';
|
||||
h += '<div class="form-error-msg"></div>';
|
||||
h += '<div class="form-success-msg"></div>';
|
||||
|
||||
h += `<label for="share-recipient">${i18n('share_with')}</label>`;
|
||||
h += '<div class="share-dialog-row">';
|
||||
h += `<input class="share-recipient" id="share-recipient" type="text" autocomplete="off" spellcheck="false"
|
||||
placeholder="${i18n('share_add_people')}" />`;
|
||||
h += `<select class="share-mode">${options_for('read', { allow_manage })}</select>`;
|
||||
h += '</div>';
|
||||
h += `<button class="share-btn button button-primary button-block button-normal">${i18n('share')}</button>`;
|
||||
|
||||
// The owner's switch between people-only and anyone with the link. A
|
||||
// delegate passes access on to people; opening the item to everyone is
|
||||
// the owner's call, so nobody else gets the control.
|
||||
if ( allow_manage ) {
|
||||
h += '<div class="share-general-access">';
|
||||
h += `<div class="share-dialog-heading">${i18n('share_general_access')}</div>`;
|
||||
h += '<div class="share-dialog-row share-link-row">';
|
||||
h += `<select class="share-link-access" aria-label="${html_encode(i18n('share_general_access'))}">`;
|
||||
h += `<option value="restricted">${i18n('share_link_restricted')}</option>`;
|
||||
h += `<option value="anyone">${i18n('share_link_anyone')}</option>`;
|
||||
h += '</select>';
|
||||
h += `<select class="share-link-mode" aria-label="${html_encode(i18n('share_access_level'))}" hidden>${options_for('read', { allow_manage: false })}</select>`;
|
||||
h += '</div>';
|
||||
h += `<p class="share-link-note">${i18n('share_link_restricted_note')}</p>`;
|
||||
h += `<button class="share-copy-link button button-block button-normal" hidden>${i18n('share_copy_link')}</button>`;
|
||||
h += '</div>';
|
||||
}
|
||||
|
||||
h += `<div class="share-dialog-heading">${i18n('share_who_has_access')}</div>`;
|
||||
h += '<div class="share-list"></div>';
|
||||
h += '</div>';
|
||||
|
||||
// One dialog per item — window-level single_instance would refocus a
|
||||
// dialog still bound to a different file.
|
||||
const $existing = $('.window[data-app="share"]').filter(
|
||||
(_, el) => $(el).attr('data-share-path') === item_path,
|
||||
);
|
||||
if ( $existing.length ) {
|
||||
$existing.focusWindow();
|
||||
return;
|
||||
}
|
||||
|
||||
const el_window = await UIWindow({
|
||||
title: `${i18n('share')} — ${item_name}`,
|
||||
app: 'share',
|
||||
icon: window.icons['share-outline.svg'],
|
||||
uid: null,
|
||||
is_dir: false,
|
||||
body_content: h,
|
||||
has_head: true,
|
||||
selectable_body: false,
|
||||
draggable_body: false,
|
||||
allow_context_menu: false,
|
||||
is_resizable: false,
|
||||
is_droppable: false,
|
||||
init_center: true,
|
||||
allow_native_ctxmenu: false,
|
||||
allow_user_select: false,
|
||||
width: 420,
|
||||
height: 'auto',
|
||||
dominant: true,
|
||||
show_in_taskbar: false,
|
||||
onAppend: function (this_window) {
|
||||
$(this_window).find('.share-recipient').get(0)?.focus({ preventScroll: true });
|
||||
},
|
||||
// The recipient field listens on the document to know when a click
|
||||
// landed outside its suggestions; that has to come off with the window.
|
||||
on_close: () => picker.destroy(),
|
||||
window_class: 'window-share',
|
||||
window_css: { height: 'initial' },
|
||||
body_css: { width: 'initial', padding: '0', 'background-color': 'rgb(245 247 249)' },
|
||||
});
|
||||
$(el_window).attr('data-share-path', item_path);
|
||||
|
||||
const $error = $(el_window).find('.form-error-msg');
|
||||
const $success = $(el_window).find('.form-success-msg');
|
||||
const $list = $(el_window).find('.share-list');
|
||||
|
||||
const show_error = (message) => {
|
||||
$success.hide();
|
||||
$error.html(html_encode(message)).show();
|
||||
};
|
||||
|
||||
const show_success = (message) => {
|
||||
$error.hide();
|
||||
$success.html(message).show();
|
||||
};
|
||||
|
||||
/** The access list as last drawn, which is what a share call changes. */
|
||||
let shown_shares = [];
|
||||
|
||||
/** The caller's teams, offered as recipients. */
|
||||
let teams = [];
|
||||
|
||||
/** The team behind each `data-team` row as last drawn. */
|
||||
const row_teams = new Map();
|
||||
|
||||
/** The item's own "anyone with the link" share as last listed, or null. */
|
||||
let link_share = null;
|
||||
/** The item's uid, which its link is built on; looked up once. */
|
||||
let item_uid = options.uid ?? null;
|
||||
|
||||
const $recipient = $(el_window).find('.share-recipient');
|
||||
const $share_btn = $(el_window).find('.share-btn');
|
||||
|
||||
// One field for every kind of recipient: a colleague, a whole team, someone
|
||||
// shared with before, or an address typed from scratch.
|
||||
const picker = shareRecipientPicker({
|
||||
$input: $recipient,
|
||||
$row: $recipient.closest('.share-dialog-row'),
|
||||
// Nobody already on the list below: offering them again would only
|
||||
// re-grant what the row next to it already shows.
|
||||
excluded: () => shown_shares.map(share_key).filter(Boolean),
|
||||
onChange: () => { $share_btn.prop('disabled', ! picker.recipient()); },
|
||||
});
|
||||
$share_btn.prop('disabled', true);
|
||||
|
||||
// Enter shares, the way it submits the Dashboard's dialog. Bound after the
|
||||
// picker, which takes the press for itself while it is choosing a row.
|
||||
$recipient.on('keydown', (e) => {
|
||||
if ( e.key !== 'Enter' || e.isDefaultPrevented() ) return;
|
||||
if ( $share_btn.prop('disabled') ) return;
|
||||
$share_btn.trigger('click');
|
||||
});
|
||||
|
||||
const render = (shares) => {
|
||||
shown_shares = Array.isArray(shares) ? shares : [];
|
||||
row_teams.clear();
|
||||
// The item's own link share drives the general-access control rather
|
||||
// than a row; a delegate, who has no control, sees it as a row.
|
||||
link_share = shown_shares.find((share) => share.anyone && ! share.inheritedFrom) ?? null;
|
||||
const listed = shown_shares.filter((share) => ! (allow_manage && share.anyone && ! share.inheritedFrom));
|
||||
let rows = '';
|
||||
// The owner's access comes from owning the item, so it can't be revoked
|
||||
rows += '<div class="share-row">';
|
||||
rows += `<span class="share-row-who">${html_encode(item_owner)}${item_owner === window.user.username ? ` (${i18n('share_you')})` : ''}</span>`;
|
||||
rows += `<span class="share-row-owner">${i18n('share_owner')}</span>`;
|
||||
rows += '</div>';
|
||||
|
||||
for ( const share of listed ) {
|
||||
const holder = share.anyone ? i18n('share_row_anyone') : html_encode(share.holder ?? '');
|
||||
if ( share.anyone && ! share.inheritedFrom ) {
|
||||
rows += '<div class="share-row share-row-inherited">';
|
||||
rows += `<span class="share-row-who">${holder}</span>`;
|
||||
rows += `<span class="share-row-mode">${mode_label(share.mode)}</span>`;
|
||||
rows += '</div>';
|
||||
continue;
|
||||
}
|
||||
if ( share.inheritedFrom ) {
|
||||
// Granted on an ancestor, so it can only be changed there
|
||||
rows += '<div class="share-row share-row-inherited">';
|
||||
rows += `<span class="share-row-who">${holder}</span>`;
|
||||
rows += `<span class="share-row-via">${i18n('share_inherited_via', { folder: path.basename(share.inheritedFrom) })}</span>`;
|
||||
rows += `<span class="share-row-mode">${mode_label(share.mode)}</span>`;
|
||||
rows += '</div>';
|
||||
continue;
|
||||
}
|
||||
if ( share.pending ) {
|
||||
// Withheld unless the invite is ours to act on: nobody to name,
|
||||
// and the server would refuse the cancellation anyway.
|
||||
const invited = html_encode(share.recipientEmail ?? '');
|
||||
rows += '<div class="share-row share-row-pending">';
|
||||
rows += `<span class="share-row-who">${invited || html_encode(i18n('share_invited_someone'))}</span>`;
|
||||
rows += `<span class="share-row-via">${i18n('share_awaiting_signup')}</span>`;
|
||||
rows += `<span class="share-row-mode">${mode_label(share.mode)}</span>`;
|
||||
if ( invited )
|
||||
rows += `<button class="share-revoke" data-holder="${invited}" title="${html_encode(i18n('share_cancel_invite'))}" aria-label="${html_encode(i18n('share_cancel_invite'))}">${icons.trash}</button>`;
|
||||
rows += '</div>';
|
||||
continue;
|
||||
}
|
||||
// A team holds the share itself, so the row has no username to
|
||||
// key on; `data-team` carries the uid the handlers address it by.
|
||||
const team = team_for_share(teams, share);
|
||||
if ( team ) row_teams.set(team.uid, team);
|
||||
const key = team
|
||||
? `data-team="${html_encode(team.uid)}"`
|
||||
: `data-holder="${holder}"`;
|
||||
rows += `<div class="share-row${team ? ' share-row-team' : ''}">`;
|
||||
rows += `<span class="share-row-who">${team ? html_encode(team_label(team)) : holder}</span>`;
|
||||
if ( team ) rows += `<span class="share-row-via">${i18n('share_row_team')}</span>`;
|
||||
rows += `<select class="share-row-mode-select" ${key}>${options_for(share.mode, { allow_manage })}</select>`;
|
||||
rows += `<button class="share-revoke" ${key} title="${html_encode(i18n('share_remove_access'))}" aria-label="${html_encode(i18n('share_remove_access'))}">${icons.trash}</button>`;
|
||||
rows += '</div>';
|
||||
}
|
||||
if ( !listed.length ) {
|
||||
rows += `<p class="share-dialog-empty">${i18n('share_no_one')}</p>`;
|
||||
}
|
||||
$list.html(rows);
|
||||
render_link_access();
|
||||
// Every share, mode change and revoke lands here.
|
||||
mark_item_shared(item_path, has_direct_share(shares));
|
||||
};
|
||||
|
||||
const refresh = async () => {
|
||||
try {
|
||||
render(await puter.fs.getShares(item_path));
|
||||
} catch (e) {
|
||||
show_error(e?.message ?? i18n('share_failed'));
|
||||
}
|
||||
};
|
||||
|
||||
// -- General access --
|
||||
|
||||
const $link_access = $(el_window).find('.share-link-access');
|
||||
const $link_mode = $(el_window).find('.share-link-mode');
|
||||
const $link_note = $(el_window).find('.share-link-note');
|
||||
const $copy_link = $(el_window).find('.share-copy-link');
|
||||
|
||||
/** Put the control where the listing says the item stands. */
|
||||
const render_link_access = () => {
|
||||
if ( ! allow_manage ) return;
|
||||
const on = link_share !== null;
|
||||
$link_access.val(on ? 'anyone' : 'restricted');
|
||||
$link_mode.prop('hidden', ! on);
|
||||
if ( on ) $link_mode.val(link_share.mode);
|
||||
$link_note.html(on
|
||||
? i18n(link_share.mode === 'write' ? 'share_link_anyone_note_write' : 'share_link_anyone_note_read')
|
||||
: i18n('share_link_restricted_note'));
|
||||
$copy_link.prop('hidden', ! (on && item_uid));
|
||||
};
|
||||
|
||||
/** Open the item to anyone with the link at `mode`, or close it with null. */
|
||||
const set_link_access = async (mode) => {
|
||||
$link_access.prop('disabled', true);
|
||||
$link_mode.prop('disabled', true);
|
||||
try {
|
||||
if ( mode ) {
|
||||
const created = await with_verification_gate(() => puter.fs.share({
|
||||
path: item_path,
|
||||
recipient: { anyone: true },
|
||||
mode,
|
||||
}));
|
||||
item_uid ??= created?.[0]?.entryUid ?? null;
|
||||
show_success(i18n(mode === 'write' ? 'share_link_on_write' : 'share_link_on_read'));
|
||||
} else {
|
||||
await puter.fs.unshare(item_path, { anyone: true });
|
||||
show_success(i18n('share_link_off'));
|
||||
}
|
||||
} catch (e) {
|
||||
// A plan gate gets the flow that clears it, where the deployment
|
||||
// has one; a refusal is otherwise reported like any other.
|
||||
if ( is_plan_gate_error(e) ) {
|
||||
if ( ! open_upgrade_flow() ) show_error(i18n('share_link_requires_plan'));
|
||||
} else {
|
||||
show_error(e?.message ?? i18n('share_failed'));
|
||||
}
|
||||
} finally {
|
||||
$link_access.prop('disabled', false);
|
||||
$link_mode.prop('disabled', false);
|
||||
}
|
||||
// The listing is the truth either way, and it puts the control back.
|
||||
await refresh();
|
||||
};
|
||||
|
||||
$link_access.on('change', function () {
|
||||
set_link_access($(this).val() === 'anyone' ? ($link_mode.val() || 'read') : null);
|
||||
});
|
||||
$link_mode.on('change', function () {
|
||||
set_link_access($(this).val());
|
||||
});
|
||||
$copy_link.on('click', async function () {
|
||||
if ( ! item_uid ) return;
|
||||
try {
|
||||
await window.copy_to_clipboard(share_link_for(
|
||||
{ owner: item_owner, uid: item_uid, name: item_name },
|
||||
window.gui_origin,
|
||||
));
|
||||
show_success(i18n('share_link_copied'));
|
||||
} catch (e) {
|
||||
show_error(e?.message ?? i18n('share_failed'));
|
||||
}
|
||||
});
|
||||
|
||||
$(el_window).on('click', '.share-btn', async function () {
|
||||
// A team is named by uid; anything typed goes as-is, since a bare
|
||||
// string is what the backend reads as an email or a username.
|
||||
const chosen = picker.recipient();
|
||||
if ( ! chosen ) return;
|
||||
|
||||
$(this).prop('disabled', true);
|
||||
try {
|
||||
const created = await with_verification_gate(() => puter.fs.share({
|
||||
path: item_path,
|
||||
recipient: chosen.value,
|
||||
mode: $(el_window).find('.share-mode').val(),
|
||||
}));
|
||||
picker.clear();
|
||||
$error.hide();
|
||||
// `i18n()` encodes its replacements; encoding first would show the
|
||||
// entities to anyone whose address or username contains one.
|
||||
show_success(
|
||||
i18n(SHARE_MESSAGE[share_outcome(created, shown_shares)], {
|
||||
recipient: chosen.label,
|
||||
}),
|
||||
);
|
||||
picker.remember(chosen, created);
|
||||
invalidate_shared_roots();
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
show_error(e?.message ?? i18n('share_failed'));
|
||||
} finally {
|
||||
$(this).prop('disabled', ! picker.recipient());
|
||||
}
|
||||
});
|
||||
|
||||
$(el_window).on('change', '.share-row-mode-select', async function () {
|
||||
const team = row_teams.get($(this).attr('data-team'));
|
||||
const holder = $(this).attr('data-holder');
|
||||
const recipient = team ? { team: team.uid } : holder;
|
||||
const name = team ? team_label(team) : holder;
|
||||
const mode = $(this).val();
|
||||
$(this).prop('disabled', true);
|
||||
try {
|
||||
await with_verification_gate(() => puter.fs.share({ path: item_path, recipient, mode }));
|
||||
show_success(i18n('share_access_updated', { recipient: name }));
|
||||
invalidate_shared_roots();
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
show_error(e?.message ?? i18n('share_failed'));
|
||||
invalidate_shared_roots();
|
||||
await refresh();
|
||||
}
|
||||
});
|
||||
|
||||
$(el_window).on('click', '.share-revoke', async function () {
|
||||
const holder = $(this).attr('data-holder');
|
||||
const is_pending = $(this).closest('.share-row').hasClass('share-row-pending');
|
||||
const team = row_teams.get($(this).attr('data-team'));
|
||||
// Losing a team's access is losing everyone in it at once, which
|
||||
// the ordinary "remove {recipient}" wording would understate.
|
||||
const removed_name = team ? team_label(team) : holder;
|
||||
const confirmed = await UIAlert({
|
||||
message: is_pending
|
||||
? i18n('share_confirm_cancel_invite', { recipient: holder })
|
||||
: i18n(team ? 'share_confirm_remove_team' : 'share_confirm_remove', { recipient: removed_name }),
|
||||
buttons: [
|
||||
{ label: i18n('share_remove'), value: true, type: 'primary' },
|
||||
{ label: i18n('cancel'), value: false },
|
||||
],
|
||||
// Stack the confirmation with the dialog that opened it. In
|
||||
// fullpage/dashboard mode this window is promoted to the
|
||||
// stay-on-top band, where an alert defaulting to `stay_on_top:
|
||||
// false` renders underneath it — leaving a confirmation the user
|
||||
// can't reach without closing the dialog behind it.
|
||||
parent_uuid: $(el_window).attr('data-element_uuid'),
|
||||
stay_on_top: $(el_window).attr('data-stay_on_top') === 'true',
|
||||
});
|
||||
if ( ! confirmed ) return;
|
||||
$(this).prop('disabled', true);
|
||||
try {
|
||||
await puter.fs.unshare(item_path, team ? { team: team.uid } : holder);
|
||||
// `i18n()` encodes what it returns, replacements included, so the
|
||||
// raw value goes in — encoding first would show the entities to
|
||||
// anyone whose address or username contains one.
|
||||
show_success(
|
||||
is_pending
|
||||
? i18n('share_invite_cancelled', { recipient: holder })
|
||||
: i18n('share_access_removed', { recipient: removed_name }),
|
||||
);
|
||||
invalidate_shared_roots();
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
show_error(e?.message ?? i18n('share_failed'));
|
||||
$(this).prop('disabled', false);
|
||||
}
|
||||
});
|
||||
|
||||
// The uid the link is built on; the copy button waits for it.
|
||||
if ( allow_manage && ! item_uid ) {
|
||||
puter.fs.stat(item_path).then((stat) => {
|
||||
item_uid = stat?.uid ?? null;
|
||||
render_link_access();
|
||||
}).catch(() => { /* the button just stays hidden */ });
|
||||
}
|
||||
|
||||
// Teams first: the access list names its rows from them, and the recipient
|
||||
// field suggests both them and the people in them.
|
||||
teams = await teams_for_sharing();
|
||||
picker.setTeams(teams);
|
||||
// Not the encoded form: an attribute set from JS shows entities literally.
|
||||
if ( teams.length ) $recipient.attr('placeholder', i18n('share_add_people_teams', [], false));
|
||||
await refresh();
|
||||
return el_window;
|
||||
}
|
||||
|
||||
export default UIWindowShare;
|
||||
@@ -1,244 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import { END_HARD, END_SOFT } from '../definitions.js';
|
||||
import UIAlert from './UIAlert.js';
|
||||
import UIContextMenu from './UIContextMenu.js';
|
||||
import UIWindow from './UIWindow.js';
|
||||
|
||||
const end_process = async (uuid, force) => {
|
||||
const svc_process = globalThis.services.get('process');
|
||||
const process = svc_process.get_by_uuid(uuid);
|
||||
if ( ! process ) {
|
||||
console.warn(`Can't end process with uuid='${uuid}': does not exist`);
|
||||
return;
|
||||
}
|
||||
|
||||
let confirmation;
|
||||
if ( process.is_init() ) {
|
||||
if ( ! force ) {
|
||||
confirmation = i18n('close_all_windows_confirm');
|
||||
} else {
|
||||
confirmation = i18n('restart_puter_confirm');
|
||||
}
|
||||
} else if ( force ) {
|
||||
confirmation = i18n('end_process_force_confirm');
|
||||
}
|
||||
|
||||
if ( confirmation ) {
|
||||
const alert_resp = await UIAlert({
|
||||
message: confirmation,
|
||||
buttons: [
|
||||
{
|
||||
label: i18n('yes'),
|
||||
value: true,
|
||||
type: 'primary',
|
||||
},
|
||||
{
|
||||
label: i18n('no'),
|
||||
value: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
if ( ! alert_resp ) return;
|
||||
}
|
||||
|
||||
process.signal(force ? END_HARD : END_SOFT);
|
||||
};
|
||||
|
||||
const calculate_indent_string = (indent_level, is_last_item_stack, is_last_item) => {
|
||||
// Returns a string of '| ├└'
|
||||
let result = '';
|
||||
|
||||
for ( let i = 0; i < indent_level; i++ ) {
|
||||
const last_cell = i === indent_level - 1;
|
||||
const has_trunk = (last_cell && ( !is_last_item )) ||
|
||||
(!last_cell && !is_last_item_stack[i + 1]);
|
||||
const has_branch = last_cell;
|
||||
|
||||
if ( has_trunk && has_branch ) {
|
||||
result += '├';
|
||||
} else if ( has_trunk ) {
|
||||
result += '|';
|
||||
} else if ( has_branch ) {
|
||||
result += '└';
|
||||
} else {
|
||||
result += ' ';
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const generate_task_rows = (items, { indent_level, is_last_item_stack }) => {
|
||||
const svc_process = globalThis.services.get('process');
|
||||
let rows_html = '';
|
||||
|
||||
for ( let i = 0; i < items.length; i++ ) {
|
||||
const item = items[i];
|
||||
const is_last_item = i === items.length - 1;
|
||||
const indentation = calculate_indent_string(indent_level, is_last_item_stack, is_last_item);
|
||||
|
||||
// Generate indentation HTML
|
||||
let indentation_html = '';
|
||||
for ( const c of indentation ) {
|
||||
indentation_html += '<div class="indentcell">';
|
||||
switch (c) {
|
||||
case ' ':
|
||||
break;
|
||||
case '|':
|
||||
indentation_html += '<div class="indentcell-trunk"></div>';
|
||||
break;
|
||||
case '└':
|
||||
indentation_html += '<div class="indentcell-branch"></div>';
|
||||
break;
|
||||
case '├':
|
||||
indentation_html += '<div class="indentcell-trunk"></div>';
|
||||
indentation_html += '<div class="indentcell-branch"></div>';
|
||||
break;
|
||||
}
|
||||
indentation_html += '</div>';
|
||||
}
|
||||
|
||||
rows_html += `
|
||||
<tr class="task-row" data-uuid="${item.uuid}">
|
||||
<td>
|
||||
<div class="task">
|
||||
<div class="task-indentation">${indentation_html}</div>
|
||||
<div class="task-name">${item.name}</div>
|
||||
</div>
|
||||
</td>
|
||||
<td><span class="process-type">${i18n(`process_type_${ item.type}`)}</span></td>
|
||||
<td><span class="process-status">${i18n(`process_status_${ item.status.i18n_key}`)}</span></td>
|
||||
</tr>
|
||||
`;
|
||||
|
||||
const children = svc_process.get_children_of(item.uuid);
|
||||
if ( children ) {
|
||||
rows_html += generate_task_rows(children, {
|
||||
indent_level: indent_level + 1,
|
||||
is_last_item_stack: [ ...is_last_item_stack, is_last_item ],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return rows_html;
|
||||
};
|
||||
|
||||
const UIWindowTaskManager = async function UIWindowTaskManager () {
|
||||
const svc_process = globalThis.services.get('process');
|
||||
|
||||
let h = '';
|
||||
|
||||
h += '<div class="task-manager-container">';
|
||||
h += '<table>';
|
||||
h += '<thead>';
|
||||
h += '<tr>';
|
||||
h += `<th>${i18n('taskmgr_header_name')}</th>`;
|
||||
h += `<th>${i18n('taskmgr_header_type')}</th>`;
|
||||
h += `<th>${i18n('taskmgr_header_status')}</th>`;
|
||||
h += '</tr>';
|
||||
h += '</thead>';
|
||||
h += '<tbody class="taskmgr-taskarea">';
|
||||
h += '</tbody>';
|
||||
h += '</table>';
|
||||
h += '</div>';
|
||||
|
||||
const el_window = await UIWindow({
|
||||
title: i18n('task_manager'),
|
||||
icon: globalThis.icons['cog.svg'],
|
||||
uid: null,
|
||||
is_dir: false,
|
||||
single_instance: true,
|
||||
app: 'taskmgr',
|
||||
is_resizable: true,
|
||||
is_droppable: false,
|
||||
has_head: true,
|
||||
selectable_body: true,
|
||||
draggable_body: false,
|
||||
allow_context_menu: false,
|
||||
show_in_taskbar: true,
|
||||
dominant: true,
|
||||
body_content: h,
|
||||
width: 350,
|
||||
window_class: 'window-task-manager',
|
||||
window_css: {
|
||||
height: 'initial',
|
||||
},
|
||||
body_css: {
|
||||
width: 'initial',
|
||||
padding: '20px',
|
||||
'background-color': `hsla(
|
||||
var(--primary-hue),
|
||||
var(--primary-saturation),
|
||||
var(--primary-lightness),
|
||||
var(--primary-alpha))`,
|
||||
'backdrop-filter': 'blur(3px)',
|
||||
'box-sizing': 'border-box',
|
||||
height: 'calc(100% - 30px)',
|
||||
display: 'flex',
|
||||
'flex-direction': 'column',
|
||||
'--scale': '2pt',
|
||||
'--line-color': '#6e6e6ebd',
|
||||
padding: '0',
|
||||
},
|
||||
});
|
||||
|
||||
const update_tasks = () => {
|
||||
const processes = [svc_process.get_init()];
|
||||
const rows_html = generate_task_rows(processes, { indent_level: 0, is_last_item_stack: [] });
|
||||
$(el_window).find('.taskmgr-taskarea').html(rows_html);
|
||||
};
|
||||
|
||||
// Set up context menu for task rows
|
||||
$(el_window).on('contextmenu', '.task-row', function (e) {
|
||||
e.preventDefault();
|
||||
const uuid = $(this).data('uuid');
|
||||
UIContextMenu({
|
||||
items: [
|
||||
{
|
||||
html: i18n('close'),
|
||||
onClick: () => {
|
||||
end_process(uuid);
|
||||
},
|
||||
},
|
||||
{
|
||||
html: i18n('force_quit'),
|
||||
onClick: () => {
|
||||
end_process(uuid, true);
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
// Initial task update
|
||||
update_tasks();
|
||||
|
||||
// Set up interval to refresh tasks
|
||||
const interval = setInterval(update_tasks, 500);
|
||||
|
||||
// Clean up interval when window is closed
|
||||
$(el_window).on('close', () => {
|
||||
clearInterval(interval);
|
||||
});
|
||||
|
||||
return el_window;
|
||||
};
|
||||
|
||||
export default UIWindowTaskManager;
|
||||
@@ -1,114 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import { UIColorPickerWidget, hslaToHex8 } from './UIColorPickerWidget.js';
|
||||
import UIWindow from './UIWindow.js';
|
||||
|
||||
const UIWindowThemeDialog = async function UIWindowThemeDialog (options) {
|
||||
options = options ?? {};
|
||||
const services = globalThis.services;
|
||||
const svc_theme = services.get('theme');
|
||||
|
||||
// Get current theme values and convert to hex8 for the color picker
|
||||
const currentHue = svc_theme.get('hue');
|
||||
const currentSat = svc_theme.get('sat');
|
||||
const currentLig = svc_theme.get('lig');
|
||||
const currentAlpha = svc_theme.get('alpha');
|
||||
const initialColor = hslaToHex8(currentHue, currentSat, currentLig, currentAlpha);
|
||||
|
||||
let h = '';
|
||||
h += '<div class="theme-dialog-content" style="display: flex; flex-direction: column; gap: 10pt;">';
|
||||
h += `<button class="button button-secondary reset-colors-btn">${i18n('reset_colors')}</button>`;
|
||||
h += '<div class="color-picker-container" style="padding: 0; margin-bottom: 10px;">';
|
||||
h += '<div class="picker"></div>';
|
||||
h += '</div>';
|
||||
h += '</div>';
|
||||
|
||||
const el_window = await UIWindow({
|
||||
title: i18n('ui_colors'),
|
||||
icon: null,
|
||||
uid: null,
|
||||
is_dir: false,
|
||||
body_content: h,
|
||||
is_resizable: false,
|
||||
is_droppable: false,
|
||||
has_head: true,
|
||||
stay_on_top: true,
|
||||
selectable_body: false,
|
||||
draggable_body: false,
|
||||
allow_context_menu: false,
|
||||
show_in_taskbar: false,
|
||||
window_class: 'window-alert',
|
||||
dominant: true,
|
||||
width: 350,
|
||||
window_css: {
|
||||
height: 'initial',
|
||||
},
|
||||
body_css: {
|
||||
width: 'initial',
|
||||
padding: '20px',
|
||||
'background-color': `hsla(
|
||||
var(--primary-hue),
|
||||
var(--primary-saturation),
|
||||
var(--primary-lightness),
|
||||
var(--primary-alpha))`,
|
||||
'backdrop-filter': 'blur(3px)',
|
||||
},
|
||||
...options.window_options,
|
||||
onAppend: function (window) {
|
||||
// Initialize the color picker widget
|
||||
const colorPickerWidget = UIColorPickerWidget($(window).find('.picker'), {
|
||||
default: initialColor,
|
||||
onColorChange: (color) => {
|
||||
// Convert color to HSLA format for theme service
|
||||
const hsla = colorPickerWidget.getHSLA();
|
||||
const state = {
|
||||
hue: hsla.h,
|
||||
sat: hsla.s,
|
||||
lig: hsla.l,
|
||||
alpha: hsla.a,
|
||||
light_text: hsla.l < 60 ? true : false,
|
||||
};
|
||||
svc_theme.apply(state);
|
||||
},
|
||||
});
|
||||
|
||||
// Store widget reference on window for reset functionality
|
||||
$(window).data('colorPickerWidget', colorPickerWidget);
|
||||
},
|
||||
});
|
||||
|
||||
// Reset button handler
|
||||
$(el_window).find('.reset-colors-btn').on('click', function () {
|
||||
svc_theme.reset();
|
||||
// Update color picker to reflect reset values
|
||||
const colorPickerWidget = $(el_window).data('colorPickerWidget');
|
||||
if ( colorPickerWidget ) {
|
||||
const resetHue = svc_theme.get('hue');
|
||||
const resetSat = svc_theme.get('sat');
|
||||
const resetLig = svc_theme.get('lig');
|
||||
const resetAlpha = svc_theme.get('alpha');
|
||||
const resetColor = hslaToHex8(resetHue, resetSat, resetLig, resetAlpha);
|
||||
colorPickerWidget.setColor(resetColor);
|
||||
}
|
||||
});
|
||||
|
||||
return {};
|
||||
};
|
||||
|
||||
export default UIWindowThemeDialog;
|
||||
@@ -1,90 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import UIWindow from './UIWindow.js';
|
||||
|
||||
async function UIWindowWelcome (options) {
|
||||
|
||||
options = options ?? {};
|
||||
|
||||
let h = '';
|
||||
// close button containing the multiplication sign
|
||||
h += '<div class="generic-close-window-button welcome-window-close-button"> × </div>';
|
||||
h += '<div style="display:flex; flex-direction: colum;">';
|
||||
h += '<div style="overflow: hidden; width: 200px; max-width: 200px; min-width: 200px; background: linear-gradient(45deg, #3d476b, #838eb7); min-height: 400px; padding: 20px; box-sizing: border-box;">';
|
||||
h += '<img style="display: block; margin: 45px auto 0; width: 270px; opacity: 0.5;" src="data:image/svg+xml,%3C%3Fxml%20version%3D%221.0%22%3F%3E%3Csvg%20width%3D%2248%22%20height%3D%2248%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Asvg%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cg%20class%3D%22layer%22%3E%3Ctitle%3ELayer%201%3C%2Ftitle%3E%3Cg%20id%3D%22svg_1%22%20stroke-width%3D%221%22%20transform%3D%22rotate(90%2024%2023.9997)%22%3E%3Cpolyline%20fill%3D%22none%22%20id%3D%22svg_2%22%20points%3D%2239%2024%2025%2024%2025%2028%22%20stroke%3D%22%23ffffff%22%20stroke-linecap%3D%22square%22%20stroke-miterlimit%3D%2210%22%20stroke-width%3D%221%22%2F%3E%3Cpolyline%20fill%3D%22none%22%20id%3D%22svg_3%22%20points%3D%2235.879%2010.121%2032%2014%2025%2014%2025%2018%22%20stroke%3D%22%23ffffff%22%20stroke-linecap%3D%22square%22%20stroke-miterlimit%3D%2210%22%20stroke-width%3D%221%22%2F%3E%3Cpath%20d%3D%22m13%2C26a10.29%2C10.29%200%200%201%20-7.2%2C-3%22%20fill%3D%22none%22%20id%3D%22svg_4%22%20stroke%3D%22%23ffffff%22%20stroke-linecap%3D%22square%22%20stroke-miterlimit%3D%2210%22%20stroke-width%3D%221%22%2F%3E%3Cpath%20d%3D%22m17%2C31.6a5.83%2C5.83%200%200%201%20-4%2C-5.6a5.73%2C5.73%200%200%201%202%2C-4.4%22%20fill%3D%22none%22%20id%3D%22svg_5%22%20stroke%3D%22%23ffffff%22%20stroke-linecap%3D%22square%22%20stroke-miterlimit%3D%2210%22%20stroke-width%3D%221%22%2F%3E%3Cpath%20d%3D%22m35.88%2C37.88l-3.88%2C-3.88l-7%2C0l0%2C2a9.9%2C9.9%200%200%201%20-10%2C10a9.9%2C9.9%200%200%201%20-10%2C-10a9.06%2C9.06%200%200%201%200.6%2C-3.2a5.63%2C5.63%200%200%201%20-2.6%2C-4.8a5.89%2C5.89%200%200%201%202.8%2C-5a9.99%2C9.99%200%200%201%20-2.8%2C-7a9.9%2C9.9%200%200%201%2010%2C-10l0.4%2C0a5.83%2C5.83%200%200%201%205.6%2C-4a5.89%2C5.89%200%200%201%206%2C6%22%20fill%3D%22none%22%20id%3D%22svg_6%22%20stroke%3D%22%23ffffff%22%20stroke-linecap%3D%22square%22%20stroke-miterlimit%3D%2210%22%20stroke-width%3D%221%22%2F%3E%3Ccircle%20cx%3D%2238%22%20cy%3D%228%22%20data-color%3D%22color-2%22%20fill%3D%22none%22%20id%3D%22svg_7%22%20r%3D%223%22%20stroke%3D%22%23ffffff%22%20stroke-linecap%3D%22square%22%20stroke-miterlimit%3D%2210%22%20stroke-width%3D%221%22%2F%3E%3Ccircle%20cx%3D%2242%22%20cy%3D%2224%22%20data-color%3D%22color-2%22%20fill%3D%22none%22%20id%3D%22svg_8%22%20r%3D%223%22%20stroke%3D%22%23ffffff%22%20stroke-linecap%3D%22square%22%20stroke-miterlimit%3D%2210%22%20stroke-width%3D%221%22%2F%3E%3Ccircle%20cx%3D%2238%22%20cy%3D%2240%22%20data-color%3D%22color-2%22%20fill%3D%22none%22%20id%3D%22svg_9%22%20r%3D%223%22%20stroke%3D%22%23ffffff%22%20stroke-linecap%3D%22square%22%20stroke-miterlimit%3D%2210%22%20stroke-width%3D%221%22%2F%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E">';
|
||||
h += '</div>';
|
||||
h += '<div style="flex-grow: 1; padding-left: 50px; padding-top: 70px; padding-right: 50px;">';
|
||||
h += `<h1 style="font-size: 25px; font-weight: 300; -webkit-font-smoothing: antialiased; color: #545763;">${i18n('welcome_title')}</h1>`;
|
||||
h += `<p style="margin-top: 25px; font-size: 16px; font-weight: 300; -webkit-font-smoothing: antialiased; color: #3e4251;">${i18n('welcome_description')}</p>`;
|
||||
h += `<button class="welcome-window-get-started" style="font-size: 15px; font-weight: 300; -webkit-font-smoothing: antialiased; cursor: pointer; padding: 8px 20px; border-radius: 5px; text-decoration: none; margin-right: 20px; border: 1px solid #656565 !important; background: none; margin-top: 10px;">${i18n('welcome_get_started')}</button>`;
|
||||
h += '<div class="welcome-window-footer">';
|
||||
h += `<a href="/terms" target="_blank">${i18n('welcome_terms')}</a>`;
|
||||
h += `<a href="/privacy" style="margin-left: 20px;" target="_blank">${i18n('welcome_privacy')}</a>`;
|
||||
h += `<a href="https://developer.puter.com" style="margin-left: 20px;" target="_blank">${i18n('welcome_developers')}</a>`;
|
||||
h += `<a href="https://github.com/heyputer/puter" style="margin-left: 20px;" target="_blank">${i18n('welcome_open_source')}</a>`;
|
||||
h += '</div>';
|
||||
h += '</div>';
|
||||
h += '</div>';
|
||||
|
||||
const el_window = await UIWindow({
|
||||
title: i18n('welcome_instant_login_title'),
|
||||
app: 'instant-login',
|
||||
single_instance: true,
|
||||
icon: null,
|
||||
uid: null,
|
||||
is_dir: false,
|
||||
body_content: h,
|
||||
has_head: false,
|
||||
selectable_body: false,
|
||||
allow_context_menu: false,
|
||||
is_resizable: false,
|
||||
is_droppable: false,
|
||||
init_center: true,
|
||||
allow_native_ctxmenu: false,
|
||||
allow_user_select: false,
|
||||
backdrop: true,
|
||||
close_on_backdrop_click: false,
|
||||
backdrop_covers_toolbar: true,
|
||||
width: 650,
|
||||
height: 'auto',
|
||||
dominant: true,
|
||||
show_in_taskbar: false,
|
||||
draggable_body: true,
|
||||
fadeIn: 1000,
|
||||
window_class: 'window-welcome',
|
||||
on_close: function () {
|
||||
// save the fact that the user has seen the welcome window
|
||||
puter.kv.set('has_seen_welcome_window', true).catch(err => console.warn('Could not save has_seen_welcome_window:', err));
|
||||
},
|
||||
body_css: {
|
||||
width: 'initial',
|
||||
height: '100%',
|
||||
'background-color': 'rgb(245 247 249)',
|
||||
'backdrop-filter': 'blur(3px)',
|
||||
padding: '0',
|
||||
},
|
||||
});
|
||||
|
||||
$(document).on('click', '.welcome-window-get-started', function () {
|
||||
$(el_window).close();
|
||||
});
|
||||
}
|
||||
|
||||
export default UIWindowWelcome;
|
||||
@@ -117,11 +117,6 @@
|
||||
--dashboard-bento-usage-surface: #eef2ff;
|
||||
--dashboard-bento-usage-header-bg: #e0e7ff;
|
||||
--dashboard-bento-usage-bar-fill: #ea580c;
|
||||
/* Emerald (matches the green icon accent used elsewhere) */
|
||||
--dashboard-bento-desktop-icon-bg: #059669;
|
||||
--dashboard-bento-desktop-icon-shadow: rgba(5, 150, 105, 0.22);
|
||||
--dashboard-bento-desktop-surface: #ecfdf5;
|
||||
--dashboard-bento-desktop-header-bg: #d1fae5;
|
||||
|
||||
--dashboard-shadow-subtle: rgba(0, 0, 0, 0.04);
|
||||
--dashboard-shadow-light: rgba(0, 0, 0, 0.06);
|
||||
@@ -244,10 +239,6 @@ body {
|
||||
--dashboard-bento-usage-surface: #1c1d2e;
|
||||
--dashboard-bento-usage-header-bg: #252a42;
|
||||
--dashboard-bento-usage-bar-fill: #fb923c;
|
||||
--dashboard-bento-desktop-icon-bg: #10b981;
|
||||
--dashboard-bento-desktop-icon-shadow: rgba(16, 185, 129, 0.32);
|
||||
--dashboard-bento-desktop-surface: #16241f;
|
||||
--dashboard-bento-desktop-header-bg: #172e26;
|
||||
|
||||
--dashboard-shadow-subtle: rgba(0, 0, 0, 0.2);
|
||||
--dashboard-shadow-light: rgba(0, 0, 0, 0.3);
|
||||
@@ -3352,8 +3343,7 @@ p.myapps-add-error {
|
||||
}
|
||||
|
||||
/* -- Share modal --
|
||||
Responsive, from-scratch replacement for UIWindowShare in the Dashboard:
|
||||
a centered card on desktop, a bottom sheet on mobile. Mirrors the item
|
||||
A centered card on desktop, a bottom sheet on mobile. Mirrors the item
|
||||
properties modal's shell so the two read as one system. */
|
||||
.share-modal-overlay {
|
||||
position: fixed;
|
||||
@@ -3714,9 +3704,8 @@ select.share-modal-row-mode:disabled {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
/* Recipient suggestions. The structure lives in style.css, shared with the
|
||||
desktop share dialog; only the palette is restated here so the list picks
|
||||
up the dashboard's tokens in both themes. */
|
||||
/* Recipient suggestions. The structure lives in style.css; only the palette
|
||||
is set here so the list picks up the dashboard's tokens in both themes. */
|
||||
.share-modal {
|
||||
--share-suggest-bg: var(--dashboard-card-background);
|
||||
--share-suggest-border: var(--dashboard-border);
|
||||
@@ -7386,11 +7375,6 @@ body.myapps-reordering .myapps-tile {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.dashboard .bento-card-fancy-icon-desktop {
|
||||
background-color: var(--dashboard-bento-desktop-icon-bg);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.dashboard .bento-card-fancy-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -7553,41 +7537,6 @@ body.myapps-reordering .myapps-tile {
|
||||
color: var(--dashboard-text-tertiary);
|
||||
}
|
||||
|
||||
/* Open Desktop bento card (full width; links to the desktop interface) */
|
||||
.dashboard .bento-desktop {
|
||||
grid-column: 1 / -1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
padding: 18px 24px;
|
||||
background-color: var(--dashboard-bento-desktop-header-bg);
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
transition: box-shadow 0.15s ease;
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
.dashboard .bento-desktop:hover {
|
||||
box-shadow:
|
||||
0 2px 4px var(--dashboard-shadow-subtle),
|
||||
0 10px 28px var(--dashboard-bento-desktop-icon-shadow);
|
||||
}
|
||||
|
||||
.dashboard .bento-desktop:hover .bento-desktop-arrow {
|
||||
transform: translateX(3px);
|
||||
color: var(--dashboard-text-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.dashboard .bento-desktop-arrow {
|
||||
margin-left: auto;
|
||||
font-size: 22px;
|
||||
font-weight: 300;
|
||||
line-height: 1;
|
||||
color: var(--dashboard-text-hint);
|
||||
transition: transform 0.15s ease, color 0.15s ease;
|
||||
}
|
||||
|
||||
/* Usage bento card (cool indigo surfaces; orange bars stay as progress accent) */
|
||||
.dashboard .bento-usage {
|
||||
grid-column: 1 / -1;
|
||||
@@ -7910,11 +7859,6 @@ body.myapps-reordering .myapps-tile {
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.dashboard .bento-desktop {
|
||||
padding: 16px 20px;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.dashboard .bento-card-fancy-icon {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
|
||||
+27
-868
File diff suppressed because it is too large.
Load diff
@@ -1,54 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
console.debug('[puter] modify-user-options-menu loaded');
|
||||
|
||||
$(window).on('ctxmenu-will-open', (event) => {
|
||||
if ( event.detail.options?.id === 'user-options-menu' ) {
|
||||
// Define array of new menu items
|
||||
const newMenuItems = [
|
||||
// Separator
|
||||
'-',
|
||||
// 'Developer', opens developer site in new tab
|
||||
{
|
||||
id: 'go_to_developer_site',
|
||||
html: 'Developer<svg style="width: 11px; height: 11px; margin-left:2px;" height="32" viewBox="0 0 32 32" width="32" xmlns="http://www.w3.org/2000/svg"><path d="m26 28h-20a2.0027 2.0027 0 0 1 -2-2v-20a2.0027 2.0027 0 0 1 2-2h10v2h-10v20h20v-10h2v10a2.0027 2.0027 0 0 1 -2 2z"/><path d="m20 2v2h6.586l-8.586 8.586 1.414 1.414 8.586-8.586v6.586h2v-10z"/><path d="m0 0h32v32h-32z" fill="none"/></svg>',
|
||||
html_active: 'Developer<svg style="width: 11px; height: 11px; margin-left:2px;" height="32" viewBox="0 0 32 32" width="32" xmlns="http://www.w3.org/2000/svg"> <path d="m26 28h-20a2.0027 2.0027 0 0 1 -2-2v-20a2.0027 2.0027 0 0 1 2-2h10v2h-10v20h20v-10h2v10a2.0027 2.0027 0 0 1 -2 2z" style="fill: rgb(255, 255, 255);"/> <path d="m20 2v2h6.586l-8.586 8.586 1.414 1.414 8.586-8.586v6.586h2v-10z" style="fill: rgb(255, 255, 255);"/> <path d="m0 0h32v32h-32z" fill="none"/> </svg>',
|
||||
action: function () {
|
||||
window.open('https://developer.puter.com', '_blank');
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
// Find the position of 'contact_us'
|
||||
const items = event.detail.options.items;
|
||||
const insertBeforeIndex = items.findIndex(item => item.id === 'contact_us');
|
||||
|
||||
// 'contact_us' not found, append new items at the end
|
||||
if ( insertBeforeIndex === -1 ) {
|
||||
event.detail.options.items = [...items, ...newMenuItems];
|
||||
return;
|
||||
}
|
||||
|
||||
// 'contact_us' found, insert new items before it
|
||||
const firstHalf = items.slice(0, insertBeforeIndex);
|
||||
const secondHalf = items.slice(insertBeforeIndex);
|
||||
event.detail.options.items = [...firstHalf, ...newMenuItems, ...secondHalf];
|
||||
}
|
||||
});
|
||||
@@ -22,6 +22,7 @@ import { encode } from 'html-entities';
|
||||
import { loadLocale } from './i18n/embedI18n.js';
|
||||
import UIWindowAppFeedback from './UI/UIWindowAppFeedback.js';
|
||||
import { embedSession } from './helpers/embedSession.js';
|
||||
import { overlayGone } from './helpers/overlayGone.js';
|
||||
|
||||
window.$ = window.jQuery = jQuery;
|
||||
window.html_encode = value => encode(String(value ?? ''), { mode: 'nonAsciiPrintable' });
|
||||
@@ -37,18 +38,6 @@ const localeReady = loadLocale(window.locale);
|
||||
/** Answers only the page frame-ancestors pinned, which the feedback is for. */
|
||||
const tellHost = (data) => window.parent.postMessage(data, config.hostOrigin);
|
||||
|
||||
/** Resolves once the dialog's overlay has left the page, after its success pane and exit. */
|
||||
const overlayGone = () => new Promise((resolve) => {
|
||||
const gone = () => !document.querySelector('.app-feedback-overlay');
|
||||
if ( gone() ) return resolve();
|
||||
const observer = new MutationObserver(() => {
|
||||
if ( ! gone() ) return;
|
||||
observer.disconnect();
|
||||
resolve();
|
||||
});
|
||||
observer.observe(document.body, { childList: true });
|
||||
});
|
||||
|
||||
/**
|
||||
* Shows the app feedback dialog for the framing page, as the signed-in user it
|
||||
* names. Without that user's session, or with an email still to confirm, the
|
||||
@@ -75,7 +64,8 @@ async function run () {
|
||||
let sent = false;
|
||||
try {
|
||||
sent = await UIWindowAppFeedback({ origin: config.hostOrigin, source: 'web' });
|
||||
await overlayGone();
|
||||
// After its success pane and exit.
|
||||
await overlayGone(document, '.app-feedback-overlay');
|
||||
} catch (e) {
|
||||
console.error('feedback embed: dialog failed', e);
|
||||
}
|
||||
|
||||
@@ -747,11 +747,6 @@ window.update_auth_data = async (auth_token, user) => {
|
||||
window.public_path = `/${ window.user.username }/Public`;
|
||||
window.shared_path = 'puter://shared';
|
||||
|
||||
if ( window.user !== null && !window.user.is_temp ) {
|
||||
$('.user-options-login-btn, .user-options-create-account-btn').hide();
|
||||
$('.user-options-menu-btn').show();
|
||||
}
|
||||
|
||||
// Search and store user templates (non-blocking)
|
||||
window.available_templates();
|
||||
};
|
||||
@@ -2032,7 +2027,6 @@ window.move_items = async function (el_items, dest_path, is_undo = false) {
|
||||
if ( $(el_item).attr('data-is_dir') === '1' ) {
|
||||
// Its websites stay registered: the server doesn't
|
||||
// serve a root in Trash, and restoring brings them back.
|
||||
$(`.mywebsites-dir-path[data-uuid="${$(el_item).attr('data-uid')}"]`).remove();
|
||||
// remove the website badge from all instances of the dir
|
||||
$(`.item[data-uid="${$(el_item).attr('data-uid')}"]`).find('.item-has-website-badge').fadeOut(300);
|
||||
}
|
||||
@@ -2195,37 +2189,6 @@ window.move_items = async function (el_items, dest_path, is_undo = false) {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Refreshes the desktop background based on the user's settings.
|
||||
* If the user has set a custom desktop background URL or color, it will use that.
|
||||
* If not, it defaults to a specific wallpaper image.
|
||||
*
|
||||
* @global
|
||||
* @function
|
||||
* @fires set_desktop_background - Calls this global function to set the desktop background.
|
||||
*
|
||||
* @example
|
||||
* // This will refresh the desktop background according to the user's preference or defaults.
|
||||
* window.refresh_desktop_background();
|
||||
*/
|
||||
window.refresh_desktop_background = function () {
|
||||
if ( window.user && (window.user.desktop_bg_url !== null || window.user.desktop_bg_color !== null) ) {
|
||||
window.set_desktop_background({
|
||||
url: window.user.desktop_bg_url,
|
||||
fit: window.user.desktop_bg_fit,
|
||||
color: window.user.desktop_bg_color,
|
||||
});
|
||||
}
|
||||
// default background
|
||||
else {
|
||||
let wallpaper = (window.gui_env === 'prod') ? 'https://puter-assets.b-cdn.net/wallpaper.webp' : '/src/images/wallpaper.webp';
|
||||
window.set_desktop_background({
|
||||
url: wallpaper,
|
||||
fit: 'cover',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
window.determine_website_url = function (fsentry_path) {
|
||||
// The address an item has under a site serving a folder above it. The
|
||||
// site's folder and address come with its root_dir.
|
||||
|
||||
@@ -20,10 +20,7 @@
|
||||
import UIAlert from '../UI/UIAlert.js';
|
||||
|
||||
import UIWindowItemProperties from '../UI/UIWindowItemProperties.js';
|
||||
import UIWindowPublishWorker from '../UI/UIWindowPublishWorker.js';
|
||||
import UIWindowShare from '../UI/UIWindowShare.js';
|
||||
import publish_as_website from './publishAsWebsite.js';
|
||||
import ensure_can_publish from './ensureCanPublish.js';
|
||||
import open_item from './openItem.js';
|
||||
import openWithAI from './openWithAI.js';
|
||||
import launch_app from './launchApp.js';
|
||||
@@ -46,9 +43,9 @@ import { is_default_app } from './defaultApp.js';
|
||||
* @param {Function} options.onOpen - Optional custom open handler (used by Dashboard)
|
||||
* @param {boolean} options.openWithInNewTab - Open the "Open With" apps in a new browser tab instead of an in-page window (used by Dashboard)
|
||||
* @param {Function} options.onShowProperties - Optional custom properties handler (used by Dashboard); receives {name, path, uid, element}
|
||||
* @param {Function} options.onShare - Optional custom share handler (used by Dashboard); receives {name, path, uid, element}
|
||||
* @param {Function} options.onShare - Opens sharing for the item; Share is left out of the menu without it. Receives {name, path, uid, element}
|
||||
* @param {Function} options.onPublishWebsite - Optional custom publish-as-website handler (used by Dashboard); receives {uid, name, path}
|
||||
* @param {Function} options.onPublishWorker - Optional custom publish-as-worker handler (used by Dashboard); receives {uid, name, path}
|
||||
* @param {Function} options.onPublishWorker - Publishes the file as a worker; Publish as Worker is left out of the menu without it. Receives {uid, name, path}
|
||||
* @param {Function} options.onPasteInto - Optional custom paste handler (used by Dashboard); receives the folder's path
|
||||
* @param {Function} options.onRemovedFromShared - Optional, called once Remove from Shared has dropped the user's own access (used by Dashboard)
|
||||
* @returns {Promise<Array>} Array of context menu items
|
||||
@@ -164,22 +161,16 @@ const generate_file_context_menu = async function (options) {
|
||||
// Publish as Worker
|
||||
// -------------------------------------------
|
||||
// The backend refuses deploys from a file someone else owns.
|
||||
if ( !is_trashed && !is_trash && !is_not_mine && !fsentry.is_dir && $(el_item).attr('data-name').toLowerCase().endsWith('.js') ) {
|
||||
if ( !is_trashed && !is_trash && !is_not_mine && !fsentry.is_dir && $(el_item).attr('data-name').toLowerCase().endsWith('.js') && options.onPublishWorker ) {
|
||||
menu_items.push({
|
||||
html: i18n('publish_as_serverless_worker'),
|
||||
disabled: is_worker,
|
||||
onClick: async function () {
|
||||
const target = {
|
||||
onClick: function () {
|
||||
options.onPublishWorker({
|
||||
uid: fsentry.uid,
|
||||
name: $(el_item).attr('data-name'),
|
||||
path: $(el_item).attr('data-path'),
|
||||
};
|
||||
if ( options.onPublishWorker ) {
|
||||
options.onPublishWorker(target);
|
||||
return;
|
||||
}
|
||||
if ( ! await ensure_can_publish(true) ) return;
|
||||
UIWindowPublishWorker(target.uid, target.name, target.path);
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -221,25 +212,15 @@ const generate_file_context_menu = async function (options) {
|
||||
// -------------------------------------------
|
||||
// Share
|
||||
// -------------------------------------------
|
||||
if ( !is_trash && !is_trashed && may_share ) {
|
||||
if ( !is_trash && !is_trashed && may_share && options.onShare ) {
|
||||
menu_items.push({
|
||||
html: i18n('share_ellipsis'),
|
||||
onClick: async function () {
|
||||
// The Dashboard swaps in its own responsive modal via this hook;
|
||||
// everywhere else falls back to the desktop share window.
|
||||
if ( options.onShare ) {
|
||||
options.onShare({
|
||||
name: $(el_item).attr('data-name'),
|
||||
path: $(el_item).attr('data-path'),
|
||||
uid: $(el_item).attr('data-uid'),
|
||||
element: el_item,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
UIWindowShare({
|
||||
path: $(el_item).attr('data-path'),
|
||||
options.onShare({
|
||||
name: $(el_item).attr('data-name'),
|
||||
path: $(el_item).attr('data-path'),
|
||||
uid: $(el_item).attr('data-uid'),
|
||||
element: el_item,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
@@ -23,18 +23,15 @@ import jQuery from '../lib/jquery-3.6.1/jquery-3.6.1.min.js';
|
||||
|
||||
vi.mock('../UI/UIAlert.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('../UI/UIWindowItemProperties.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('../UI/UIWindowPublishWorker.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('../UI/UIWindowShare.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./publishAsWebsite.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./ensureCanPublish.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./openItem.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./openWithAI.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./launchApp.js', () => ({ default: vi.fn() }));
|
||||
vi.mock('./pathOwner.js', () => ({ is_owned_by_me: () => false }));
|
||||
vi.mock('./pathOwner.js', () => ({ is_owned_by_me: vi.fn(() => false) }));
|
||||
vi.mock('./sharedAccess.js', () => ({
|
||||
can_rename: async () => false,
|
||||
can_restructure: async () => false,
|
||||
can_share: async () => false,
|
||||
can_share: vi.fn(async () => false),
|
||||
invalidate_shared_roots: vi.fn(),
|
||||
}));
|
||||
|
||||
@@ -52,6 +49,8 @@ const { default: generate_file_context_menu } =
|
||||
await import('./generateFileContextMenu.js');
|
||||
const { default: launch_app } = await import('./launchApp.js');
|
||||
const { default: UIAlert } = await import('../UI/UIAlert.js');
|
||||
const { can_share } = await import('./sharedAccess.js');
|
||||
const { is_owned_by_me } = await import('./pathOwner.js');
|
||||
|
||||
const sharedRow = () => {
|
||||
const row = document.createElement('div');
|
||||
@@ -89,6 +88,62 @@ it('does not offer it on a share held through a team', async () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe('Share', () => {
|
||||
const shareItem = async (options) => {
|
||||
can_share.mockResolvedValueOnce(true);
|
||||
const items = await generate_file_context_menu({
|
||||
element: sharedRow(),
|
||||
fsentry: { name: 'notes.txt', path: '/ann/uid-1/notes.txt' },
|
||||
associated_app_name: 'editor',
|
||||
...options,
|
||||
});
|
||||
return items.find((item) => item !== '-' && item.html === 'share_ellipsis');
|
||||
};
|
||||
|
||||
it('hands the item to onShare', async () => {
|
||||
const onShare = vi.fn();
|
||||
await (await shareItem({ onShare })).onClick();
|
||||
expect(onShare).toHaveBeenCalledWith(expect.objectContaining({
|
||||
name: 'notes.txt',
|
||||
path: '/ann/uid-1/notes.txt',
|
||||
}));
|
||||
});
|
||||
|
||||
it('is left out without onShare', async () => {
|
||||
expect(await shareItem({})).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Publish as Worker', () => {
|
||||
const publishItem = async (options) => {
|
||||
is_owned_by_me.mockReturnValueOnce(true);
|
||||
const row = document.createElement('div');
|
||||
row.setAttribute('data-path', '/me/worker.js');
|
||||
row.setAttribute('data-name', 'worker.js');
|
||||
const items = await generate_file_context_menu({
|
||||
element: row,
|
||||
fsentry: { uid: 'file-1', name: 'worker.js', path: '/me/worker.js' },
|
||||
associated_app_name: 'editor',
|
||||
...options,
|
||||
});
|
||||
return items.find((item) => item !== '-' && item.html === 'publish_as_serverless_worker');
|
||||
};
|
||||
|
||||
it('hands the file to onPublishWorker', async () => {
|
||||
const onPublishWorker = vi.fn();
|
||||
await (await publishItem({ onPublishWorker })).onClick();
|
||||
expect(onPublishWorker).toHaveBeenCalledWith({
|
||||
uid: 'file-1',
|
||||
name: 'worker.js',
|
||||
path: '/me/worker.js',
|
||||
});
|
||||
});
|
||||
|
||||
it('is left out without onPublishWorker', async () => {
|
||||
expect(await publishItem({})).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Remove from Shared', () => {
|
||||
const remove = async (fsentry) => {
|
||||
const row = sharedRow();
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Resolves once no element matching `selector` is left on `doc`'s body, such
|
||||
* as a dialog's overlay after its exit transition.
|
||||
*
|
||||
* @param {Document} doc
|
||||
* @param {string} selector
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export const overlayGone = (doc, selector) => new Promise((resolve) => {
|
||||
const gone = () => !doc.querySelector(selector);
|
||||
if ( gone() ) return resolve();
|
||||
const observer = new doc.defaultView.MutationObserver(() => {
|
||||
if ( ! gone() ) return;
|
||||
observer.disconnect();
|
||||
resolve();
|
||||
});
|
||||
observer.observe(doc.body, { childList: true });
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright (C) 2024-present Puter Technologies Inc.
|
||||
*
|
||||
* This file is part of Puter.
|
||||
*
|
||||
* Puter is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published
|
||||
* by the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { overlayGone } from './overlayGone.js';
|
||||
|
||||
const settled = async (promise) => {
|
||||
let done = false;
|
||||
promise.then(() => {
|
||||
done = true;
|
||||
});
|
||||
// Mutation observers report in a microtask.
|
||||
await new Promise((resolve) => setTimeout(resolve));
|
||||
return done;
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
describe('overlayGone', () => {
|
||||
it('resolves at once when no overlay is on the page', async () => {
|
||||
expect(await settled(overlayGone(document, '.overlay'))).toBe(true);
|
||||
});
|
||||
|
||||
it('waits until the overlay is removed', async () => {
|
||||
document.body.innerHTML = '<div class="overlay"></div><p></p>';
|
||||
const gone = overlayGone(document, '.overlay');
|
||||
expect(await settled(gone)).toBe(false);
|
||||
|
||||
// Another element leaving isn't the overlay leaving.
|
||||
document.querySelector('p').remove();
|
||||
expect(await settled(gone)).toBe(false);
|
||||
|
||||
document.querySelector('.overlay').remove();
|
||||
expect(await settled(gone)).toBe(true);
|
||||
});
|
||||
|
||||
it('waits for every matching overlay', async () => {
|
||||
document.body.innerHTML = '<div class="overlay"></div><div class="overlay"></div>';
|
||||
const gone = overlayGone(document, '.overlay');
|
||||
document.querySelector('.overlay').remove();
|
||||
expect(await settled(gone)).toBe(false);
|
||||
document.querySelector('.overlay').remove();
|
||||
expect(await settled(gone)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -30,7 +30,9 @@ export const FRAMED_POPUP_ACTIONS = new Set([
|
||||
'show-save-file-picker',
|
||||
'show-directory-picker',
|
||||
'upgrade',
|
||||
'top-up',
|
||||
'request-email-confirmation',
|
||||
'attach-custom-domain',
|
||||
]);
|
||||
|
||||
// Actions a frame shows only for the user the framing page is signed in as.
|
||||
@@ -39,17 +41,19 @@ const HOST_USER_ACTIONS = new Set([
|
||||
'show-save-file-picker',
|
||||
'show-directory-picker',
|
||||
'upgrade',
|
||||
'top-up',
|
||||
'request-email-confirmation',
|
||||
'attach-custom-domain',
|
||||
]);
|
||||
|
||||
// Actions framed over the whole page with no box, which their own dialog's
|
||||
// scrim covers.
|
||||
const TRANSPARENT_ACTIONS = new Set(['upgrade', 'request-email-confirmation']);
|
||||
const TRANSPARENT_ACTIONS = new Set(['upgrade', 'top-up', 'request-email-confirmation', 'attach-custom-domain']);
|
||||
|
||||
const UPGRADE_REASONS = new Set(['funds', 'subscription', 'storage']);
|
||||
const UPGRADE_METHOD_MAX = 200;
|
||||
|
||||
// Modal UI the upgrade dialog and the GUI's windows show. Once some has shown
|
||||
// Modal UI the upgrade and top-up dialogs and the GUI's windows show. Once some has shown
|
||||
// and all of it has been gone this long, the dialog closed without reporting
|
||||
// it, and the frame mustn't be left covering the page.
|
||||
const UPGRADE_MODAL_UI = '.window, [aria-modal="true"]';
|
||||
@@ -64,7 +68,7 @@ const FOCUS_RETRIES = 20;
|
||||
export const POPUP_FRAME_MSG = 'puterPopupFrame';
|
||||
|
||||
// The popup's query parameters a framing page may pass, in the fragment.
|
||||
const FRAGMENT_PARAMS = ['msg_id', 'options', 'request_auth'];
|
||||
const FRAGMENT_PARAMS = ['msg_id', 'options', 'request_auth', 'subdomain'];
|
||||
|
||||
// The account checks a sign-in can show (email, phone, card), and the
|
||||
// save-account window an email confirmation shows a temporary account first,
|
||||
@@ -233,6 +237,20 @@ export const closeAccountChecksOnEscape = (win, close = () => win.close()) => {
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether the GUI session `session` (its `/whoami`) has no account check
|
||||
* waiting. Those show at boot with no way to close the frame.
|
||||
*
|
||||
* @param {Record<string, unknown> | null} session
|
||||
* @returns {boolean}
|
||||
*/
|
||||
const hasNoAccountCheck = (session) =>
|
||||
!!session &&
|
||||
!session.requires_email_confirmation &&
|
||||
!session.requires_phone_verification &&
|
||||
!session.requires_card_verification &&
|
||||
!session.requires_password_change;
|
||||
|
||||
/**
|
||||
* Whether a framed upgrade can show for the GUI session `session` (its
|
||||
* `/whoami`): the deployment has an upgrade dialog that reports when it
|
||||
@@ -244,12 +262,29 @@ export const closeAccountChecksOnEscape = (win, close = () => win.close()) => {
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export const canShowUpgradeFrame = (win, session) =>
|
||||
win.UIUpgradeAccount?.embeddable === true &&
|
||||
!!session &&
|
||||
!session.requires_email_confirmation &&
|
||||
!session.requires_phone_verification &&
|
||||
!session.requires_card_verification &&
|
||||
!session.requires_password_change;
|
||||
win.UIUpgradeAccount?.embeddable === true && hasNoAccountCheck(session);
|
||||
|
||||
/**
|
||||
* Whether a framed custom domain dialog can show for the GUI session
|
||||
* `session` (its `/whoami`): no account check is waiting, which a frame
|
||||
* couldn't be closed from.
|
||||
*
|
||||
* @param {Record<string, unknown> | null} session
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export const canShowCustomDomainFrame = (session) => hasNoAccountCheck(session);
|
||||
|
||||
/**
|
||||
* Whether a framed top-up can show for the GUI session `session` (its
|
||||
* `/whoami`): the deployment has a top-up dialog that reports when it closes,
|
||||
* and no account check is waiting, which a frame couldn't be closed from.
|
||||
*
|
||||
* @param {Window} win
|
||||
* @param {Record<string, unknown> | null} session
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export const canShowTopUpFrame = (win, session) =>
|
||||
win.UITopUp?.embeddable === true && hasNoAccountCheck(session);
|
||||
|
||||
/**
|
||||
* Whether a framed email confirmation can show for the GUI session `session`
|
||||
@@ -300,19 +335,18 @@ export const framedUpgradeDetails = (hash) => {
|
||||
};
|
||||
|
||||
/**
|
||||
* Shows the deployment's upgrade dialog in a framed popup and tells the
|
||||
* Shows one of the deployment's dialogs in a framed popup and tells the
|
||||
* framing page it's ready once it's open, or before it opens when the page
|
||||
* still hides the frame. Resolves whether the user upgraded,
|
||||
* once the dialog closes, or false once every dialog and window it showed has
|
||||
* gone without it reporting a close.
|
||||
* still hides the frame. Resolves what the dialog reports when it closes, or
|
||||
* false once every dialog and window it showed has gone without it reporting
|
||||
* a close.
|
||||
*
|
||||
* @param {Window} win
|
||||
* @param {{ appUid?: string, reason?: string, method?: string }} attribution - what prompted it;
|
||||
* an empty one is passed as null, so the dialog credits the prompt it remembers
|
||||
* @param {(closed: (result: boolean) => void) => unknown} open - opens the dialog, which calls `closed` when it closes
|
||||
* @param {(state: 'ready') => void} tell
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
export const showFramedUpgrade = (win, attribution, tell) => new Promise((resolve, reject) => {
|
||||
const showFramedDialog = (win, open, tell) => new Promise((resolve, reject) => {
|
||||
let settled = false;
|
||||
let seen = false;
|
||||
let goneTimer = null;
|
||||
@@ -345,21 +379,47 @@ export const showFramedUpgrade = (win, attribution, tell) => new Promise((resolv
|
||||
toldReady = true;
|
||||
tell('ready');
|
||||
};
|
||||
const open = () => {
|
||||
const dialog = new win.UIUpgradeAccount({
|
||||
attribution: Object.keys(attribution).length ? attribution : null,
|
||||
onClose: (result) => settle(() => resolve(result?.upgraded === true)),
|
||||
});
|
||||
return dialog.open_as_window();
|
||||
};
|
||||
whenFrameSized(win, ready)
|
||||
.then(open)
|
||||
.then(() => open((result) => settle(() => resolve(result))))
|
||||
.then(() => {
|
||||
check();
|
||||
ready();
|
||||
}, (e) => settle(() => reject(e)));
|
||||
});
|
||||
|
||||
/**
|
||||
* Shows the deployment's upgrade dialog in a framed popup. Resolves whether
|
||||
* the user upgraded, once the dialog closes.
|
||||
*
|
||||
* @param {Window} win
|
||||
* @param {{ appUid?: string, reason?: string, method?: string }} attribution - what prompted it;
|
||||
* an empty one is passed as null, so the dialog credits the prompt it remembers
|
||||
* @param {(state: 'ready') => void} tell
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
export const showFramedUpgrade = (win, attribution, tell) => showFramedDialog(win, (closed) => {
|
||||
const dialog = new win.UIUpgradeAccount({
|
||||
attribution: Object.keys(attribution).length ? attribution : null,
|
||||
onClose: (result) => closed(result?.upgraded === true),
|
||||
});
|
||||
return dialog.open_as_window();
|
||||
}, tell);
|
||||
|
||||
/**
|
||||
* Shows the deployment's top-up dialog in a framed popup. Resolves whether
|
||||
* the user bought credit, once the dialog closes.
|
||||
*
|
||||
* @param {Window} win
|
||||
* @param {(state: 'ready') => void} tell
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
export const showFramedTopUp = (win, tell) => showFramedDialog(win, (closed) => {
|
||||
const dialog = new win.UITopUp({
|
||||
onClose: (result) => closed(result?.toppedUp === true),
|
||||
});
|
||||
return dialog.open();
|
||||
}, tell);
|
||||
|
||||
/**
|
||||
* Resolves once the frame has a viewport. The page keeps a loading frame
|
||||
* hidden, which Chromium and WebKit lay out at 0x0, and a GUI window opened
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
POPUP_FRAME_MSG,
|
||||
canShowCustomDomainFrame,
|
||||
canShowEmailConfirmationFrame,
|
||||
canShowTopUpFrame,
|
||||
canShowUpgradeFrame,
|
||||
closeAccountChecksOnEscape,
|
||||
confirmEmailInFrame,
|
||||
@@ -11,6 +13,7 @@ import {
|
||||
framedPopupParams,
|
||||
framedUpgradeDetails,
|
||||
framesHostUser,
|
||||
showFramedTopUp,
|
||||
showFramedUpgrade,
|
||||
startPopupFrame,
|
||||
} from './popupFrame.js';
|
||||
@@ -50,7 +53,9 @@ describe('framedPopupAction', () => {
|
||||
['/embed/show-save-file-picker', 'show-save-file-picker'],
|
||||
['/embed/show-directory-picker', 'show-directory-picker'],
|
||||
['/embed/upgrade', 'upgrade'],
|
||||
['/embed/top-up', 'top-up'],
|
||||
['/embed/request-email-confirmation', 'request-email-confirmation'],
|
||||
['/embed/attach-custom-domain', 'attach-custom-domain'],
|
||||
['/embed/apps', null],
|
||||
['/embed/feedback', null],
|
||||
['/embed/request-permission', null],
|
||||
@@ -65,11 +70,12 @@ describe('framedPopupAction', () => {
|
||||
|
||||
describe('framedPopupParams', () => {
|
||||
it('keeps only the popup parameters a framing page may pass', () => {
|
||||
const params = framedPopupParams('#msg_id=7&options=%7B%22multiple%22%3Atrue%7D&request_auth=true&user=abc&auth_token=x&attempt_temp_user_creation=true&api_origin=https%3A%2F%2Fevil.test');
|
||||
const params = framedPopupParams('#msg_id=7&options=%7B%22multiple%22%3Atrue%7D&request_auth=true&subdomain=mysite&user=abc&auth_token=x&attempt_temp_user_creation=true&api_origin=https%3A%2F%2Fevil.test');
|
||||
expect(Object.fromEntries(params)).toEqual({
|
||||
msg_id: '7',
|
||||
options: '{"multiple":true}',
|
||||
request_auth: 'true',
|
||||
subdomain: 'mysite',
|
||||
});
|
||||
});
|
||||
|
||||
@@ -85,7 +91,9 @@ describe('framesHostUser', () => {
|
||||
['show-save-file-picker', true],
|
||||
['show-directory-picker', true],
|
||||
['upgrade', true],
|
||||
['top-up', true],
|
||||
['request-email-confirmation', true],
|
||||
['attach-custom-domain', true],
|
||||
['sign-in', false],
|
||||
[null, false],
|
||||
])('%s serves only the framing page\'s user: %s', (action, expected) => {
|
||||
@@ -133,6 +141,55 @@ describe('canShowUpgradeFrame', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('canShowTopUpFrame', () => {
|
||||
const win = { UITopUp: Object.assign(function () {}, { embeddable: true }) };
|
||||
const session = { uuid: 'u-1' };
|
||||
|
||||
it('shows for a session with nothing to verify, when the dialog reports its close', () => {
|
||||
expect(canShowTopUpFrame(win, session)).toBe(true);
|
||||
});
|
||||
|
||||
it('needs a top-up dialog that reports its close, whatever the upgrade dialog does', () => {
|
||||
expect(canShowTopUpFrame({}, session)).toBe(false);
|
||||
expect(canShowTopUpFrame({ UITopUp: function () {} }, session)).toBe(false);
|
||||
expect(canShowTopUpFrame({ UIUpgradeAccount: Object.assign(function () {}, { embeddable: true }) }, session)).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'requires_email_confirmation',
|
||||
'requires_phone_verification',
|
||||
'requires_card_verification',
|
||||
'requires_password_change',
|
||||
])('leaves an account with %s to the tab', (check) => {
|
||||
expect(canShowTopUpFrame(win, { ...session, [check]: true })).toBe(false);
|
||||
});
|
||||
|
||||
it('needs a session', () => {
|
||||
expect(canShowTopUpFrame(win, null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('canShowCustomDomainFrame', () => {
|
||||
const session = { uuid: 'u-1' };
|
||||
|
||||
it('shows for a session with nothing to verify', () => {
|
||||
expect(canShowCustomDomainFrame(session)).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'requires_email_confirmation',
|
||||
'requires_phone_verification',
|
||||
'requires_card_verification',
|
||||
'requires_password_change',
|
||||
])('leaves an account with %s to the popup', (check) => {
|
||||
expect(canShowCustomDomainFrame({ ...session, [check]: true })).toBe(false);
|
||||
});
|
||||
|
||||
it('needs a session', () => {
|
||||
expect(canShowCustomDomainFrame(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('canShowEmailConfirmationFrame', () => {
|
||||
const session = { uuid: 'u-1' };
|
||||
|
||||
@@ -361,6 +418,64 @@ describe('showFramedUpgrade', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('showFramedTopUp', () => {
|
||||
const topUpWindow = (open) => {
|
||||
const events = new EventTarget();
|
||||
return {
|
||||
document,
|
||||
innerWidth: 1280,
|
||||
innerHeight: 800,
|
||||
addEventListener: events.addEventListener.bind(events),
|
||||
removeEventListener: events.removeEventListener.bind(events),
|
||||
MutationObserver: window.MutationObserver,
|
||||
UITopUp: function (options) {
|
||||
this.open = () => open(options);
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('tells the page it is ready once open, and resolves whether credit was bought', async () => {
|
||||
const tell = vi.fn();
|
||||
let options;
|
||||
const result = showFramedTopUp(topUpWindow(async (o) => {
|
||||
options = o;
|
||||
}), tell);
|
||||
await vi.waitFor(() => expect(tell).toHaveBeenCalledWith('ready'));
|
||||
expect(tell).toHaveBeenCalledTimes(1);
|
||||
|
||||
options.onClose({ toppedUp: true });
|
||||
await expect(result).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it('resolves false for a close without a purchase', async () => {
|
||||
await expect(showFramedTopUp(topUpWindow(async (o) => o.onClose({ toppedUp: false })), vi.fn())).resolves.toBe(false);
|
||||
await expect(showFramedTopUp(topUpWindow(async (o) => o.onClose()), vi.fn())).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('resolves false once the dialog is gone without reporting a close', async () => {
|
||||
vi.useFakeTimers();
|
||||
const root = document.createElement('div');
|
||||
root.setAttribute('aria-modal', 'true');
|
||||
const result = showFramedTopUp(topUpWindow(async () => {
|
||||
document.body.append(root);
|
||||
}), vi.fn());
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
root.remove();
|
||||
await vi.advanceTimersByTimeAsync(600);
|
||||
await expect(result).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('rejects when the dialog fails to open', async () => {
|
||||
await expect(showFramedTopUp(topUpWindow(async () => {
|
||||
throw new Error('no dialog');
|
||||
}), vi.fn())).rejects.toThrow('no dialog');
|
||||
});
|
||||
});
|
||||
|
||||
describe('startPopupFrame', () => {
|
||||
it('does nothing without a framing page to answer', () => {
|
||||
const win = frameWindow();
|
||||
@@ -396,6 +511,11 @@ describe('startPopupFrame', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('lets the framing page show through a top-up frame', () => {
|
||||
startPopupFrame({ ...frameWindow(), location: { pathname: '/embed/top-up' } }, HOST);
|
||||
expect(document.documentElement.classList.contains('popup-frame-transparent')).toBe(true);
|
||||
});
|
||||
|
||||
it('lets the framing page show through an upgrade or email confirmation frame only', () => {
|
||||
startPopupFrame({ ...frameWindow(), location: { pathname: '/embed/sign-in' } }, HOST);
|
||||
expect(document.documentElement.classList.contains('popup-frame-transparent')).toBe(false);
|
||||
@@ -406,6 +526,10 @@ describe('startPopupFrame', () => {
|
||||
document.documentElement.classList.remove('popup-frame-transparent');
|
||||
startPopupFrame({ ...frameWindow(), location: { pathname: '/embed/request-email-confirmation' } }, HOST);
|
||||
expect(document.documentElement.classList.contains('popup-frame-transparent')).toBe(true);
|
||||
|
||||
document.documentElement.classList.remove('popup-frame-transparent');
|
||||
startPopupFrame({ ...frameWindow(), location: { pathname: '/embed/attach-custom-domain' } }, HOST);
|
||||
expect(document.documentElement.classList.contains('popup-frame-transparent')).toBe(true);
|
||||
});
|
||||
|
||||
it('sends a boolean field with a state', () => {
|
||||
|
||||
@@ -23,10 +23,10 @@ import { colleagues_for_sharing } from './shareTeams.js';
|
||||
import { recent_recipients, remember_recipient } from './shareRecents.js';
|
||||
import { build_suggestions, recipient_for } from './shareSuggest.js';
|
||||
|
||||
// Turns the sharing dialogs' recipient field into one control for every kind of
|
||||
// Turns the share modal's recipient field into one control for every kind of
|
||||
// recipient: a colleague, a whole team, someone shared with before, or an
|
||||
// address typed from scratch. Shared by both dialogs so the two can't drift;
|
||||
// each styles the `share-suggest-*` classes through its own tokens.
|
||||
// address typed from scratch. The host styles the `share-suggest-*` classes
|
||||
// through its own tokens.
|
||||
|
||||
const teamIcon = `<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"/></svg>`;
|
||||
const clearIcon = `<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" aria-hidden="true"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>`;
|
||||
@@ -77,7 +77,7 @@ export default function shareRecipientPicker ({
|
||||
const list_id = `share-suggest-list-${++picker_seq}`;
|
||||
|
||||
const $field = $('<div class="share-suggest-field"></div>');
|
||||
// Both dialogs focus this field as they open, and an element that leaves
|
||||
// The share modal focuses this field as it opens, and an element that leaves
|
||||
// the document — which is what moving it into the wrapper does — takes its
|
||||
// focus with it. Put it back rather than leaving the caller to notice.
|
||||
const had_focus = document.activeElement === $input.get(0);
|
||||
@@ -360,8 +360,8 @@ export default function shareRecipientPicker ({
|
||||
|
||||
// -- Input wiring --
|
||||
|
||||
// Opened by a real interaction, not by focus: both dialogs focus this field
|
||||
// as they open, and a list unfurled before the user has looked at the
|
||||
// Opened by a real interaction, not by focus: the share modal focuses this
|
||||
// field as it opens, and a list unfurled before the user has looked at the
|
||||
// dialog would push everything else out of view.
|
||||
$input.on('click', () => open_list());
|
||||
|
||||
|
||||
Loaded 100 of 182 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user