@tacoshell/sdk 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/assets.d.ts +2 -1
- package/src/csv.ts +44 -0
- package/src/index.ts +169 -7
- package/src/zip.ts +56 -0
package/package.json
CHANGED
package/src/assets.d.ts
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
// Lets module code import its own CSS (Vite bundles it with the app); included by the editor tsconfig taco-cli writes.
|
|
1
|
+
// Lets module code import its own CSS (Vite bundles it with the app) and text files as strings (`import sql from './query.sql?raw'`); included by the editor tsconfig taco-cli writes.
|
|
2
2
|
declare module '*.css';
|
|
3
|
+
declare module '*?raw' { const text: string; export default text; }
|
package/src/csv.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// RFC 4180 CSV parse / stringify for module code (the shell has the same logic in core/csv.ts; ADR-045, as CommunityOS lib/csv.js): quoted fields, "" escapes, CRLF or LF, a BOM, embedded newlines.
|
|
2
|
+
|
|
3
|
+
export function parseCsv(text: string): string[][] {
|
|
4
|
+
const rows: string[][] = [];
|
|
5
|
+
let row: string[] = [];
|
|
6
|
+
let field = '';
|
|
7
|
+
let quoted = false;
|
|
8
|
+
const s = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
|
|
9
|
+
for (let i = 0; i < s.length; i++) {
|
|
10
|
+
const ch = s[i];
|
|
11
|
+
if (quoted) {
|
|
12
|
+
if (ch === '"') {
|
|
13
|
+
if (s[i + 1] === '"') { field += '"'; i++; } else quoted = false;
|
|
14
|
+
} else field += ch;
|
|
15
|
+
continue;
|
|
16
|
+
}
|
|
17
|
+
if (ch === '"' && field === '') quoted = true;
|
|
18
|
+
else if (ch === ',') { row.push(field); field = ''; }
|
|
19
|
+
else if (ch === '\n' || ch === '\r') {
|
|
20
|
+
if (ch === '\r' && s[i + 1] === '\n') i++;
|
|
21
|
+
row.push(field); field = '';
|
|
22
|
+
rows.push(row); row = [];
|
|
23
|
+
} else field += ch;
|
|
24
|
+
}
|
|
25
|
+
if (field !== '' || row.length) { row.push(field); rows.push(row); }
|
|
26
|
+
return rows.filter((r) => !(r.length === 1 && r[0] === ''));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const quote = (v: unknown) => {
|
|
30
|
+
const s = v === null || v === undefined ? '' : typeof v === 'object' ? JSON.stringify(v) : String(v);
|
|
31
|
+
return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export function stringifyCsv(columns: string[], rows: Record<string, unknown>[]): string {
|
|
35
|
+
return [columns.map(quote).join(','), ...rows.map((r) => columns.map((c) => quote(r[c])).join(','))].join('\r\n') + '\r\n';
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Header row + data rows → objects keyed by the (trimmed) header. */
|
|
39
|
+
export function csvToRows(text: string): Record<string, string>[] {
|
|
40
|
+
const [head, ...rest] = parseCsv(text);
|
|
41
|
+
if (!head) return [];
|
|
42
|
+
const keys = head.map((h) => h.trim());
|
|
43
|
+
return rest.map((cells) => Object.fromEntries(keys.map((k, i) => [k, cells[i] ?? ''])));
|
|
44
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
// @tacoshell/sdk: the only framework import module code needs (TECH-GUIDANCE §6).
|
|
2
|
-
|
|
2
|
+
export { csvToRows, parseCsv, stringifyCsv } from './csv.ts';
|
|
3
|
+
export { createZip, crc32, downloadFile, type ZipEntry } from './zip.ts';
|
|
4
|
+
import { useEffect, useSyncExternalStore, type ComponentType, type CSSProperties, type ReactNode } from 'react';
|
|
3
5
|
// Generated taco.gen.ts files declare structurally identical ref types inline, so a module also type-checks before this package is installed.
|
|
4
6
|
|
|
5
7
|
// ── References (built by generated code; ADR-020) ────────────────────────────────────────────────────────────────
|
|
@@ -68,7 +70,135 @@ export interface Tool {
|
|
|
68
70
|
run(): void | Promise<void>;
|
|
69
71
|
}
|
|
70
72
|
|
|
73
|
+
// ── Feature types, Related, Actions, indicators ──────────────────────────────────────────────────────────────────────
|
|
74
|
+
|
|
75
|
+
/** GENERAL = you build the whole UX; CSV and ITEM standardize one; ACTION opens in a modal over an ITEM; ITEMS is reserved (multi-select ITEM). */
|
|
76
|
+
export type FeatureType = 'GENERAL' | 'CSV' | 'ITEM' | 'ITEMS' | 'ACTION';
|
|
77
|
+
|
|
78
|
+
/** What the framework tells a contributor about the feature being viewed. `href` is relative (`#/v/<module>/<view>`). */
|
|
79
|
+
export interface FeatureInfo { module: string; view: string; /** `<module>/<view>` */ id: string; /** The nav feature the view belongs to. */ feature: string; label: string; type: FeatureType; href: string }
|
|
80
|
+
|
|
81
|
+
/** One entry a feature adds to another feature's Related menu or Actions section. The link to the contributing feature is derived by the framework. */
|
|
82
|
+
export interface Contribution {
|
|
83
|
+
label: string;
|
|
84
|
+
/** Font Awesome classes ("fa-solid fa-copy"). */
|
|
85
|
+
icon?: string;
|
|
86
|
+
/** Extra context for the contributing feature (its own keys). The viewed feature's context always arrives separately as `context.referrer`. */
|
|
87
|
+
context?: Context;
|
|
88
|
+
/** Related only: one small action button beside the link, which launches an ACTION feature in a modal. */
|
|
89
|
+
button?: ContributionButton;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export type ButtonStyleType = 'success' | 'error' | 'info' | 'warn';
|
|
93
|
+
export const BUTTON_LABEL_MAX = 10;
|
|
94
|
+
/**
|
|
95
|
+
* A button on a Related entry. Give one style (all are optional); if several, they layer: `styleType` is the framework's base look (success = green,
|
|
96
|
+
* error = red, info = blue, warn = yellow), `styleClass` (a CSS class of yours) overrides it, and `styleInline` overrides both.
|
|
97
|
+
*/
|
|
98
|
+
export interface ContributionButton {
|
|
99
|
+
/** At most 10 characters (an emoji counts as one); longer text is clipped. */
|
|
100
|
+
label: string;
|
|
101
|
+
styleType?: ButtonStyleType;
|
|
102
|
+
styleClass?: string;
|
|
103
|
+
styleInline?: CSSProperties;
|
|
104
|
+
/** The action's own context (its primary context). The viewed feature's context arrives as `context.referrer`. */
|
|
105
|
+
context?: Context;
|
|
106
|
+
/** The ACTION feature to launch (e.g. `uses.x.view` or `own.views.x.view`). It runs in a modal and may close it with `framework.close()`. */
|
|
107
|
+
action: ViewRef<any>;
|
|
108
|
+
}
|
|
109
|
+
/** `contributeRelated` / `contributeActions`: export one from a view's entry file (and opt in with `related` / `actions` in its manifest). Return nothing to stay out. */
|
|
110
|
+
/** What a contributor may use: the framework as its own module (send to services, storage) and its logger. Reads that need the vault wait for the unlock prompt, so check cheaply first. */
|
|
111
|
+
export interface ContributorEnv { framework: Framework; log: Logger }
|
|
112
|
+
export type Contributor = (feature: FeatureInfo, context: Context, env: ContributorEnv) => Contribution[] | void | Promise<Contribution[] | void>;
|
|
113
|
+
/** The reserved context key: the exact context of the feature the user came from (Related or Actions). */
|
|
114
|
+
export const REFERRER = 'referrer';
|
|
115
|
+
/** Relative URL of a feature (no extension origin). */
|
|
116
|
+
export const featureUrl = (module: string, view: string) => `#/v/${encodeURIComponent(module)}/${encodeURIComponent(view)}`;
|
|
117
|
+
|
|
118
|
+
/** A bubble beside the feature in the left navigation. `text` is at most 4 characters (emoji count as one); colors default from the theme's 16-pair palette. */
|
|
119
|
+
export interface Indicator {
|
|
120
|
+
id: string; text: string; color?: string; background?: string; title?: string;
|
|
121
|
+
/** The feature's view (3rd-level item) this belongs to. It shows on that view's row while the feature is expanded, and rolls up onto the feature's row while collapsed. Without it, it sits on the feature's row. */
|
|
122
|
+
view?: string;
|
|
123
|
+
}
|
|
124
|
+
export interface Indicators {
|
|
125
|
+
add(indicator: Indicator): void;
|
|
126
|
+
update(id: string, patch: Partial<Omit<Indicator, 'id'>>): void;
|
|
127
|
+
remove(id: string): void;
|
|
128
|
+
clear(): void;
|
|
129
|
+
list(): Indicator[];
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export interface BackgroundContext { framework: Framework; log: Logger }
|
|
133
|
+
/** A feature's optional background job (manifest `background: { entry, everySeconds }`). Typically updates `framework.indicators`. */
|
|
134
|
+
export interface BackgroundJob { run(ctx: BackgroundContext): Promise<void> | void }
|
|
135
|
+
export const defineBackground = (job: BackgroundJob): BackgroundJob => job;
|
|
136
|
+
|
|
137
|
+
export type RowStatus = 'ok' | 'warn' | 'error';
|
|
138
|
+
export interface RowResult { status: RowStatus; message?: string }
|
|
139
|
+
export interface CsvColumn { key: string; label?: string; /** Example value for the generated template. */ sample?: string; /** The upload must have this column. */ required?: boolean; /** false = kept in the row sent to the processor but not shown (default true). */ show?: boolean }
|
|
140
|
+
export interface CsvRowContext { framework: Framework; index: number; total: number; log: Logger }
|
|
141
|
+
export interface CsvFeatureDef {
|
|
142
|
+
kind: 'csv';
|
|
143
|
+
columns: CsvColumn[];
|
|
144
|
+
/** Overrides the one-row template built from `columns[].sample`. */
|
|
145
|
+
template?: { filename?: string; rows?: Record<string, string>[] };
|
|
146
|
+
intro?: string;
|
|
147
|
+
/** Return a problem to reject the whole file (listed in the Activity Log). */
|
|
148
|
+
validateRow?(row: Record<string, string>, line: number): string | null;
|
|
149
|
+
/** Return a reason to drop the row before the preview (logged with its line number). */
|
|
150
|
+
skipRow?(row: Record<string, string>, line: number): string | null;
|
|
151
|
+
confirm: { title?: string; steps: string[]; warning?: string };
|
|
152
|
+
processLabel?: string;
|
|
153
|
+
/** Pause between rows. */
|
|
154
|
+
delayMs?: number;
|
|
155
|
+
/** Receives the full CSV row. Throwing counts as 'error'. */
|
|
156
|
+
processRow(row: Record<string, string>, ctx: CsvRowContext): Promise<RowStatus | RowResult> | RowStatus | RowResult;
|
|
157
|
+
}
|
|
158
|
+
export const defineCsvFeature = (def: Omit<CsvFeatureDef, 'kind'>): CsvFeatureDef => ({ kind: 'csv', ...def });
|
|
159
|
+
|
|
160
|
+
export interface ItemFeatureDef {
|
|
161
|
+
kind: 'item';
|
|
162
|
+
/** The main pane: whatever you want. */
|
|
163
|
+
leftPane: ComponentType<ViewProps>;
|
|
164
|
+
/** Right rail (400px) above / below the framework's Actions section; leave out to not show. */
|
|
165
|
+
rightRailHeader?: ComponentType<ViewProps>;
|
|
166
|
+
rightRailFooter?: ComponentType<ViewProps>;
|
|
167
|
+
}
|
|
168
|
+
export const defineItemFeature = (def: Omit<ItemFeatureDef, 'kind'>): ItemFeatureDef => ({ kind: 'item', ...def });
|
|
169
|
+
export type FeatureDef = CsvFeatureDef | ItemFeatureDef;
|
|
170
|
+
|
|
171
|
+
/** One of this module's datasets, live. */
|
|
172
|
+
export interface DatasetInfo {
|
|
173
|
+
name: string; label: string; kind: 'importOnly' | 'refreshable'; key?: string; rows: number; columns: string[];
|
|
174
|
+
/** ISO time of the last refresh or import. */
|
|
175
|
+
updatedAt?: string; source?: 'csv' | 'routine' | 'set';
|
|
176
|
+
refreshing: boolean; /** What the running refresh says it is doing (`ctx.progress`). */ progress?: string; cancelling: boolean;
|
|
177
|
+
/** Plain-English schedule ("Manual only", "Every day at 2:00 AM"). */
|
|
178
|
+
schedule: string; lastError?: string;
|
|
179
|
+
/** Declared `incremental: true`, and which load the next refresh will do. */
|
|
180
|
+
incremental: boolean; load: 'full' | 'incremental';
|
|
181
|
+
}
|
|
182
|
+
export interface DatasetsApi extends Store<DatasetInfo[]> {
|
|
183
|
+
/** Refresh one of this module's datasets (queued behind any refresh already running); `load: 'full'` forces a Full Load. */
|
|
184
|
+
refresh(name: string, opts?: { load?: 'full' | 'incremental' }): Promise<SendResult<DatasetInfo>>;
|
|
185
|
+
/** Ask the running refresh to stop (its routine sees `ctx.signal`). */
|
|
186
|
+
cancel(name: string): void;
|
|
187
|
+
}
|
|
188
|
+
/** What a Settings tab component receives (ADR-072). */
|
|
189
|
+
export interface SettingsTabProps { framework: Framework }
|
|
190
|
+
|
|
71
191
|
export interface Framework {
|
|
192
|
+
/** This module's datasets, live, with refresh and cancel: what a Settings → Datasets tab is built from. */
|
|
193
|
+
datasets: DatasetsApi;
|
|
194
|
+
/** Declare what this feature is showing now. It is the `context` Related and Actions contributors receive (empty until you call it). */
|
|
195
|
+
expose(context: Context): void;
|
|
196
|
+
/** Add, update and remove this feature's indicator bubbles in the left navigation (also from its background job). */
|
|
197
|
+
indicators: Indicators;
|
|
198
|
+
/** Relative URL of a feature: `urlOf(feature)` or `urlOf(viewRef)`. */
|
|
199
|
+
urlOf(target: FeatureInfo | ViewRef<any>): string;
|
|
200
|
+
/** Closes this view when it is shown as an ACTION modal; does nothing elsewhere. Call it when the action is done and needs no further user interaction (a quick action that renders nothing never shows its modal). */
|
|
201
|
+
close(): void;
|
|
72
202
|
/** Request/response to a topic (a service operation, a dataset query…). Never throws; check `ok`. */
|
|
73
203
|
send<Req, Res>(message: Message<Req, Res>): Promise<SendResult<Res>>;
|
|
74
204
|
/** Fire an event topic to every subscriber. */
|
|
@@ -111,6 +241,13 @@ export const usePageContext = <C = Context,>(framework: Framework) => useStoreVa
|
|
|
111
241
|
export function usePageRefresh(framework: Framework, reload: (reason?: string) => void) {
|
|
112
242
|
useEffect(() => framework.page.onRefresh(reload), [framework, reload]);
|
|
113
243
|
}
|
|
244
|
+
/** This module's datasets, re-rendering as they refresh. */
|
|
245
|
+
export const useDatasets = (framework: Framework) => useStoreValue(framework.datasets);
|
|
246
|
+
/** Keeps what Related and Actions contributors see in step with `context` while mounted. */
|
|
247
|
+
export function useExposeContext(framework: Framework, context: Context) {
|
|
248
|
+
const key = JSON.stringify(context);
|
|
249
|
+
useEffect(() => framework.expose(context), [framework, key]);
|
|
250
|
+
}
|
|
114
251
|
/** Adds a Tools menu entry while the component is mounted. */
|
|
115
252
|
export function useTool(framework: Framework, tool: Tool | null) {
|
|
116
253
|
useEffect(() => (tool ? framework.tools.add(tool) : undefined), [framework, tool?.id]);
|
|
@@ -135,9 +272,9 @@ export interface ViewProps {
|
|
|
135
272
|
|
|
136
273
|
export interface ServiceContext {
|
|
137
274
|
instance: { module: string; type: string; name: string };
|
|
138
|
-
/** Non-secret field values from Settings → Services. */
|
|
275
|
+
/** Non-secret field values from Settings → Services (a field's declared `default` fills in when it is empty). Features read them with the standard `config` topic. */
|
|
139
276
|
config: Record<string, string>;
|
|
140
|
-
authMode: 'session' | 'apikey' | 'basic' | 'oauth';
|
|
277
|
+
authMode: 'session' | 'apikey' | 'basic' | 'oauth' | 'none';
|
|
141
278
|
/** A secret field from the vault. Waits for the unlock prompt while the vault is locked. */
|
|
142
279
|
secret(field: string): Promise<string>;
|
|
143
280
|
/**
|
|
@@ -162,8 +299,22 @@ export interface ServiceImpl {
|
|
|
162
299
|
* Return `{ active: false }` (or throw) when there is no session. If you leave this out, a passing `test()` counts as an active session.
|
|
163
300
|
*/
|
|
164
301
|
session?(ctx: ServiceContext): Promise<{ active: boolean; who?: string; detail?: string }>;
|
|
165
|
-
/**
|
|
166
|
-
|
|
302
|
+
/**
|
|
303
|
+
* Re-establish the session: the Sessions menu offers "Sign in again" on a service whose `session()` says it isn't active and that implements this
|
|
304
|
+
* (open the provider's sign-in, or ask a local bridge to run `gcloud auth login`). Throw to report why it failed; the menu re-checks afterwards.
|
|
305
|
+
* A service with `auth: ["none"]` and a `sessionRequirement` is listed in the Sessions menu too: it reports its own status with `session()`.
|
|
306
|
+
*/
|
|
307
|
+
reauth?(ctx: ServiceContext): Promise<void>;
|
|
308
|
+
/**
|
|
309
|
+
* The Test button on the service page: your script that proves the saved configuration works. Throw to fail (red). Return `who` to show "Connected as …",
|
|
310
|
+
* or `status: 'warn'` (with `detail`) when it works but something needs attention (yellow), e.g. the token is fine but a configured board isn't reachable.
|
|
311
|
+
*/
|
|
312
|
+
test?(ctx: ServiceContext): Promise<{ who?: string; status?: 'ok' | 'warn'; detail?: string } | void>;
|
|
313
|
+
/**
|
|
314
|
+
* Your own authentication for `ctx.fetch`: return the headers to send. When present it replaces the auth mode's built-in header (e.g. Trello wants
|
|
315
|
+
* `Authorization: OAuth oauth_consumer_key="<key>", oauth_token="<token>"` built from two credentials). Read credentials with `ctx.secret(field)` and `ctx.config`.
|
|
316
|
+
*/
|
|
317
|
+
authorize?(ctx: ServiceContext): Promise<Record<string, string>> | Record<string, string>;
|
|
167
318
|
/** Handlers for the service's custom topics (declared in taco.module.json). */
|
|
168
319
|
topics?: Record<string, (payload: any, ctx: ServiceContext) => Promise<unknown>>;
|
|
169
320
|
}
|
|
@@ -177,9 +328,20 @@ export interface RoutineContext {
|
|
|
177
328
|
framework: Framework;
|
|
178
329
|
log: Logger;
|
|
179
330
|
previous: { rows: number; updatedAt?: string };
|
|
331
|
+
/**
|
|
332
|
+
* 'full' replaces everything; 'incremental' (only for a dataset declared `incremental: true`, once it has data) means load just what changed since
|
|
333
|
+
* `previous.updatedAt` and return `mode: 'append'` or `'upsert'`. The user can switch a dataset to a Full Load.
|
|
334
|
+
*/
|
|
335
|
+
load: 'full' | 'incremental';
|
|
336
|
+
/** Say what the refresh is doing ("Signing in…", "Running query…"): shown on Settings → Datasets and the header icon while it runs. */
|
|
337
|
+
progress(message: string): void;
|
|
338
|
+
/** Aborted when the user cancels the refresh. Stop and throw (or return); anything you return after a cancel is discarded. */
|
|
339
|
+
signal: AbortSignal;
|
|
180
340
|
}
|
|
341
|
+
/** What a routine returns. `replace` (default) swaps all rows; `append` adds them; `upsert` adds or updates by the dataset's key. Stored data changes only when the routine succeeds. */
|
|
342
|
+
export interface RoutineResult { rows: Record<string, unknown>[]; columns?: string[]; mode?: 'replace' | 'append' | 'upsert' }
|
|
181
343
|
export interface Routine {
|
|
182
|
-
/**
|
|
183
|
-
run(ctx: RoutineContext): Promise<
|
|
344
|
+
/** Produces the rows (a Full Load returns every row). A failed or cancelled refresh loses nothing. */
|
|
345
|
+
run(ctx: RoutineContext): Promise<RoutineResult>;
|
|
184
346
|
}
|
|
185
347
|
export const defineRoutine = (routine: Routine): Routine => routine;
|
package/src/zip.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// A small ZIP writer (stored entries, no compression) for things a module hands the user: a setup bundle, an export. Dependency-free (CommunityOS ADR-068 / Taco ADR-045).
|
|
2
|
+
|
|
3
|
+
const TABLE = (() => { const t = new Uint32Array(256); for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; } return t; })();
|
|
4
|
+
/** CRC-32 (the ZIP / PNG polynomial) of some bytes. */
|
|
5
|
+
export function crc32(bytes: Uint8Array): number {
|
|
6
|
+
let c = 0xffffffff;
|
|
7
|
+
for (let i = 0; i < bytes.length; i++) c = TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);
|
|
8
|
+
return (c ^ 0xffffffff) >>> 0;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface ZipEntry {
|
|
12
|
+
/** Path inside the ZIP, "/" separated ("bridge/dataset-bridge.py"). End with "/" for a folder. */
|
|
13
|
+
name: string;
|
|
14
|
+
data?: string | Uint8Array;
|
|
15
|
+
/** Unix permissions (0o755 for a script that must be executable); default 0o644. */
|
|
16
|
+
mode?: number;
|
|
17
|
+
modified?: Date;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const dosTime = (d: Date) => ((d.getHours() << 11) | (d.getMinutes() << 5) | (d.getSeconds() >> 1)) & 0xffff;
|
|
21
|
+
const dosDate = (d: Date) => ((Math.max(0, d.getFullYear() - 1980) << 9) | ((d.getMonth() + 1) << 5) | d.getDate()) & 0xffff;
|
|
22
|
+
|
|
23
|
+
/** Builds a ZIP file (stored, UTF-8 names, unix modes kept) from entries. */
|
|
24
|
+
export function createZip(entries: ZipEntry[]): Uint8Array {
|
|
25
|
+
const enc = new TextEncoder();
|
|
26
|
+
const chunks: Uint8Array[] = [];
|
|
27
|
+
const central: Uint8Array[] = [];
|
|
28
|
+
let offset = 0;
|
|
29
|
+
const u16 = (v: number) => [v & 0xff, (v >>> 8) & 0xff];
|
|
30
|
+
const u32 = (v: number) => [v & 0xff, (v >>> 8) & 0xff, (v >>> 16) & 0xff, (v >>> 24) & 0xff];
|
|
31
|
+
for (const e of entries) {
|
|
32
|
+
const name = enc.encode(e.name);
|
|
33
|
+
const data = typeof e.data === 'string' ? enc.encode(e.data) : e.data ?? new Uint8Array(0);
|
|
34
|
+
const crc = crc32(data), when = e.modified ?? new Date(), isDir = e.name.endsWith('/');
|
|
35
|
+
const mode = e.mode ?? (isDir ? 0o755 : 0o644);
|
|
36
|
+
const header = Uint8Array.from([...u32(0x04034b50), ...u16(20), ...u16(0x0800), ...u16(0), ...u16(dosTime(when)), ...u16(dosDate(when)), ...u32(crc), ...u32(data.length), ...u32(data.length), ...u16(name.length), ...u16(0)]);
|
|
37
|
+
chunks.push(header, name, data);
|
|
38
|
+
central.push(Uint8Array.from([...u32(0x02014b50), ...u16((3 << 8) | 20), ...u16(20), ...u16(0x0800), ...u16(0), ...u16(dosTime(when)), ...u16(dosDate(when)), ...u32(crc), ...u32(data.length), ...u32(data.length), ...u16(name.length), ...u16(0), ...u16(0), ...u16(0), ...u16(0), ...u32(((isDir ? 0o040000 : 0o100000) | mode) * 0x10000 + (isDir ? 0x10 : 0)), ...u32(offset)]), name);
|
|
39
|
+
offset += header.length + name.length + data.length;
|
|
40
|
+
}
|
|
41
|
+
const centralSize = central.reduce((n, c) => n + c.length, 0);
|
|
42
|
+
const end = Uint8Array.from([...u32(0x06054b50), ...u16(0), ...u16(0), ...u16(entries.length), ...u16(entries.length), ...u32(centralSize), ...u32(offset), ...u16(0)]);
|
|
43
|
+
const all = [...chunks, ...central, end];
|
|
44
|
+
const out = new Uint8Array(all.reduce((n, c) => n + c.length, 0));
|
|
45
|
+
let p = 0;
|
|
46
|
+
for (const c of all) { out.set(c, p); p += c.length; }
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Offers bytes or text to the user as a file download (in a browser page). */
|
|
51
|
+
export function downloadFile(name: string, data: string | Uint8Array, mime = 'application/octet-stream') {
|
|
52
|
+
const url = URL.createObjectURL(new Blob([data as BlobPart], { type: mime }));
|
|
53
|
+
const a = Object.assign(document.createElement('a'), { href: url, download: name });
|
|
54
|
+
a.click();
|
|
55
|
+
setTimeout(() => URL.revokeObjectURL(url), 10_000);
|
|
56
|
+
}
|