@hot-updater/cloudflare 1.2.0-rc.6 → 1.2.0-rc.61

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/dist/index.cjs CHANGED
@@ -24,9 +24,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
24
24
  let _hot_updater_plugin_core = require("@hot-updater/plugin-core");
25
25
  let cloudflare = require("cloudflare");
26
26
  cloudflare = __toESM(cloudflare, 1);
27
- let _aws_sdk_client_s3 = require("@aws-sdk/client-s3");
28
- let _aws_sdk_lib_storage = require("@aws-sdk/lib-storage");
29
- let _aws_sdk_s3_request_presigner = require("@aws-sdk/s3-request-presigner");
27
+ let _hot_updater_storage_s3 = require("@hot-updater/storage-s3");
30
28
  //#region src/d1Executor.ts
31
29
  var D1ExecutionError = class extends Error {
32
30
  name = "D1ExecutionError";
@@ -48,18 +46,50 @@ const withSqliteCode = (error) => {
48
46
  return code === void 0 ? error : Object.assign(new Error(message, { cause: error }), { code });
49
47
  };
50
48
  /**
49
+ * The D1 errors Cloudflare's D1 guide says to retry ("Retry the operation"):
50
+ * a dropped connection, a reset or restarted database object, a transient
51
+ * failure to reach its node, and a replica cut off from its primary.
52
+ */
53
+ const TRANSIENT_D1_ERROR = /Network connection lost|storage caused object to be reset|reset because its code was updated|Cannot resolve D1 DB due to transient issue|Replica disconnected from primary/iu;
54
+ /** The SQL core's reads, the only statements a retry can't apply twice. */
55
+ const READ_ONLY_STATEMENT = /^\s*SELECT\b/iu;
56
+ /** Attempts of a read in all, the first included. */
57
+ const READ_ATTEMPTS = 3;
58
+ /** The longest wait before the second attempt, doubling after it, with full jitter. */
59
+ const READ_RETRY_BASE_MS = 25;
60
+ const isTransient = (error) => TRANSIENT_D1_ERROR.test(error instanceof Error ? error.message : String(error));
61
+ /**
62
+ * Runs a read again when D1 failed it with a transient error, at most
63
+ * {@link READ_ATTEMPTS} times, and throws the last error. D1 retries a
64
+ * read-only query twice on its own; an error that outlasts those retries
65
+ * still answers a request with 500, where one more attempt after a short
66
+ * wait usually reads. A write may have committed when it fails, so it never
67
+ * runs again.
68
+ */
69
+ const retryingReads = (query) => async (statement) => {
70
+ if (!READ_ONLY_STATEMENT.test(statement.sql)) return query(statement);
71
+ for (let attempt = 1;; attempt += 1) try {
72
+ return await query(statement);
73
+ } catch (error) {
74
+ if (attempt >= READ_ATTEMPTS || !isTransient(error)) throw error;
75
+ const wait = Math.random() * READ_RETRY_BASE_MS * 2 ** (attempt - 1);
76
+ await new Promise((resolve) => setTimeout(resolve, wait));
77
+ }
78
+ };
79
+ /**
51
80
  * Hot Updater's database on D1: the storage engine through the shared SQL
52
81
  * core, fenced by the schema settings. D1 has no interactive transactions,
53
82
  * so each write is one atomic batch that evaluates its guards first
54
83
  * (`_hu_write`).
55
84
  */
56
85
  const createD1Database = (runner) => {
86
+ const query = retryingReads((statement) => runner.query(statement));
57
87
  return (0, _hot_updater_plugin_core.createEngineDatabase)({
58
88
  name: "d1Database",
59
89
  adapter: (0, _hot_updater_plugin_core.createSqlAdapter)({
60
90
  executor: {
61
91
  dialect: "sqlite",
62
- execute: (statement) => runner.query(statement).catch((error) => {
92
+ execute: (statement) => query(statement).catch((error) => {
63
93
  throw withSqliteCode(error);
64
94
  }),
65
95
  batch: (statements) => runner.batch(statements).catch((error) => {
@@ -157,94 +187,17 @@ const d1Database = (config) => ({
157
187
  });
158
188
  //#endregion
159
189
  //#region src/r2S3Storage.ts
160
- /** Devices download right after the update check that returns the URL. */
161
- const PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
162
- const isObjectNotFoundError = (error) => {
163
- if (error instanceof Error && (error.name === "NotFound" || error.name === "NoSuchKey")) return true;
164
- return typeof error === "object" && error !== null && "$metadata" in error && error.$metadata?.httpStatusCode === 404;
165
- };
166
190
  const createR2S3Storage = (config) => {
167
- const { accountId, basePath, bucketName, endpoint, forcePathStyle, region, ...s3Config } = config;
168
- const client = new _aws_sdk_client_s3.S3Client({
191
+ const { accountId, endpoint, forcePathStyle, region, ...s3Config } = config;
192
+ return (0, _hot_updater_storage_s3.createS3Storage)({
193
+ name: "r2Storage",
194
+ protocol: "r2"
195
+ }, {
169
196
  ...s3Config,
170
197
  endpoint: endpoint ?? `https://${accountId}.r2.cloudflarestorage.com`,
171
198
  forcePathStyle: forcePathStyle ?? true,
172
199
  region: region ?? "auto"
173
200
  });
174
- const getStorageKey = (0, _hot_updater_plugin_core.createStorageKeyBuilder)(basePath);
175
- const parseAndValidate = (storageUri) => {
176
- const parsed = (0, _hot_updater_plugin_core.parseStorageUri)(storageUri, "r2");
177
- if (parsed.bucket !== bucketName) throw new Error(`Bucket name mismatch: expected "${bucketName}", but found "${parsed.bucket}".`);
178
- return parsed;
179
- };
180
- return (0, _hot_updater_plugin_core.createStorageAdapter)({
181
- name: "r2Storage",
182
- protocol: "r2",
183
- async put({ key, body, contentLength, contentType }) {
184
- const storageKey = getStorageKey(key);
185
- await new _aws_sdk_lib_storage.Upload({
186
- client,
187
- params: {
188
- Body: body,
189
- Bucket: bucketName,
190
- CacheControl: "max-age=31536000",
191
- ContentLength: contentLength,
192
- ContentType: contentType,
193
- Key: storageKey
194
- }
195
- }).done();
196
- return { storageUri: (0, _hot_updater_plugin_core.createStorageUri)({
197
- protocol: "r2",
198
- bucket: bucketName,
199
- key: storageKey
200
- }) };
201
- },
202
- async get({ storageUri }) {
203
- const { key } = parseAndValidate(storageUri);
204
- try {
205
- const response = await client.send(new _aws_sdk_client_s3.GetObjectCommand({
206
- Bucket: bucketName,
207
- Key: key
208
- }));
209
- if (!response.Body) return { response: null };
210
- const headers = new Headers();
211
- if (response.ContentType) headers.set("content-type", response.ContentType);
212
- if (response.ContentLength !== void 0) headers.set("content-length", String(response.ContentLength));
213
- return { response: new Response(response.Body.transformToWebStream(), { headers }) };
214
- } catch (error) {
215
- if (isObjectNotFoundError(error)) return { response: null };
216
- throw error;
217
- }
218
- },
219
- async getDownloadUrl({ storageUri }) {
220
- const { key } = parseAndValidate(storageUri);
221
- return { url: await (0, _aws_sdk_s3_request_presigner.getSignedUrl)(client, new _aws_sdk_client_s3.GetObjectCommand({
222
- Bucket: bucketName,
223
- Key: key
224
- }), { expiresIn: PRESIGNED_URL_EXPIRES_IN_SECONDS }) };
225
- },
226
- async exists({ storageUri }) {
227
- const { key } = parseAndValidate(storageUri);
228
- try {
229
- await client.send(new _aws_sdk_client_s3.HeadObjectCommand({
230
- Bucket: bucketName,
231
- Key: key
232
- }));
233
- return { exists: true };
234
- } catch (error) {
235
- if (isObjectNotFoundError(error)) return { exists: false };
236
- throw error;
237
- }
238
- },
239
- async delete({ storageUri }) {
240
- const { key } = parseAndValidate(storageUri);
241
- await client.send(new _aws_sdk_client_s3.DeleteObjectCommand({
242
- Bucket: bucketName,
243
- Key: key
244
- }));
245
- return { deleted: true };
246
- }
247
- });
248
201
  };
249
202
  //#endregion
250
203
  //#region src/r2Storage.ts
package/dist/index.d.cts CHANGED
@@ -1,15 +1,15 @@
1
- import { StorageAdapterWith, ToolingDatabase } from "@hot-updater/plugin-core";
2
- import { S3ClientConfig } from "@aws-sdk/client-s3";
1
+ import { Lazy, StorageAdapterWith, ToolingDatabase } from "@hot-updater/plugin-core";
2
+ import { S3ClientConfig, S3CredentialsOption, S3StorageOperations } from "@hot-updater/storage-s3";
3
3
  //#region src/d1Rest.d.ts
4
4
  interface D1RestConfig {
5
5
  readonly databaseId: string;
6
6
  readonly accountId: string;
7
7
  /**
8
8
  * An API token with D1 edit permission, or a function that returns it,
9
- * such as one that reads it with `secretEnv`: called on the first query,
10
- * so a config loads without the token.
9
+ * such as `secret("<name>")` in `hot-updater.config.ts`: called on the
10
+ * first query, so a config loads without the token.
11
11
  */
12
- readonly cloudflareApiToken: string | (() => string | Promise<string>);
12
+ readonly cloudflareApiToken: Lazy<string>;
13
13
  }
14
14
  //#endregion
15
15
  //#region src/d1Executor.d.ts
@@ -31,16 +31,17 @@ type D1DatabaseConfig = D1RestConfig;
31
31
  declare const d1Database: (config: D1DatabaseConfig) => ToolingDatabase;
32
32
  //#endregion
33
33
  //#region src/r2S3Storage.d.ts
34
- interface R2S3StorageConfig extends S3ClientConfig {
34
+ interface R2S3StorageConfig extends Omit<S3ClientConfig, "credentials"> {
35
35
  accountId: string;
36
36
  bucketName: string;
37
- credentials: NonNullable<S3ClientConfig["credentials"]>;
37
+ /** The SDK's credentials, or an R2 access key whose fields are lazy. */
38
+ credentials: NonNullable<S3CredentialsOption>;
38
39
  /** Base path where bundles will be stored in the bucket. */
39
40
  basePath?: string;
40
41
  }
41
42
  //#endregion
42
43
  //#region src/r2Storage.d.ts
43
44
  type R2StorageConfig = R2S3StorageConfig;
44
- declare const r2Storage: (config: R2S3StorageConfig) => StorageAdapterWith<"put" | "get" | "getDownloadUrl" | "exists" | "delete">;
45
+ declare const r2Storage: (config: R2S3StorageConfig) => StorageAdapterWith<S3StorageOperations>;
45
46
  //#endregion
46
47
  export { D1DatabaseConfig, D1ExecutionError, type R2S3StorageConfig, R2StorageConfig, d1Database, r2Storage };
package/dist/index.d.mts CHANGED
@@ -1,15 +1,15 @@
1
- import { StorageAdapterWith, ToolingDatabase } from "@hot-updater/plugin-core";
2
- import { S3ClientConfig } from "@aws-sdk/client-s3";
1
+ import { Lazy, StorageAdapterWith, ToolingDatabase } from "@hot-updater/plugin-core";
2
+ import { S3ClientConfig, S3CredentialsOption, S3StorageOperations } from "@hot-updater/storage-s3";
3
3
  //#region src/d1Rest.d.ts
4
4
  interface D1RestConfig {
5
5
  readonly databaseId: string;
6
6
  readonly accountId: string;
7
7
  /**
8
8
  * An API token with D1 edit permission, or a function that returns it,
9
- * such as one that reads it with `secretEnv`: called on the first query,
10
- * so a config loads without the token.
9
+ * such as `secret("<name>")` in `hot-updater.config.ts`: called on the
10
+ * first query, so a config loads without the token.
11
11
  */
12
- readonly cloudflareApiToken: string | (() => string | Promise<string>);
12
+ readonly cloudflareApiToken: Lazy<string>;
13
13
  }
14
14
  //#endregion
15
15
  //#region src/d1Executor.d.ts
@@ -31,16 +31,17 @@ type D1DatabaseConfig = D1RestConfig;
31
31
  declare const d1Database: (config: D1DatabaseConfig) => ToolingDatabase;
32
32
  //#endregion
33
33
  //#region src/r2S3Storage.d.ts
34
- interface R2S3StorageConfig extends S3ClientConfig {
34
+ interface R2S3StorageConfig extends Omit<S3ClientConfig, "credentials"> {
35
35
  accountId: string;
36
36
  bucketName: string;
37
- credentials: NonNullable<S3ClientConfig["credentials"]>;
37
+ /** The SDK's credentials, or an R2 access key whose fields are lazy. */
38
+ credentials: NonNullable<S3CredentialsOption>;
38
39
  /** Base path where bundles will be stored in the bucket. */
39
40
  basePath?: string;
40
41
  }
41
42
  //#endregion
42
43
  //#region src/r2Storage.d.ts
43
44
  type R2StorageConfig = R2S3StorageConfig;
44
- declare const r2Storage: (config: R2S3StorageConfig) => StorageAdapterWith<"put" | "get" | "getDownloadUrl" | "exists" | "delete">;
45
+ declare const r2Storage: (config: R2S3StorageConfig) => StorageAdapterWith<S3StorageOperations>;
45
46
  //#endregion
46
47
  export { D1DatabaseConfig, D1ExecutionError, type R2S3StorageConfig, R2StorageConfig, d1Database, r2Storage };
package/dist/index.mjs CHANGED
@@ -1,8 +1,6 @@
1
- import { WRITE_GUARD_TABLE, coreSettings, coreTarget, createEngineDatabase, createSqlAdapter, createStorageAdapter, createStorageKeyBuilder, createStorageUri, createTableStatements, generateEngineSql, parseStorageUri } from "@hot-updater/plugin-core";
1
+ import { WRITE_GUARD_TABLE, coreSettings, coreTarget, createEngineDatabase, createSqlAdapter, createTableStatements, generateEngineSql } from "@hot-updater/plugin-core";
2
2
  import Cloudflare from "cloudflare";
3
- import { DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, S3Client } from "@aws-sdk/client-s3";
4
- import { Upload } from "@aws-sdk/lib-storage";
5
- import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
3
+ import { createS3Storage } from "@hot-updater/storage-s3";
6
4
  //#region src/d1Executor.ts
7
5
  var D1ExecutionError = class extends Error {
8
6
  name = "D1ExecutionError";
@@ -24,18 +22,50 @@ const withSqliteCode = (error) => {
24
22
  return code === void 0 ? error : Object.assign(new Error(message, { cause: error }), { code });
25
23
  };
26
24
  /**
25
+ * The D1 errors Cloudflare's D1 guide says to retry ("Retry the operation"):
26
+ * a dropped connection, a reset or restarted database object, a transient
27
+ * failure to reach its node, and a replica cut off from its primary.
28
+ */
29
+ const TRANSIENT_D1_ERROR = /Network connection lost|storage caused object to be reset|reset because its code was updated|Cannot resolve D1 DB due to transient issue|Replica disconnected from primary/iu;
30
+ /** The SQL core's reads, the only statements a retry can't apply twice. */
31
+ const READ_ONLY_STATEMENT = /^\s*SELECT\b/iu;
32
+ /** Attempts of a read in all, the first included. */
33
+ const READ_ATTEMPTS = 3;
34
+ /** The longest wait before the second attempt, doubling after it, with full jitter. */
35
+ const READ_RETRY_BASE_MS = 25;
36
+ const isTransient = (error) => TRANSIENT_D1_ERROR.test(error instanceof Error ? error.message : String(error));
37
+ /**
38
+ * Runs a read again when D1 failed it with a transient error, at most
39
+ * {@link READ_ATTEMPTS} times, and throws the last error. D1 retries a
40
+ * read-only query twice on its own; an error that outlasts those retries
41
+ * still answers a request with 500, where one more attempt after a short
42
+ * wait usually reads. A write may have committed when it fails, so it never
43
+ * runs again.
44
+ */
45
+ const retryingReads = (query) => async (statement) => {
46
+ if (!READ_ONLY_STATEMENT.test(statement.sql)) return query(statement);
47
+ for (let attempt = 1;; attempt += 1) try {
48
+ return await query(statement);
49
+ } catch (error) {
50
+ if (attempt >= READ_ATTEMPTS || !isTransient(error)) throw error;
51
+ const wait = Math.random() * READ_RETRY_BASE_MS * 2 ** (attempt - 1);
52
+ await new Promise((resolve) => setTimeout(resolve, wait));
53
+ }
54
+ };
55
+ /**
27
56
  * Hot Updater's database on D1: the storage engine through the shared SQL
28
57
  * core, fenced by the schema settings. D1 has no interactive transactions,
29
58
  * so each write is one atomic batch that evaluates its guards first
30
59
  * (`_hu_write`).
31
60
  */
32
61
  const createD1Database = (runner) => {
62
+ const query = retryingReads((statement) => runner.query(statement));
33
63
  return createEngineDatabase({
34
64
  name: "d1Database",
35
65
  adapter: createSqlAdapter({
36
66
  executor: {
37
67
  dialect: "sqlite",
38
- execute: (statement) => runner.query(statement).catch((error) => {
68
+ execute: (statement) => query(statement).catch((error) => {
39
69
  throw withSqliteCode(error);
40
70
  }),
41
71
  batch: (statements) => runner.batch(statements).catch((error) => {
@@ -133,94 +163,17 @@ const d1Database = (config) => ({
133
163
  });
134
164
  //#endregion
135
165
  //#region src/r2S3Storage.ts
136
- /** Devices download right after the update check that returns the URL. */
137
- const PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
138
- const isObjectNotFoundError = (error) => {
139
- if (error instanceof Error && (error.name === "NotFound" || error.name === "NoSuchKey")) return true;
140
- return typeof error === "object" && error !== null && "$metadata" in error && error.$metadata?.httpStatusCode === 404;
141
- };
142
166
  const createR2S3Storage = (config) => {
143
- const { accountId, basePath, bucketName, endpoint, forcePathStyle, region, ...s3Config } = config;
144
- const client = new S3Client({
167
+ const { accountId, endpoint, forcePathStyle, region, ...s3Config } = config;
168
+ return createS3Storage({
169
+ name: "r2Storage",
170
+ protocol: "r2"
171
+ }, {
145
172
  ...s3Config,
146
173
  endpoint: endpoint ?? `https://${accountId}.r2.cloudflarestorage.com`,
147
174
  forcePathStyle: forcePathStyle ?? true,
148
175
  region: region ?? "auto"
149
176
  });
150
- const getStorageKey = createStorageKeyBuilder(basePath);
151
- const parseAndValidate = (storageUri) => {
152
- const parsed = parseStorageUri(storageUri, "r2");
153
- if (parsed.bucket !== bucketName) throw new Error(`Bucket name mismatch: expected "${bucketName}", but found "${parsed.bucket}".`);
154
- return parsed;
155
- };
156
- return createStorageAdapter({
157
- name: "r2Storage",
158
- protocol: "r2",
159
- async put({ key, body, contentLength, contentType }) {
160
- const storageKey = getStorageKey(key);
161
- await new Upload({
162
- client,
163
- params: {
164
- Body: body,
165
- Bucket: bucketName,
166
- CacheControl: "max-age=31536000",
167
- ContentLength: contentLength,
168
- ContentType: contentType,
169
- Key: storageKey
170
- }
171
- }).done();
172
- return { storageUri: createStorageUri({
173
- protocol: "r2",
174
- bucket: bucketName,
175
- key: storageKey
176
- }) };
177
- },
178
- async get({ storageUri }) {
179
- const { key } = parseAndValidate(storageUri);
180
- try {
181
- const response = await client.send(new GetObjectCommand({
182
- Bucket: bucketName,
183
- Key: key
184
- }));
185
- if (!response.Body) return { response: null };
186
- const headers = new Headers();
187
- if (response.ContentType) headers.set("content-type", response.ContentType);
188
- if (response.ContentLength !== void 0) headers.set("content-length", String(response.ContentLength));
189
- return { response: new Response(response.Body.transformToWebStream(), { headers }) };
190
- } catch (error) {
191
- if (isObjectNotFoundError(error)) return { response: null };
192
- throw error;
193
- }
194
- },
195
- async getDownloadUrl({ storageUri }) {
196
- const { key } = parseAndValidate(storageUri);
197
- return { url: await getSignedUrl(client, new GetObjectCommand({
198
- Bucket: bucketName,
199
- Key: key
200
- }), { expiresIn: PRESIGNED_URL_EXPIRES_IN_SECONDS }) };
201
- },
202
- async exists({ storageUri }) {
203
- const { key } = parseAndValidate(storageUri);
204
- try {
205
- await client.send(new HeadObjectCommand({
206
- Bucket: bucketName,
207
- Key: key
208
- }));
209
- return { exists: true };
210
- } catch (error) {
211
- if (isObjectNotFoundError(error)) return { exists: false };
212
- throw error;
213
- }
214
- },
215
- async delete({ storageUri }) {
216
- const { key } = parseAndValidate(storageUri);
217
- await client.send(new DeleteObjectCommand({
218
- Bucket: bucketName,
219
- Key: key
220
- }));
221
- return { deleted: true };
222
- }
223
- });
224
177
  };
225
178
  //#endregion
226
179
  //#region src/r2Storage.ts
@@ -75,18 +75,50 @@ const withSqliteCode = (error) => {
75
75
  return code === void 0 ? error : Object.assign(new Error(message, { cause: error }), { code });
76
76
  };
77
77
  /**
78
+ * The D1 errors Cloudflare's D1 guide says to retry ("Retry the operation"):
79
+ * a dropped connection, a reset or restarted database object, a transient
80
+ * failure to reach its node, and a replica cut off from its primary.
81
+ */
82
+ const TRANSIENT_D1_ERROR = /Network connection lost|storage caused object to be reset|reset because its code was updated|Cannot resolve D1 DB due to transient issue|Replica disconnected from primary/iu;
83
+ /** The SQL core's reads, the only statements a retry can't apply twice. */
84
+ const READ_ONLY_STATEMENT = /^\s*SELECT\b/iu;
85
+ /** Attempts of a read in all, the first included. */
86
+ const READ_ATTEMPTS = 3;
87
+ /** The longest wait before the second attempt, doubling after it, with full jitter. */
88
+ const READ_RETRY_BASE_MS = 25;
89
+ const isTransient = (error) => TRANSIENT_D1_ERROR.test(error instanceof Error ? error.message : String(error));
90
+ /**
91
+ * Runs a read again when D1 failed it with a transient error, at most
92
+ * {@link READ_ATTEMPTS} times, and throws the last error. D1 retries a
93
+ * read-only query twice on its own; an error that outlasts those retries
94
+ * still answers a request with 500, where one more attempt after a short
95
+ * wait usually reads. A write may have committed when it fails, so it never
96
+ * runs again.
97
+ */
98
+ const retryingReads = (query) => async (statement) => {
99
+ if (!READ_ONLY_STATEMENT.test(statement.sql)) return query(statement);
100
+ for (let attempt = 1;; attempt += 1) try {
101
+ return await query(statement);
102
+ } catch (error) {
103
+ if (attempt >= READ_ATTEMPTS || !isTransient(error)) throw error;
104
+ const wait = Math.random() * READ_RETRY_BASE_MS * 2 ** (attempt - 1);
105
+ await new Promise((resolve) => setTimeout(resolve, wait));
106
+ }
107
+ };
108
+ /**
78
109
  * Hot Updater's database on D1: the storage engine through the shared SQL
79
110
  * core, fenced by the schema settings. D1 has no interactive transactions,
80
111
  * so each write is one atomic batch that evaluates its guards first
81
112
  * (`_hu_write`).
82
113
  */
83
114
  const createD1Database = (runner) => {
115
+ const query = retryingReads((statement) => runner.query(statement));
84
116
  return (0, _hot_updater_plugin_core.createEngineDatabase)({
85
117
  name: "d1Database",
86
118
  adapter: (0, _hot_updater_plugin_core.createSqlAdapter)({
87
119
  executor: {
88
120
  dialect: "sqlite",
89
- execute: (statement) => runner.query(statement).catch((error) => {
121
+ execute: (statement) => query(statement).catch((error) => {
90
122
  throw withSqliteCode(error);
91
123
  }),
92
124
  batch: (statements) => runner.batch(statements).catch((error) => {
@@ -11207,6 +11239,15 @@ const getValidWranglerAuthToken = () => {
11207
11239
  const resolveCloudflareInfrastructureApiToken = async ({ cwd, nonInteractive }) => {
11208
11240
  const existingToken = getValidWranglerAuthToken();
11209
11241
  if (existingToken) return existingToken;
11242
+ if (getWranglerLoginAuthToken()?.refresh_token) {
11243
+ await execa("npx", ["wrangler", "whoami"], {
11244
+ cwd,
11245
+ reject: false,
11246
+ stdio: "ignore"
11247
+ });
11248
+ const renewedToken = getValidWranglerAuthToken();
11249
+ if (renewedToken) return renewedToken;
11250
+ }
11210
11251
  if (nonInteractive) throw new CloudflareWranglerLoginRequiredError();
11211
11252
  await execa("npx", [
11212
11253
  "wrangler",
@@ -11420,10 +11461,11 @@ const inputCloudflareInitSecrets = async ({ accountId, bucketName, apiToken, acc
11420
11461
  //#region iac/configTemplate.ts
11421
11462
  /**
11422
11463
  * The config init writes. With the `resources` init set up, it names them,
11423
- * and reads the API token and R2 keys with `secretEnv`, from the
11464
+ * and reads the API token and R2 keys with `secret()`, from the
11424
11465
  * environment and `.env.hotupdater`, then the config's `secrets` adapter.
11425
- * Without them, as the agent scaffold writes it, it reads every value from
11426
- * the environment.
11466
+ * Without them, as the agent scaffold writes it before the agent creates the
11467
+ * resources, it reads their IDs from the environment, where the agent
11468
+ * records them, and the credentials with `secret()` alike.
11427
11469
  */
11428
11470
  const getConfigScaffold = (build, resources) => {
11429
11471
  const builder = new _hot_updater_cli_tools.ConfigBuilder().setBuildType(build).setPlugins({
@@ -11446,8 +11488,8 @@ const getConfigScaffold = (build, resources) => {
11446
11488
  bucketName: process.env.HOT_UPDATER_CLOUDFLARE_R2_BUCKET_NAME!,
11447
11489
  accountId: process.env.HOT_UPDATER_CLOUDFLARE_ACCOUNT_ID!,
11448
11490
  credentials: {
11449
- accessKeyId: process.env.HOT_UPDATER_CLOUDFLARE_R2_ACCESS_KEY_ID!,
11450
- secretAccessKey: process.env.HOT_UPDATER_CLOUDFLARE_R2_SECRET_ACCESS_KEY!,
11491
+ accessKeyId: secret("HOT_UPDATER_CLOUDFLARE_R2_ACCESS_KEY_ID"),
11492
+ secretAccessKey: secret("HOT_UPDATER_CLOUDFLARE_R2_SECRET_ACCESS_KEY"),
11451
11493
  },
11452
11494
  })`
11453
11495
  }).setDatabase({
@@ -11458,8 +11500,11 @@ const getConfigScaffold = (build, resources) => {
11458
11500
  configString: `d1Database({
11459
11501
  databaseId: process.env.HOT_UPDATER_CLOUDFLARE_D1_DATABASE_ID!,
11460
11502
  accountId: process.env.HOT_UPDATER_CLOUDFLARE_ACCOUNT_ID!,
11461
- cloudflareApiToken: process.env.HOT_UPDATER_CLOUDFLARE_API_TOKEN!,
11503
+ cloudflareApiToken: secret("HOT_UPDATER_CLOUDFLARE_API_TOKEN"),
11462
11504
  })`
11505
+ }).addImport({
11506
+ pkg: "hot-updater",
11507
+ named: ["secret"]
11463
11508
  }));
11464
11509
  const accountId = JSON.stringify(resources.accountId);
11465
11510
  const storageConfig = {
@@ -11470,12 +11515,9 @@ const getConfigScaffold = (build, resources) => {
11470
11515
  configString: `r2Storage({
11471
11516
  bucketName: ${JSON.stringify(resources.bucketName)},
11472
11517
  accountId: ${accountId},
11473
- credentials: async () => {
11474
- const env = await storageSecrets();
11475
- return {
11476
- accessKeyId: env.HOT_UPDATER_CLOUDFLARE_R2_ACCESS_KEY_ID,
11477
- secretAccessKey: env.HOT_UPDATER_CLOUDFLARE_R2_SECRET_ACCESS_KEY,
11478
- };
11518
+ credentials: {
11519
+ accessKeyId: secret("HOT_UPDATER_CLOUDFLARE_R2_ACCESS_KEY_ID"),
11520
+ secretAccessKey: secret("HOT_UPDATER_CLOUDFLARE_R2_SECRET_ACCESS_KEY"),
11479
11521
  },
11480
11522
  })`
11481
11523
  };
@@ -11487,15 +11529,13 @@ const getConfigScaffold = (build, resources) => {
11487
11529
  configString: `d1Database({
11488
11530
  databaseId: ${JSON.stringify(resources.d1DatabaseId)},
11489
11531
  accountId: ${accountId},
11490
- cloudflareApiToken: async () =>
11491
- (await databaseSecrets()).HOT_UPDATER_CLOUDFLARE_API_TOKEN,
11532
+ cloudflareApiToken: secret("HOT_UPDATER_CLOUDFLARE_API_TOKEN"),
11492
11533
  })`
11493
11534
  };
11494
- const helperStatements = [(0, _hot_updater_cli_tools.secretEnvHelper)("storageSecrets", ["HOT_UPDATER_CLOUDFLARE_R2_ACCESS_KEY_ID", "HOT_UPDATER_CLOUDFLARE_R2_SECRET_ACCESS_KEY"]), (0, _hot_updater_cli_tools.secretEnvHelper)("databaseSecrets", ["HOT_UPDATER_CLOUDFLARE_API_TOKEN"])];
11495
11535
  return (0, _hot_updater_cli_tools.createHotUpdaterConfigScaffoldFromBuilder)(builder.setStorage(storageConfig).setDatabase(databaseConfig).addImport({
11496
11536
  pkg: "hot-updater",
11497
- named: ["secretEnv"]
11498
- }).setIntermediateCode(helperStatements.map(({ code }) => code).join("\n\n")), { helperStatements });
11537
+ named: ["secret"]
11538
+ }));
11499
11539
  };
11500
11540
  //#endregion
11501
11541
  //#region iac/managedWorker.ts
@@ -11911,6 +11951,8 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
11911
11951
  });
11912
11952
  let credential;
11913
11953
  try {
11954
+ await (0, _hot_updater_cli_tools.fillReleaseLabels)(server);
11955
+ await (0, _hot_updater_cli_tools.backfillInsightsReleaseRefs)(server);
11914
11956
  credential = await (0, _hot_updater_cli_tools.provisionClientCredential)(server, {
11915
11957
  env: initInputEnv,
11916
11958
  name: "Cloudflare init"
@@ -11933,8 +11975,7 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
11933
11975
  ...credential === void 0 ? {} : { credential },
11934
11976
  clientPlugins: server.clientPlugins
11935
11977
  });
11936
- _hot_updater_cli_tools.p.log.message(`Next step: ${(0, _hot_updater_cli_tools.link)("https://hot-updater.dev/docs/managed/cloudflare#step-3-add-hotupdater-to-your-project")}`);
11937
- _hot_updater_cli_tools.p.log.success("Done! 🎉");
11978
+ return { nextSteps: [(0, _hot_updater_cli_tools.link)("https://hot-updater.dev/docs/managed/cloudflare#step-3-add-hotupdater-to-your-project")] };
11938
11979
  };
11939
11980
  //#endregion
11940
11981
  exports.initProvider = initProvider;
@@ -1,4 +1,4 @@
1
- import { RunInitOptions } from "@hot-updater/cli-tools";
1
+ import { RunInitOptions, RunInitResult } from "@hot-updater/cli-tools";
2
2
  //#region iac/init/index.d.ts
3
3
  declare const initProvider: {
4
4
  readonly label: "Cloudflare D1 + R2 + Worker";
@@ -86,6 +86,6 @@ declare const initProvider: {
86
86
  };
87
87
  //#endregion
88
88
  //#region iac/index.d.ts
89
- declare const runInit: ({ build, envFile, secretsEnv }: RunInitOptions) => Promise<void>;
89
+ declare const runInit: ({ build, envFile, secretsEnv }: RunInitOptions) => Promise<RunInitResult>;
90
90
  //#endregion
91
91
  export { initProvider, runInit };
@@ -1,4 +1,4 @@
1
- import { RunInitOptions } from "@hot-updater/cli-tools";
1
+ import { RunInitOptions, RunInitResult } from "@hot-updater/cli-tools";
2
2
  //#region iac/init/index.d.ts
3
3
  declare const initProvider: {
4
4
  readonly label: "Cloudflare D1 + R2 + Worker";
@@ -86,6 +86,6 @@ declare const initProvider: {
86
86
  };
87
87
  //#endregion
88
88
  //#region iac/index.d.ts
89
- declare const runInit: ({ build, envFile, secretsEnv }: RunInitOptions) => Promise<void>;
89
+ declare const runInit: ({ build, envFile, secretsEnv }: RunInitOptions) => Promise<RunInitResult>;
90
90
  //#endregion
91
91
  export { initProvider, runInit };