wrangler 3.3.0 → 3.5.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.
@@ -1,244 +0,0 @@
1
- /// <reference path="middleware-d1-beta.d.ts"/>
2
-
3
- import { D1_IMPORTS } from "config:middleware/d1-beta";
4
-
5
- // src/index.ts
6
- class D1Database {
7
- constructor(readonly binding: Fetcher) {}
8
- prepare(query: string) {
9
- return new D1PreparedStatement(this, query);
10
- }
11
- async dump() {
12
- const response = await this.binding.fetch("http://d1/dump", {
13
- method: "POST",
14
- headers: {
15
- "content-type": "application/json",
16
- },
17
- });
18
- if (response.status !== 200) {
19
- try {
20
- const err = (await response.json()) as { error: string };
21
- throw new Error(`D1_DUMP_ERROR: ${err.error}`, {
22
- cause: new Error(err.error),
23
- });
24
- } catch (e) {
25
- throw new Error(`D1_DUMP_ERROR: Status + ${response.status}`, {
26
- cause: new Error("Status " + response.status),
27
- });
28
- }
29
- }
30
- return await response.arrayBuffer();
31
- }
32
- async batch(statements: D1PreparedStatement[]) {
33
- const exec = await this._send(
34
- "/query",
35
- statements.map((s) => s.statement),
36
- statements.map((s) => s.params)
37
- );
38
- return exec;
39
- }
40
- async exec(query: string) {
41
- const lines = query.trim().split("\n");
42
- const _exec = await this._send("/query", lines, [], false);
43
- const exec = Array.isArray(_exec) ? _exec : [_exec];
44
- const error = exec
45
- .map((r) => {
46
- return r.error ? 1 : 0;
47
- })
48
- .indexOf(1);
49
- if (error !== -1) {
50
- throw new Error(
51
- `D1_EXEC_ERROR: Error in line ${error + 1}: ${lines[error]}: ${
52
- exec[error].error
53
- }`,
54
- {
55
- cause: new Error(
56
- "Error in line " +
57
- (error + 1) +
58
- ": " +
59
- lines[error] +
60
- ": " +
61
- exec[error].error
62
- ),
63
- }
64
- );
65
- } else {
66
- return {
67
- count: exec.length,
68
- duration: exec.reduce((p, c) => {
69
- return p + (c.meta.duration as number);
70
- }, 0),
71
- };
72
- }
73
- }
74
- async _send(
75
- endpoint: string,
76
- query: string | string[],
77
- params: unknown[],
78
- dothrow = true
79
- ) {
80
- const body = JSON.stringify(
81
- typeof query == "object"
82
- ? query.map((s, index) => {
83
- return { sql: s, params: params[index] };
84
- })
85
- : {
86
- sql: query,
87
- params,
88
- }
89
- );
90
- const response = await this.binding.fetch(new URL(endpoint, "http://d1"), {
91
- method: "POST",
92
- headers: {
93
- "content-type": "application/json",
94
- },
95
- body,
96
- });
97
- try {
98
- const answer = (await response.json()) as { error?: string };
99
- if (answer.error && dothrow) {
100
- const err = answer;
101
- throw new Error(`D1_ERROR: ${err.error}`, {
102
- cause: new Error(err.error),
103
- });
104
- } else {
105
- return Array.isArray(answer)
106
- ? answer.map((r) => mapD1Result(r))
107
- : mapD1Result(answer);
108
- }
109
- } catch (e) {
110
- const error = e as Error;
111
- throw new Error(`D1_ERROR: ${error.cause || "Something went wrong"}`, {
112
- cause: new Error(`${error.cause}` || "Something went wrong"),
113
- });
114
- }
115
- }
116
- }
117
-
118
- class D1PreparedStatement {
119
- constructor(
120
- readonly database: D1Database,
121
- readonly statement: string,
122
- readonly params: unknown[] = []
123
- ) {}
124
- bind(...values: unknown[]) {
125
- for (var r in values) {
126
- const value = values[r];
127
- switch (typeof value) {
128
- case "number":
129
- case "string":
130
- break;
131
- case "object":
132
- if (value == null) break;
133
- if (
134
- Array.isArray(value) &&
135
- value
136
- .map((b) => {
137
- return typeof b == "number" && b >= 0 && b < 256 ? 1 : 0;
138
- })
139
- .indexOf(0) == -1
140
- )
141
- break;
142
- if (value instanceof ArrayBuffer) {
143
- values[r] = Array.from(new Uint8Array(value));
144
- break;
145
- }
146
- if (ArrayBuffer.isView(value)) {
147
- values[r] = Array.from(new Uint8Array(value.buffer));
148
- break;
149
- }
150
- default:
151
- throw new Error(
152
- `D1_TYPE_ERROR: Type '${typeof value}' not supported for value '${value}'`,
153
- {
154
- cause: new Error(
155
- `Type '${typeof value}' not supported for value '${value}'`
156
- ),
157
- }
158
- );
159
- }
160
- }
161
- return new D1PreparedStatement(this.database, this.statement, values);
162
- }
163
- async first(colName: string) {
164
- const info = firstIfArray(
165
- await this.database._send("/query", this.statement, this.params)
166
- );
167
- const results = info.results;
168
- if (colName !== void 0) {
169
- if (results.length > 0 && results[0][colName] === void 0) {
170
- throw new Error(`D1_COLUMN_NOTFOUND: Column not found (${colName})`, {
171
- cause: new Error("Column not found"),
172
- });
173
- }
174
- return results.length < 1 ? null : results[0][colName];
175
- } else {
176
- return results.length < 1 ? null : results[0];
177
- }
178
- }
179
- async run() {
180
- return firstIfArray(
181
- await this.database._send("/execute", this.statement, this.params)
182
- );
183
- }
184
- async all() {
185
- return firstIfArray(
186
- await this.database._send("/query", this.statement, this.params)
187
- );
188
- }
189
- async raw() {
190
- const s = firstIfArray(
191
- await this.database._send("/query", this.statement, this.params)
192
- );
193
- const raw = [];
194
- for (var r in s.results) {
195
- const entry = Object.keys(s.results[r]).map((k) => {
196
- return s.results[r][k];
197
- });
198
- raw.push(entry);
199
- }
200
- return raw;
201
- }
202
- }
203
- function firstIfArray(results: unknown) {
204
- return Array.isArray(results) ? results[0] : results;
205
- }
206
- function mapD1Result(result: Partial<D1Result>): D1Result {
207
- let map: D1Result = {
208
- results: result.results || [],
209
- success: result.success === void 0 ? true : result.success,
210
- meta: result.meta || {},
211
- };
212
- result.error && (map.error = result.error);
213
- return map;
214
- }
215
-
216
- type D1Result = {
217
- results: unknown[];
218
- success: boolean;
219
- meta: Record<string, unknown>;
220
- error?: string;
221
- };
222
-
223
- // src/shim.ts
224
- var D1_BETA_PREFIX = `__D1_BETA__`;
225
- var envMap = /* @__PURE__ */ new Map();
226
- function getMaskedEnv(env: Record<string, Fetcher | D1Database>) {
227
- if (envMap.has(env)) return envMap.get(env);
228
- const newEnv = new Map(Object.entries(env));
229
- D1_IMPORTS.filter((bindingName) =>
230
- bindingName.startsWith(D1_BETA_PREFIX)
231
- ).forEach((bindingName) => {
232
- newEnv.delete(bindingName);
233
- const newName = bindingName.slice(D1_BETA_PREFIX.length);
234
- const newBinding = new D1Database(env[bindingName] as Fetcher);
235
- newEnv.set(newName, newBinding);
236
- });
237
- const newEnvObj = Object.fromEntries(newEnv.entries());
238
- envMap.set(env, newEnvObj);
239
- return newEnvObj;
240
- }
241
-
242
- export function wrap(env: Record<string, D1Database | Fetcher>) {
243
- return getMaskedEnv(env);
244
- }