@open-workspace/create 0.2.0 → 0.4.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.
- package/README.md +29 -5
- package/create.ts +86 -0
- package/import/args.ts +57 -0
- package/import/cli.ts +432 -0
- package/import/concurrency.ts +52 -0
- package/import/csv.ts +56 -0
- package/import/directory/command.ts +320 -0
- package/import/directory/google.ts +510 -0
- package/import/directory/plan.ts +367 -0
- package/import/gmail.ts +195 -0
- package/import/headers.ts +105 -0
- package/import/imap-command.ts +182 -0
- package/import/imap-source.ts +397 -0
- package/import/invariant.ts +22 -0
- package/import/mbox-source.ts +174 -0
- package/import/mbox.ts +198 -0
- package/import/oauth.ts +423 -0
- package/import/protocol.ts +59 -0
- package/import/uploader.ts +235 -0
- package/import/workspace.ts +218 -0
- package/index.ts +13 -121
- package/module-templates.ts +409 -0
- package/module.ts +105 -0
- package/package.json +18 -6
- package/setup/alchemy-helper.ts +258 -0
- package/setup/alchemy-protocol.ts +63 -0
- package/setup/alchemy.ts +163 -0
- package/setup/args.ts +128 -0
- package/setup/cloudflare-api.ts +156 -0
- package/setup/domains.ts +102 -0
- package/setup/flow.ts +987 -0
- package/setup/ui.ts +146 -0
- package/templates.ts +193 -140
- package/keys.ts +0 -31
package/README.md
CHANGED
|
@@ -1,12 +1,36 @@
|
|
|
1
1
|
# @open-workspace/create
|
|
2
2
|
|
|
3
|
+
Creates and deploys an [OpenWorkspace](https://openworkspace.dev) in one run.
|
|
4
|
+
|
|
3
5
|
```sh
|
|
4
6
|
bun create @open-workspace
|
|
5
7
|
```
|
|
6
8
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
9
|
+
It signs you in to Cloudflare, lets you pick the account, the mail domains and
|
|
10
|
+
the hostname from your zones, writes the project, starts a git repository and
|
|
11
|
+
deploys. It ends with the address to open and create the first administrator.
|
|
12
|
+
`--help` lists the flags for scripted runs.
|
|
13
|
+
|
|
14
|
+
## Adding a module
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
bunx @open-workspace/create module time-off
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Writes a module skeleton to `modules/time-off/` in a deployment's directory and
|
|
21
|
+
adds it to `alchemy.run.ts`.
|
|
22
|
+
|
|
23
|
+
## Importing mail and people
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
bunx @open-workspace/create import mbox ~/Takeout/Mail --workspace https://mail.acme.com --into ada@acme.com
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Imports mail from an mbox file, a Google Takeout export or an IMAP account, and
|
|
30
|
+
people and teams from a Google Workspace directory.
|
|
31
|
+
|
|
32
|
+
## Documentation
|
|
11
33
|
|
|
12
|
-
|
|
34
|
+
- [Deploying](https://openworkspace.dev/docs/deploy)
|
|
35
|
+
- [Writing a module](https://openworkspace.dev/docs/modules)
|
|
36
|
+
- [Migration](https://openworkspace.dev/docs/migration)
|
package/create.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { projectAlchemy } from "./setup/alchemy.ts";
|
|
2
|
+
import { createUsage, parseCreateArgs } from "./setup/args.ts";
|
|
3
|
+
import { cloudflareApi } from "./setup/cloudflare-api.ts";
|
|
4
|
+
import { runCreate } from "./setup/flow.ts";
|
|
5
|
+
import { clackUi } from "./setup/ui.ts";
|
|
6
|
+
|
|
7
|
+
/** `bun create @open-workspace`: the flow in setup/flow.ts on the real terminal, Alchemy, Cloudflare API and bun. */
|
|
8
|
+
export function main(args: readonly string[]) {
|
|
9
|
+
const parsed = parseCreateArgs(args);
|
|
10
|
+
|
|
11
|
+
if ("error" in parsed) {
|
|
12
|
+
console.error(`${parsed.error}\n\n${createUsage}`);
|
|
13
|
+
|
|
14
|
+
return 2;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const { options } = parsed;
|
|
18
|
+
|
|
19
|
+
if (options.help) {
|
|
20
|
+
console.log(createUsage);
|
|
21
|
+
|
|
22
|
+
return 0;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const interactive =
|
|
26
|
+
!options.yes && Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
27
|
+
|
|
28
|
+
return runCreate(options, {
|
|
29
|
+
ui: clackUi,
|
|
30
|
+
cwd: process.cwd(),
|
|
31
|
+
env: process.env,
|
|
32
|
+
interactive,
|
|
33
|
+
async install(directory) {
|
|
34
|
+
const child = Bun.spawn([process.execPath, "install"], {
|
|
35
|
+
cwd: directory,
|
|
36
|
+
stdin: "ignore",
|
|
37
|
+
stdout: "ignore",
|
|
38
|
+
stderr: "pipe",
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
const [output, exitCode] = await Promise.all([
|
|
42
|
+
new Response(child.stderr).text(),
|
|
43
|
+
child.exited,
|
|
44
|
+
]);
|
|
45
|
+
|
|
46
|
+
return { ok: exitCode === 0, output };
|
|
47
|
+
},
|
|
48
|
+
alchemy: (directory, profile) =>
|
|
49
|
+
projectAlchemy(directory, { profile, interactive }),
|
|
50
|
+
cloudflare: (auth) => cloudflareApi(auth),
|
|
51
|
+
git: (directory) => startRepository(directory),
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** `git init` plus a first commit, in a project that isn't already inside a repository. */
|
|
56
|
+
export async function startRepository(directory: string) {
|
|
57
|
+
if (!Bun.which("git")) return "skipped";
|
|
58
|
+
|
|
59
|
+
const git = async (...args: string[]) => {
|
|
60
|
+
const child = Bun.spawn(["git", ...args], {
|
|
61
|
+
cwd: directory,
|
|
62
|
+
stdin: "ignore",
|
|
63
|
+
stdout: "ignore",
|
|
64
|
+
stderr: "ignore",
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
return (await child.exited) === 0;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
if (await git("rev-parse", "--is-inside-work-tree")) return "skipped";
|
|
71
|
+
|
|
72
|
+
if (!(await git("init", "--quiet", "--initial-branch=main"))) {
|
|
73
|
+
return "skipped";
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (!(await git("add", "--all"))) return "initialized";
|
|
77
|
+
|
|
78
|
+
const committed = await git(
|
|
79
|
+
"commit",
|
|
80
|
+
"--quiet",
|
|
81
|
+
"--message",
|
|
82
|
+
"Create the OpenWorkspace project"
|
|
83
|
+
);
|
|
84
|
+
|
|
85
|
+
return committed ? "committed" : "initialized";
|
|
86
|
+
}
|
package/import/args.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { parseArgs } from "node:util";
|
|
2
|
+
import type { ParseArgsConfig } from "node:util";
|
|
3
|
+
|
|
4
|
+
type Options = NonNullable<ParseArgsConfig["options"]>;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Joins each long string option to a value that starts with a dash, so
|
|
8
|
+
* `--token -abc` reads as `--token=-abc`. `parseArgs` rejects the spaced
|
|
9
|
+
* form as ambiguous, but tokens, passwords and other secrets may begin with
|
|
10
|
+
* a dash. A dash value that is itself one of the options (`--token --login`)
|
|
11
|
+
* is left alone, and so is everything after `--`.
|
|
12
|
+
*/
|
|
13
|
+
export function joinDashValues(args: readonly string[], options: Options) {
|
|
14
|
+
const known = new Set<string>();
|
|
15
|
+
const takesValue = new Set<string>();
|
|
16
|
+
|
|
17
|
+
for (const [name, option] of Object.entries(options)) {
|
|
18
|
+
known.add(`--${name}`);
|
|
19
|
+
|
|
20
|
+
if (option.short) known.add(`-${option.short}`);
|
|
21
|
+
|
|
22
|
+
if (option.type === "string") takesValue.add(`--${name}`);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const isOption = (arg: string) =>
|
|
26
|
+
arg === "--" || known.has(arg.split("=", 1)[0] ?? arg);
|
|
27
|
+
|
|
28
|
+
const joined: string[] = [];
|
|
29
|
+
|
|
30
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
31
|
+
const arg = args[index] ?? "";
|
|
32
|
+
|
|
33
|
+
if (arg === "--") {
|
|
34
|
+
joined.push(...args.slice(index));
|
|
35
|
+
break;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const next = args[index + 1];
|
|
39
|
+
|
|
40
|
+
if (takesValue.has(arg) && next?.startsWith("-") && !isOption(next)) {
|
|
41
|
+
joined.push(`${arg}=${next}`);
|
|
42
|
+
index += 1;
|
|
43
|
+
} else {
|
|
44
|
+
joined.push(arg);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return joined;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** `parseArgs` that accepts option values starting with a dash (`joinDashValues`). */
|
|
52
|
+
export function parseCliArgs<T extends ParseArgsConfig>(config: T) {
|
|
53
|
+
return parseArgs({
|
|
54
|
+
...config,
|
|
55
|
+
args: joinDashValues(config.args ?? [], config.options ?? {}),
|
|
56
|
+
});
|
|
57
|
+
}
|
package/import/cli.ts
ADDED
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { basename } from "node:path";
|
|
3
|
+
|
|
4
|
+
import { parseCliArgs } from "./args.ts";
|
|
5
|
+
import { parseCsv } from "./csv.ts";
|
|
6
|
+
import { mboxFiles, mboxItems, scanMbox } from "./mbox-source.ts";
|
|
7
|
+
import type { MboxSourceOptions } from "./mbox-source.ts";
|
|
8
|
+
import { OAuthSession, StaticToken } from "./oauth.ts";
|
|
9
|
+
import type { Fetch, TokenSource } from "./oauth.ts";
|
|
10
|
+
import { MAIL_IMPORT_SCOPES, placementSchema } from "./protocol.ts";
|
|
11
|
+
import type { ImportItem, Placement, SkippedItem } from "./protocol.ts";
|
|
12
|
+
import { progressLine, ResumeState, upload } from "./uploader.ts";
|
|
13
|
+
import type { UploadStats } from "./uploader.ts";
|
|
14
|
+
import { Workspace } from "./workspace.ts";
|
|
15
|
+
|
|
16
|
+
const USAGE = `Bring people and mail into an OpenWorkspace.
|
|
17
|
+
|
|
18
|
+
bunx @open-workspace/create import mbox <file or Takeout folder>... --into <mailbox>
|
|
19
|
+
bunx @open-workspace/create import imap --host <host> --user <user> --into <mailbox>
|
|
20
|
+
bunx @open-workspace/create import people --google-credentials <file.json> [--admin <email>]
|
|
21
|
+
|
|
22
|
+
Common options:
|
|
23
|
+
--workspace <url> The workspace, e.g. https://mail.acme.com (or OPENWORKSPACE_URL)
|
|
24
|
+
--into <mailbox> Target mailbox: its address or id
|
|
25
|
+
--map <file.csv> Many sources at once: rows of "source,target" (imap: "user,target[,password]")
|
|
26
|
+
--concurrency <n> Uploads in flight per mailbox (default 2)
|
|
27
|
+
--state-dir <dir> Where resume state is kept (default .openworkspace-import)
|
|
28
|
+
--dry-run Read the source and print what would be imported
|
|
29
|
+
--token <token> An access token instead of signing in (or OPENWORKSPACE_TOKEN)
|
|
30
|
+
--login Sign in again even with a stored sign-in
|
|
31
|
+
|
|
32
|
+
mbox options:
|
|
33
|
+
--skip <places> Places not to import, e.g. spam,trash
|
|
34
|
+
--archived-labels <archive|folder>
|
|
35
|
+
Gmail mail with your labels but not in the Inbox: Archive
|
|
36
|
+
(default; the label is lost) or the label's folder (in the Inbox)
|
|
37
|
+
--folder-priority <labels>
|
|
38
|
+
Labels to prefer as a thread's folder, comma-separated
|
|
39
|
+
--placement <inbox|archive>, --folder <name>
|
|
40
|
+
For mbox files without Gmail labels (default archive)
|
|
41
|
+
|
|
42
|
+
See https://openworkspace.dev/docs/migration for every source, what maps and what does not.`;
|
|
43
|
+
|
|
44
|
+
/** What the commands need from outside; tests replace them. */
|
|
45
|
+
export type CliDeps = {
|
|
46
|
+
fetch?: Fetch;
|
|
47
|
+
openBrowser?: (url: string) => void | Promise<void>;
|
|
48
|
+
credentialsPath?: string | null;
|
|
49
|
+
log?: (message: string) => void;
|
|
50
|
+
/** Progress lines; a terminal rewrites one line. */
|
|
51
|
+
progress?: (line: string) => void;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
export const commonOptions = {
|
|
55
|
+
workspace: { type: "string" },
|
|
56
|
+
into: { type: "string" },
|
|
57
|
+
map: { type: "string" },
|
|
58
|
+
concurrency: { type: "string" },
|
|
59
|
+
"state-dir": { type: "string" },
|
|
60
|
+
"dry-run": { type: "boolean" },
|
|
61
|
+
token: { type: "string" },
|
|
62
|
+
login: { type: "boolean" },
|
|
63
|
+
help: { type: "boolean", short: "h" },
|
|
64
|
+
} as const;
|
|
65
|
+
|
|
66
|
+
export type CommonValues = {
|
|
67
|
+
workspace?: string;
|
|
68
|
+
into?: string;
|
|
69
|
+
map?: string;
|
|
70
|
+
concurrency?: string;
|
|
71
|
+
"state-dir"?: string;
|
|
72
|
+
"dry-run"?: boolean;
|
|
73
|
+
token?: string;
|
|
74
|
+
login?: boolean;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
export class UsageError extends Error {}
|
|
78
|
+
|
|
79
|
+
function required<T>(value: T | undefined, message: string): T {
|
|
80
|
+
if (value === undefined || value === "") throw new UsageError(message);
|
|
81
|
+
|
|
82
|
+
return value;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Signs in (or uses a given token) and returns the workspace's API. */
|
|
86
|
+
export async function connect(
|
|
87
|
+
values: CommonValues,
|
|
88
|
+
scopes: string[],
|
|
89
|
+
deps: CliDeps
|
|
90
|
+
) {
|
|
91
|
+
const url = required(
|
|
92
|
+
values.workspace ?? process.env.OPENWORKSPACE_URL,
|
|
93
|
+
"Pass --workspace https://your-workspace"
|
|
94
|
+
);
|
|
95
|
+
|
|
96
|
+
const token = values.token ?? process.env.OPENWORKSPACE_TOKEN;
|
|
97
|
+
|
|
98
|
+
const auth: TokenSource = token
|
|
99
|
+
? new StaticToken(token)
|
|
100
|
+
: await OAuthSession.login({
|
|
101
|
+
workspace: url,
|
|
102
|
+
scopes,
|
|
103
|
+
fetch: deps.fetch,
|
|
104
|
+
openBrowser: deps.openBrowser,
|
|
105
|
+
credentialsPath: deps.credentialsPath,
|
|
106
|
+
fresh: values.login,
|
|
107
|
+
log: deps.log,
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
return new Workspace(url, auth, deps.fetch);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** One source and the mailbox it goes into (and, for IMAP, the account's password). */
|
|
114
|
+
export type Job = { source: string; target: string; password?: string };
|
|
115
|
+
|
|
116
|
+
/** Source → target pairs from --map, or the one source with --into. */
|
|
117
|
+
export function jobs(values: CommonValues, sources: string[]): Job[] {
|
|
118
|
+
if (values.map) {
|
|
119
|
+
const rows = parseCsv(readFileSync(values.map, "utf-8"));
|
|
120
|
+
|
|
121
|
+
return rows.flatMap((row, index): Job[] => {
|
|
122
|
+
const [source = "", target = "", password] = row;
|
|
123
|
+
|
|
124
|
+
// A header row ("source,target") is allowed.
|
|
125
|
+
if (index === 0 && /^(source|path|user)$/iu.test(source)) return [];
|
|
126
|
+
|
|
127
|
+
if (!source || !target) {
|
|
128
|
+
throw new UsageError(
|
|
129
|
+
`Row ${index + 1} of ${values.map} needs a source and a target`
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const job: Job = { source, target };
|
|
134
|
+
|
|
135
|
+
if (password) job.password = password;
|
|
136
|
+
|
|
137
|
+
return [job];
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const into = required(
|
|
142
|
+
values.into,
|
|
143
|
+
"Pass --into <mailbox address or id>, or --map"
|
|
144
|
+
);
|
|
145
|
+
|
|
146
|
+
if (!sources.length) throw new UsageError("Name the source to import");
|
|
147
|
+
|
|
148
|
+
return [{ source: sources.join("\u0000"), target: into }];
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function progressPrinter(deps: CliDeps) {
|
|
152
|
+
if (deps.progress) return deps.progress;
|
|
153
|
+
|
|
154
|
+
if (process.stderr.isTTY) {
|
|
155
|
+
return (line: string) => process.stderr.write(`\r\u001B[2K${line}`);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
let last = 0;
|
|
159
|
+
|
|
160
|
+
return (line: string) => {
|
|
161
|
+
if (Date.now() - last < 5000) return;
|
|
162
|
+
last = Date.now();
|
|
163
|
+
console.error(line);
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Uploads one source's items into one mailbox and reports the outcome. */
|
|
168
|
+
export async function runJob(input: {
|
|
169
|
+
workspace: Workspace;
|
|
170
|
+
target: string;
|
|
171
|
+
label: string;
|
|
172
|
+
job: string;
|
|
173
|
+
items: AsyncIterable<ImportItem | SkippedItem>;
|
|
174
|
+
total: number | null;
|
|
175
|
+
values: CommonValues;
|
|
176
|
+
deps: CliDeps;
|
|
177
|
+
}) {
|
|
178
|
+
const log = input.deps.log ?? ((message: string) => console.error(message));
|
|
179
|
+
const mailbox = await input.workspace.importTarget(input.target);
|
|
180
|
+
|
|
181
|
+
const state = new ResumeState(
|
|
182
|
+
input.values["state-dir"] ?? ".openworkspace-import",
|
|
183
|
+
`${new URL(input.workspace.origin).host}-${mailbox.id}-${input.job}`
|
|
184
|
+
);
|
|
185
|
+
|
|
186
|
+
const print = progressPrinter(input.deps);
|
|
187
|
+
const label = `${input.label} → ${mailbox.address}`;
|
|
188
|
+
|
|
189
|
+
const stats: UploadStats = await upload({
|
|
190
|
+
workspace: input.workspace,
|
|
191
|
+
mailboxId: mailbox.id,
|
|
192
|
+
items: input.items,
|
|
193
|
+
state,
|
|
194
|
+
concurrency: Math.max(1, Number(input.values.concurrency ?? 2) || 2),
|
|
195
|
+
total: input.total,
|
|
196
|
+
onProgress: (current) => print(progressLine(label, current)),
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
if (process.stderr.isTTY && !input.deps.progress) process.stderr.write("\n");
|
|
200
|
+
log(progressLine(label, stats));
|
|
201
|
+
|
|
202
|
+
if (stats.failed) {
|
|
203
|
+
log(
|
|
204
|
+
` ${stats.failed} failed; see ${state.failuresPath}. Run the same command again to retry them.`
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
if (stats.folderSkipped) {
|
|
209
|
+
log(
|
|
210
|
+
` ${stats.folderSkipped} messages kept no folder (a mailbox has at most 100, and system folder names are taken).`
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
return stats;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Tallies what a dry run would import. */
|
|
218
|
+
export async function describeItems(
|
|
219
|
+
items: AsyncIterable<ImportItem | SkippedItem>,
|
|
220
|
+
log: (message: string) => void,
|
|
221
|
+
label: string
|
|
222
|
+
) {
|
|
223
|
+
const places = new Map<string, number>();
|
|
224
|
+
const folders = new Map<string, number>();
|
|
225
|
+
const skipped = new Map<string, number>();
|
|
226
|
+
let unread = 0;
|
|
227
|
+
let count = 0;
|
|
228
|
+
|
|
229
|
+
for await (const item of items) {
|
|
230
|
+
count += 1;
|
|
231
|
+
|
|
232
|
+
if ("skipped" in item) {
|
|
233
|
+
skipped.set(item.skipped, (skipped.get(item.skipped) ?? 0) + 1);
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
places.set(item.placement, (places.get(item.placement) ?? 0) + 1);
|
|
238
|
+
|
|
239
|
+
if (item.folder) {
|
|
240
|
+
folders.set(item.folder, (folders.get(item.folder) ?? 0) + 1);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
if (!item.seen) unread += 1;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const list = (map: Map<string, number>) =>
|
|
247
|
+
[...map].map(([name, n]) => `${name} ${n}`).join(", ") || "none";
|
|
248
|
+
|
|
249
|
+
log(`${label}: ${count} messages`);
|
|
250
|
+
log(` places: ${list(places)}`);
|
|
251
|
+
log(` folders: ${list(folders)}`);
|
|
252
|
+
log(` unread: ${unread}`);
|
|
253
|
+
log(` skipped: ${list(skipped)}`);
|
|
254
|
+
|
|
255
|
+
return { count, places, folders, skipped, unread };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** --skip: comma-separated places. */
|
|
259
|
+
export function placementList(value: string | undefined) {
|
|
260
|
+
const list = new Set<Placement>();
|
|
261
|
+
|
|
262
|
+
for (const name of (value ?? "").split(",")) {
|
|
263
|
+
const item = name.trim().toLowerCase();
|
|
264
|
+
|
|
265
|
+
if (!item) continue;
|
|
266
|
+
const place = placementSchema.safeParse(item);
|
|
267
|
+
|
|
268
|
+
if (!place.success) throw new UsageError(`Unknown place: ${item}`);
|
|
269
|
+
list.add(place.data);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
return list;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
export async function mboxCommand(args: string[], deps: CliDeps) {
|
|
276
|
+
const { values, positionals } = parseCliArgs({
|
|
277
|
+
args,
|
|
278
|
+
allowPositionals: true,
|
|
279
|
+
options: {
|
|
280
|
+
...commonOptions,
|
|
281
|
+
skip: { type: "string" },
|
|
282
|
+
"archived-labels": { type: "string" },
|
|
283
|
+
"folder-priority": { type: "string" },
|
|
284
|
+
placement: { type: "string" },
|
|
285
|
+
folder: { type: "string" },
|
|
286
|
+
},
|
|
287
|
+
});
|
|
288
|
+
|
|
289
|
+
if (values.help) {
|
|
290
|
+
console.log(USAGE);
|
|
291
|
+
|
|
292
|
+
return 0;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
const archivedLabels = values["archived-labels"] ?? "archive";
|
|
296
|
+
|
|
297
|
+
if (archivedLabels !== "archive" && archivedLabels !== "folder") {
|
|
298
|
+
throw new UsageError("--archived-labels is archive or folder");
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const parsedPlacement = placementSchema.safeParse(
|
|
302
|
+
values.placement ?? "archive"
|
|
303
|
+
);
|
|
304
|
+
|
|
305
|
+
if (!parsedPlacement.success) {
|
|
306
|
+
throw new UsageError(`Unknown --placement: ${values.placement}`);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const placement = parsedPlacement.data;
|
|
310
|
+
|
|
311
|
+
const options: MboxSourceOptions = {
|
|
312
|
+
archivedLabels,
|
|
313
|
+
folderPriority: (values["folder-priority"] ?? "")
|
|
314
|
+
.split(",")
|
|
315
|
+
.map((label) => label.trim())
|
|
316
|
+
.filter(Boolean),
|
|
317
|
+
skip: placementList(values.skip),
|
|
318
|
+
placement,
|
|
319
|
+
folder: values.folder ?? null,
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
const log = deps.log ?? ((message: string) => console.error(message));
|
|
323
|
+
const pairs = jobs(values, positionals);
|
|
324
|
+
|
|
325
|
+
const workspace = values["dry-run"]
|
|
326
|
+
? null
|
|
327
|
+
: await connect(values, MAIL_IMPORT_SCOPES, deps);
|
|
328
|
+
|
|
329
|
+
const results: UploadStats[] = [];
|
|
330
|
+
|
|
331
|
+
const mboxJob = async ({ source, target }: Job) => {
|
|
332
|
+
const files = mboxFiles(source.split("\u0000"));
|
|
333
|
+
|
|
334
|
+
if (!files.length) throw new UsageError(`No mbox files in ${source}`);
|
|
335
|
+
log(
|
|
336
|
+
`Reading ${files.length === 1 ? files[0] : `${files.length} mbox files`}…`
|
|
337
|
+
);
|
|
338
|
+
const scan = await scanMbox(files, options);
|
|
339
|
+
const [only] = files;
|
|
340
|
+
|
|
341
|
+
const label =
|
|
342
|
+
files.length === 1 && only
|
|
343
|
+
? basename(only)
|
|
344
|
+
: `${files.length} mbox files`;
|
|
345
|
+
|
|
346
|
+
if (!workspace) {
|
|
347
|
+
await describeItems(
|
|
348
|
+
mboxItems(files, options, scan.threads),
|
|
349
|
+
log,
|
|
350
|
+
`${label} → ${target}`
|
|
351
|
+
);
|
|
352
|
+
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
results.push(
|
|
357
|
+
await runJob({
|
|
358
|
+
workspace,
|
|
359
|
+
target,
|
|
360
|
+
label,
|
|
361
|
+
job: `mbox-${new Bun.CryptoHasher("sha256").update(files.join("\n")).digest("hex").slice(0, 12)}`,
|
|
362
|
+
items: mboxItems(files, options, scan.threads),
|
|
363
|
+
total: scan.count,
|
|
364
|
+
values,
|
|
365
|
+
deps,
|
|
366
|
+
})
|
|
367
|
+
);
|
|
368
|
+
};
|
|
369
|
+
|
|
370
|
+
for (const job of pairs) {
|
|
371
|
+
// oxlint-disable-next-line eslint/no-await-in-loop -- one mailbox at a time: each job reports on the one progress line, and a failure stops the jobs after it
|
|
372
|
+
await mboxJob(job);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
return results.some((stats) => stats.failed) ? 1 : 0;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
type Command = (args: string[], deps: CliDeps) => Promise<number>;
|
|
379
|
+
|
|
380
|
+
/** Each source's command; the IMAP and directory ones load their dependencies only when used. */
|
|
381
|
+
const commands = new Map<string, () => Promise<Command>>([
|
|
382
|
+
["mbox", () => Promise.resolve(mboxCommand)],
|
|
383
|
+
["takeout", () => Promise.resolve(mboxCommand)],
|
|
384
|
+
[
|
|
385
|
+
"imap",
|
|
386
|
+
() => import("./imap-command.ts").then((module) => module.imapCommand),
|
|
387
|
+
],
|
|
388
|
+
[
|
|
389
|
+
"people",
|
|
390
|
+
() =>
|
|
391
|
+
import("./directory/command.ts").then((module) => module.peopleCommand),
|
|
392
|
+
],
|
|
393
|
+
]);
|
|
394
|
+
|
|
395
|
+
export async function main(args: string[], deps: CliDeps = {}) {
|
|
396
|
+
const [name, ...rest] = args;
|
|
397
|
+
|
|
398
|
+
if (!name || name === "--help" || name === "-h" || name === "help") {
|
|
399
|
+
console.log(USAGE);
|
|
400
|
+
|
|
401
|
+
return name ? 0 : 1;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
const command = commands.get(name);
|
|
405
|
+
|
|
406
|
+
if (!command) {
|
|
407
|
+
console.error(`Unknown import source: ${name}\n\n${USAGE}`);
|
|
408
|
+
|
|
409
|
+
return 1;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
try {
|
|
413
|
+
return await (
|
|
414
|
+
await command()
|
|
415
|
+
)(rest, deps);
|
|
416
|
+
} catch (error) {
|
|
417
|
+
if (
|
|
418
|
+
error instanceof UsageError ||
|
|
419
|
+
(error instanceof Error &&
|
|
420
|
+
error.name === "TypeError" &&
|
|
421
|
+
/option|argument/iu.test(error.message))
|
|
422
|
+
) {
|
|
423
|
+
console.error(`${error.message}\n\nRun with --help for usage.`);
|
|
424
|
+
|
|
425
|
+
return 1;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
console.error(error instanceof Error ? error.message : error);
|
|
429
|
+
|
|
430
|
+
return 1;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs `task` for each item with at most `limit` running at once, taking
|
|
3
|
+
* items in order as tasks finish. The first task that fails stops taking
|
|
4
|
+
* new items; the ones already running finish, the source is closed (an
|
|
5
|
+
* async generator's `finally` runs) and that first failure is thrown.
|
|
6
|
+
*/
|
|
7
|
+
export async function forEachConcurrent<Item>(
|
|
8
|
+
items: AsyncIterable<Item> | Iterable<Item>,
|
|
9
|
+
limit: number,
|
|
10
|
+
task: (item: Item, index: number) => Promise<void>
|
|
11
|
+
): Promise<void> {
|
|
12
|
+
// An async generator queues concurrent next() calls, so workers can share it.
|
|
13
|
+
const source = (async function* () {
|
|
14
|
+
yield* items;
|
|
15
|
+
})();
|
|
16
|
+
|
|
17
|
+
let taken = 0;
|
|
18
|
+
let stopped = false;
|
|
19
|
+
const failures: Promise<void>[] = [];
|
|
20
|
+
|
|
21
|
+
const work = async () => {
|
|
22
|
+
/* oxlint-disable eslint/no-await-in-loop -- a worker takes its next item only when its last task is done: that is the concurrency bound */
|
|
23
|
+
for (;;) {
|
|
24
|
+
// Set by another worker's failure while this one waited.
|
|
25
|
+
if (stopped) return;
|
|
26
|
+
const next = await source.next();
|
|
27
|
+
|
|
28
|
+
if (next.done) return;
|
|
29
|
+
const index = taken;
|
|
30
|
+
taken += 1;
|
|
31
|
+
await task(next.value, index);
|
|
32
|
+
}
|
|
33
|
+
/* oxlint-enable eslint/no-await-in-loop */
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const worker = async () => {
|
|
37
|
+
const running = work();
|
|
38
|
+
|
|
39
|
+
try {
|
|
40
|
+
await running;
|
|
41
|
+
} catch {
|
|
42
|
+
stopped = true;
|
|
43
|
+
failures.push(running);
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
await Promise.all(Array.from({ length: Math.max(1, limit) }, worker));
|
|
48
|
+
await source.return(undefined);
|
|
49
|
+
|
|
50
|
+
// Rethrows the first failure, as it was thrown.
|
|
51
|
+
if (failures.length > 0) await failures[0];
|
|
52
|
+
}
|