@axium/office 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,257 @@
1
+ import * as z from 'zod';
2
+ export declare const kinds: readonly ["document", "spreadsheet", "presentation"];
3
+ export declare const Kind: z.ZodLiteral<"document" | "spreadsheet" | "presentation">;
4
+ export type Kind = z.infer<typeof Kind>;
5
+ export interface Format {
6
+ extension: string;
7
+ type: string;
8
+ kind: Kind;
9
+ }
10
+ export declare const formats: readonly Format[];
11
+ /** The format new documents of each kind are created in */
12
+ export declare const newFormats: {
13
+ document: Format;
14
+ spreadsheet: Format;
15
+ presentation: Format;
16
+ };
17
+ export declare const icons: {
18
+ document: string;
19
+ spreadsheet: string;
20
+ presentation: string;
21
+ };
22
+ /** Matches by MIME type first, since browsers set it on upload, then by extension */
23
+ export declare function formatOf(item: {
24
+ name: string;
25
+ type: string;
26
+ }): Format | undefined;
27
+ export declare const Config: z.ZodObject<{
28
+ server_url: z.ZodOptional<z.ZodNullable<z.ZodURL>>;
29
+ internal_url: z.ZodOptional<z.ZodNullable<z.ZodURL>>;
30
+ secret: z.ZodString;
31
+ }, z.core.$strip>;
32
+ export interface Config extends z.infer<typeof Config> {
33
+ }
34
+ declare module '@axium/core/plugins' {
35
+ interface $PluginConfigs {
36
+ '@axium/office': Config;
37
+ }
38
+ }
39
+ export declare const EditorOptions: z.ZodObject<{
40
+ mobile: z.ZodBoolean;
41
+ }, z.core.$strip>;
42
+ export interface EditorOptions extends z.infer<typeof EditorOptions> {
43
+ }
44
+ export declare const Editor: z.ZodObject<{
45
+ url: z.ZodURL;
46
+ config: z.ZodRecord<z.ZodString, z.ZodUnknown>;
47
+ }, z.core.$strip>;
48
+ export interface Editor extends z.infer<typeof Editor> {
49
+ }
50
+ export declare const EditorSession: z.ZodObject<{
51
+ item: z.ZodObject<{
52
+ createdAt: z.ZodCoercedDate<unknown>;
53
+ dataURL: z.ZodString;
54
+ hash: z.ZodOptional<z.ZodNullable<z.ZodString>>;
55
+ id: z.ZodUUID;
56
+ immutable: z.ZodBoolean;
57
+ modifiedAt: z.ZodCoercedDate<unknown>;
58
+ name: z.ZodString;
59
+ userId: z.ZodUUID;
60
+ parentId: z.ZodNullable<z.ZodUUID>;
61
+ size: z.ZodCoercedBigInt<unknown>;
62
+ trashedAt: z.ZodNullable<z.ZodCoercedDate<unknown>>;
63
+ type: z.ZodString;
64
+ metadata: z.ZodRecord<z.ZodString, z.ZodUnknown>;
65
+ acl: z.ZodOptional<z.ZodArray<z.ZodObject<{
66
+ itemId: z.ZodUUID;
67
+ userId: z.ZodOptional<z.ZodNullable<z.ZodUUID>>;
68
+ role: z.ZodOptional<z.ZodNullable<z.ZodString>>;
69
+ tag: z.ZodOptional<z.ZodNullable<z.ZodString>>;
70
+ user: z.ZodOptional<z.ZodNullable<z.ZodObject<{
71
+ id: z.ZodUUID;
72
+ name: z.ZodString;
73
+ username: z.ZodString;
74
+ email: z.ZodOptional<z.ZodOptional<z.ZodNullable<z.ZodEmail>>>;
75
+ emailVerified: z.ZodOptional<z.ZodOptional<z.ZodNullable<z.ZodCoercedDate<unknown>>>>;
76
+ preferences: z.ZodOptional<z.ZodLazy<z.ZodObject<{
77
+ debug: z.ZodDefault<z.ZodBoolean>;
78
+ theme: z.ZodDefault<z.ZodLiteral<"default" | "light" | "forest" | "midnight" | "beach" | "cherry" | "volcano">>;
79
+ time_zone: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<string>, z.ZodString]>>;
80
+ }, z.core.$strip>>>;
81
+ roles: z.ZodArray<z.ZodString>;
82
+ tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
83
+ registeredAt: z.ZodCoercedDate<unknown>;
84
+ isAdmin: z.ZodOptional<z.ZodBoolean>;
85
+ isSuspended: z.ZodOptional<z.ZodBoolean>;
86
+ }, z.core.$strip>>>;
87
+ createdAt: z.ZodCoercedDate<unknown>;
88
+ }, z.core.$catchall<z.ZodBoolean>>>>;
89
+ parents: z.ZodOptional<z.ZodArray<z.ZodObject<{
90
+ id: z.ZodUUID;
91
+ name: z.ZodString;
92
+ }, z.core.$strip>>>;
93
+ sync: z.ZodOptional<z.ZodNullable<z.ZodObject<{
94
+ rules: z.ZodArray<z.ZodTemplateLiteral<`+${string}` | `-${string}`>>;
95
+ hidden: z.ZodBoolean;
96
+ createdAt: z.ZodCoercedDate<unknown>;
97
+ devices: z.ZodArray<z.ZodObject<{
98
+ host: z.ZodString;
99
+ localPath: z.ZodString;
100
+ lastSynced: z.ZodNullable<z.ZodCoercedDate<unknown>>;
101
+ itemId: z.ZodUUID;
102
+ userId: z.ZodUUID;
103
+ }, z.core.$strip>>;
104
+ }, z.core.$strip>>>;
105
+ }, z.core.$strip>;
106
+ readOnly: z.ZodBoolean;
107
+ canRename: z.ZodBoolean;
108
+ editor: z.ZodObject<{
109
+ url: z.ZodURL;
110
+ config: z.ZodRecord<z.ZodString, z.ZodUnknown>;
111
+ }, z.core.$strip>;
112
+ }, z.core.$strip>;
113
+ export interface EditorSession extends z.infer<typeof EditorSession> {
114
+ }
115
+ export declare const NewDocument: z.ZodObject<{
116
+ kind: z.ZodLiteral<"document" | "spreadsheet" | "presentation">;
117
+ name: z.ZodString;
118
+ parentId: z.ZodOptional<z.ZodNullable<z.ZodUUID>>;
119
+ }, z.core.$strip>;
120
+ export interface NewDocument extends z.infer<typeof NewDocument> {
121
+ }
122
+ declare const OfficeAPI: {
123
+ readonly office: {
124
+ readonly PUT: readonly [z.ZodObject<{
125
+ kind: z.ZodLiteral<"document" | "spreadsheet" | "presentation">;
126
+ name: z.ZodString;
127
+ parentId: z.ZodOptional<z.ZodNullable<z.ZodUUID>>;
128
+ }, z.core.$strip>, z.ZodObject<{
129
+ createdAt: z.ZodCoercedDate<unknown>;
130
+ dataURL: z.ZodString;
131
+ hash: z.ZodOptional<z.ZodNullable<z.ZodString>>;
132
+ id: z.ZodUUID;
133
+ immutable: z.ZodBoolean;
134
+ modifiedAt: z.ZodCoercedDate<unknown>;
135
+ name: z.ZodString;
136
+ userId: z.ZodUUID;
137
+ parentId: z.ZodNullable<z.ZodUUID>;
138
+ size: z.ZodCoercedBigInt<unknown>;
139
+ trashedAt: z.ZodNullable<z.ZodCoercedDate<unknown>>;
140
+ type: z.ZodString;
141
+ metadata: z.ZodRecord<z.ZodString, z.ZodUnknown>;
142
+ acl: z.ZodOptional<z.ZodArray<z.ZodObject<{
143
+ itemId: z.ZodUUID;
144
+ userId: z.ZodOptional<z.ZodNullable<z.ZodUUID>>;
145
+ role: z.ZodOptional<z.ZodNullable<z.ZodString>>;
146
+ tag: z.ZodOptional<z.ZodNullable<z.ZodString>>;
147
+ user: z.ZodOptional<z.ZodNullable<z.ZodObject<{
148
+ id: z.ZodUUID;
149
+ name: z.ZodString;
150
+ username: z.ZodString;
151
+ email: z.ZodOptional<z.ZodOptional<z.ZodNullable<z.ZodEmail>>>;
152
+ emailVerified: z.ZodOptional<z.ZodOptional<z.ZodNullable<z.ZodCoercedDate<unknown>>>>;
153
+ preferences: z.ZodOptional<z.ZodLazy<z.ZodObject<{
154
+ debug: z.ZodDefault<z.ZodBoolean>;
155
+ theme: z.ZodDefault<z.ZodLiteral<"default" | "light" | "forest" | "midnight" | "beach" | "cherry" | "volcano">>;
156
+ time_zone: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<string>, z.ZodString]>>;
157
+ }, z.core.$strip>>>;
158
+ roles: z.ZodArray<z.ZodString>;
159
+ tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
160
+ registeredAt: z.ZodCoercedDate<unknown>;
161
+ isAdmin: z.ZodOptional<z.ZodBoolean>;
162
+ isSuspended: z.ZodOptional<z.ZodBoolean>;
163
+ }, z.core.$strip>>>;
164
+ createdAt: z.ZodCoercedDate<unknown>;
165
+ }, z.core.$catchall<z.ZodBoolean>>>>;
166
+ parents: z.ZodOptional<z.ZodArray<z.ZodObject<{
167
+ id: z.ZodUUID;
168
+ name: z.ZodString;
169
+ }, z.core.$strip>>>;
170
+ sync: z.ZodOptional<z.ZodNullable<z.ZodObject<{
171
+ rules: z.ZodArray<z.ZodTemplateLiteral<`+${string}` | `-${string}`>>;
172
+ hidden: z.ZodBoolean;
173
+ createdAt: z.ZodCoercedDate<unknown>;
174
+ devices: z.ZodArray<z.ZodObject<{
175
+ host: z.ZodString;
176
+ localPath: z.ZodString;
177
+ lastSynced: z.ZodNullable<z.ZodCoercedDate<unknown>>;
178
+ itemId: z.ZodUUID;
179
+ userId: z.ZodUUID;
180
+ }, z.core.$strip>>;
181
+ }, z.core.$strip>>>;
182
+ }, z.core.$strip>];
183
+ };
184
+ readonly 'office/:id': {
185
+ readonly GET: readonly [z.ZodObject<{
186
+ mobile: z.ZodBoolean;
187
+ }, z.core.$strip>, z.ZodObject<{
188
+ item: z.ZodObject<{
189
+ createdAt: z.ZodCoercedDate<unknown>;
190
+ dataURL: z.ZodString;
191
+ hash: z.ZodOptional<z.ZodNullable<z.ZodString>>;
192
+ id: z.ZodUUID;
193
+ immutable: z.ZodBoolean;
194
+ modifiedAt: z.ZodCoercedDate<unknown>;
195
+ name: z.ZodString;
196
+ userId: z.ZodUUID;
197
+ parentId: z.ZodNullable<z.ZodUUID>;
198
+ size: z.ZodCoercedBigInt<unknown>;
199
+ trashedAt: z.ZodNullable<z.ZodCoercedDate<unknown>>;
200
+ type: z.ZodString;
201
+ metadata: z.ZodRecord<z.ZodString, z.ZodUnknown>;
202
+ acl: z.ZodOptional<z.ZodArray<z.ZodObject<{
203
+ itemId: z.ZodUUID;
204
+ userId: z.ZodOptional<z.ZodNullable<z.ZodUUID>>;
205
+ role: z.ZodOptional<z.ZodNullable<z.ZodString>>;
206
+ tag: z.ZodOptional<z.ZodNullable<z.ZodString>>;
207
+ user: z.ZodOptional<z.ZodNullable<z.ZodObject<{
208
+ id: z.ZodUUID;
209
+ name: z.ZodString;
210
+ username: z.ZodString;
211
+ email: z.ZodOptional<z.ZodOptional<z.ZodNullable<z.ZodEmail>>>;
212
+ emailVerified: z.ZodOptional<z.ZodOptional<z.ZodNullable<z.ZodCoercedDate<unknown>>>>;
213
+ preferences: z.ZodOptional<z.ZodLazy<z.ZodObject<{
214
+ debug: z.ZodDefault<z.ZodBoolean>;
215
+ theme: z.ZodDefault<z.ZodLiteral<"default" | "light" | "forest" | "midnight" | "beach" | "cherry" | "volcano">>;
216
+ time_zone: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<string>, z.ZodString]>>;
217
+ }, z.core.$strip>>>;
218
+ roles: z.ZodArray<z.ZodString>;
219
+ tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
220
+ registeredAt: z.ZodCoercedDate<unknown>;
221
+ isAdmin: z.ZodOptional<z.ZodBoolean>;
222
+ isSuspended: z.ZodOptional<z.ZodBoolean>;
223
+ }, z.core.$strip>>>;
224
+ createdAt: z.ZodCoercedDate<unknown>;
225
+ }, z.core.$catchall<z.ZodBoolean>>>>;
226
+ parents: z.ZodOptional<z.ZodArray<z.ZodObject<{
227
+ id: z.ZodUUID;
228
+ name: z.ZodString;
229
+ }, z.core.$strip>>>;
230
+ sync: z.ZodOptional<z.ZodNullable<z.ZodObject<{
231
+ rules: z.ZodArray<z.ZodTemplateLiteral<`+${string}` | `-${string}`>>;
232
+ hidden: z.ZodBoolean;
233
+ createdAt: z.ZodCoercedDate<unknown>;
234
+ devices: z.ZodArray<z.ZodObject<{
235
+ host: z.ZodString;
236
+ localPath: z.ZodString;
237
+ lastSynced: z.ZodNullable<z.ZodCoercedDate<unknown>>;
238
+ itemId: z.ZodUUID;
239
+ userId: z.ZodUUID;
240
+ }, z.core.$strip>>;
241
+ }, z.core.$strip>>>;
242
+ }, z.core.$strip>;
243
+ readOnly: z.ZodBoolean;
244
+ canRename: z.ZodBoolean;
245
+ editor: z.ZodObject<{
246
+ url: z.ZodURL;
247
+ config: z.ZodRecord<z.ZodString, z.ZodUnknown>;
248
+ }, z.core.$strip>;
249
+ }, z.core.$strip>];
250
+ };
251
+ };
252
+ type OfficeAPI = typeof OfficeAPI;
253
+ declare module '@axium/core/api' {
254
+ interface $API extends OfficeAPI {
255
+ }
256
+ }
257
+ export {};
@@ -0,0 +1,4 @@
1
+ import './common.js';
2
+ import './server/api.js';
3
+ /** Trusts the certificate Axium serves with, which a self-hosted document server may share */
4
+ export declare function load(): void;
package/dist/hooks.js ADDED
@@ -0,0 +1,12 @@
1
+ import serverConfig from '@axium/server/config';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import tls from 'node:tls';
4
+ import './common.js';
5
+ import './server/api.js';
6
+ /** Trusts the certificate Axium serves with, which a self-hosted document server may share */
7
+ export function load() {
8
+ const { ssl_cert } = serverConfig.web;
9
+ if (!existsSync(ssl_cert))
10
+ return;
11
+ tls.setDefaultCACertificates([...tls.getCACertificates('default'), readFileSync(ssl_cert, 'utf8')]);
12
+ }
@@ -0,0 +1,60 @@
1
+ import { authSessionForItem, requireSession } from '@axium/server/auth';
2
+ import { error, isResponseError, parseBody, parseSearch } from '@axium/server/requests';
3
+ import { addRoute } from '@axium/server/routes';
4
+ import { parseItem } from '@axium/storage/server/db';
5
+ import { checkNewItem, createNewItem } from '@axium/storage/server/item';
6
+ import { createHash } from 'node:crypto';
7
+ import { readFileSync, writeFileSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ import * as z from 'zod';
10
+ import { EditorOptions, formatOf, NewDocument, newFormats } from '../common.js';
11
+ import { editorFor } from './documentserver.js';
12
+ async function isAllowed(itemId, permissions, session) {
13
+ return await authSessionForItem('storage', itemId, permissions, session, true).then(() => true, (e) => {
14
+ if (isResponseError(e) && e.status == 403)
15
+ return false;
16
+ throw e;
17
+ });
18
+ }
19
+ /**
20
+ * @todo reduce DB round trips (currently 3)
21
+ */
22
+ addRoute({
23
+ path: '/api/office/:id',
24
+ params: { id: z.uuid() },
25
+ async GET(request, { id }) {
26
+ const options = parseSearch(request, EditorOptions);
27
+ const session = await requireSession(request);
28
+ const { item: rawItem } = await authSessionForItem('storage', id, { read: true }, session, true);
29
+ const item = parseItem(rawItem);
30
+ if (item.trashedAt)
31
+ error(410, 'Trashed items can not be opened');
32
+ const format = formatOf(item);
33
+ if (!format || item.type == 'inode/directory')
34
+ error(415, 'Office can not open this kind of file');
35
+ const isOwner = item.userId == session.userId;
36
+ const canWrite = !item.immutable && (isOwner || (await isAllowed(id, { write: true }, session)));
37
+ const canRename = isOwner || (await isAllowed(id, { manage: true }, session));
38
+ const editor = editorFor({ item, format, user: session.user, canWrite, options });
39
+ return { item, readOnly: !canWrite, canRename, editor };
40
+ },
41
+ });
42
+ const assets = join(import.meta.dirname, '../../assets/');
43
+ addRoute({
44
+ path: '/api/office',
45
+ async PUT(request) {
46
+ const { kind, name, parentId } = await parseBody(request, NewDocument);
47
+ const session = await requireSession(request);
48
+ const format = newFormats[kind];
49
+ const content = readFileSync(join(assets, `blank.${format.extension}`));
50
+ const init = {
51
+ name: `${name}.${format.extension}`,
52
+ size: BigInt(content.byteLength),
53
+ type: format.type,
54
+ parentId,
55
+ hash: createHash('BLAKE2b512').update(content).digest('hex'),
56
+ };
57
+ await checkNewItem(init, session);
58
+ return await createNewItem(init, session.userId, path => writeFileSync(path, content));
59
+ },
60
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,14 @@
1
+ import { type User } from '@axium/core';
2
+ import type { StorageItemMetadata } from '@axium/storage/common';
3
+ import type { Editor, EditorOptions, Format } from '../common.js';
4
+ /** An item the document server may open: it exists, is not trashed, and is not a directory */
5
+ export declare function getItem(itemId: string): Promise<StorageItemMetadata>;
6
+ export interface EditorRequest {
7
+ item: StorageItemMetadata;
8
+ format: Format;
9
+ user: User;
10
+ canWrite: boolean;
11
+ options: EditorOptions;
12
+ }
13
+ /** Everything the browser needs to open `item` in the document server's editor */
14
+ export declare function editorFor({ item, format, user, canWrite, options }: EditorRequest): Editor;
@@ -0,0 +1,17 @@
1
+ export declare const defaultBase = "ghcr.io/euro-office/documentserver:v9.3.8";
2
+ /** The first container engine that is installed */
3
+ export declare function detectEngine(): string;
4
+ export interface ImageOptions {
5
+ /** The Euro-Office image to patch */
6
+ base: string;
7
+ engine: string;
8
+ /** The directory that receives the build context, which is replaced */
9
+ context: string;
10
+ }
11
+ /** Writes the build context of Axium's document server image: the base image's files patched for Axium, plus Axium's themes */
12
+ export declare function writeContext({ base, engine, context }: ImageOptions): void;
13
+ /** Writes the build context to `context`, or a temporary directory that is removed afterwards, and builds the image as `tag` */
14
+ export declare function buildImage(options: Omit<ImageOptions, 'context'> & {
15
+ context?: string;
16
+ tag: string;
17
+ }): void;
@@ -0,0 +1,161 @@
1
+ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
2
+ if (value !== null && value !== void 0) {
3
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
4
+ var dispose, inner;
5
+ if (async) {
6
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
7
+ dispose = value[Symbol.asyncDispose];
8
+ }
9
+ if (dispose === void 0) {
10
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
11
+ dispose = value[Symbol.dispose];
12
+ if (async) inner = dispose;
13
+ }
14
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
15
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
16
+ env.stack.push({ value: value, dispose: dispose, async: async });
17
+ }
18
+ else if (async) {
19
+ env.stack.push({ async: true });
20
+ }
21
+ return value;
22
+ };
23
+ var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
24
+ return function (env) {
25
+ function fail(e) {
26
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
27
+ env.hasError = true;
28
+ }
29
+ var r, s = 0;
30
+ function next() {
31
+ while (r = env.stack.pop()) {
32
+ try {
33
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
34
+ if (r.dispose) {
35
+ var result = r.dispose.call(r.value);
36
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
37
+ }
38
+ else s |= 1;
39
+ }
40
+ catch (e) {
41
+ fail(e);
42
+ }
43
+ }
44
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
45
+ if (env.hasError) throw env.error;
46
+ }
47
+ return next();
48
+ };
49
+ })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
50
+ var e = new Error(message);
51
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
52
+ });
53
+ import { execFileSync, spawnSync } from 'node:child_process';
54
+ import { chmodSync, cpSync, globSync, mkdirSync, mkdtempDisposableSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync, } from 'node:fs';
55
+ import { tmpdir } from 'node:os';
56
+ import { dirname, join } from 'node:path';
57
+ import { brotliCompressSync, gzipSync } from 'node:zlib';
58
+ import patches from './patches.json' with { type: 'json' };
59
+ import { editorThemes } from './themes.js';
60
+ export const defaultBase = 'ghcr.io/euro-office/documentserver:v9.3.8';
61
+ /** The source of the base themes' tokens */
62
+ const stylesheet = 'documenteditor/main/app.css';
63
+ const engines = ['docker', 'podman'];
64
+ /** The first container engine that is installed */
65
+ export function detectEngine() {
66
+ const engine = engines.find(engine => spawnSync(engine, ['--version'], { stdio: 'ignore' }).status === 0);
67
+ if (!engine)
68
+ throw new Error(`Neither ${engines.join(' nor ')} is installed`);
69
+ return engine;
70
+ }
71
+ function container(engine, ...args) {
72
+ return execFileSync(engine, args, { maxBuffer: 2 ** 30 });
73
+ }
74
+ /** The environment variables an image sets */
75
+ function imageEnvironment(engine, image) {
76
+ const entries = JSON.parse(container(engine, 'image', 'inspect', '--format', '{{json .Config.Env}}', image).toString());
77
+ return Object.fromEntries(entries.map(entry => entry.split(/=(.*)/s, 2)));
78
+ }
79
+ /** The tokens of a built-in theme's rule in an editor stylesheet */
80
+ function baseColors(css, themeId) {
81
+ const rule = new RegExp(`:root \\.${themeId}\\s*\\{([^}]*)\\}`).exec(css);
82
+ if (!rule)
83
+ throw new Error(`No rule for ${themeId} in ${stylesheet}`);
84
+ const declarations = rule[1].split(';').filter(declaration => declaration.includes(':'));
85
+ return Object.fromEntries(declarations.map(declaration => {
86
+ const [name, value] = declaration.split(/:(.*)/s, 2);
87
+ return [name.trim().replace(/^--/, ''), value.trim()];
88
+ }));
89
+ }
90
+ /** Applies every patch to the files in `extracted`, failing unless each file holds the anchor exactly `count` times */
91
+ function applyPatches(extracted) {
92
+ const patched = new Map();
93
+ for (const { group, count, anchor, replacement } of patches.patches) {
94
+ for (const file of globSync(patches.groups[group], { cwd: extracted })) {
95
+ const content = patched.get(file) ?? readFileSync(join(extracted, file), 'utf8');
96
+ const found = content.split(anchor).length - 1;
97
+ if (found != count)
98
+ throw new Error(`Expected ${count} of ${JSON.stringify(anchor)} in ${file}, found ${found}`);
99
+ patched.set(file, content.replaceAll(anchor, replacement));
100
+ }
101
+ }
102
+ return patched;
103
+ }
104
+ /** Writes the build context of Axium's document server image: the base image's files patched for Axium, plus Axium's themes */
105
+ export function writeContext({ base, engine, context }) {
106
+ const env_1 = { stack: [], error: void 0, hasError: false };
107
+ try {
108
+ const extracted = __addDisposableResource(env_1, mkdtempDisposableSync(join(tmpdir(), 'axium-documentserver-base-')), false);
109
+ const patterns = [...new Set(Object.values(patches.groups).flat())];
110
+ const archive = container(engine, 'run', '--rm', '--entrypoint', 'sh', base, '-c', `cd "\${EO_ROOT:?${base} is not a Euro-Office image}/web-apps/apps" && tar -c ${patterns.join(' ')}`);
111
+ execFileSync('tar', ['-x', '-C', extracted.path], { input: archive });
112
+ const { EO_ROOT: root, EO_CONF: configDirectory } = imageEnvironment(engine, base);
113
+ if (!root || !configDirectory)
114
+ throw new Error(`${base} is not a Euro-Office image: it does not set EO_ROOT and EO_CONF`);
115
+ rmSync(context, { recursive: true, force: true });
116
+ const apps = join(context, 'web-apps/apps');
117
+ for (const [file, content] of applyPatches(extracted.path)) {
118
+ const destination = join(apps, file);
119
+ mkdirSync(dirname(destination), { recursive: true });
120
+ writeFileSync(destination, content);
121
+ writeFileSync(destination + '.gz', gzipSync(content));
122
+ writeFileSync(destination + '.br', brotliCompressSync(content));
123
+ for (const path of [destination, destination + '.gz', destination + '.br'])
124
+ chmodSync(path, statSync(join(extracted.path, file)).mode);
125
+ }
126
+ const css = readFileSync(join(extracted.path, stylesheet), 'utf8');
127
+ const themes = join(apps, 'common/main/resources/themes');
128
+ mkdirSync(themes, { recursive: true });
129
+ for (const { base: themeBase, ...theme } of editorThemes()) {
130
+ const complete = { ...theme, colors: { ...baseColors(css, themeBase), ...theme.colors } };
131
+ writeFileSync(join(themes, theme.id.replace(/^theme-/, '') + '.json'), JSON.stringify(complete, null, '\t') + '\n');
132
+ }
133
+ cpSync(join(import.meta.dirname, '../../assets/documentserver.json'), join(context, 'local-production-linux.json'));
134
+ writeFileSync(join(context, 'Containerfile'), `FROM ${base}
135
+ COPY --chown=ds:ds web-apps ${root}/web-apps
136
+ COPY --chown=ds:ds local-production-linux.json ${configDirectory}/
137
+ RUN find ${root}/web-apps -type d -exec chmod 555 {} + && documentserver-flush-cache.sh -r false
138
+ `);
139
+ }
140
+ catch (e_1) {
141
+ env_1.error = e_1;
142
+ env_1.hasError = true;
143
+ }
144
+ finally {
145
+ __disposeResources(env_1);
146
+ }
147
+ }
148
+ /** Writes the build context to `context`, or a temporary directory that is removed afterwards, and builds the image as `tag` */
149
+ export function buildImage(options) {
150
+ const context = options.context ?? mkdtempSync(join(tmpdir(), 'axium-documentserver-'));
151
+ try {
152
+ writeContext({ ...options, context });
153
+ execFileSync(options.engine, ['build', '--file', join(context, 'Containerfile'), '--tag', options.tag, context], {
154
+ stdio: 'inherit',
155
+ });
156
+ }
157
+ finally {
158
+ if (!options.context)
159
+ rmSync(context, { recursive: true, force: true });
160
+ }
161
+ }
@@ -0,0 +1,6 @@
1
+ /** Signs `payload` with HS256 */
2
+ export declare function sign(payload: object, secret: string): string;
3
+ /** Returns the payload of an HS256 token with a valid signature that has not expired, or null */
4
+ export declare function verify<T extends object>(token: string, secret: string): (T & {
5
+ exp?: number;
6
+ }) | null;
@@ -0,0 +1,37 @@
1
+ import { createHmac, timingSafeEqual } from 'node:crypto';
2
+ import { decodeUTF8, encodeUTF8 } from 'utilium';
3
+ function base64url(bytes) {
4
+ return bytes.toBase64({ alphabet: 'base64url', omitPadding: true });
5
+ }
6
+ const header = base64url(encodeUTF8(JSON.stringify({ alg: 'HS256', typ: 'JWT' })));
7
+ function signature(signingInput, secret) {
8
+ return createHmac('sha256', secret).update(signingInput).digest();
9
+ }
10
+ /** Signs `payload` with HS256 */
11
+ export function sign(payload, secret) {
12
+ const signingInput = `${header}.${base64url(encodeUTF8(JSON.stringify(payload)))}`;
13
+ return `${signingInput}.${base64url(signature(signingInput, secret))}`;
14
+ }
15
+ /** Returns the payload of an HS256 token with a valid signature that has not expired, or null */
16
+ export function verify(token, secret) {
17
+ if (!secret)
18
+ return null;
19
+ const [tokenHeader, body, tokenSignature, ...extra] = token.split('.');
20
+ if (!tokenHeader || !body || !tokenSignature || extra.length)
21
+ return null;
22
+ const expected = signature(`${tokenHeader}.${body}`, secret);
23
+ const actual = Uint8Array.fromBase64(tokenSignature, { alphabet: 'base64url' });
24
+ if (actual.length != expected.length || !timingSafeEqual(actual, expected))
25
+ return null;
26
+ try {
27
+ if (JSON.parse(decodeUTF8(Uint8Array.fromBase64(tokenHeader, { alphabet: 'base64url' }))).alg != 'HS256')
28
+ return null;
29
+ const payload = JSON.parse(decodeUTF8(Uint8Array.fromBase64(body, { alphabet: 'base64url' })));
30
+ if (typeof payload.exp == 'number' && payload.exp * 1000 < Date.now())
31
+ return null;
32
+ return payload;
33
+ }
34
+ catch {
35
+ return null;
36
+ }
37
+ }
@@ -0,0 +1,57 @@
1
+ {
2
+ "groups": {
3
+ "pages": [
4
+ "*/main/index.html",
5
+ "*/main/index_loader.html",
6
+ "spreadsheeteditor/main/index_internal.html",
7
+ "documenteditor/forms/index.html",
8
+ "common/index.html"
9
+ ],
10
+ "bundles": ["*/main/app.js", "documenteditor/forms/app.js"],
11
+ "stylesheets": ["*/main/app.css", "documenteditor/forms/app.css"],
12
+ "discussionStylesheets": [
13
+ "documenteditor/main/app.css",
14
+ "pdfeditor/main/app.css",
15
+ "presentationeditor/main/app.css",
16
+ "spreadsheeteditor/main/app.css"
17
+ ]
18
+ },
19
+ "patches": [
20
+ {
21
+ "group": "pages",
22
+ "count": 2,
23
+ "anchor": "getItem(\"content-theme\") == 'dark'",
24
+ "replacement": "getItem(\"content-theme\") != 'light'"
25
+ },
26
+ {
27
+ "group": "bundles",
28
+ "count": 1,
29
+ "anchor": "const check_launched_custom_theme=function(){let theme_id=window.uitheme.id;if(themes_map[theme_id]){if(\"static\"!=themes_map[theme_id].source){",
30
+ "replacement": "const check_launched_custom_theme=function(){let theme_id=window.uitheme.id;if(themes_map[theme_id]){if(\"static\"!=themes_map[theme_id].source){if(themes_map[theme_id].src)return apply_theme.call(Common.UI.Themes,theme_id),void Common.NotificationCenter.trigger(\"uitheme:changed\",theme_id);"
31
+ },
32
+ {
33
+ "group": "bundles",
34
+ "count": 1,
35
+ "anchor": "document.getElementsByTagName(\"head\")[0].appendChild(style)}}(t.src.id,function(id,colors){if(colors&&id){var _css_array=[\":root .\",id,\"{\"]",
36
+ "replacement": "document.body.appendChild(style)}}(t.src.id,function(id,colors){if(colors&&id){var _css_array=[\":root body.\",id,\"{\"]"
37
+ },
38
+ {
39
+ "group": "pages",
40
+ "count": 1,
41
+ "anchor": "inject_style_tag('.' + objtheme.id + '{'",
42
+ "replacement": "inject_style_tag(':root body.' + objtheme.id + '{'"
43
+ },
44
+ {
45
+ "group": "stylesheets",
46
+ "count": 1,
47
+ "anchor": " background: #4A87E7;\n color: #fff;",
48
+ "replacement": " background: var(--background-primary-dialog-button);\n color: var(--text-inverse);"
49
+ },
50
+ {
51
+ "group": "discussionStylesheets",
52
+ "count": 1,
53
+ "anchor": " background: #3494fb;\n color: white;",
54
+ "replacement": " background: var(--highlight-text-select);\n color: var(--text-inverse);"
55
+ }
56
+ ]
57
+ }
@@ -0,0 +1,9 @@
1
+ export interface EditorTheme {
2
+ id: string;
3
+ name: string;
4
+ type: 'dark' | 'light';
5
+ /** The built-in theme that supplies every color not set here */
6
+ base: string;
7
+ colors: Record<string, string>;
8
+ }
9
+ export declare function editorThemes(): EditorTheme[];
@@ -0,0 +1,179 @@
1
+ // The document server's Axium themes, one per Axium theme.
2
+ import { themeStyles } from '@axium/client/themes';
3
+ import { hslToHex } from 'utilium/color';
4
+ /** The defaults in `@axium/client/assets/theme.css`, which the `default` theme uses */
5
+ const defaults = {
6
+ 'color-scheme': 'dark',
7
+ hue: '240',
8
+ 'fg-light': '73%',
9
+ 'bg-light': '13.3%',
10
+ 'light-step': '6.6%',
11
+ };
12
+ /** `saturation` and `lightness` are percentages, `hue` is in degrees */
13
+ function hex(hue, saturation, lightness) {
14
+ const fraction = (value) => Math.min(100, Math.max(0, value)) / 100;
15
+ return '#' + hslToHex(hue / 360, fraction(saturation), fraction(lightness));
16
+ }
17
+ /** Axium's colors, using the formulas in `theme.css` */
18
+ function axiumColors(style) {
19
+ const hue = parseFloat(style.hue);
20
+ const foreground = parseFloat(style['fg-light']);
21
+ const background = parseFloat(style['bg-light']);
22
+ const step = parseFloat(style['light-step']);
23
+ return {
24
+ 'bg-normal': hex(0, 0, background),
25
+ 'bg-menu': hex(0, 0, background - step),
26
+ 'bg-accent': hex(hue, 15, background + step * 2),
27
+ 'bg-alt': hex(hue, 5, background + step),
28
+ 'bg-strong': hex(hue, 20, background + step),
29
+ 'fg-normal': hex(0, 0, foreground),
30
+ 'fg-accent': hex(hue, 15, foreground),
31
+ 'fg-disabled': hex(0, 0, foreground - step),
32
+ 'border-accent': hex(hue, 10, background + step * 3),
33
+ 'border-strong': hex(hue, 20, background + step * 3),
34
+ };
35
+ }
36
+ const perEditor = (token) => ['document', 'spreadsheet', 'presentation', 'pdf', 'visio'].map(editor => `${token}-${editor}`);
37
+ /**
38
+ * Editor color tokens by the Axium color they take.
39
+ * The base theme keeps status colors (alt key hints, badges, form filling, sheet views, red and green icons), overlays, shadows,
40
+ * the spreadsheet's fixed header shades and the page itself.
41
+ */
42
+ function editorColors(axium) {
43
+ const mapping = {
44
+ 'bg-normal': [
45
+ ...perEditor('toolbar-header'),
46
+ ...perEditor('text-toolbar-header-on-background'),
47
+ 'background-normal',
48
+ 'background-toolbar',
49
+ 'background-toolbar-tab',
50
+ 'border-toolbar-active-panel-top',
51
+ 'canvas-ruler-background',
52
+ 'canvas-cell-title-background',
53
+ 'slider-thumb-border-normal',
54
+ 'text-inverse',
55
+ ],
56
+ 'bg-menu': ['background-pane', 'background-contrast-popover', 'canvas-background'],
57
+ 'bg-alt': [
58
+ 'background-toolbar-additional',
59
+ 'canvas-ruler-margins-background',
60
+ 'canvas-cell-title-background-hover',
61
+ 'canvas-scroll-thumb',
62
+ 'highlight-comment-hover',
63
+ 'highlight-category-button-hover',
64
+ ],
65
+ 'bg-strong': [
66
+ 'background-notification-popover',
67
+ 'highlight-button-pressed',
68
+ 'highlight-header-button-pressed',
69
+ 'highlight-comment-pressed',
70
+ 'highlight-category-button-pressed',
71
+ 'highlight-primary-dialog-button-pressed',
72
+ ],
73
+ 'bg-accent': [
74
+ 'eo-app-accent',
75
+ 'highlight-button-hover',
76
+ 'highlight-button-pressed-hover',
77
+ 'highlight-header-button-hover',
78
+ 'chb-background-normal-hover',
79
+ 'chb-background-checked-hover',
80
+ 'rb-background-normal-hover',
81
+ 'rb-background-checked-hover',
82
+ 'canvas-cell-title-background-selected',
83
+ 'canvas-scroll-thumb-hover',
84
+ 'canvas-scroll-thumb-pressed',
85
+ 'icon-blue-secondary',
86
+ ],
87
+ 'border-accent': [
88
+ 'border-toolbar',
89
+ 'border-divider',
90
+ 'border-color-shading',
91
+ 'border-contrast-popover',
92
+ 'canvas-ruler-border',
93
+ 'canvas-ruler-handle-border-disabled',
94
+ 'canvas-cell-title-border',
95
+ 'canvas-scroll-thumb-border',
96
+ 'slider-track-background-normal',
97
+ ],
98
+ 'border-strong': [
99
+ 'border-regular-control',
100
+ 'border-preview-hover',
101
+ 'chb-border-normal',
102
+ 'chb-border-checked',
103
+ 'rb-border-normal',
104
+ 'rb-border-checked',
105
+ 'canvas-cell-title-border-hover',
106
+ 'canvas-high-contrast-disabled',
107
+ 'canvas-scroll-thumb-border-hover',
108
+ ],
109
+ 'fg-normal': [
110
+ 'text-normal',
111
+ 'text-normal-pressed',
112
+ 'text-toolbar-header',
113
+ 'text-link-hover',
114
+ 'text-link-active',
115
+ 'icon-normal',
116
+ 'icon-normal-pressed',
117
+ 'icon-toolbar-header',
118
+ 'icon-gray-primary',
119
+ 'canvas-high-contrast',
120
+ 'canvas-scroll-arrow',
121
+ 'canvas-scroll-arrow-hover',
122
+ 'canvas-scroll-arrow-pressed',
123
+ 'canvas-scroll-thumb-target',
124
+ 'canvas-scroll-thumb-target-hover',
125
+ 'canvas-scroll-thumb-target-pressed',
126
+ 'highlight-primary-dialog-button-hover',
127
+ 'slider-thumb-background-hover',
128
+ ],
129
+ 'fg-accent': [
130
+ ...perEditor('highlight-header-tab-underline'),
131
+ ...perEditor('highlight-toolbar-tab-underline'),
132
+ 'text-secondary',
133
+ 'text-link',
134
+ 'text-link-visited',
135
+ 'icon-gray-secondary',
136
+ 'icon-blue-primary',
137
+ 'canvas-cell-title-text',
138
+ 'background-primary-dialog-button',
139
+ 'background-accent-button',
140
+ 'highlight-text-select',
141
+ 'border-preview-select',
142
+ 'border-control-focus',
143
+ 'border-button-pressed-focus',
144
+ 'border-fill-input-focused',
145
+ 'chb-border-normal-focus',
146
+ 'chb-border-checked-focus',
147
+ 'rb-border-normal-focus',
148
+ 'rb-border-checked-focus',
149
+ 'slider-track-background-filled',
150
+ 'slider-thumb-background-normal',
151
+ 'slider-thumb-background-active',
152
+ ],
153
+ 'fg-disabled': [
154
+ 'text-tertiary',
155
+ 'chb-border-normal-hover',
156
+ 'chb-border-checked-hover',
157
+ 'rb-border-normal-hover',
158
+ 'rb-border-checked-hover',
159
+ 'canvas-ruler-mark',
160
+ 'canvas-ruler-handle-border',
161
+ 'canvas-cell-title-border-selected',
162
+ 'canvas-scroll-thumb-border-pressed',
163
+ ],
164
+ };
165
+ return Object.fromEntries(Object.entries(mapping).flatMap(([color, tokens]) => tokens.map(token => [token, axium[color]])));
166
+ }
167
+ export function editorThemes() {
168
+ return [['default', {}], ...Object.entries(themeStyles)].map(([name, overrides]) => {
169
+ const style = { ...defaults, ...overrides };
170
+ const type = style['color-scheme'] == 'light' ? 'light' : 'dark';
171
+ return {
172
+ id: `theme-axium-${name}`,
173
+ name: name == 'default' ? 'Axium' : `Axium ${name}`,
174
+ type,
175
+ base: type == 'dark' ? 'theme-night' : 'theme-white',
176
+ colors: editorColors(axiumColors(style)),
177
+ };
178
+ });
179
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,7 @@
1
+ import { openers } from '@axium/storage/client/3rd-party';
2
+ import { formats } from './common.js';
3
+ openers.push({
4
+ name: 'Office',
5
+ types: formats.map(format => format.type),
6
+ openURL: item => `/office/${item.id}`,
7
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@axium/office",
3
- "version": "0.0.1",
3
+ "version": "0.1.0",
4
4
  "author": "James Prevett <axium@jamespre.dev>",
5
5
  "description": "Office documents for Axium, edited with Euro-Office or OnlyOffice",
6
6
  "funding": {
File without changes