@astrale-os/adapter-cloudflare 0.5.0-beta.20 → 0.5.0-beta.201
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 +245 -0
- package/dist/adapter.d.ts +9 -15
- package/dist/adapter.js +43 -129
- package/dist/build/bundle/admit.d.ts +3 -0
- package/dist/build/bundle/admit.js +47 -0
- package/dist/build/bundle/compiled-wasm-loader.d.ts +8 -0
- package/dist/build/bundle/compiled-wasm-loader.js +21 -0
- package/dist/build/bundler.d.ts +21 -0
- package/dist/build/bundler.js +96 -0
- package/dist/build/closure.d.ts +4 -1
- package/dist/build/closure.js +7 -1
- package/dist/build/codegen/execution.d.ts +3 -13
- package/dist/build/codegen/execution.js +2 -44
- package/dist/build/codegen/wrangler.d.ts +28 -10
- package/dist/build/codegen/wrangler.js +71 -21
- package/dist/build/configuration/invocation-timeout.d.ts +2 -0
- package/dist/build/configuration/invocation-timeout.js +9 -0
- package/dist/build/configuration/request-limit.d.ts +2 -0
- package/dist/build/configuration/request-limit.js +9 -0
- package/dist/build/configuration/router.d.ts +7 -0
- package/dist/build/configuration/router.js +17 -0
- package/dist/build/configuration/settings.d.ts +6 -0
- package/dist/build/configuration/settings.js +40 -0
- package/dist/build/configuration.d.ts +4 -9
- package/dist/build/configuration.js +4 -40
- package/dist/build/frontend/files.d.ts +19 -0
- package/dist/build/frontend/files.js +99 -0
- package/dist/build/frontend/readiness.d.ts +16 -0
- package/dist/build/frontend/readiness.js +21 -0
- package/dist/build/frontend/revision.d.ts +5 -0
- package/dist/build/frontend/revision.js +14 -0
- package/dist/build/frontend/vite.d.ts +14 -0
- package/dist/build/frontend/vite.js +42 -0
- package/dist/build/frontend/vite.process.d.ts +7 -0
- package/dist/build/frontend/vite.process.js +65 -0
- package/dist/build/frontend/vite.runner.d.ts +1 -0
- package/dist/build/frontend/vite.runner.js +155 -0
- package/dist/build/index.d.ts +10 -6
- package/dist/build/index.js +10 -6
- package/dist/build/material.d.ts +10 -0
- package/dist/build/material.js +25 -0
- package/dist/build/worker/codegen/entry.d.ts +9 -0
- package/dist/build/worker/codegen/entry.js +65 -0
- package/dist/build/worker/codegen/literal.d.ts +28 -0
- package/dist/build/worker/codegen/literal.js +136 -0
- package/dist/build/worker/codegen/service.d.ts +14 -0
- package/dist/build/worker/codegen/service.js +57 -0
- package/dist/build/worker/execution.prepare.d.ts +20 -0
- package/dist/build/worker/execution.prepare.js +129 -0
- package/dist/build/worker/media-type.d.ts +1 -0
- package/dist/build/worker/media-type.js +20 -0
- package/dist/build/worker/modules.d.ts +20 -0
- package/dist/build/worker/modules.js +32 -0
- package/dist/build/worker/specifier.d.ts +5 -0
- package/dist/build/worker/specifier.js +15 -0
- package/dist/build/worker/upload.d.ts +23 -0
- package/dist/build/worker/upload.js +42 -0
- package/dist/hosting/activation.d.ts +38 -0
- package/dist/hosting/activation.js +109 -0
- package/dist/hosting/assets.d.ts +14 -0
- package/dist/hosting/assets.js +53 -0
- package/dist/hosting/bounded.d.ts +10 -0
- package/dist/hosting/bounded.js +32 -0
- package/dist/hosting/bytes.d.ts +6 -0
- package/dist/hosting/bytes.js +25 -0
- package/dist/hosting/client.d.ts +144 -0
- package/dist/hosting/client.js +491 -0
- package/dist/hosting/dispatcher/cron.d.mts +10 -0
- package/dist/hosting/dispatcher/cron.mjs +135 -0
- package/dist/hosting/dispatcher/deployments.d.mts +26 -0
- package/dist/hosting/dispatcher/deployments.mjs +158 -0
- package/dist/hosting/dispatcher/dispatcher.d.mts +17 -0
- package/dist/hosting/dispatcher/dispatcher.mjs +76 -0
- package/dist/hosting/dispatcher/env.d.mts +51 -0
- package/dist/hosting/dispatcher/failure.d.mts +4 -0
- package/dist/hosting/dispatcher/failure.mjs +15 -0
- package/dist/hosting/dispatcher/index.d.mts +4 -0
- package/dist/hosting/dispatcher/index.mjs +8 -0
- package/dist/hosting/dispatcher/modules.d.ts +24 -0
- package/dist/hosting/dispatcher/modules.js +55 -0
- package/dist/hosting/dispatcher/services.d.mts +23 -0
- package/dist/hosting/dispatcher/services.mjs +202 -0
- package/dist/hosting/identity.d.ts +15 -0
- package/dist/hosting/identity.js +36 -0
- package/dist/hosting/index.d.ts +34 -0
- package/dist/hosting/index.js +32 -0
- package/dist/hosting/kv.d.ts +90 -0
- package/dist/hosting/kv.js +207 -0
- package/dist/hosting/listing.d.ts +34 -0
- package/dist/hosting/listing.js +50 -0
- package/dist/hosting/names.d.ts +16 -0
- package/dist/hosting/names.js +28 -0
- package/dist/hosting/provision/account.d.ts +11 -0
- package/dist/hosting/provision/account.js +86 -0
- package/dist/hosting/provision/dispatcher.d.ts +42 -0
- package/dist/hosting/provision/dispatcher.js +99 -0
- package/dist/hosting/provision/ingress.d.ts +12 -0
- package/dist/hosting/provision/ingress.js +31 -0
- package/dist/hosting/provision/plan.d.ts +143 -0
- package/dist/hosting/provision/plan.js +246 -0
- package/dist/hosting/provision/routing.d.ts +82 -0
- package/dist/hosting/provision/routing.js +226 -0
- package/dist/hosting/readiness.d.ts +53 -0
- package/dist/hosting/readiness.js +82 -0
- package/dist/hosting/refusal.d.ts +28 -0
- package/dist/hosting/refusal.js +13 -0
- package/dist/hosting/retirement.d.ts +70 -0
- package/dist/hosting/retirement.js +107 -0
- package/dist/hosting/retry-after.d.ts +6 -0
- package/dist/hosting/retry-after.js +55 -0
- package/dist/hosting/script.d.ts +186 -0
- package/dist/hosting/script.js +324 -0
- package/dist/hosting/testing/fake-cloudflare.d.ts +212 -0
- package/dist/hosting/testing/fake-cloudflare.js +757 -0
- package/dist/hosting/testing/index.d.ts +6 -0
- package/dist/hosting/testing/index.js +6 -0
- package/dist/hosting/time.d.ts +4 -0
- package/dist/hosting/time.js +20 -0
- package/dist/identity/binding.d.ts +1 -1
- package/dist/identity/binding.js +1 -1
- package/dist/identity/material.d.ts +1 -2
- package/dist/identity/material.js +5 -18
- package/dist/index.d.ts +14 -12
- package/dist/index.js +13 -11
- package/dist/namespace/configure.d.ts +22 -0
- package/dist/namespace/configure.js +199 -0
- package/dist/namespace/coordinates.d.ts +15 -0
- package/dist/namespace/coordinates.js +49 -0
- package/dist/namespace/deploy-release.d.ts +53 -0
- package/dist/namespace/deploy-release.js +389 -0
- package/dist/namespace/hosting.d.ts +29 -0
- package/dist/namespace/hosting.js +120 -0
- package/dist/namespace/index.d.ts +12 -0
- package/dist/namespace/index.js +12 -0
- package/dist/namespace/list.d.ts +18 -0
- package/dist/namespace/list.js +63 -0
- package/dist/namespace/readiness.d.ts +30 -0
- package/dist/namespace/readiness.js +31 -0
- package/dist/namespace/record.d.ts +21 -0
- package/dist/namespace/record.js +53 -0
- package/dist/params.d.ts +60 -76
- package/dist/release/build.d.ts +35 -0
- package/dist/release/build.js +44 -0
- package/dist/release/deployment.d.ts +44 -0
- package/dist/release/deployment.js +141 -0
- package/dist/release/index.d.ts +2 -2
- package/dist/release/index.js +2 -2
- package/dist/worker/binary.d.ts +21 -0
- package/dist/worker/binary.js +31 -0
- package/dist/worker/build-digest.d.ts +10 -0
- package/dist/worker/build-digest.js +22 -0
- package/dist/worker/cache.d.ts +28 -0
- package/dist/worker/cache.js +70 -0
- package/dist/worker/durable.d.ts +3 -0
- package/dist/worker/durable.js +5 -0
- package/dist/worker/entry.d.ts +38 -25
- package/dist/worker/entry.js +87 -109
- package/dist/worker/front.d.ts +56 -0
- package/dist/worker/front.js +59 -0
- package/dist/worker/frontend.d.ts +4 -0
- package/dist/worker/frontend.js +83 -0
- package/dist/worker/index.d.ts +4 -1
- package/dist/worker/index.js +4 -1
- package/dist/worker/restate.d.ts +6 -0
- package/dist/worker/restate.js +6 -0
- package/dist/worker/settings.d.ts +47 -0
- package/dist/worker/settings.js +163 -0
- package/dist/wrangler/bundle.d.ts +10 -0
- package/dist/wrangler/bundle.js +27 -0
- package/dist/wrangler/index.d.ts +3 -0
- package/dist/wrangler/index.js +3 -0
- package/dist/wrangler/process.d.ts +15 -0
- package/dist/wrangler/process.js +113 -0
- package/dist/wrangler/type-generation.d.ts +6 -0
- package/dist/wrangler/type-generation.js +19 -0
- package/package.json +39 -12
- package/template/astrale.config.ts +42 -36
- package/dist/build/artifact.d.ts +0 -8
- package/dist/build/artifact.js +0 -179
- package/dist/build/codegen/gateway.d.ts +0 -1
- package/dist/build/codegen/gateway.js +0 -7
- package/dist/build/frontend-v1.d.ts +0 -16
- package/dist/build/frontend-v1.js +0 -133
- package/dist/build/parse-output.d.ts +0 -26
- package/dist/build/parse-output.js +0 -57
- package/dist/build/wrangler-cli.d.ts +0 -105
- package/dist/build/wrangler-cli.js +0 -448
- package/dist/deploy/deploy.d.ts +0 -17
- package/dist/deploy/deploy.js +0 -207
- package/dist/deploy/index.d.ts +0 -1
- package/dist/deploy/index.js +0 -1
- package/dist/identity/secret.d.ts +0 -3
- package/dist/identity/secret.js +0 -7
- package/dist/identity/source.d.ts +0 -26
- package/dist/identity/source.js +0 -98
- package/dist/release/namespace.d.ts +0 -2
- package/dist/release/namespace.js +0 -6
- package/dist/release/target.d.ts +0 -2
- package/dist/release/target.js +0 -9
- package/dist/worker/gateway.d.ts +0 -15
- package/dist/worker/gateway.js +0 -26
|
@@ -0,0 +1,757 @@
|
|
|
1
|
+
import { sha256Hex } from '../bytes.js';
|
|
2
|
+
import kitDispatcher from '../dispatcher/index.mjs';
|
|
3
|
+
import { callsDataset, routingKvTitle } from '../names.js';
|
|
4
|
+
export const FAKE_ACCOUNT = '0123456789abcdef0123456789abcdef';
|
|
5
|
+
export const FAKE_TOKEN = 'hosting-test-token';
|
|
6
|
+
export const FAKE_API_BASE = 'https://api.cloudflare.test/client/v4';
|
|
7
|
+
export const FAKE_ZONE = 'fake-zone';
|
|
8
|
+
/**
|
|
9
|
+
* One fake Cloudflare account: dispatch namespaces and their scripts (create-only uploads, asset
|
|
10
|
+
* sessions, secrets, settings, deletion), Workers KV, account Workers with their settings,
|
|
11
|
+
* schedules and workers.dev, zones with DNS records and Worker routes, and Workers custom domains.
|
|
12
|
+
* It answers as the OPS-2 transcripts recorded Cloudflare: a create-only upload over an existing
|
|
13
|
+
* script answers 412 with code 10018; a secret PUT keeps the script's etag and tags, mints a new
|
|
14
|
+
* `deployment_id` and answers only `{ name, type }`.
|
|
15
|
+
*
|
|
16
|
+
* A request to any other host is a public request: the zone route that matches it names an account
|
|
17
|
+
* Worker, which runs the REAL kit dispatcher (or the consumer's) over the bindings its upload
|
|
18
|
+
* declared — `DEPLOYMENTS` reaching the namespace's scripts, `SCHEDULES` the KV, `CALLS` recording
|
|
19
|
+
* data points (Analytics Engine is otherwise a no-op). Every API request is recorded.
|
|
20
|
+
*/
|
|
21
|
+
export class FakeCloudflare {
|
|
22
|
+
account;
|
|
23
|
+
token;
|
|
24
|
+
requests = [];
|
|
25
|
+
/** Requests to fail before they reach the fake, by `METHOD path` (as recorded). */
|
|
26
|
+
failures = new Map();
|
|
27
|
+
namespaces = new Map();
|
|
28
|
+
kvs = [];
|
|
29
|
+
workers = new Map();
|
|
30
|
+
zones = new Map();
|
|
31
|
+
customDomains = [];
|
|
32
|
+
/** The data points the dispatchers wrote to their `CALLS` datasets. */
|
|
33
|
+
points = [];
|
|
34
|
+
/** How many dispatched calls still reach the previous version after a secret write. */
|
|
35
|
+
propagation = 0;
|
|
36
|
+
/** The clock scripts are created on. */
|
|
37
|
+
now = () => Date.now();
|
|
38
|
+
options;
|
|
39
|
+
assetSessions = new Map();
|
|
40
|
+
assetUploads = new Map();
|
|
41
|
+
completions = new Map();
|
|
42
|
+
sequence = 0;
|
|
43
|
+
constructor(options = {}) {
|
|
44
|
+
this.options = options;
|
|
45
|
+
this.account = options.account ?? FAKE_ACCOUNT;
|
|
46
|
+
this.token = options.token ?? FAKE_TOKEN;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* A fake account with one hosting already provisioned, as `provisionHosting` leaves it: the
|
|
50
|
+
* namespace, its routing KV under the derived title (after `otherKvs` other KV namespaces), the
|
|
51
|
+
* dispatcher Worker bound to both and to the calls dataset, and the zone's wildcard route to it.
|
|
52
|
+
*/
|
|
53
|
+
static async provisioned(hosting, options = {}) {
|
|
54
|
+
const fake = new FakeCloudflare(options);
|
|
55
|
+
for (let index = 0; index < (hosting.otherKvs ?? 0); index += 1) {
|
|
56
|
+
fake.addKv(`other-kv-${index}`);
|
|
57
|
+
}
|
|
58
|
+
fake.namespaces.set(hosting.namespace, new Map());
|
|
59
|
+
const kv = fake.addKv(hosting.routingKvTitle ?? (await routingKvTitle(hosting.namespace)));
|
|
60
|
+
const worker = hosting.worker ?? `${hosting.namespace}-dispatcher`;
|
|
61
|
+
fake.workers.set(worker, {
|
|
62
|
+
metadata: {
|
|
63
|
+
main_module: 'index.mjs',
|
|
64
|
+
bindings: [
|
|
65
|
+
{ type: 'dispatch_namespace', name: 'DEPLOYMENTS', namespace: hosting.namespace },
|
|
66
|
+
{ type: 'kv_namespace', name: 'SCHEDULES', namespace_id: kv.id },
|
|
67
|
+
{
|
|
68
|
+
type: 'analytics_engine',
|
|
69
|
+
name: 'CALLS',
|
|
70
|
+
dataset: await callsDataset(hosting.namespace),
|
|
71
|
+
},
|
|
72
|
+
],
|
|
73
|
+
},
|
|
74
|
+
modules: new Map(),
|
|
75
|
+
schedules: [],
|
|
76
|
+
});
|
|
77
|
+
const zone = fake.addZone(hosting.routingDomain);
|
|
78
|
+
zone.dns.push({
|
|
79
|
+
id: fake.id('dns'),
|
|
80
|
+
type: 'AAAA',
|
|
81
|
+
name: `*.${hosting.routingDomain}`,
|
|
82
|
+
content: '100::',
|
|
83
|
+
proxied: true,
|
|
84
|
+
});
|
|
85
|
+
zone.routes.push({
|
|
86
|
+
id: fake.id('route'),
|
|
87
|
+
pattern: `*.${hosting.routingDomain}/*`,
|
|
88
|
+
script: worker,
|
|
89
|
+
});
|
|
90
|
+
return fake;
|
|
91
|
+
}
|
|
92
|
+
/** Add one KV namespace; its id is derived from its title. */
|
|
93
|
+
addKv(title) {
|
|
94
|
+
const kv = {
|
|
95
|
+
id: `kv${this.kvs.length}-${title}`.slice(0, 32),
|
|
96
|
+
title,
|
|
97
|
+
values: new Map(),
|
|
98
|
+
metadata: new Map(),
|
|
99
|
+
};
|
|
100
|
+
this.kvs.push(kv);
|
|
101
|
+
return kv;
|
|
102
|
+
}
|
|
103
|
+
/** Add one zone named `name` (the fake's first zone is `FAKE_ZONE`). */
|
|
104
|
+
addZone(name) {
|
|
105
|
+
const id = this.zones.size === 0 ? FAKE_ZONE : this.id('zone');
|
|
106
|
+
const zone = { id, name, dns: [], routes: [] };
|
|
107
|
+
this.zones.set(id, zone);
|
|
108
|
+
return zone;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* The values of the KV namespace titled `title` (or with that id), as UTF-8 text: the fake keeps
|
|
112
|
+
* UTF-8 values only. A value set here keeps the metadata its key already has (`kvMetadata`), and
|
|
113
|
+
* a new key has none: a deployment record set here needs its `{"contentType":...}` set there too,
|
|
114
|
+
* or the kit refuses it as no record it writes.
|
|
115
|
+
*/
|
|
116
|
+
kv(titleOrId) {
|
|
117
|
+
return this.kvNamespace(titleOrId).values;
|
|
118
|
+
}
|
|
119
|
+
/** The metadata of the values of the KV namespace titled `title` (or with that id), by key. */
|
|
120
|
+
kvMetadata(titleOrId) {
|
|
121
|
+
return this.kvNamespace(titleOrId).metadata;
|
|
122
|
+
}
|
|
123
|
+
kvNamespace(titleOrId) {
|
|
124
|
+
const kv = this.kvs.find((candidate) => candidate.title === titleOrId || candidate.id === titleOrId);
|
|
125
|
+
if (kv === undefined)
|
|
126
|
+
throw new TypeError(`The fake account has no KV ${titleOrId}.`);
|
|
127
|
+
return kv;
|
|
128
|
+
}
|
|
129
|
+
/** The scripts of one dispatch namespace. */
|
|
130
|
+
scripts(namespace) {
|
|
131
|
+
const scripts = this.namespaces.get(namespace);
|
|
132
|
+
if (scripts === undefined)
|
|
133
|
+
throw new TypeError(`The fake account has no namespace ${namespace}.`);
|
|
134
|
+
return scripts;
|
|
135
|
+
}
|
|
136
|
+
/** A provider version in the UUID form a Worker's version metadata reports. */
|
|
137
|
+
static uuid(version) {
|
|
138
|
+
return `${version.slice(0, 8)}-${version.slice(8, 12)}-${version.slice(12, 16)}-${version.slice(16, 20)}-${version.slice(20)}`;
|
|
139
|
+
}
|
|
140
|
+
/** Every request, to the API or to a public host. */
|
|
141
|
+
fetch = async (input, init) => {
|
|
142
|
+
const request = new Request(input, init);
|
|
143
|
+
const url = new URL(request.url);
|
|
144
|
+
if (request.url.startsWith(`${FAKE_API_BASE}/`))
|
|
145
|
+
return this.api(request, url);
|
|
146
|
+
return this.publicRequest(request, url);
|
|
147
|
+
};
|
|
148
|
+
/** Fire one account Worker's `scheduled` handler, as its cron trigger would. */
|
|
149
|
+
async scheduled(worker, scheduledTime) {
|
|
150
|
+
const found = this.workers.get(worker);
|
|
151
|
+
if (found === undefined)
|
|
152
|
+
throw new TypeError(`The fake account has no Worker ${worker}.`);
|
|
153
|
+
await this.dispatcher().scheduled({ scheduledTime }, this.environment(found));
|
|
154
|
+
}
|
|
155
|
+
dispatcher() {
|
|
156
|
+
return (this.options.dispatcher ??
|
|
157
|
+
kitDispatcher);
|
|
158
|
+
}
|
|
159
|
+
/** Answer one public request: the zone route matching its host runs its Worker. */
|
|
160
|
+
async publicRequest(request, url) {
|
|
161
|
+
for (const zone of this.zones.values()) {
|
|
162
|
+
const route = zone.routes.find((candidate) => matchesRoute(candidate.pattern, url));
|
|
163
|
+
if (route === undefined || route.script === undefined)
|
|
164
|
+
continue;
|
|
165
|
+
const worker = this.workers.get(route.script);
|
|
166
|
+
if (worker === undefined)
|
|
167
|
+
return new Response('worker not found', { status: 522 });
|
|
168
|
+
return this.dispatcher().fetch(request, this.environment(worker));
|
|
169
|
+
}
|
|
170
|
+
throw new TypeError(`The fake Cloudflare routes no host ${url.host}.`);
|
|
171
|
+
}
|
|
172
|
+
/** The environment an account Worker runs with: its upload's bindings, live. */
|
|
173
|
+
environment(worker) {
|
|
174
|
+
const environment = {};
|
|
175
|
+
for (const binding of worker.metadata.bindings) {
|
|
176
|
+
if (binding.type === 'dispatch_namespace') {
|
|
177
|
+
environment[binding.name] = this.namespaceBinding(String(binding.namespace));
|
|
178
|
+
}
|
|
179
|
+
else if (binding.type === 'kv_namespace') {
|
|
180
|
+
environment[binding.name] = this.kvBinding(String(binding.namespace_id));
|
|
181
|
+
}
|
|
182
|
+
else if (binding.type === 'analytics_engine') {
|
|
183
|
+
const dataset = String(binding.dataset);
|
|
184
|
+
environment[binding.name] = {
|
|
185
|
+
writeDataPoint: (point) => {
|
|
186
|
+
this.points.push({ dataset, indexes: [...point.indexes] });
|
|
187
|
+
},
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
else if (binding.type === 'plain_text' || binding.type === 'secret_text') {
|
|
191
|
+
environment[binding.name] = binding.text;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return environment;
|
|
195
|
+
}
|
|
196
|
+
namespaceBinding(namespace) {
|
|
197
|
+
return {
|
|
198
|
+
get: (name) => ({
|
|
199
|
+
fetch: async (input, init) => {
|
|
200
|
+
const script = this.namespaces.get(namespace)?.get(name);
|
|
201
|
+
if (script === undefined)
|
|
202
|
+
throw new Error('Worker not found.');
|
|
203
|
+
return this.run(new Request(input, init), script);
|
|
204
|
+
},
|
|
205
|
+
}),
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
kvBinding(id) {
|
|
209
|
+
const namespace = () => {
|
|
210
|
+
const kv = this.kvs.find((candidate) => candidate.id === id);
|
|
211
|
+
if (kv === undefined)
|
|
212
|
+
throw new Error('KV namespace not found.');
|
|
213
|
+
return kv;
|
|
214
|
+
};
|
|
215
|
+
const values = () => namespace().values;
|
|
216
|
+
return {
|
|
217
|
+
get: async (key) => values().get(key) ?? null,
|
|
218
|
+
getWithMetadata: async (key, type) => {
|
|
219
|
+
if (type !== 'arrayBuffer')
|
|
220
|
+
throw new TypeError('The fake reads metadata as bytes only.');
|
|
221
|
+
const value = values().get(key);
|
|
222
|
+
if (value === undefined)
|
|
223
|
+
return { value: null, metadata: null };
|
|
224
|
+
const bytes = new TextEncoder().encode(value);
|
|
225
|
+
return {
|
|
226
|
+
value: bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),
|
|
227
|
+
metadata: namespace().metadata.get(key) ?? null,
|
|
228
|
+
};
|
|
229
|
+
},
|
|
230
|
+
list: async ({ prefix, cursor }) => {
|
|
231
|
+
const names = [...values().keys()].filter((key) => key.startsWith(prefix)).sort();
|
|
232
|
+
const size = this.options.kvKeysPageSize ?? 1000;
|
|
233
|
+
const start = cursor === undefined ? 0 : Number(cursor);
|
|
234
|
+
const page = names.slice(start, start + size).map((name) => ({ name }));
|
|
235
|
+
return start + size < names.length
|
|
236
|
+
? { keys: page, list_complete: false, cursor: String(start + size) }
|
|
237
|
+
: { keys: page, list_complete: true };
|
|
238
|
+
},
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
/** Run one script for one call, from its stale version while a secret write propagates. */
|
|
242
|
+
run(request, script) {
|
|
243
|
+
const runner = this.options.runScript ?? defaultRunner;
|
|
244
|
+
if (script.stale !== undefined && script.stale.requests > 0) {
|
|
245
|
+
script.stale.requests -= 1;
|
|
246
|
+
return runner(request, {
|
|
247
|
+
name: script.name,
|
|
248
|
+
namespace: script.namespace,
|
|
249
|
+
version: FakeCloudflare.uuid(script.stale.version),
|
|
250
|
+
bindings: script.stale.bindings,
|
|
251
|
+
script,
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
return runner(request, {
|
|
255
|
+
name: script.name,
|
|
256
|
+
namespace: script.namespace,
|
|
257
|
+
version: FakeCloudflare.uuid(script.version),
|
|
258
|
+
bindings: script.bindings,
|
|
259
|
+
script,
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
async api(request, url) {
|
|
263
|
+
const accountPrefix = `/client/v4/accounts/${this.account}`;
|
|
264
|
+
const zonePrefix = '/client/v4/zones';
|
|
265
|
+
let path;
|
|
266
|
+
if (url.pathname.startsWith(`${accountPrefix}/`)) {
|
|
267
|
+
path = `${url.pathname.slice(accountPrefix.length)}${url.search}`;
|
|
268
|
+
}
|
|
269
|
+
else if (url.pathname === zonePrefix || url.pathname.startsWith(`${zonePrefix}/`)) {
|
|
270
|
+
path = `${url.pathname.slice('/client/v4'.length)}${url.search}`;
|
|
271
|
+
}
|
|
272
|
+
else {
|
|
273
|
+
return failure(404, 7003, 'No route.');
|
|
274
|
+
}
|
|
275
|
+
const recorded = (status, body) => this.requests.push({
|
|
276
|
+
method: request.method,
|
|
277
|
+
path,
|
|
278
|
+
...(request.headers.get('if-none-match') === null
|
|
279
|
+
? {}
|
|
280
|
+
: { ifNoneMatch: request.headers.get('if-none-match') }),
|
|
281
|
+
status,
|
|
282
|
+
...(body === undefined ? {} : { body }),
|
|
283
|
+
});
|
|
284
|
+
const injected = this.failures.get(`${request.method} ${path}`);
|
|
285
|
+
if (injected !== undefined) {
|
|
286
|
+
this.failures.delete(`${request.method} ${path}`);
|
|
287
|
+
recorded(injected.status);
|
|
288
|
+
return injected;
|
|
289
|
+
}
|
|
290
|
+
const bearer = request.headers.get('authorization');
|
|
291
|
+
const assetUpload = url.pathname.endsWith('/workers/assets/upload');
|
|
292
|
+
if (!assetUpload && bearer !== `Bearer ${this.token}`) {
|
|
293
|
+
recorded(403);
|
|
294
|
+
return failure(403, 10000, 'Authentication error');
|
|
295
|
+
}
|
|
296
|
+
const answered = await this.route(request, url, bearer);
|
|
297
|
+
recorded(answered.response.status, answered.body);
|
|
298
|
+
return answered.response;
|
|
299
|
+
}
|
|
300
|
+
async route(request, url, bearer) {
|
|
301
|
+
const method = request.method;
|
|
302
|
+
const path = url.pathname.replace(`/client/v4/accounts/${this.account}`, '');
|
|
303
|
+
if (url.pathname.startsWith('/client/v4/zones'))
|
|
304
|
+
return this.zoneRoute(request, url);
|
|
305
|
+
// KV namespaces.
|
|
306
|
+
if (path === '/storage/kv/namespaces' && method === 'GET') {
|
|
307
|
+
const size = Number(url.searchParams.get('per_page') ?? '20');
|
|
308
|
+
const pageSize = Math.min(size, this.options.kvPageSize ?? size);
|
|
309
|
+
const page = Number(url.searchParams.get('page') ?? '1');
|
|
310
|
+
const totalPages = Math.max(1, Math.ceil(this.kvs.length / pageSize));
|
|
311
|
+
return {
|
|
312
|
+
response: envelope(this.kvs
|
|
313
|
+
.slice((page - 1) * pageSize, page * pageSize)
|
|
314
|
+
.map(({ id, title }) => ({ id, title })), { page, per_page: pageSize, total_pages: totalPages, total_count: this.kvs.length }),
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
if (path === '/storage/kv/namespaces' && method === 'POST') {
|
|
318
|
+
const { title } = (await request.json());
|
|
319
|
+
if (this.kvs.some((kv) => kv.title === title)) {
|
|
320
|
+
return { response: failure(400, 10014, 'a namespace with this title already exists') };
|
|
321
|
+
}
|
|
322
|
+
const kv = this.addKv(title);
|
|
323
|
+
return { response: envelope({ id: kv.id, title }), body: { title } };
|
|
324
|
+
}
|
|
325
|
+
const kvNamespace = /^\/storage\/kv\/namespaces\/([^/]+)$/u.exec(path);
|
|
326
|
+
if (kvNamespace !== null && method === 'GET') {
|
|
327
|
+
const kv = this.kvs.find((candidate) => candidate.id === decodeURIComponent(kvNamespace[1]));
|
|
328
|
+
return {
|
|
329
|
+
response: kv === undefined
|
|
330
|
+
? failure(404, 10013, 'namespace not found')
|
|
331
|
+
: envelope({ id: kv.id, title: kv.title }),
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
const keys = /^\/storage\/kv\/namespaces\/([^/]+)\/keys$/u.exec(path);
|
|
335
|
+
if (keys !== null && method === 'GET') {
|
|
336
|
+
const kv = this.kvs.find((candidate) => candidate.id === decodeURIComponent(keys[1]));
|
|
337
|
+
if (kv === undefined)
|
|
338
|
+
return { response: failure(404, 10013, 'namespace not found') };
|
|
339
|
+
const prefix = url.searchParams.get('prefix') ?? '';
|
|
340
|
+
const limit = Math.min(Number(url.searchParams.get('limit') ?? '1000'), this.options.kvKeysPageSize ?? 1000);
|
|
341
|
+
const cursor = url.searchParams.get('cursor');
|
|
342
|
+
const start = cursor === null ? 0 : Number(atob(cursor));
|
|
343
|
+
const names = [...kv.values.keys()].filter((key) => key.startsWith(prefix)).sort();
|
|
344
|
+
const page = names.slice(start, start + limit);
|
|
345
|
+
const next = start + limit < names.length ? btoa(String(start + limit)) : '';
|
|
346
|
+
return {
|
|
347
|
+
response: envelope(page.map((name) => ({ name })), { count: page.length, cursor: next }),
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
const metadata = /^\/storage\/kv\/namespaces\/([^/]+)\/metadata\/(.+)$/u.exec(path);
|
|
351
|
+
if (metadata !== null && method === 'GET') {
|
|
352
|
+
const kv = this.kvs.find((candidate) => candidate.id === decodeURIComponent(metadata[1]));
|
|
353
|
+
if (kv === undefined)
|
|
354
|
+
return { response: failure(404, 10013, 'namespace not found') };
|
|
355
|
+
const key = decodeURIComponent(metadata[2]);
|
|
356
|
+
return {
|
|
357
|
+
response: kv.values.has(key)
|
|
358
|
+
? envelope(kv.metadata.get(key) ?? null)
|
|
359
|
+
: failure(404, 10009, 'get: key not found'),
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
const value = /^\/storage\/kv\/namespaces\/([^/]+)\/values\/(.+)$/u.exec(path);
|
|
363
|
+
if (value !== null) {
|
|
364
|
+
const kv = this.kvs.find((candidate) => candidate.id === decodeURIComponent(value[1]));
|
|
365
|
+
if (kv === undefined)
|
|
366
|
+
return { response: failure(404, 10013, 'namespace not found') };
|
|
367
|
+
const key = decodeURIComponent(value[2]);
|
|
368
|
+
if (method === 'GET') {
|
|
369
|
+
const stored = kv.values.get(key);
|
|
370
|
+
return {
|
|
371
|
+
response: stored === undefined
|
|
372
|
+
? failure(404, 10009, 'get: key not found')
|
|
373
|
+
: new Response(stored, { status: 200 }),
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
if (method === 'PUT') {
|
|
377
|
+
const contentType = request.headers.get('content-type');
|
|
378
|
+
// A value written with metadata is a multipart form: its `value` and its JSON `metadata`.
|
|
379
|
+
if (contentType?.startsWith('multipart/form-data') === true) {
|
|
380
|
+
const form = await request.formData();
|
|
381
|
+
const part = form.get('value');
|
|
382
|
+
const written = typeof part === 'string' ? part : await utf8(part);
|
|
383
|
+
const declared = JSON.parse(String(form.get('metadata')));
|
|
384
|
+
kv.values.set(key, written);
|
|
385
|
+
kv.metadata.set(key, declared);
|
|
386
|
+
return { response: envelope(null), body: { key, value: written, metadata: declared } };
|
|
387
|
+
}
|
|
388
|
+
const text = await request.text();
|
|
389
|
+
kv.values.set(key, text);
|
|
390
|
+
kv.metadata.delete(key);
|
|
391
|
+
return { response: envelope(null), body: { key, value: text, contentType } };
|
|
392
|
+
}
|
|
393
|
+
if (method === 'DELETE') {
|
|
394
|
+
kv.values.delete(key);
|
|
395
|
+
kv.metadata.delete(key);
|
|
396
|
+
return { response: envelope(null), body: { key } };
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
// Dispatch namespaces.
|
|
400
|
+
if (path === '/workers/dispatch/namespaces' && method === 'POST') {
|
|
401
|
+
const { name } = (await request.json());
|
|
402
|
+
if (!this.namespaces.has(name))
|
|
403
|
+
this.namespaces.set(name, new Map());
|
|
404
|
+
return { response: envelope({ namespace_name: name }), body: { name } };
|
|
405
|
+
}
|
|
406
|
+
const namespace = /^\/workers\/dispatch\/namespaces\/([^/]+)$/u.exec(path);
|
|
407
|
+
if (namespace !== null && method === 'GET') {
|
|
408
|
+
const name = decodeURIComponent(namespace[1]);
|
|
409
|
+
return {
|
|
410
|
+
response: this.namespaces.has(name)
|
|
411
|
+
? envelope({ namespace_name: name, script_count: this.namespaces.get(name).size })
|
|
412
|
+
: failure(404, 100119, 'namespace not found'),
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
const listing = /^\/workers\/dispatch\/namespaces\/([^/]+)\/scripts$/u.exec(path);
|
|
416
|
+
if (listing !== null && method === 'GET') {
|
|
417
|
+
const scripts = this.namespaces.get(decodeURIComponent(listing[1]));
|
|
418
|
+
if (scripts === undefined)
|
|
419
|
+
return { response: failure(404, 100119, 'namespace not found') };
|
|
420
|
+
return {
|
|
421
|
+
response: envelope([...scripts.keys()].sort().map((id) => ({ id })), { cursor: '' }),
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
const script = /^\/workers\/dispatch\/namespaces\/([^/]+)\/scripts\/([^/]+)(\/.*)?$/u.exec(path);
|
|
425
|
+
if (script !== null) {
|
|
426
|
+
return this.script(request, url, decodeURIComponent(script[1]), decodeURIComponent(script[2]), script[3] ?? '');
|
|
427
|
+
}
|
|
428
|
+
if (path === '/workers/assets/upload' && method === 'POST') {
|
|
429
|
+
const session = this.assetSessions.get(bearer?.slice('Bearer '.length) ?? '');
|
|
430
|
+
if (session === undefined)
|
|
431
|
+
return { response: failure(401, 10001, 'invalid asset session') };
|
|
432
|
+
const form = await request.formData();
|
|
433
|
+
for (const [hash, file] of form.entries()) {
|
|
434
|
+
const text = await file.text();
|
|
435
|
+
this.assetUploads.set(hash, Uint8Array.from(atob(text), (char) => char.charCodeAt(0)));
|
|
436
|
+
}
|
|
437
|
+
const completion = `completion-${(this.sequence += 1)}`;
|
|
438
|
+
this.completions.set(completion, session);
|
|
439
|
+
return { response: envelope({ jwt: completion }) };
|
|
440
|
+
}
|
|
441
|
+
// Account Workers.
|
|
442
|
+
const worker = /^\/workers\/scripts\/([^/]+)(\/settings|\/schedules|\/subdomain)?$/u.exec(path);
|
|
443
|
+
if (worker !== null)
|
|
444
|
+
return this.accountWorker(request, decodeURIComponent(worker[1]), worker[2]);
|
|
445
|
+
if (path === '/workers/domains' && method === 'GET') {
|
|
446
|
+
return { response: envelope(this.customDomains.map((domain) => ({ ...domain }))) };
|
|
447
|
+
}
|
|
448
|
+
return { response: failure(404, 7003, `No route for ${method} ${path}.`) };
|
|
449
|
+
}
|
|
450
|
+
async script(request, url, namespaceName, name, suffix) {
|
|
451
|
+
const scripts = this.namespaces.get(namespaceName);
|
|
452
|
+
if (scripts === undefined)
|
|
453
|
+
return { response: failure(404, 100119, 'namespace not found') };
|
|
454
|
+
const script = scripts.get(name);
|
|
455
|
+
const method = request.method;
|
|
456
|
+
if (suffix === '' && method === 'GET') {
|
|
457
|
+
if (script === undefined) {
|
|
458
|
+
return { response: failure(404, 10007, 'This Worker does not exist.') };
|
|
459
|
+
}
|
|
460
|
+
return {
|
|
461
|
+
response: envelope({
|
|
462
|
+
created_on: script.createdOn,
|
|
463
|
+
modified_on: script.createdOn,
|
|
464
|
+
dispatch_namespace: namespaceName,
|
|
465
|
+
script: {
|
|
466
|
+
id: name,
|
|
467
|
+
etag: script.etag,
|
|
468
|
+
created_on: script.createdOn,
|
|
469
|
+
deployment_id: script.version,
|
|
470
|
+
tags: script.tags.length === 0 ? null : [...script.tags],
|
|
471
|
+
},
|
|
472
|
+
}),
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
if (suffix === '' && method === 'PUT') {
|
|
476
|
+
const form = await request.formData();
|
|
477
|
+
const metadata = JSON.parse(await form.get('metadata').text());
|
|
478
|
+
if (script !== undefined && request.headers.get('if-none-match') === '*') {
|
|
479
|
+
return {
|
|
480
|
+
response: failure(412, 10018, 'The request could not be completed due to a precondition failure.'),
|
|
481
|
+
body: { metadata: redact(metadata) },
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
const modules = new Map();
|
|
485
|
+
for (const [field, part] of form.entries()) {
|
|
486
|
+
if (field === 'metadata')
|
|
487
|
+
continue;
|
|
488
|
+
const file = part;
|
|
489
|
+
// Cloudflare types each module part by its kind: WASM is never a JavaScript module.
|
|
490
|
+
const expected = field.endsWith('.wasm')
|
|
491
|
+
? ['application/wasm']
|
|
492
|
+
: /\.m?js$/u.test(field)
|
|
493
|
+
? ['application/javascript+module']
|
|
494
|
+
: ['text/plain', 'application/octet-stream'];
|
|
495
|
+
if (!expected.includes(file.type)) {
|
|
496
|
+
return { response: failure(400, 10021, `module ${field} is not typed ${expected[0]}`) };
|
|
497
|
+
}
|
|
498
|
+
modules.set(field, { type: file.type, bytes: new Uint8Array(await file.arrayBuffer()) });
|
|
499
|
+
}
|
|
500
|
+
const assetsJwt = metadata.assets?.jwt;
|
|
501
|
+
const assets = new Map();
|
|
502
|
+
if (assetsJwt !== undefined) {
|
|
503
|
+
const manifest = this.completions.get(assetsJwt);
|
|
504
|
+
if (manifest === undefined)
|
|
505
|
+
return { response: failure(400, 10021, 'invalid assets token') };
|
|
506
|
+
for (const [assetPath, hash] of manifest)
|
|
507
|
+
assets.set(assetPath, this.assetUploads.get(hash));
|
|
508
|
+
}
|
|
509
|
+
const created = {
|
|
510
|
+
name,
|
|
511
|
+
namespace: namespaceName,
|
|
512
|
+
etag: await sha256Hex(JSON.stringify([...modules].map(([key, module]) => [key, [...module.bytes]]))),
|
|
513
|
+
version: this.version(),
|
|
514
|
+
createdOn: new Date(this.now()).toISOString(),
|
|
515
|
+
tags: metadata.tags ?? [],
|
|
516
|
+
compatibilityDate: metadata.compatibility_date,
|
|
517
|
+
compatibilityFlags: metadata.compatibility_flags ?? [],
|
|
518
|
+
mainModule: metadata.main_module,
|
|
519
|
+
modules,
|
|
520
|
+
assets,
|
|
521
|
+
bindings: metadata.bindings,
|
|
522
|
+
};
|
|
523
|
+
scripts.set(name, created);
|
|
524
|
+
return {
|
|
525
|
+
response: envelope({
|
|
526
|
+
id: name,
|
|
527
|
+
etag: created.etag,
|
|
528
|
+
created_on: created.createdOn,
|
|
529
|
+
deployment_id: created.version,
|
|
530
|
+
tags: created.tags.length === 0 ? null : [...created.tags],
|
|
531
|
+
compatibility_date: created.compatibilityDate,
|
|
532
|
+
compatibility_flags: created.compatibilityFlags,
|
|
533
|
+
has_assets: assets.size > 0,
|
|
534
|
+
has_modules: true,
|
|
535
|
+
}),
|
|
536
|
+
body: { metadata: redact(metadata), modules: [...modules.keys()] },
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
if (suffix === '' && method === 'DELETE') {
|
|
540
|
+
if (script === undefined) {
|
|
541
|
+
return { response: failure(404, 10007, 'This Worker does not exist.') };
|
|
542
|
+
}
|
|
543
|
+
scripts.delete(name);
|
|
544
|
+
return { response: envelope(null), body: { force: url.searchParams.get('force') } };
|
|
545
|
+
}
|
|
546
|
+
// An upload session precedes the script it uploads assets for.
|
|
547
|
+
if (suffix === '/assets-upload-session' && method === 'POST') {
|
|
548
|
+
const body = (await request.json());
|
|
549
|
+
const session = `session-${(this.sequence += 1)}`;
|
|
550
|
+
const manifest = new Map(Object.entries(body.manifest).map(([assetPath, { hash }]) => [assetPath, hash]));
|
|
551
|
+
this.assetSessions.set(session, manifest);
|
|
552
|
+
return { response: envelope({ jwt: session, buckets: [[...new Set(manifest.values())]] }) };
|
|
553
|
+
}
|
|
554
|
+
if (script === undefined)
|
|
555
|
+
return { response: failure(404, 10007, 'This Worker does not exist.') };
|
|
556
|
+
if (suffix === '/secrets' && method === 'GET') {
|
|
557
|
+
return {
|
|
558
|
+
response: envelope(script.bindings
|
|
559
|
+
.filter((binding) => binding.type === 'secret_text')
|
|
560
|
+
.map((binding) => ({ name: binding.name, type: 'secret_text' }))),
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
if (suffix === '/secrets' && method === 'PUT') {
|
|
564
|
+
const body = (await request.json());
|
|
565
|
+
script.stale = {
|
|
566
|
+
version: script.version,
|
|
567
|
+
bindings: script.bindings,
|
|
568
|
+
requests: this.propagation,
|
|
569
|
+
};
|
|
570
|
+
// Cloudflare adds a secret it does not have, which a deploy must never ask for.
|
|
571
|
+
script.bindings = [
|
|
572
|
+
...script.bindings.filter((binding) => binding.name !== body.name),
|
|
573
|
+
{ type: 'secret_text', name: body.name, text: body.text },
|
|
574
|
+
];
|
|
575
|
+
script.version = this.version();
|
|
576
|
+
return { response: envelope({ name: body.name, type: 'secret_text' }), body };
|
|
577
|
+
}
|
|
578
|
+
if (suffix === '/settings' && method === 'GET') {
|
|
579
|
+
return {
|
|
580
|
+
response: envelope({
|
|
581
|
+
compatibility_date: script.compatibilityDate,
|
|
582
|
+
compatibility_flags: script.compatibilityFlags,
|
|
583
|
+
tags: script.tags,
|
|
584
|
+
bindings: script.bindings.map((binding) => {
|
|
585
|
+
if (binding.type === 'secret_text')
|
|
586
|
+
return { name: binding.name, type: binding.type };
|
|
587
|
+
if (binding.type === 'service')
|
|
588
|
+
return { ...binding, environment: 'production' };
|
|
589
|
+
return binding;
|
|
590
|
+
}),
|
|
591
|
+
}),
|
|
592
|
+
};
|
|
593
|
+
}
|
|
594
|
+
return { response: failure(404, 7003, `No route for ${method} ${suffix}.`) };
|
|
595
|
+
}
|
|
596
|
+
async accountWorker(request, name, suffix) {
|
|
597
|
+
const method = request.method;
|
|
598
|
+
const worker = this.workers.get(name);
|
|
599
|
+
if (suffix === undefined && method === 'PUT') {
|
|
600
|
+
const form = await request.formData();
|
|
601
|
+
const metadata = JSON.parse(await form.get('metadata').text());
|
|
602
|
+
const modules = new Map();
|
|
603
|
+
for (const [field, part] of form.entries()) {
|
|
604
|
+
if (field === 'metadata')
|
|
605
|
+
continue;
|
|
606
|
+
const file = part;
|
|
607
|
+
modules.set(field, { type: file.type, bytes: new Uint8Array(await file.arrayBuffer()) });
|
|
608
|
+
}
|
|
609
|
+
if (!modules.has(metadata.main_module)) {
|
|
610
|
+
return { response: failure(400, 10021, 'main module is not uploaded') };
|
|
611
|
+
}
|
|
612
|
+
this.workers.set(name, {
|
|
613
|
+
metadata,
|
|
614
|
+
modules,
|
|
615
|
+
schedules: worker?.schedules ?? [],
|
|
616
|
+
...(worker?.subdomain === undefined ? {} : { subdomain: worker.subdomain }),
|
|
617
|
+
});
|
|
618
|
+
return {
|
|
619
|
+
response: envelope({ id: name, etag: this.id('etag') }),
|
|
620
|
+
body: { metadata, modules: [...modules.keys()] },
|
|
621
|
+
};
|
|
622
|
+
}
|
|
623
|
+
if (worker === undefined) {
|
|
624
|
+
return { response: failure(404, 10007, 'This Worker does not exist.') };
|
|
625
|
+
}
|
|
626
|
+
if (suffix === '/settings' && method === 'GET') {
|
|
627
|
+
return {
|
|
628
|
+
response: envelope({
|
|
629
|
+
compatibility_date: worker.metadata.compatibility_date,
|
|
630
|
+
bindings: worker.metadata.bindings,
|
|
631
|
+
}),
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
if (suffix === '/schedules' && method === 'PUT') {
|
|
635
|
+
const schedules = (await request.json());
|
|
636
|
+
worker.schedules = schedules;
|
|
637
|
+
return { response: envelope({ schedules }), body: schedules };
|
|
638
|
+
}
|
|
639
|
+
if (suffix === '/subdomain' && method === 'POST') {
|
|
640
|
+
const subdomain = (await request.json());
|
|
641
|
+
worker.subdomain = subdomain;
|
|
642
|
+
return { response: envelope(subdomain), body: subdomain };
|
|
643
|
+
}
|
|
644
|
+
return { response: failure(404, 7003, `No route for ${method} ${suffix ?? ''}.`) };
|
|
645
|
+
}
|
|
646
|
+
async zoneRoute(request, url) {
|
|
647
|
+
const method = request.method;
|
|
648
|
+
if (url.pathname === '/client/v4/zones' && method === 'GET') {
|
|
649
|
+
const name = url.searchParams.get('name');
|
|
650
|
+
return {
|
|
651
|
+
response: envelope([...this.zones.values()]
|
|
652
|
+
.filter((zone) => zone.name === name)
|
|
653
|
+
.map((zone) => ({ id: zone.id, name: zone.name }))),
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
const match = /^\/client\/v4\/zones\/([^/]+)(\/dns_records|\/workers\/routes)(?:\/([^/]+))?$/u.exec(url.pathname);
|
|
657
|
+
const zone = match === null ? undefined : this.zones.get(decodeURIComponent(match[1]));
|
|
658
|
+
if (match === null || zone === undefined) {
|
|
659
|
+
return { response: failure(404, 7003, 'No such zone.') };
|
|
660
|
+
}
|
|
661
|
+
const id = match[3] === undefined ? undefined : decodeURIComponent(match[3]);
|
|
662
|
+
if (match[2] === '/dns_records') {
|
|
663
|
+
if (method === 'GET' && id === undefined) {
|
|
664
|
+
const type = url.searchParams.get('type');
|
|
665
|
+
const name = url.searchParams.get('name');
|
|
666
|
+
const records = zone.dns.filter((record) => (type === null || record.type === type) && (name === null || record.name === name));
|
|
667
|
+
const perPage = Number(url.searchParams.get('per_page') ?? '100');
|
|
668
|
+
const page = Number(url.searchParams.get('page') ?? '1');
|
|
669
|
+
return {
|
|
670
|
+
response: envelope(records.slice((page - 1) * perPage, page * perPage), {
|
|
671
|
+
page,
|
|
672
|
+
per_page: perPage,
|
|
673
|
+
total_pages: Math.max(1, Math.ceil(records.length / perPage)),
|
|
674
|
+
}),
|
|
675
|
+
};
|
|
676
|
+
}
|
|
677
|
+
const body = (await request.json());
|
|
678
|
+
if (method === 'POST' && id === undefined) {
|
|
679
|
+
const record = { ...body, id: this.id('dns') };
|
|
680
|
+
zone.dns.push(record);
|
|
681
|
+
return { response: envelope(record), body };
|
|
682
|
+
}
|
|
683
|
+
const index = zone.dns.findIndex((record) => record.id === id);
|
|
684
|
+
if (method === 'PUT' && index >= 0) {
|
|
685
|
+
zone.dns[index] = { ...body, id: id };
|
|
686
|
+
return { response: envelope(zone.dns[index]), body };
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
else {
|
|
690
|
+
if (method === 'GET' && id === undefined)
|
|
691
|
+
return { response: envelope(zone.routes) };
|
|
692
|
+
const body = (await request.json());
|
|
693
|
+
if (method === 'POST' && id === undefined) {
|
|
694
|
+
const route = { ...body, id: this.id('route') };
|
|
695
|
+
zone.routes.push(route);
|
|
696
|
+
return { response: envelope(route), body };
|
|
697
|
+
}
|
|
698
|
+
const index = zone.routes.findIndex((route) => route.id === id);
|
|
699
|
+
if (method === 'PUT' && index >= 0) {
|
|
700
|
+
zone.routes[index] = { ...body, id: id };
|
|
701
|
+
return { response: envelope(zone.routes[index]), body };
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
return { response: failure(404, 7003, `No route for ${method} ${url.pathname}.`) };
|
|
705
|
+
}
|
|
706
|
+
version() {
|
|
707
|
+
this.sequence += 1;
|
|
708
|
+
return this.sequence.toString(16).padStart(32, '0').replace(/^0/u, 'a');
|
|
709
|
+
}
|
|
710
|
+
id(kind) {
|
|
711
|
+
return `${kind}-${(this.sequence += 1)}`;
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
/** A generated Worker's answer, reduced to its name and version. */
|
|
715
|
+
const defaultRunner = async (_request, script) => new Response(`script ${script.name}`, {
|
|
716
|
+
status: 200,
|
|
717
|
+
headers: { 'x-astrale-worker-version': script.version },
|
|
718
|
+
});
|
|
719
|
+
/** Whether a Worker route pattern (`*.<domain>/*`, `<host>/*`) matches a request URL. */
|
|
720
|
+
function matchesRoute(pattern, url) {
|
|
721
|
+
const [host = '', ...rest] = pattern.split('/');
|
|
722
|
+
const path = `/${rest.join('/')}`;
|
|
723
|
+
const hostMatches = host.startsWith('*.')
|
|
724
|
+
? url.hostname.endsWith(host.slice(1))
|
|
725
|
+
: url.hostname === host;
|
|
726
|
+
const pathMatches = path.endsWith('*')
|
|
727
|
+
? url.pathname.startsWith(path.slice(0, -1))
|
|
728
|
+
: url.pathname === path;
|
|
729
|
+
return hostMatches && pathMatches;
|
|
730
|
+
}
|
|
731
|
+
function envelope(result, resultInfo) {
|
|
732
|
+
return Response.json({
|
|
733
|
+
result,
|
|
734
|
+
success: true,
|
|
735
|
+
errors: [],
|
|
736
|
+
messages: [],
|
|
737
|
+
...(resultInfo === undefined ? {} : { result_info: resultInfo }),
|
|
738
|
+
});
|
|
739
|
+
}
|
|
740
|
+
function failure(status, code, message) {
|
|
741
|
+
return Response.json({ result: null, success: false, errors: [{ code, message }], messages: [] }, { status });
|
|
742
|
+
}
|
|
743
|
+
/** Upload metadata as recorded: secret values replaced by their length. */
|
|
744
|
+
function redact(metadata) {
|
|
745
|
+
return {
|
|
746
|
+
...metadata,
|
|
747
|
+
bindings: (metadata.bindings ?? []).map((binding) => binding.type === 'secret_text'
|
|
748
|
+
? { ...binding, text: `<${String(binding.text).length} characters>` }
|
|
749
|
+
: binding),
|
|
750
|
+
};
|
|
751
|
+
}
|
|
752
|
+
/** A value part as UTF-8 text: the fake keeps UTF-8 values only, and refuses any other bytes. */
|
|
753
|
+
async function utf8(part) {
|
|
754
|
+
if (part === null)
|
|
755
|
+
throw new TypeError('The fake KV write has no value.');
|
|
756
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(await part.arrayBuffer());
|
|
757
|
+
}
|