@sekiban/dcb-cloudflare 0.0.0-stage → 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.
- package/LICENSE +90 -0
- package/README.md +48 -2
- package/dist/cli.js +320 -0
- package/dist/compose.d.ts +39 -0
- package/dist/compose.js +87 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +101 -0
- package/package.json +46 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
Elastic License 2.0
|
|
2
|
+
|
|
3
|
+
Acceptance
|
|
4
|
+
|
|
5
|
+
By using the software, you agree to all of the terms and conditions below.
|
|
6
|
+
|
|
7
|
+
Copyright License
|
|
8
|
+
|
|
9
|
+
The licensor grants you a non-exclusive, royalty-free, worldwide,
|
|
10
|
+
non-sublicensable, non-transferable license to use, copy, distribute, make
|
|
11
|
+
available, and prepare derivative works of the software, in each case subject
|
|
12
|
+
to the limitations and conditions below.
|
|
13
|
+
|
|
14
|
+
Limitations
|
|
15
|
+
|
|
16
|
+
You may not provide the software to third parties as a hosted or managed
|
|
17
|
+
service, where the service provides users with access to any substantial set
|
|
18
|
+
of the features or functionality of the software.
|
|
19
|
+
|
|
20
|
+
You may not move, change, disable, or circumvent the license key functionality
|
|
21
|
+
in the software, and you may not remove or obscure any functionality in the
|
|
22
|
+
software that is protected by the license key.
|
|
23
|
+
|
|
24
|
+
You may not alter, remove, or obscure any licensing, copyright, or other
|
|
25
|
+
notices of the licensor. Any use of the licensor's trademarks is subject to
|
|
26
|
+
applicable law.
|
|
27
|
+
|
|
28
|
+
Patents
|
|
29
|
+
|
|
30
|
+
The licensor grants you a non-exclusive, royalty-free, worldwide,
|
|
31
|
+
non-sublicensable, non-transferable license under any patent claims the
|
|
32
|
+
licensor can license, or becomes able to license, to make, have made, use,
|
|
33
|
+
sell, offer for sale, import and have imported the software. This license does
|
|
34
|
+
not cover any patent claims that you cause to be infringed by modifications or
|
|
35
|
+
additions to the software.
|
|
36
|
+
|
|
37
|
+
If you or your company make any written claim that the software infringes or
|
|
38
|
+
contributes to infringement of any patent, your patent license for the software
|
|
39
|
+
granted under these terms ends immediately. If your company makes such a
|
|
40
|
+
claim, your patent license ends immediately for work on behalf of your company.
|
|
41
|
+
|
|
42
|
+
Notices
|
|
43
|
+
|
|
44
|
+
You must ensure that anyone who gets a copy of any part of the software from
|
|
45
|
+
you also gets a copy of these terms.
|
|
46
|
+
|
|
47
|
+
If you modify the software, you must include in any modified copies of the
|
|
48
|
+
software prominent notices stating that you have modified the software.
|
|
49
|
+
|
|
50
|
+
No Other Rights
|
|
51
|
+
|
|
52
|
+
These terms do not imply any licenses other than those expressly granted in
|
|
53
|
+
this license.
|
|
54
|
+
|
|
55
|
+
Termination
|
|
56
|
+
|
|
57
|
+
If you use the software in violation of these terms, your license is not
|
|
58
|
+
licensed, and your licenses will automatically terminate. If the licensor
|
|
59
|
+
provides you with a notice of your violation, and you cease all violation of
|
|
60
|
+
the license no later than 30 days after your receipt of the notice, your
|
|
61
|
+
licenses will be reinstated retroactively. However, if you violate these terms
|
|
62
|
+
after such reinstatement, any additional violation of these terms will cause
|
|
63
|
+
your licenses to terminate automatically and permanently.
|
|
64
|
+
|
|
65
|
+
No Liability
|
|
66
|
+
|
|
67
|
+
As far as the law allows, the software comes as is, without any warranty or
|
|
68
|
+
condition, and the licensor will not be liable for any damages arising out of
|
|
69
|
+
these terms or the use or nature of the software, under any kind of legal
|
|
70
|
+
claim.
|
|
71
|
+
|
|
72
|
+
Definitions
|
|
73
|
+
|
|
74
|
+
The licensor is the entity offering these terms, including any portion of the
|
|
75
|
+
software.
|
|
76
|
+
|
|
77
|
+
you refers to the individual or entity agreeing to these terms.
|
|
78
|
+
|
|
79
|
+
your company is any legal entity, sole proprietorship, or other entity that
|
|
80
|
+
has control over, is under the control of, or is under common control with
|
|
81
|
+
that organization.
|
|
82
|
+
|
|
83
|
+
control means ownership of substantially all the assets of an entity, or the
|
|
84
|
+
power to direct its management and policies by vote, contract, or otherwise.
|
|
85
|
+
|
|
86
|
+
your licenses are all the licenses granted to you under these terms.
|
|
87
|
+
|
|
88
|
+
use means anything requiring one of your licenses.
|
|
89
|
+
|
|
90
|
+
trademark means trademarks, service marks, or trade names.
|
package/README.md
CHANGED
|
@@ -1,3 +1,49 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @sekiban/dcb-cloudflare
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Optional helper for callers who already have a Worker and want Sekiban storage beside it.
|
|
4
|
+
|
|
5
|
+
This package is not an application, not a matched-set member, and not a hosted service. The caller keeps their routes, authentication, wrangler config, and Worker name. Pass that config to `dcb-cloudflare migrate` and `dcb-cloudflare deploy`.
|
|
6
|
+
|
|
7
|
+
The default backend is Wrangler. `dcb-cloudflare migrate --config <path> --cli cf`
|
|
8
|
+
is an opt-in remote D1 migration path: it applies each config entry by its real
|
|
9
|
+
UUID `database_id`, honors `migrations_dir` and `migrations_table`, and runs cf
|
|
10
|
+
from the directory containing the config. It does not support `--local`,
|
|
11
|
+
`--env`, extra arguments, or deployment; `--cli cf` is refused for `deploy`.
|
|
12
|
+
The helper passes the caller's environment through, so cf uses its normal
|
|
13
|
+
credential order, including `CLOUDFLARE_API_TOKEN` before OAuth profiles.
|
|
14
|
+
The caller must have cf 1.0.0-beta.5 or a compatible beta installed separately
|
|
15
|
+
and Node 22 or newer. cf is intentionally not a dependency of this package.
|
|
16
|
+
|
|
17
|
+
`composeFetch` publishes runtime HTTP routes only when the caller supplies `authorize`. The default forward list is the five serialized paths. `queue` and `scheduled` from the runtime and the caller both run, runtime first.
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { composeHandlers, requireHandlers } from "@sekiban/dcb-cloudflare";
|
|
21
|
+
import { createCloudflareOnlyRuntimeWorker, type CloudflareOnlyEnv } from "@sekiban/dcb-runtime/cloudflare";
|
|
22
|
+
|
|
23
|
+
interface Env extends CloudflareOnlyEnv {
|
|
24
|
+
readonly SDT_SERVICE_ID: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const runtime = requireHandlers(createCloudflareOnlyRuntimeWorker({ /* domain, config */ }));
|
|
28
|
+
|
|
29
|
+
const worker: ExportedHandler<Env> = composeHandlers<Env>({
|
|
30
|
+
application: { fetch: (request, env, ctx) => new Response("app") },
|
|
31
|
+
sekiban: {
|
|
32
|
+
prefix: "/internal/sekiban",
|
|
33
|
+
fetch: runtime.fetch,
|
|
34
|
+
authorize: (request) => request.headers.get("authorization") === "Bearer <token>",
|
|
35
|
+
queue: runtime.queue,
|
|
36
|
+
scheduled: runtime.scheduled,
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
export default worker;
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
The declarations reference Workers types, so TypeScript consumers install `@cloudflare/workers-types`, include `"@cloudflare/workers-types"` in `compilerOptions.types`, and pass the environment type explicitly at the Worker boundary. The generated starter already does both. `requireHandlers()` bridges `createCloudflareOnlyRuntimeWorker()`'s result, whose handler members are optional in the Workers types.
|
|
44
|
+
|
|
45
|
+
If `npm view @sekiban/dcb-cloudflare` reports E404, the package has not been published yet; use the repository-checkout alternative. The helper requires `@sekiban/dcb-runtime` 0.2.x, and the generated starter pins 0.2.0.
|
|
46
|
+
|
|
47
|
+
## License
|
|
48
|
+
|
|
49
|
+
Elastic License 2.0. See [LICENSE](./LICENSE).
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { accessSync, constants, existsSync, readFileSync } from "node:fs";
|
|
5
|
+
import { spawn } from "node:child_process";
|
|
6
|
+
import { dirname, isAbsolute, join, normalize, resolve } from "node:path";
|
|
7
|
+
import { pathToFileURL } from "node:url";
|
|
8
|
+
var CF_HELPER_MARKER = "d1-migrations";
|
|
9
|
+
var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
10
|
+
var CF_INSTALL_HINT = "cf executable not found; install cf with `npm i -g cf` or `npm i -D cf` (cf needs node >=22)";
|
|
11
|
+
function parseWranglerConfig(text) {
|
|
12
|
+
const stripped = text.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, "");
|
|
13
|
+
const parsed = JSON.parse(stripped);
|
|
14
|
+
if (!Array.isArray(parsed.d1_databases) || parsed.d1_databases.length === 0) {
|
|
15
|
+
throw new Error("no-d1");
|
|
16
|
+
}
|
|
17
|
+
if (parsed.account_id !== void 0 && typeof parsed.account_id !== "string") {
|
|
18
|
+
throw new Error("invalid-account-id");
|
|
19
|
+
}
|
|
20
|
+
const d1 = [];
|
|
21
|
+
for (const entry of parsed.d1_databases) {
|
|
22
|
+
if (typeof entry !== "object" || entry === null) throw new Error("no-d1");
|
|
23
|
+
const record = entry;
|
|
24
|
+
if (typeof record.binding !== "string" || record.binding.length === 0) throw new Error("no-d1");
|
|
25
|
+
if (typeof record.database_name !== "string" || record.database_name.length === 0) throw new Error("no-d1");
|
|
26
|
+
if (record.database_id !== void 0 && typeof record.database_id !== "string") throw new Error("invalid-database-id");
|
|
27
|
+
if (record.migrations_dir !== void 0 && typeof record.migrations_dir !== "string") throw new Error("invalid-migrations-dir");
|
|
28
|
+
if (record.migrations_table !== void 0 && typeof record.migrations_table !== "string") throw new Error("invalid-migrations-table");
|
|
29
|
+
d1.push({
|
|
30
|
+
binding: record.binding,
|
|
31
|
+
databaseName: record.database_name,
|
|
32
|
+
...record.database_id === void 0 ? {} : { databaseId: record.database_id },
|
|
33
|
+
...record.migrations_dir === void 0 ? {} : { migrationsDir: record.migrations_dir },
|
|
34
|
+
...record.migrations_table === void 0 ? {} : { migrationsTable: record.migrations_table }
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
return {
|
|
38
|
+
d1,
|
|
39
|
+
...parsed.account_id === void 0 ? {} : { accountId: parsed.account_id }
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function option(argv, name) {
|
|
43
|
+
const index = argv.indexOf(name);
|
|
44
|
+
if (index < 0) return void 0;
|
|
45
|
+
const value = argv[index + 1];
|
|
46
|
+
if (value === void 0 || value.startsWith("--")) throw new Error(`missing value for ${name}`);
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
function parseArguments(argv) {
|
|
50
|
+
const split = argv.indexOf("--");
|
|
51
|
+
const before = split < 0 ? [...argv] : [...argv.slice(0, split)];
|
|
52
|
+
const extra = split < 0 ? [] : [...argv.slice(split + 1)];
|
|
53
|
+
let backend = "wrangler";
|
|
54
|
+
let cliSeen = false;
|
|
55
|
+
const flags = [];
|
|
56
|
+
for (let index = 0; index < before.length; index += 1) {
|
|
57
|
+
const argument = before[index];
|
|
58
|
+
if (argument !== "--cli") {
|
|
59
|
+
flags.push(argument);
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (cliSeen) throw new Error("repeated --cli is not allowed");
|
|
63
|
+
cliSeen = true;
|
|
64
|
+
const value = before[index + 1];
|
|
65
|
+
if (value === void 0 || value.startsWith("--")) throw new Error("--cli requires a value: use --cli wrangler or --cli cf");
|
|
66
|
+
if (value !== "wrangler" && value !== "cf") throw new Error(`unsupported --cli value ${value}; use wrangler or cf`);
|
|
67
|
+
backend = value;
|
|
68
|
+
index += 1;
|
|
69
|
+
}
|
|
70
|
+
return { backend, command: flags[0], flags, extra };
|
|
71
|
+
}
|
|
72
|
+
function validateCfArguments(parsed, configPath) {
|
|
73
|
+
if (parsed.command !== "migrate") throw new Error("--cli cf is supported only for migrate; deploy remains a Wrangler operation");
|
|
74
|
+
if (configPath === void 0) throw new Error("--cli cf requires --config <path>");
|
|
75
|
+
if (parsed.extra.length > 0) throw new Error("--cli cf refuses arguments after --");
|
|
76
|
+
const seen = /* @__PURE__ */ new Set();
|
|
77
|
+
for (let index = 1; index < parsed.flags.length; index += 1) {
|
|
78
|
+
const argument = parsed.flags[index];
|
|
79
|
+
if (!argument.startsWith("--")) throw new Error(`--cli cf refuses unexpected argument ${argument}`);
|
|
80
|
+
if (seen.has(argument)) throw new Error(`--cli cf refuses repeated flag ${argument}`);
|
|
81
|
+
seen.add(argument);
|
|
82
|
+
if (argument !== "--config") {
|
|
83
|
+
if (argument === "--keep-vars") throw new Error("--cli cf refuses --keep-vars");
|
|
84
|
+
if (argument === "--local") throw new Error("--cli cf refuses --local; cf local state is not Wrangler's .wrangler/state");
|
|
85
|
+
if (argument === "--env") throw new Error("--cli cf refuses --env because env blocks can swap databases");
|
|
86
|
+
throw new Error(`--cli cf refuses ${argument}; only --config and --cli are supported`);
|
|
87
|
+
}
|
|
88
|
+
const value = parsed.flags[index + 1];
|
|
89
|
+
if (value === void 0 || value.startsWith("--")) throw new Error("--config requires a value");
|
|
90
|
+
index += 1;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function migrationDirectory(database) {
|
|
94
|
+
if (database.migrationsDir !== void 0 && isAbsolute(database.migrationsDir)) return database.migrationsDir;
|
|
95
|
+
return normalize(database.migrationsDir ?? "migrations");
|
|
96
|
+
}
|
|
97
|
+
function cfDatabaseId(database) {
|
|
98
|
+
if (database.databaseId === void 0 || !UUID_PATTERN.test(database.databaseId)) {
|
|
99
|
+
const detail = database.databaseId === void 0 ? "is missing" : `is not a UUID (${database.databaseId})`;
|
|
100
|
+
throw new Error(`--cli cf requires a real UUID database_id for ${database.binding}; database_id ${detail}; paste the real Cloudflare database ID`);
|
|
101
|
+
}
|
|
102
|
+
return database.databaseId;
|
|
103
|
+
}
|
|
104
|
+
function childEnvironment(base, backend, accountId) {
|
|
105
|
+
const env = { ...base, CI: "true" };
|
|
106
|
+
if (backend === "cf") {
|
|
107
|
+
if (accountId !== void 0 && base.CLOUDFLARE_ACCOUNT_ID !== void 0 && base.CLOUDFLARE_ACCOUNT_ID !== accountId) {
|
|
108
|
+
throw new Error("--cli cf refuses a different pre-set CLOUDFLARE_ACCOUNT_ID than the config account_id");
|
|
109
|
+
}
|
|
110
|
+
if (accountId !== void 0) env.CLOUDFLARE_ACCOUNT_ID = accountId;
|
|
111
|
+
env.SEKIBAN_DCB_CF_HELPER = CF_HELPER_MARKER;
|
|
112
|
+
} else {
|
|
113
|
+
delete env.SEKIBAN_DCB_CF_HELPER;
|
|
114
|
+
}
|
|
115
|
+
return env;
|
|
116
|
+
}
|
|
117
|
+
function wranglerPlans(config, command, flags, extra) {
|
|
118
|
+
const configPath = option(flags, "--config");
|
|
119
|
+
if (configPath === void 0) throw new Error("missing-config");
|
|
120
|
+
const envName = option(flags, "--env");
|
|
121
|
+
const local = flags.includes("--local");
|
|
122
|
+
const keepVars = flags.includes("--keep-vars");
|
|
123
|
+
if (command === "deploy" && local) throw new Error("deploy-local");
|
|
124
|
+
const remoteFlag = command === "migrate" && local ? "--local" : "--remote";
|
|
125
|
+
const envArgs = envName === void 0 ? [] : ["--env", envName];
|
|
126
|
+
const migrations = config.d1.map((database) => [
|
|
127
|
+
"wrangler",
|
|
128
|
+
"d1",
|
|
129
|
+
"migrations",
|
|
130
|
+
"apply",
|
|
131
|
+
database.databaseName,
|
|
132
|
+
"--config",
|
|
133
|
+
configPath,
|
|
134
|
+
remoteFlag,
|
|
135
|
+
...envArgs
|
|
136
|
+
]);
|
|
137
|
+
if (command === "migrate") return migrations;
|
|
138
|
+
return [
|
|
139
|
+
...migrations,
|
|
140
|
+
["wrangler", "deploy", "--config", configPath, ...envArgs, ...keepVars ? ["--keep-vars"] : [], ...extra]
|
|
141
|
+
];
|
|
142
|
+
}
|
|
143
|
+
function cfPlans(config) {
|
|
144
|
+
return config.d1.map((database) => [
|
|
145
|
+
"cf",
|
|
146
|
+
"d1",
|
|
147
|
+
"migrations",
|
|
148
|
+
"apply",
|
|
149
|
+
cfDatabaseId(database),
|
|
150
|
+
"--dir",
|
|
151
|
+
migrationDirectory(database),
|
|
152
|
+
...database.migrationsTable === void 0 ? [] : ["--table", database.migrationsTable]
|
|
153
|
+
]);
|
|
154
|
+
}
|
|
155
|
+
function planCloudflareOperations(argv, configText, options = {}) {
|
|
156
|
+
const parsed = parseArguments(argv);
|
|
157
|
+
const command = parsed.command;
|
|
158
|
+
if (command !== "migrate" && command !== "deploy") throw new Error("usage");
|
|
159
|
+
const configPath = option(parsed.flags, "--config");
|
|
160
|
+
if (parsed.backend === "cf") validateCfArguments(parsed, configPath);
|
|
161
|
+
if (configPath === void 0) throw new Error("missing-config");
|
|
162
|
+
const config = parseWranglerConfig(configText);
|
|
163
|
+
const cwd = options.cwd ?? process.cwd();
|
|
164
|
+
const env = options.env ?? process.env;
|
|
165
|
+
if (parsed.backend === "cf") {
|
|
166
|
+
const configDir = dirname(resolve(cwd, configPath));
|
|
167
|
+
const childEnv2 = childEnvironment(env, "cf", config.accountId);
|
|
168
|
+
const commands2 = cfPlans(config);
|
|
169
|
+
return commands2.map((plannedCommand) => ({
|
|
170
|
+
backend: "cf",
|
|
171
|
+
plannedCommand,
|
|
172
|
+
command: plannedCommand,
|
|
173
|
+
cwd: configDir,
|
|
174
|
+
env: childEnv2
|
|
175
|
+
}));
|
|
176
|
+
}
|
|
177
|
+
const commands = wranglerPlans(config, command, parsed.flags, parsed.extra);
|
|
178
|
+
const childEnv = childEnvironment(env, "wrangler");
|
|
179
|
+
return commands.map((plannedCommand) => ({
|
|
180
|
+
backend: "wrangler",
|
|
181
|
+
plannedCommand,
|
|
182
|
+
command: plannedCommand,
|
|
183
|
+
cwd,
|
|
184
|
+
env: childEnv
|
|
185
|
+
}));
|
|
186
|
+
}
|
|
187
|
+
function planCloudflareCommands(argv, configText, options = {}) {
|
|
188
|
+
return planCloudflareOperations(argv, configText, options).map((plan) => [...plan.plannedCommand]);
|
|
189
|
+
}
|
|
190
|
+
function executableFile(path) {
|
|
191
|
+
try {
|
|
192
|
+
accessSync(path, constants.X_OK);
|
|
193
|
+
return true;
|
|
194
|
+
} catch {
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
function pathExecutable(name, env) {
|
|
199
|
+
const pathValue = env.PATH ?? "";
|
|
200
|
+
for (const directory of pathValue.split(":").filter((value) => value.length > 0)) {
|
|
201
|
+
const candidate = join(directory, name);
|
|
202
|
+
if (executableFile(candidate)) return candidate;
|
|
203
|
+
}
|
|
204
|
+
return void 0;
|
|
205
|
+
}
|
|
206
|
+
function resolveCfExecutable(configDir, env) {
|
|
207
|
+
if (env.CF_BIN !== void 0 && env.CF_BIN.length > 0) return env.CF_BIN;
|
|
208
|
+
const local = join(configDir, "node_modules", ".bin", "cf");
|
|
209
|
+
if (existsSync(local)) return local;
|
|
210
|
+
const fromPath = pathExecutable("cf", env);
|
|
211
|
+
if (fromPath !== void 0) return fromPath;
|
|
212
|
+
throw new Error(CF_INSTALL_HINT);
|
|
213
|
+
}
|
|
214
|
+
function oneLine(error) {
|
|
215
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
216
|
+
return message.replace(/[\r\n]+/g, " ").replace(/\s+/g, " ").trim();
|
|
217
|
+
}
|
|
218
|
+
async function executeCloudflareCli(argv, deps) {
|
|
219
|
+
let configPath;
|
|
220
|
+
try {
|
|
221
|
+
configPath = option(parseArguments(argv).flags, "--config");
|
|
222
|
+
} catch (error) {
|
|
223
|
+
const message = oneLine(error);
|
|
224
|
+
(deps.stderr ?? ((value) => process.stderr.write(`${value}
|
|
225
|
+
`)))(message);
|
|
226
|
+
return { exitCode: 1, commands: [] };
|
|
227
|
+
}
|
|
228
|
+
if (configPath === void 0) {
|
|
229
|
+
const message = "missing-config";
|
|
230
|
+
(deps.stderr ?? ((value) => process.stderr.write(`${value}
|
|
231
|
+
`)))(message);
|
|
232
|
+
return { exitCode: 1, commands: [] };
|
|
233
|
+
}
|
|
234
|
+
let configText;
|
|
235
|
+
try {
|
|
236
|
+
configText = deps.readText(configPath);
|
|
237
|
+
} catch {
|
|
238
|
+
const message = `unable to read config ${configPath}`;
|
|
239
|
+
(deps.stderr ?? ((value) => process.stderr.write(`${value}
|
|
240
|
+
`)))(message);
|
|
241
|
+
return { exitCode: 1, commands: [] };
|
|
242
|
+
}
|
|
243
|
+
let plans;
|
|
244
|
+
try {
|
|
245
|
+
plans = planCloudflareOperations(argv, configText, { cwd: deps.cwd, env: deps.env });
|
|
246
|
+
} catch (error) {
|
|
247
|
+
const message = oneLine(error);
|
|
248
|
+
(deps.stderr ?? ((value) => process.stderr.write(`${value}
|
|
249
|
+
`)))(message);
|
|
250
|
+
return { exitCode: 1, commands: [] };
|
|
251
|
+
}
|
|
252
|
+
const commands = plans.map((plan) => [...plan.plannedCommand]);
|
|
253
|
+
for (const plan of plans) {
|
|
254
|
+
let request;
|
|
255
|
+
try {
|
|
256
|
+
request = plan.backend === "cf" ? { command: [resolveCfExecutable(plan.cwd, plan.env), ...plan.command.slice(1)], cwd: plan.cwd, env: plan.env } : { command: plan.command, cwd: plan.cwd, env: plan.env };
|
|
257
|
+
} catch (error) {
|
|
258
|
+
const message = oneLine(error);
|
|
259
|
+
(deps.stderr ?? ((value) => process.stderr.write(`${value}
|
|
260
|
+
`)))(message);
|
|
261
|
+
return { exitCode: 1, commands };
|
|
262
|
+
}
|
|
263
|
+
let status;
|
|
264
|
+
try {
|
|
265
|
+
status = await deps.spawn(request, plan.backend);
|
|
266
|
+
} catch (error) {
|
|
267
|
+
const message = oneLine(error);
|
|
268
|
+
(deps.stderr ?? ((value) => process.stderr.write(`${value}
|
|
269
|
+
`)))(message);
|
|
270
|
+
return { exitCode: 1, commands };
|
|
271
|
+
}
|
|
272
|
+
if (status !== 0) return { exitCode: status, commands };
|
|
273
|
+
}
|
|
274
|
+
return { exitCode: 0, commands };
|
|
275
|
+
}
|
|
276
|
+
function spawnWrangler(request) {
|
|
277
|
+
const bin = request.env.WRANGLER_BIN;
|
|
278
|
+
const executable = bin !== void 0 && bin.length > 0 ? bin : "npx";
|
|
279
|
+
const args = bin !== void 0 && bin.length > 0 ? request.command.slice(1) : ["--no-install", ...request.command];
|
|
280
|
+
return new Promise((resolveExit) => {
|
|
281
|
+
const child = spawn(executable, args, {
|
|
282
|
+
cwd: request.cwd,
|
|
283
|
+
stdio: "inherit",
|
|
284
|
+
env: request.env
|
|
285
|
+
});
|
|
286
|
+
child.on("close", (code) => resolveExit(code ?? 1));
|
|
287
|
+
child.on("error", () => resolveExit(1));
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
function spawnCf(request) {
|
|
291
|
+
return new Promise((resolveExit) => {
|
|
292
|
+
const child = spawn(request.command[0], request.command.slice(1), {
|
|
293
|
+
cwd: request.cwd,
|
|
294
|
+
stdio: "inherit",
|
|
295
|
+
env: request.env
|
|
296
|
+
});
|
|
297
|
+
child.on("close", (code) => resolveExit(code ?? 1));
|
|
298
|
+
child.on("error", () => {
|
|
299
|
+
process.stderr.write(`${CF_INSTALL_HINT}
|
|
300
|
+
`);
|
|
301
|
+
resolveExit(1);
|
|
302
|
+
});
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
var invokedDirectly = process.argv[1] !== void 0 && import.meta.url === pathToFileURL(process.argv[1]).href;
|
|
306
|
+
if (invokedDirectly) {
|
|
307
|
+
const runner = async (request, backend) => backend === "wrangler" ? spawnWrangler(request) : spawnCf(request);
|
|
308
|
+
const result = await executeCloudflareCli(process.argv.slice(2), {
|
|
309
|
+
readText: (path) => readFileSync(path, "utf8"),
|
|
310
|
+
spawn: runner
|
|
311
|
+
});
|
|
312
|
+
process.exit(result.exitCode);
|
|
313
|
+
}
|
|
314
|
+
export {
|
|
315
|
+
executeCloudflareCli,
|
|
316
|
+
parseWranglerConfig,
|
|
317
|
+
planCloudflareCommands,
|
|
318
|
+
planCloudflareOperations,
|
|
319
|
+
resolveCfExecutable
|
|
320
|
+
};
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export declare const SERIALIZED_PATHS: readonly ["/api/sekiban/serialized/commit", "/api/sekiban/serialized/query", "/api/sekiban/serialized/list-query", "/api/sekiban/serialized/tag-latest-sortable", "/api/sekiban/serialized/tag-state"];
|
|
2
|
+
export type IncomingRequest<CfHostMetadata = unknown> = Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>;
|
|
3
|
+
export type FetchHandler<Env = unknown, Ctx = ExecutionContext, RequestType extends Request = IncomingRequest> = (request: RequestType, env: Env, ctx: Ctx) => Promise<Response> | Response;
|
|
4
|
+
export type QueueHandler<Env = unknown, Ctx = ExecutionContext, Batch = MessageBatch<unknown>> = (batch: Batch, env: Env, ctx: Ctx) => Promise<void> | void;
|
|
5
|
+
export type ScheduledHandler<Env = unknown, Ctx = ExecutionContext, Controller = ScheduledController> = (controller: Controller, env: Env, ctx: Ctx) => Promise<void> | void;
|
|
6
|
+
export type AuthorizeResult = boolean | Response;
|
|
7
|
+
export type Authorize<RequestType extends Request = IncomingRequest> = (request: RequestType) => AuthorizeResult | Promise<AuthorizeResult>;
|
|
8
|
+
export interface SekibanMount<Env = unknown, Ctx = ExecutionContext, RequestType extends Request = IncomingRequest, Batch = MessageBatch<unknown>, Controller = ScheduledController> {
|
|
9
|
+
prefix: string;
|
|
10
|
+
fetch: FetchHandler<Env, Ctx, Request>;
|
|
11
|
+
authorize: Authorize<RequestType>;
|
|
12
|
+
extraPaths?: readonly string[];
|
|
13
|
+
queue?: QueueHandler<Env, Ctx, Batch>;
|
|
14
|
+
scheduled?: ScheduledHandler<Env, Ctx, Controller>;
|
|
15
|
+
}
|
|
16
|
+
export interface ApplicationHandlers<Env = unknown, Ctx = ExecutionContext, RequestType extends Request = IncomingRequest, Batch = MessageBatch<unknown>, Controller = ScheduledController> {
|
|
17
|
+
fetch: FetchHandler<Env, Ctx, RequestType>;
|
|
18
|
+
queue?: QueueHandler<Env, Ctx, Batch>;
|
|
19
|
+
scheduled?: ScheduledHandler<Env, Ctx, Controller>;
|
|
20
|
+
}
|
|
21
|
+
export interface RequiredHandlers<Env, Ctx = ExecutionContext, Batch = MessageBatch<unknown>, Controller = ScheduledController> {
|
|
22
|
+
fetch: (request: Request, env: Env, ctx: Ctx) => Promise<Response>;
|
|
23
|
+
queue: QueueHandler<Env, Ctx, Batch>;
|
|
24
|
+
scheduled: ScheduledHandler<Env, Ctx, Controller>;
|
|
25
|
+
}
|
|
26
|
+
/** Bridge the optional handler members returned by createCloudflareOnlyRuntimeWorker(). */
|
|
27
|
+
export declare function requireHandlers<Env, Ctx, CfHostMetadata, Batch, Controller>(handlers: {
|
|
28
|
+
fetch?: FetchHandler<Env, Ctx, IncomingRequest<CfHostMetadata>>;
|
|
29
|
+
queue?: QueueHandler<Env, Ctx, Batch>;
|
|
30
|
+
scheduled?: ScheduledHandler<Env, Ctx, Controller>;
|
|
31
|
+
}): RequiredHandlers<Env, Ctx, Batch, Controller>;
|
|
32
|
+
export declare function composeFetch<Env = unknown, Ctx = ExecutionContext, RequestType extends Request = IncomingRequest>(input: {
|
|
33
|
+
application: FetchHandler<Env, Ctx, RequestType>;
|
|
34
|
+
sekiban?: SekibanMount<Env, Ctx, RequestType, never, never>;
|
|
35
|
+
}): FetchHandler<Env, Ctx, RequestType>;
|
|
36
|
+
export declare function composeHandlers<Env = unknown, Ctx = ExecutionContext, RequestType extends Request = IncomingRequest, Batch = MessageBatch<unknown>, Controller = ScheduledController>(input: {
|
|
37
|
+
application: ApplicationHandlers<Env, Ctx, RequestType, Batch, Controller>;
|
|
38
|
+
sekiban?: SekibanMount<Env, Ctx, RequestType, Batch, Controller>;
|
|
39
|
+
}): ApplicationHandlers<Env, Ctx, RequestType, Batch, Controller>;
|
package/dist/compose.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// src/compose.ts
|
|
2
|
+
var SERIALIZED_PATHS = [
|
|
3
|
+
"/api/sekiban/serialized/commit",
|
|
4
|
+
"/api/sekiban/serialized/query",
|
|
5
|
+
"/api/sekiban/serialized/list-query",
|
|
6
|
+
"/api/sekiban/serialized/tag-latest-sortable",
|
|
7
|
+
"/api/sekiban/serialized/tag-state"
|
|
8
|
+
];
|
|
9
|
+
function requireHandlers(handlers) {
|
|
10
|
+
const { fetch, queue, scheduled } = handlers;
|
|
11
|
+
if (fetch === void 0) throw new Error("fetch handler is required");
|
|
12
|
+
if (queue === void 0) throw new Error("queue handler is required");
|
|
13
|
+
if (scheduled === void 0) throw new Error("scheduled handler is required");
|
|
14
|
+
return {
|
|
15
|
+
fetch: async (request, env, ctx) => fetch(request, env, ctx),
|
|
16
|
+
queue,
|
|
17
|
+
scheduled
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
function assertPrefix(prefix) {
|
|
21
|
+
if (prefix === "" || prefix === "/") {
|
|
22
|
+
throw new Error("prefix must not be empty or /");
|
|
23
|
+
}
|
|
24
|
+
if (!prefix.startsWith("/") || prefix.endsWith("/")) {
|
|
25
|
+
throw new Error("prefix must be an absolute path without a trailing slash");
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function segmentPrefix(pathname, prefix) {
|
|
29
|
+
return pathname === prefix || pathname.startsWith(`${prefix}/`);
|
|
30
|
+
}
|
|
31
|
+
function stripPrefix(pathname, prefix) {
|
|
32
|
+
if (pathname === prefix) return "/";
|
|
33
|
+
return pathname.slice(prefix.length);
|
|
34
|
+
}
|
|
35
|
+
function rewriteRequest(request, pathname) {
|
|
36
|
+
const url = new URL(request.url);
|
|
37
|
+
url.pathname = pathname;
|
|
38
|
+
return new Request(url, request);
|
|
39
|
+
}
|
|
40
|
+
function allowlist(mount) {
|
|
41
|
+
return /* @__PURE__ */ new Set([...SERIALIZED_PATHS, ...mount.extraPaths ?? []]);
|
|
42
|
+
}
|
|
43
|
+
function composeFetch(input) {
|
|
44
|
+
const mount = input.sekiban;
|
|
45
|
+
if (mount !== void 0) {
|
|
46
|
+
if (typeof mount.authorize !== "function") {
|
|
47
|
+
throw new Error("authorize is required to mount runtime routes");
|
|
48
|
+
}
|
|
49
|
+
assertPrefix(mount.prefix);
|
|
50
|
+
}
|
|
51
|
+
const allowed = mount === void 0 ? /* @__PURE__ */ new Set() : allowlist(mount);
|
|
52
|
+
return async (request, env, ctx) => {
|
|
53
|
+
if (mount === void 0) return input.application(request, env, ctx);
|
|
54
|
+
const url = new URL(request.url);
|
|
55
|
+
if (!segmentPrefix(url.pathname, mount.prefix)) return input.application(request, env, ctx);
|
|
56
|
+
const stripped = stripPrefix(url.pathname, mount.prefix);
|
|
57
|
+
if (!allowed.has(stripped)) return new Response("runtime route is not forwarded", { status: 404 });
|
|
58
|
+
const decision = await mount.authorize(request);
|
|
59
|
+
if (decision instanceof Response) return decision;
|
|
60
|
+
if (decision !== true) return new Response("runtime route denied", { status: 403 });
|
|
61
|
+
return mount.fetch(rewriteRequest(request, stripped), env, ctx);
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
function chain(first, second) {
|
|
65
|
+
if (first === void 0 && second === void 0) return void 0;
|
|
66
|
+
const wrapped = async (...args) => {
|
|
67
|
+
if (first !== void 0) await first(...args);
|
|
68
|
+
if (second !== void 0) await second(...args);
|
|
69
|
+
};
|
|
70
|
+
return wrapped;
|
|
71
|
+
}
|
|
72
|
+
function composeHandlers(input) {
|
|
73
|
+
const fetch = composeFetch({ application: input.application.fetch, sekiban: input.sekiban });
|
|
74
|
+
const queue = chain(input.sekiban?.queue, input.application.queue);
|
|
75
|
+
const scheduled = chain(input.sekiban?.scheduled, input.application.scheduled);
|
|
76
|
+
return {
|
|
77
|
+
fetch,
|
|
78
|
+
...queue === void 0 ? {} : { queue },
|
|
79
|
+
...scheduled === void 0 ? {} : { scheduled }
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
export {
|
|
83
|
+
SERIALIZED_PATHS,
|
|
84
|
+
composeFetch,
|
|
85
|
+
composeHandlers,
|
|
86
|
+
requireHandlers
|
|
87
|
+
};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { AllocatorDurableObject, BootstrapCoordinatorDurableObject, JournalDurableObject, TagDurableObject, TagStateDurableObject, } from "@sekiban/dcb-runtime/cloudflare";
|
|
2
|
+
export { SERIALIZED_PATHS, composeFetch, composeHandlers, requireHandlers, } from "./compose.js";
|
|
3
|
+
export type { ApplicationHandlers, Authorize, AuthorizeResult, FetchHandler, IncomingRequest, QueueHandler, RequiredHandlers, ScheduledHandler, SekibanMount, } from "./compose.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import {
|
|
3
|
+
AllocatorDurableObject,
|
|
4
|
+
BootstrapCoordinatorDurableObject,
|
|
5
|
+
JournalDurableObject,
|
|
6
|
+
TagDurableObject,
|
|
7
|
+
TagStateDurableObject
|
|
8
|
+
} from "@sekiban/dcb-runtime/cloudflare";
|
|
9
|
+
|
|
10
|
+
// src/compose.ts
|
|
11
|
+
var SERIALIZED_PATHS = [
|
|
12
|
+
"/api/sekiban/serialized/commit",
|
|
13
|
+
"/api/sekiban/serialized/query",
|
|
14
|
+
"/api/sekiban/serialized/list-query",
|
|
15
|
+
"/api/sekiban/serialized/tag-latest-sortable",
|
|
16
|
+
"/api/sekiban/serialized/tag-state"
|
|
17
|
+
];
|
|
18
|
+
function requireHandlers(handlers) {
|
|
19
|
+
const { fetch, queue, scheduled } = handlers;
|
|
20
|
+
if (fetch === void 0) throw new Error("fetch handler is required");
|
|
21
|
+
if (queue === void 0) throw new Error("queue handler is required");
|
|
22
|
+
if (scheduled === void 0) throw new Error("scheduled handler is required");
|
|
23
|
+
return {
|
|
24
|
+
fetch: async (request, env, ctx) => fetch(request, env, ctx),
|
|
25
|
+
queue,
|
|
26
|
+
scheduled
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
function assertPrefix(prefix) {
|
|
30
|
+
if (prefix === "" || prefix === "/") {
|
|
31
|
+
throw new Error("prefix must not be empty or /");
|
|
32
|
+
}
|
|
33
|
+
if (!prefix.startsWith("/") || prefix.endsWith("/")) {
|
|
34
|
+
throw new Error("prefix must be an absolute path without a trailing slash");
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function segmentPrefix(pathname, prefix) {
|
|
38
|
+
return pathname === prefix || pathname.startsWith(`${prefix}/`);
|
|
39
|
+
}
|
|
40
|
+
function stripPrefix(pathname, prefix) {
|
|
41
|
+
if (pathname === prefix) return "/";
|
|
42
|
+
return pathname.slice(prefix.length);
|
|
43
|
+
}
|
|
44
|
+
function rewriteRequest(request, pathname) {
|
|
45
|
+
const url = new URL(request.url);
|
|
46
|
+
url.pathname = pathname;
|
|
47
|
+
return new Request(url, request);
|
|
48
|
+
}
|
|
49
|
+
function allowlist(mount) {
|
|
50
|
+
return /* @__PURE__ */ new Set([...SERIALIZED_PATHS, ...mount.extraPaths ?? []]);
|
|
51
|
+
}
|
|
52
|
+
function composeFetch(input) {
|
|
53
|
+
const mount = input.sekiban;
|
|
54
|
+
if (mount !== void 0) {
|
|
55
|
+
if (typeof mount.authorize !== "function") {
|
|
56
|
+
throw new Error("authorize is required to mount runtime routes");
|
|
57
|
+
}
|
|
58
|
+
assertPrefix(mount.prefix);
|
|
59
|
+
}
|
|
60
|
+
const allowed = mount === void 0 ? /* @__PURE__ */ new Set() : allowlist(mount);
|
|
61
|
+
return async (request, env, ctx) => {
|
|
62
|
+
if (mount === void 0) return input.application(request, env, ctx);
|
|
63
|
+
const url = new URL(request.url);
|
|
64
|
+
if (!segmentPrefix(url.pathname, mount.prefix)) return input.application(request, env, ctx);
|
|
65
|
+
const stripped = stripPrefix(url.pathname, mount.prefix);
|
|
66
|
+
if (!allowed.has(stripped)) return new Response("runtime route is not forwarded", { status: 404 });
|
|
67
|
+
const decision = await mount.authorize(request);
|
|
68
|
+
if (decision instanceof Response) return decision;
|
|
69
|
+
if (decision !== true) return new Response("runtime route denied", { status: 403 });
|
|
70
|
+
return mount.fetch(rewriteRequest(request, stripped), env, ctx);
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
function chain(first, second) {
|
|
74
|
+
if (first === void 0 && second === void 0) return void 0;
|
|
75
|
+
const wrapped = async (...args) => {
|
|
76
|
+
if (first !== void 0) await first(...args);
|
|
77
|
+
if (second !== void 0) await second(...args);
|
|
78
|
+
};
|
|
79
|
+
return wrapped;
|
|
80
|
+
}
|
|
81
|
+
function composeHandlers(input) {
|
|
82
|
+
const fetch = composeFetch({ application: input.application.fetch, sekiban: input.sekiban });
|
|
83
|
+
const queue = chain(input.sekiban?.queue, input.application.queue);
|
|
84
|
+
const scheduled = chain(input.sekiban?.scheduled, input.application.scheduled);
|
|
85
|
+
return {
|
|
86
|
+
fetch,
|
|
87
|
+
...queue === void 0 ? {} : { queue },
|
|
88
|
+
...scheduled === void 0 ? {} : { scheduled }
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
export {
|
|
92
|
+
AllocatorDurableObject,
|
|
93
|
+
BootstrapCoordinatorDurableObject,
|
|
94
|
+
JournalDurableObject,
|
|
95
|
+
SERIALIZED_PATHS,
|
|
96
|
+
TagDurableObject,
|
|
97
|
+
TagStateDurableObject,
|
|
98
|
+
composeFetch,
|
|
99
|
+
composeHandlers,
|
|
100
|
+
requireHandlers
|
|
101
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sekiban/dcb-cloudflare",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": false,
|
|
5
|
+
"description": "Optional Cloudflare composition helper. Mounts Sekiban storage beside the caller's own Worker. Not an application and not part of the matched set.",
|
|
6
|
+
"license": "Elastic-2.0",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/J-Tech-Japan/sekiban-dcb-ts.git",
|
|
10
|
+
"directory": "packages/dcb-cloudflare"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/J-Tech-Japan/sekiban-dcb-ts/tree/main/packages/dcb-cloudflare#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/J-Tech-Japan/sekiban-dcb-ts/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": ["sekiban", "dcb", "cloudflare", "compose"],
|
|
17
|
+
"engines": {
|
|
18
|
+
"node": ">=20"
|
|
19
|
+
},
|
|
20
|
+
"type": "module",
|
|
21
|
+
"sideEffects": false,
|
|
22
|
+
"bin": {
|
|
23
|
+
"dcb-cloudflare": "./dist/cli.js"
|
|
24
|
+
},
|
|
25
|
+
"exports": {
|
|
26
|
+
".": {
|
|
27
|
+
"types": "./dist/index.d.ts",
|
|
28
|
+
"import": "./dist/index.js"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"files": ["dist", "README.md", "LICENSE"],
|
|
33
|
+
"publishConfig": {
|
|
34
|
+
"access": "public",
|
|
35
|
+
"provenance": true
|
|
36
|
+
},
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"@sekiban/dcb-runtime": "0.2.0"
|
|
39
|
+
},
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"@cloudflare/workers-types": "^5.20260820.1"
|
|
42
|
+
},
|
|
43
|
+
"scripts": {
|
|
44
|
+
"build": "tsc -p tsconfig.build.json && esbuild src/compose.ts --bundle --format=esm --platform=neutral --outfile=dist/compose.js && esbuild src/index.ts --bundle --format=esm --platform=neutral --external:@sekiban/dcb-runtime --external:@sekiban/dcb-runtime/cloudflare --outfile=dist/index.js && esbuild src/cli.ts --bundle --format=esm --platform=node --banner:js='#!/usr/bin/env node' --outfile=dist/cli.js",
|
|
45
|
+
"test": "npm run build && node --test test/cli.node-test.mjs",
|
|
46
|
+
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
47
|
+
}
|
|
48
|
+
}
|