@hot-updater/standalone 1.2.0-rc.5 → 1.2.0-rc.50

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
@@ -12,11 +12,13 @@ var StandaloneDatabaseError = class extends Error {
12
12
  }
13
13
  };
14
14
  const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
15
+ /** `headers` with each lazy value resolved. */
16
+ const resolveHeaders = async (headers = {}) => Object.fromEntries(await Promise.all(Object.entries(headers).map(async ([name, value]) => [name, await (0, _hot_updater_plugin_core.resolveLazy)(value)])));
15
17
  const createStandaloneHttp = (config) => {
16
18
  const buildUrl = (path) => `${config.baseUrl.replace(/\/+$/, "")}${path}`;
17
- const headers = (routeHeaders) => ({
19
+ const headers = async (routeHeaders) => ({
18
20
  "Content-Type": "application/json",
19
- ...config.commonHeaders,
21
+ ...await resolveHeaders(config.commonHeaders),
20
22
  ...routeHeaders
21
23
  });
22
24
  const requestFailed = async (response) => {
@@ -68,21 +70,31 @@ const refusal = (status, value, fallback) => {
68
70
  const message = isRecord(value) && typeof value.error === "string" ? value.error : fallback;
69
71
  if (typeof code === "string" && MANAGEMENT_CODES.has(code)) return new _hot_updater_plugin_core.ReleaseManagementError(code, message);
70
72
  if (typeof code === "string" && CATALOG_CODES.has(code)) return new _hot_updater_plugin_core.ReleaseCatalogMutationError(code, message);
73
+ if (code === "CATALOG_OVERSIZE") return new _hot_updater_plugin_core.ReleaseCatalogCompilationError(code, message);
71
74
  if (code === "BUNDLE_NOT_FOUND" && isRecord(value)) {
72
75
  const id = /"([^"]+)"/u.exec(message)?.[1] ?? "";
73
76
  return new _hot_updater_plugin_core.DatabaseBundleNotFoundError(id);
74
77
  }
75
78
  return new StandaloneDatabaseError("request-failed", message, status);
76
79
  };
77
- const nativeBuildScopeParams = ({ platform, channel, fingerprintHash, appVersion }) => ({
80
+ const nativeBuildScopeParams = ({ platform, channel, fingerprintHash, appVersion, sandbox }) => ({
78
81
  platform,
79
82
  channel,
80
- ...fingerprintHash === null ? { appVersion } : { fingerprintHash }
83
+ ...fingerprintHash === null ? { appVersion } : { fingerprintHash },
84
+ ...sandbox === void 0 || sandbox === null ? {} : {
85
+ sandboxAppId: sandbox.appId,
86
+ sandboxUrlScheme: sandbox.urlScheme,
87
+ artifactKind: sandbox.artifactKind,
88
+ distribution: sandbox.distribution
89
+ }
81
90
  });
82
- const keysetParams = ({ order, after, limit }) => ({
91
+ /** The most IDs the admin API takes in one request. */
92
+ const MAX_IDS = 100;
93
+ const keysetParams = ({ order, after, through, limit }) => ({
83
94
  limit: String(limit),
84
95
  ...order === void 0 ? {} : { order },
85
- ...after === void 0 ? {} : { cursor: after }
96
+ ...after === void 0 ? {} : { cursor: after },
97
+ ...through === void 0 ? {} : { through }
86
98
  });
87
99
  const filterParams = (filter) => {
88
100
  switch (filter.kind) {
@@ -108,7 +120,7 @@ const createStandaloneCoreApi = (config) => {
108
120
  const http = createStandaloneHttp(config);
109
121
  let checked;
110
122
  const checkProtocol = async () => {
111
- const response = await fetch(http.buildUrl("/version"), { headers: http.headers({ "Cache-Control": "no-cache" }) });
123
+ const response = await fetch(http.buildUrl("/version"), { headers: await http.headers({ "Cache-Control": "no-cache" }) });
112
124
  const body = response.status === 404 ? {} : await http.parseJson(response);
113
125
  const protocol = isRecord(body) ? body.adminProtocol : void 0;
114
126
  if (typeof protocol !== "number" || protocol < 2) throw new StandaloneDatabaseError("request-failed", `The server at ${config.baseUrl} does not report Hot Updater admin API protocol 2 at /version. Set baseUrl to the path where the server mounts handlers.admin, such as https://example.com/hot-updater/admin.`, response.status);
@@ -125,7 +137,7 @@ const createStandaloneCoreApi = (config) => {
125
137
  for (const [key, value] of Object.entries(query)) url.searchParams.set(key, value);
126
138
  const response = await fetch(url, {
127
139
  method,
128
- headers: http.headers(method === "GET" ? { "Cache-Control": "no-cache" } : void 0),
140
+ headers: await http.headers(method === "GET" ? { "Cache-Control": "no-cache" } : void 0),
129
141
  ...body === void 0 ? {} : { body: JSON.stringify(body) }
130
142
  });
131
143
  if (response.status === 204) return null;
@@ -180,20 +192,57 @@ const createStandaloneCoreApi = (config) => {
180
192
  }),
181
193
  getReleaseCatalogRow: (scopeKey) => call("GET", `/release-catalogs/${encode(scopeKey)}`),
182
194
  listReleaseCatalogs: (input) => list("/release-catalogs", keysetParams(input)),
183
- listChannels: () => list("/channels", {}),
195
+ listReleaseScopeKeys: async ({ after, limit }) => await call("GET", "/release-scopes", {
196
+ query: {
197
+ limit: String(limit),
198
+ ...after === void 0 ? {} : { cursor: after }
199
+ },
200
+ requiredRoute: "release scope"
201
+ }) ?? [],
202
+ listChannels: async (input) => {
203
+ if (input === void 0) return list("/channels", {});
204
+ const rows = await list("/channels", keysetParams(input));
205
+ const desc = input.order === "desc";
206
+ const { after, through } = input;
207
+ const past = (name, bound) => desc ? (0, _hot_updater_plugin_core.compareUtf8)(name, bound) < 0 : (0, _hot_updater_plugin_core.compareUtf8)(name, bound) > 0;
208
+ return rows.filter(({ name }) => (after === void 0 || past(name, after)) && (through === void 0 || !past(name, through))).sort((left, right) => desc ? (0, _hot_updater_plugin_core.compareUtf8)(right.name, left.name) : (0, _hot_updater_plugin_core.compareUtf8)(left.name, right.name)).slice(0, input.limit);
209
+ },
210
+ getChannels: async (ids) => {
211
+ const unique = [...new Set(ids)];
212
+ const found = /* @__PURE__ */ new Map();
213
+ for (let start = 0; start < unique.length; start += MAX_IDS) {
214
+ const chunk = unique.slice(start, start + MAX_IDS);
215
+ const asked = new Set(chunk);
216
+ for (const row of await list("/channels", { ids: chunk.join(",") })) if (asked.has(row.id)) found.set(row.id, row);
217
+ }
218
+ return unique.flatMap((id) => {
219
+ const row = found.get(id);
220
+ return row === void 0 ? [] : [row];
221
+ });
222
+ },
184
223
  findChannelByName: (name) => call("GET", "/channels", { query: { name } }),
185
224
  getNativeBuild: (id) => call("GET", `/native-builds/${encode(id)}`, { requiredRoute: "native build" }),
225
+ findNativeBuildByBuiltInBundle: (bundleId) => call("GET", `/native-builds/built-in/${encode(bundleId)}`, { requiredRoute: "native build" }),
186
226
  findNativeBuild: async (scope, options) => {
187
227
  const buildKey = options?.buildKey;
188
228
  const row = await call("GET", "/native-builds/latest", {
189
229
  query: {
190
230
  ...nativeBuildScopeParams(scope),
191
- ...buildKey === void 0 ? {} : { buildKey }
231
+ ...buildKey === void 0 ? {} : { buildKey },
232
+ ...options?.storeBuild ? { storeBuild: "true" } : {},
233
+ ...options?.builtInOlderThan === void 0 ? {} : { builtInOlderThan: options.builtInOlderThan },
234
+ ...options?.artifactKind === void 0 ? {} : { kind: options.artifactKind }
192
235
  },
193
236
  requiredRoute: "native build"
194
237
  });
195
- return buildKey !== void 0 && row?.build_key !== buildKey ? null : row;
238
+ if (buildKey !== void 0 && row?.build_key !== buildKey) return null;
239
+ if (options?.artifactKind !== void 0 && row !== null && row.artifact_kind !== options.artifactKind) return null;
240
+ if (options?.storeBuild && row?.is_store_build !== true) return null;
241
+ const sandbox = scope.sandbox;
242
+ if (sandbox && row !== null && (row.is_sandbox !== true || row.artifact_kind !== sandbox.artifactKind || row.sandbox_url_scheme !== sandbox.urlScheme)) return null;
243
+ return row;
196
244
  },
245
+ findNativeBuildSibling: (build) => call("GET", `/native-builds/${encode(build.id)}/sibling`),
197
246
  listNativeBuilds: ({ channelId, ...input }) => list("/native-builds", {
198
247
  ...keysetParams(input),
199
248
  ...channelId === void 0 ? {} : { channelId }
@@ -236,6 +285,59 @@ const createStandaloneCoreApi = (config) => {
236
285
  body: submission,
237
286
  requiredRoute: "native build submission"
238
287
  }),
288
+ markNativeBuild: (id, mark) => call("POST", `/native-builds/${encode(id)}/store-build`, {
289
+ body: mark,
290
+ requiredRoute: "native build store mark"
291
+ }),
292
+ listIosDevices: async ({ status, ...input }) => await call("GET", "/ios-devices", {
293
+ query: {
294
+ ...keysetParams(input),
295
+ ...status === void 0 ? {} : { status }
296
+ },
297
+ requiredRoute: "iOS device registry"
298
+ }) ?? [],
299
+ findIosDevice: (udid) => call("GET", `/ios-devices/udid/${encode(udid)}`, { requiredRoute: "iOS device registry" }),
300
+ requestIosDevice: async (input) => await call("POST", "/ios-devices", {
301
+ body: input,
302
+ requiredRoute: "iOS device registry"
303
+ }),
304
+ approveIosDevice: (id, input) => call("POST", `/ios-devices/${encode(id)}/approval`, {
305
+ body: input,
306
+ requiredRoute: "iOS device registry"
307
+ }),
308
+ renameIosDevice: (id, name) => call("PATCH", `/ios-devices/${encode(id)}`, {
309
+ body: { name },
310
+ requiredRoute: "iOS device registry"
311
+ }),
312
+ recordIosDeviceOutcome: ({ id, ...input }) => call("POST", `/ios-devices/${encode(id)}/outcome`, {
313
+ body: input,
314
+ requiredRoute: "iOS device registry"
315
+ }),
316
+ markIosDevicesInBuild: async ({ buildId, ids }) => {
317
+ let start = 0;
318
+ do {
319
+ await request("POST", "/ios-devices/in-build", {
320
+ body: {
321
+ buildId,
322
+ ids: ids.slice(start, start + MAX_IDS)
323
+ },
324
+ requiredRoute: "iOS device registry"
325
+ });
326
+ start += MAX_IDS;
327
+ } while (start < ids.length);
328
+ },
329
+ findIosDeviceAccount: () => call("GET", "/ios-devices/account", { requiredRoute: "iOS device registry" }),
330
+ claimIosDeviceAccount: async (issuerId) => await call("POST", "/ios-devices/account", {
331
+ body: { issuerId },
332
+ requiredRoute: "iOS device registry"
333
+ }),
334
+ deleteIosDevice: (id, only) => call("DELETE", `/ios-devices/${encode(id)}`, {
335
+ query: {
336
+ ...only?.status === void 0 ? {} : { status: only.status },
337
+ ...only?.requestedBy === void 0 ? {} : { requestedBy: only.requestedBy }
338
+ },
339
+ requiredRoute: "iOS device registry"
340
+ }),
239
341
  deleteNativeBuild: async (id) => await call("DELETE", `/native-builds/${encode(id)}`, { requiredRoute: "native build deletion" })
240
342
  };
241
343
  };
@@ -252,8 +354,8 @@ const standaloneRepository = (config) => {
252
354
  return Object.freeze({
253
355
  name: "standalone-repository",
254
356
  core: createStandaloneCoreApi(config),
255
- fetchAdmin: (path, init = {}) => {
256
- const headers = new Headers(http.headers({ "Cache-Control": "no-cache" }));
357
+ fetchAdmin: async (path, init = {}) => {
358
+ const headers = new Headers(await http.headers({ "Cache-Control": "no-cache" }));
257
359
  new Headers(init.headers).forEach((value, name) => {
258
360
  headers.set(name, value);
259
361
  });
@@ -270,8 +372,12 @@ const defaultRoutes = {
270
372
  put: () => ({ path: "/upload" }),
271
373
  get: () => ({ path: "/get" }),
272
374
  exists: () => ({ path: "/exists" }),
273
- delete: () => ({ path: "/delete" })
375
+ delete: () => ({ path: "/delete" }),
376
+ listObjects: () => ({ path: "/list" }),
377
+ deleteObjects: () => ({ path: "/delete-objects" })
274
378
  };
379
+ /** Keys sent in one `deleteObjects` request. */
380
+ const DELETE_BATCH_SIZE = 1e3;
275
381
  const createRoute = (defaultRoute, customRoute) => ({
276
382
  path: customRoute?.path ?? defaultRoute.path,
277
383
  headers: {
@@ -280,8 +386,8 @@ const createRoute = (defaultRoute, customRoute) => ({
280
386
  }
281
387
  });
282
388
  const standaloneStorage = (config) => {
283
- const getHeaders = (routeHeaders) => ({
284
- ...config.commonHeaders,
389
+ const getHeaders = async (routeHeaders) => ({
390
+ ...await resolveHeaders(config.commonHeaders),
285
391
  ...routeHeaders
286
392
  });
287
393
  const resolveRoute = (name, args) => {
@@ -289,6 +395,14 @@ const standaloneStorage = (config) => {
289
395
  const custom = config.routes?.[name];
290
396
  return createRoute(fallback(...args), custom?.(...args));
291
397
  };
398
+ const postJson = async (path, headers, body) => fetch(`${config.baseUrl}${path}`, {
399
+ method: "POST",
400
+ headers: {
401
+ "content-type": "application/json",
402
+ ...await getHeaders(headers)
403
+ },
404
+ body: JSON.stringify(body)
405
+ });
292
406
  const requestStorageUri = async (routeName, storageUri) => {
293
407
  (0, _hot_updater_plugin_core.parseStorageUri)(storageUri, config.protocol);
294
408
  const { path, headers } = resolveRoute(routeName, [{ storageUri }]);
@@ -296,7 +410,7 @@ const standaloneStorage = (config) => {
296
410
  method: routeName === "delete" ? "DELETE" : "POST",
297
411
  headers: {
298
412
  "content-type": "application/json",
299
- ...getHeaders(headers)
413
+ ...await getHeaders(headers)
300
414
  },
301
415
  body: JSON.stringify({ storageUri })
302
416
  });
@@ -319,7 +433,7 @@ const standaloneStorage = (config) => {
319
433
  formData.append("key", key);
320
434
  const response = await fetch(`${config.baseUrl}${path}`, {
321
435
  method: "POST",
322
- headers: getHeaders(headers),
436
+ headers: await getHeaders(headers),
323
437
  body: formData
324
438
  });
325
439
  if (!response.ok) throw new Error(`Failed to upload bundle: ${response.statusText}`);
@@ -340,6 +454,39 @@ const standaloneStorage = (config) => {
340
454
  async delete({ storageUri }) {
341
455
  await requestStorageUri("delete", storageUri);
342
456
  return { deleted: true };
457
+ },
458
+ async listObjects(prefix) {
459
+ const { path, headers } = resolveRoute("listObjects", [{ prefix }]);
460
+ const objects = [];
461
+ let cursor;
462
+ do {
463
+ const response = await postJson(path, headers, {
464
+ prefix,
465
+ cursor
466
+ });
467
+ if (response.status === 404) throw new Error(`The storage service has no ${path} route, which storage prune needs.`);
468
+ if (!response.ok) throw new Error(`Failed to list storage objects: ${response.statusText}`);
469
+ const page = await response.json();
470
+ for (const object of page.objects) {
471
+ (0, _hot_updater_plugin_core.parseStorageUri)(object.storageUri, config.protocol);
472
+ objects.push({
473
+ key: object.key,
474
+ storageUri: object.storageUri,
475
+ size: object.size,
476
+ ...object.lastModifiedAt === void 0 ? {} : { lastModifiedAt: new Date(object.lastModifiedAt) }
477
+ });
478
+ }
479
+ cursor = page.cursor;
480
+ } while (cursor !== void 0);
481
+ return objects;
482
+ },
483
+ async deleteObjects(keys) {
484
+ for (let offset = 0; offset < keys.length; offset += DELETE_BATCH_SIZE) {
485
+ const batch = keys.slice(offset, offset + DELETE_BATCH_SIZE);
486
+ const { path, headers } = resolveRoute("deleteObjects", [{ keys: batch }]);
487
+ const response = await postJson(path, headers, { keys: batch });
488
+ if (!response.ok) throw new Error(`Failed to delete storage objects: ${response.statusText}`);
489
+ }
343
490
  }
344
491
  });
345
492
  };
package/dist/index.d.cts CHANGED
@@ -1,10 +1,14 @@
1
- import { HotUpdaterCoreApi, RemoteDatabase, StorageDeleteInput, StorageExistsInput, StorageGetInput, StoragePutInput } from "@hot-updater/plugin-core";
1
+ import { HotUpdaterCoreApi, Lazy, RemoteDatabase, StorageDeleteInput, StorageExistsInput, StorageGetInput, StorageObject, StoragePutInput } from "@hot-updater/plugin-core";
2
2
  //#region src/standaloneRoutes.d.ts
3
3
  interface StandaloneRepositoryConfig {
4
4
  /** Base URL of the Hot Updater admin handler. */
5
5
  readonly baseUrl: string;
6
- /** Headers sent with every admin request, such as its authorization. */
7
- readonly commonHeaders?: Readonly<Record<string, string>>;
6
+ /**
7
+ * Headers sent with every admin request, such as its authorization. A
8
+ * value may be a function that returns it, such as `secret("<name>")` in
9
+ * `hot-updater.config.ts`, called on the first request.
10
+ */
11
+ readonly commonHeaders?: Readonly<Record<string, Lazy<string>>>;
8
12
  }
9
13
  //#endregion
10
14
  //#region src/standaloneCore.d.ts
@@ -48,12 +52,25 @@ interface StorageRoutes {
48
52
  get: (input: StorageGetInput) => RouteConfig;
49
53
  exists: (input: StorageExistsInput) => RouteConfig;
50
54
  delete: (input: StorageDeleteInput) => RouteConfig;
55
+ /** Lists objects for `hot-updater storage prune`. */
56
+ listObjects: (input: {
57
+ readonly prefix?: string;
58
+ }) => RouteConfig;
59
+ /** Deletes exact keys for `hot-updater storage prune --yes`. */
60
+ deleteObjects: (input: {
61
+ readonly keys: readonly string[];
62
+ }) => RouteConfig;
51
63
  }
52
64
  interface StandaloneStorageConfig {
53
65
  baseUrl: string;
54
66
  /** Storage URI protocol owned by the remote implementation. */
55
67
  protocol: string;
56
- commonHeaders?: Record<string, string>;
68
+ /**
69
+ * Headers sent with every request. A value may be a function that returns
70
+ * it, such as `secret("<name>")` in `hot-updater.config.ts`, called on
71
+ * the first request.
72
+ */
73
+ commonHeaders?: Record<string, Lazy<string>>;
57
74
  routes?: Partial<StorageRoutes>;
58
75
  }
59
76
  declare const standaloneStorage: (config: StandaloneStorageConfig) => {
@@ -71,6 +88,8 @@ declare const standaloneStorage: (config: StandaloneStorageConfig) => {
71
88
  readonly delete: ({ storageUri }: StorageDeleteInput) => Promise<{
72
89
  deleted: true;
73
90
  }>;
91
+ readonly listObjects: (prefix?: string) => Promise<StorageObject[]>;
92
+ readonly deleteObjects: (keys: readonly string[]) => Promise<void>;
74
93
  };
75
94
  //#endregion
76
95
  export { RouteConfig, STANDALONE_ADMIN_PROTOCOL, StandaloneDatabaseError, StandaloneRepository, type StandaloneRepositoryConfig, StandaloneStorageConfig, StorageRoutes, createStandaloneCoreApi, standaloneRepository, standaloneStorage };
package/dist/index.d.mts CHANGED
@@ -1,10 +1,14 @@
1
- import { HotUpdaterCoreApi, RemoteDatabase, StorageDeleteInput, StorageExistsInput, StorageGetInput, StoragePutInput } from "@hot-updater/plugin-core";
1
+ import { HotUpdaterCoreApi, Lazy, RemoteDatabase, StorageDeleteInput, StorageExistsInput, StorageGetInput, StorageObject, StoragePutInput } from "@hot-updater/plugin-core";
2
2
  //#region src/standaloneRoutes.d.ts
3
3
  interface StandaloneRepositoryConfig {
4
4
  /** Base URL of the Hot Updater admin handler. */
5
5
  readonly baseUrl: string;
6
- /** Headers sent with every admin request, such as its authorization. */
7
- readonly commonHeaders?: Readonly<Record<string, string>>;
6
+ /**
7
+ * Headers sent with every admin request, such as its authorization. A
8
+ * value may be a function that returns it, such as `secret("<name>")` in
9
+ * `hot-updater.config.ts`, called on the first request.
10
+ */
11
+ readonly commonHeaders?: Readonly<Record<string, Lazy<string>>>;
8
12
  }
9
13
  //#endregion
10
14
  //#region src/standaloneCore.d.ts
@@ -48,12 +52,25 @@ interface StorageRoutes {
48
52
  get: (input: StorageGetInput) => RouteConfig;
49
53
  exists: (input: StorageExistsInput) => RouteConfig;
50
54
  delete: (input: StorageDeleteInput) => RouteConfig;
55
+ /** Lists objects for `hot-updater storage prune`. */
56
+ listObjects: (input: {
57
+ readonly prefix?: string;
58
+ }) => RouteConfig;
59
+ /** Deletes exact keys for `hot-updater storage prune --yes`. */
60
+ deleteObjects: (input: {
61
+ readonly keys: readonly string[];
62
+ }) => RouteConfig;
51
63
  }
52
64
  interface StandaloneStorageConfig {
53
65
  baseUrl: string;
54
66
  /** Storage URI protocol owned by the remote implementation. */
55
67
  protocol: string;
56
- commonHeaders?: Record<string, string>;
68
+ /**
69
+ * Headers sent with every request. A value may be a function that returns
70
+ * it, such as `secret("<name>")` in `hot-updater.config.ts`, called on
71
+ * the first request.
72
+ */
73
+ commonHeaders?: Record<string, Lazy<string>>;
57
74
  routes?: Partial<StorageRoutes>;
58
75
  }
59
76
  declare const standaloneStorage: (config: StandaloneStorageConfig) => {
@@ -71,6 +88,8 @@ declare const standaloneStorage: (config: StandaloneStorageConfig) => {
71
88
  readonly delete: ({ storageUri }: StorageDeleteInput) => Promise<{
72
89
  deleted: true;
73
90
  }>;
91
+ readonly listObjects: (prefix?: string) => Promise<StorageObject[]>;
92
+ readonly deleteObjects: (keys: readonly string[]) => Promise<void>;
74
93
  };
75
94
  //#endregion
76
95
  export { RouteConfig, STANDALONE_ADMIN_PROTOCOL, StandaloneDatabaseError, StandaloneRepository, type StandaloneRepositoryConfig, StandaloneStorageConfig, StorageRoutes, createStandaloneCoreApi, standaloneRepository, standaloneStorage };
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { DatabaseBundleNotFoundError, ReleaseCatalogMutationError, ReleaseManagementError, createStorageAdapter, parseStorageUri } from "@hot-updater/plugin-core";
1
+ import { DatabaseBundleNotFoundError, ReleaseCatalogCompilationError, ReleaseCatalogMutationError, ReleaseManagementError, compareUtf8, createStorageAdapter, parseStorageUri, resolveLazy } from "@hot-updater/plugin-core";
2
2
  //#region src/standaloneHttp.ts
3
3
  var StandaloneDatabaseError = class extends Error {
4
4
  code;
@@ -11,11 +11,13 @@ var StandaloneDatabaseError = class extends Error {
11
11
  }
12
12
  };
13
13
  const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
14
+ /** `headers` with each lazy value resolved. */
15
+ const resolveHeaders = async (headers = {}) => Object.fromEntries(await Promise.all(Object.entries(headers).map(async ([name, value]) => [name, await resolveLazy(value)])));
14
16
  const createStandaloneHttp = (config) => {
15
17
  const buildUrl = (path) => `${config.baseUrl.replace(/\/+$/, "")}${path}`;
16
- const headers = (routeHeaders) => ({
18
+ const headers = async (routeHeaders) => ({
17
19
  "Content-Type": "application/json",
18
- ...config.commonHeaders,
20
+ ...await resolveHeaders(config.commonHeaders),
19
21
  ...routeHeaders
20
22
  });
21
23
  const requestFailed = async (response) => {
@@ -67,21 +69,31 @@ const refusal = (status, value, fallback) => {
67
69
  const message = isRecord(value) && typeof value.error === "string" ? value.error : fallback;
68
70
  if (typeof code === "string" && MANAGEMENT_CODES.has(code)) return new ReleaseManagementError(code, message);
69
71
  if (typeof code === "string" && CATALOG_CODES.has(code)) return new ReleaseCatalogMutationError(code, message);
72
+ if (code === "CATALOG_OVERSIZE") return new ReleaseCatalogCompilationError(code, message);
70
73
  if (code === "BUNDLE_NOT_FOUND" && isRecord(value)) {
71
74
  const id = /"([^"]+)"/u.exec(message)?.[1] ?? "";
72
75
  return new DatabaseBundleNotFoundError(id);
73
76
  }
74
77
  return new StandaloneDatabaseError("request-failed", message, status);
75
78
  };
76
- const nativeBuildScopeParams = ({ platform, channel, fingerprintHash, appVersion }) => ({
79
+ const nativeBuildScopeParams = ({ platform, channel, fingerprintHash, appVersion, sandbox }) => ({
77
80
  platform,
78
81
  channel,
79
- ...fingerprintHash === null ? { appVersion } : { fingerprintHash }
82
+ ...fingerprintHash === null ? { appVersion } : { fingerprintHash },
83
+ ...sandbox === void 0 || sandbox === null ? {} : {
84
+ sandboxAppId: sandbox.appId,
85
+ sandboxUrlScheme: sandbox.urlScheme,
86
+ artifactKind: sandbox.artifactKind,
87
+ distribution: sandbox.distribution
88
+ }
80
89
  });
81
- const keysetParams = ({ order, after, limit }) => ({
90
+ /** The most IDs the admin API takes in one request. */
91
+ const MAX_IDS = 100;
92
+ const keysetParams = ({ order, after, through, limit }) => ({
82
93
  limit: String(limit),
83
94
  ...order === void 0 ? {} : { order },
84
- ...after === void 0 ? {} : { cursor: after }
95
+ ...after === void 0 ? {} : { cursor: after },
96
+ ...through === void 0 ? {} : { through }
85
97
  });
86
98
  const filterParams = (filter) => {
87
99
  switch (filter.kind) {
@@ -107,7 +119,7 @@ const createStandaloneCoreApi = (config) => {
107
119
  const http = createStandaloneHttp(config);
108
120
  let checked;
109
121
  const checkProtocol = async () => {
110
- const response = await fetch(http.buildUrl("/version"), { headers: http.headers({ "Cache-Control": "no-cache" }) });
122
+ const response = await fetch(http.buildUrl("/version"), { headers: await http.headers({ "Cache-Control": "no-cache" }) });
111
123
  const body = response.status === 404 ? {} : await http.parseJson(response);
112
124
  const protocol = isRecord(body) ? body.adminProtocol : void 0;
113
125
  if (typeof protocol !== "number" || protocol < 2) throw new StandaloneDatabaseError("request-failed", `The server at ${config.baseUrl} does not report Hot Updater admin API protocol 2 at /version. Set baseUrl to the path where the server mounts handlers.admin, such as https://example.com/hot-updater/admin.`, response.status);
@@ -124,7 +136,7 @@ const createStandaloneCoreApi = (config) => {
124
136
  for (const [key, value] of Object.entries(query)) url.searchParams.set(key, value);
125
137
  const response = await fetch(url, {
126
138
  method,
127
- headers: http.headers(method === "GET" ? { "Cache-Control": "no-cache" } : void 0),
139
+ headers: await http.headers(method === "GET" ? { "Cache-Control": "no-cache" } : void 0),
128
140
  ...body === void 0 ? {} : { body: JSON.stringify(body) }
129
141
  });
130
142
  if (response.status === 204) return null;
@@ -179,20 +191,57 @@ const createStandaloneCoreApi = (config) => {
179
191
  }),
180
192
  getReleaseCatalogRow: (scopeKey) => call("GET", `/release-catalogs/${encode(scopeKey)}`),
181
193
  listReleaseCatalogs: (input) => list("/release-catalogs", keysetParams(input)),
182
- listChannels: () => list("/channels", {}),
194
+ listReleaseScopeKeys: async ({ after, limit }) => await call("GET", "/release-scopes", {
195
+ query: {
196
+ limit: String(limit),
197
+ ...after === void 0 ? {} : { cursor: after }
198
+ },
199
+ requiredRoute: "release scope"
200
+ }) ?? [],
201
+ listChannels: async (input) => {
202
+ if (input === void 0) return list("/channels", {});
203
+ const rows = await list("/channels", keysetParams(input));
204
+ const desc = input.order === "desc";
205
+ const { after, through } = input;
206
+ const past = (name, bound) => desc ? compareUtf8(name, bound) < 0 : compareUtf8(name, bound) > 0;
207
+ return rows.filter(({ name }) => (after === void 0 || past(name, after)) && (through === void 0 || !past(name, through))).sort((left, right) => desc ? compareUtf8(right.name, left.name) : compareUtf8(left.name, right.name)).slice(0, input.limit);
208
+ },
209
+ getChannels: async (ids) => {
210
+ const unique = [...new Set(ids)];
211
+ const found = /* @__PURE__ */ new Map();
212
+ for (let start = 0; start < unique.length; start += MAX_IDS) {
213
+ const chunk = unique.slice(start, start + MAX_IDS);
214
+ const asked = new Set(chunk);
215
+ for (const row of await list("/channels", { ids: chunk.join(",") })) if (asked.has(row.id)) found.set(row.id, row);
216
+ }
217
+ return unique.flatMap((id) => {
218
+ const row = found.get(id);
219
+ return row === void 0 ? [] : [row];
220
+ });
221
+ },
183
222
  findChannelByName: (name) => call("GET", "/channels", { query: { name } }),
184
223
  getNativeBuild: (id) => call("GET", `/native-builds/${encode(id)}`, { requiredRoute: "native build" }),
224
+ findNativeBuildByBuiltInBundle: (bundleId) => call("GET", `/native-builds/built-in/${encode(bundleId)}`, { requiredRoute: "native build" }),
185
225
  findNativeBuild: async (scope, options) => {
186
226
  const buildKey = options?.buildKey;
187
227
  const row = await call("GET", "/native-builds/latest", {
188
228
  query: {
189
229
  ...nativeBuildScopeParams(scope),
190
- ...buildKey === void 0 ? {} : { buildKey }
230
+ ...buildKey === void 0 ? {} : { buildKey },
231
+ ...options?.storeBuild ? { storeBuild: "true" } : {},
232
+ ...options?.builtInOlderThan === void 0 ? {} : { builtInOlderThan: options.builtInOlderThan },
233
+ ...options?.artifactKind === void 0 ? {} : { kind: options.artifactKind }
191
234
  },
192
235
  requiredRoute: "native build"
193
236
  });
194
- return buildKey !== void 0 && row?.build_key !== buildKey ? null : row;
237
+ if (buildKey !== void 0 && row?.build_key !== buildKey) return null;
238
+ if (options?.artifactKind !== void 0 && row !== null && row.artifact_kind !== options.artifactKind) return null;
239
+ if (options?.storeBuild && row?.is_store_build !== true) return null;
240
+ const sandbox = scope.sandbox;
241
+ if (sandbox && row !== null && (row.is_sandbox !== true || row.artifact_kind !== sandbox.artifactKind || row.sandbox_url_scheme !== sandbox.urlScheme)) return null;
242
+ return row;
195
243
  },
244
+ findNativeBuildSibling: (build) => call("GET", `/native-builds/${encode(build.id)}/sibling`),
196
245
  listNativeBuilds: ({ channelId, ...input }) => list("/native-builds", {
197
246
  ...keysetParams(input),
198
247
  ...channelId === void 0 ? {} : { channelId }
@@ -235,6 +284,59 @@ const createStandaloneCoreApi = (config) => {
235
284
  body: submission,
236
285
  requiredRoute: "native build submission"
237
286
  }),
287
+ markNativeBuild: (id, mark) => call("POST", `/native-builds/${encode(id)}/store-build`, {
288
+ body: mark,
289
+ requiredRoute: "native build store mark"
290
+ }),
291
+ listIosDevices: async ({ status, ...input }) => await call("GET", "/ios-devices", {
292
+ query: {
293
+ ...keysetParams(input),
294
+ ...status === void 0 ? {} : { status }
295
+ },
296
+ requiredRoute: "iOS device registry"
297
+ }) ?? [],
298
+ findIosDevice: (udid) => call("GET", `/ios-devices/udid/${encode(udid)}`, { requiredRoute: "iOS device registry" }),
299
+ requestIosDevice: async (input) => await call("POST", "/ios-devices", {
300
+ body: input,
301
+ requiredRoute: "iOS device registry"
302
+ }),
303
+ approveIosDevice: (id, input) => call("POST", `/ios-devices/${encode(id)}/approval`, {
304
+ body: input,
305
+ requiredRoute: "iOS device registry"
306
+ }),
307
+ renameIosDevice: (id, name) => call("PATCH", `/ios-devices/${encode(id)}`, {
308
+ body: { name },
309
+ requiredRoute: "iOS device registry"
310
+ }),
311
+ recordIosDeviceOutcome: ({ id, ...input }) => call("POST", `/ios-devices/${encode(id)}/outcome`, {
312
+ body: input,
313
+ requiredRoute: "iOS device registry"
314
+ }),
315
+ markIosDevicesInBuild: async ({ buildId, ids }) => {
316
+ let start = 0;
317
+ do {
318
+ await request("POST", "/ios-devices/in-build", {
319
+ body: {
320
+ buildId,
321
+ ids: ids.slice(start, start + MAX_IDS)
322
+ },
323
+ requiredRoute: "iOS device registry"
324
+ });
325
+ start += MAX_IDS;
326
+ } while (start < ids.length);
327
+ },
328
+ findIosDeviceAccount: () => call("GET", "/ios-devices/account", { requiredRoute: "iOS device registry" }),
329
+ claimIosDeviceAccount: async (issuerId) => await call("POST", "/ios-devices/account", {
330
+ body: { issuerId },
331
+ requiredRoute: "iOS device registry"
332
+ }),
333
+ deleteIosDevice: (id, only) => call("DELETE", `/ios-devices/${encode(id)}`, {
334
+ query: {
335
+ ...only?.status === void 0 ? {} : { status: only.status },
336
+ ...only?.requestedBy === void 0 ? {} : { requestedBy: only.requestedBy }
337
+ },
338
+ requiredRoute: "iOS device registry"
339
+ }),
238
340
  deleteNativeBuild: async (id) => await call("DELETE", `/native-builds/${encode(id)}`, { requiredRoute: "native build deletion" })
239
341
  };
240
342
  };
@@ -251,8 +353,8 @@ const standaloneRepository = (config) => {
251
353
  return Object.freeze({
252
354
  name: "standalone-repository",
253
355
  core: createStandaloneCoreApi(config),
254
- fetchAdmin: (path, init = {}) => {
255
- const headers = new Headers(http.headers({ "Cache-Control": "no-cache" }));
356
+ fetchAdmin: async (path, init = {}) => {
357
+ const headers = new Headers(await http.headers({ "Cache-Control": "no-cache" }));
256
358
  new Headers(init.headers).forEach((value, name) => {
257
359
  headers.set(name, value);
258
360
  });
@@ -269,8 +371,12 @@ const defaultRoutes = {
269
371
  put: () => ({ path: "/upload" }),
270
372
  get: () => ({ path: "/get" }),
271
373
  exists: () => ({ path: "/exists" }),
272
- delete: () => ({ path: "/delete" })
374
+ delete: () => ({ path: "/delete" }),
375
+ listObjects: () => ({ path: "/list" }),
376
+ deleteObjects: () => ({ path: "/delete-objects" })
273
377
  };
378
+ /** Keys sent in one `deleteObjects` request. */
379
+ const DELETE_BATCH_SIZE = 1e3;
274
380
  const createRoute = (defaultRoute, customRoute) => ({
275
381
  path: customRoute?.path ?? defaultRoute.path,
276
382
  headers: {
@@ -279,8 +385,8 @@ const createRoute = (defaultRoute, customRoute) => ({
279
385
  }
280
386
  });
281
387
  const standaloneStorage = (config) => {
282
- const getHeaders = (routeHeaders) => ({
283
- ...config.commonHeaders,
388
+ const getHeaders = async (routeHeaders) => ({
389
+ ...await resolveHeaders(config.commonHeaders),
284
390
  ...routeHeaders
285
391
  });
286
392
  const resolveRoute = (name, args) => {
@@ -288,6 +394,14 @@ const standaloneStorage = (config) => {
288
394
  const custom = config.routes?.[name];
289
395
  return createRoute(fallback(...args), custom?.(...args));
290
396
  };
397
+ const postJson = async (path, headers, body) => fetch(`${config.baseUrl}${path}`, {
398
+ method: "POST",
399
+ headers: {
400
+ "content-type": "application/json",
401
+ ...await getHeaders(headers)
402
+ },
403
+ body: JSON.stringify(body)
404
+ });
291
405
  const requestStorageUri = async (routeName, storageUri) => {
292
406
  parseStorageUri(storageUri, config.protocol);
293
407
  const { path, headers } = resolveRoute(routeName, [{ storageUri }]);
@@ -295,7 +409,7 @@ const standaloneStorage = (config) => {
295
409
  method: routeName === "delete" ? "DELETE" : "POST",
296
410
  headers: {
297
411
  "content-type": "application/json",
298
- ...getHeaders(headers)
412
+ ...await getHeaders(headers)
299
413
  },
300
414
  body: JSON.stringify({ storageUri })
301
415
  });
@@ -318,7 +432,7 @@ const standaloneStorage = (config) => {
318
432
  formData.append("key", key);
319
433
  const response = await fetch(`${config.baseUrl}${path}`, {
320
434
  method: "POST",
321
- headers: getHeaders(headers),
435
+ headers: await getHeaders(headers),
322
436
  body: formData
323
437
  });
324
438
  if (!response.ok) throw new Error(`Failed to upload bundle: ${response.statusText}`);
@@ -339,6 +453,39 @@ const standaloneStorage = (config) => {
339
453
  async delete({ storageUri }) {
340
454
  await requestStorageUri("delete", storageUri);
341
455
  return { deleted: true };
456
+ },
457
+ async listObjects(prefix) {
458
+ const { path, headers } = resolveRoute("listObjects", [{ prefix }]);
459
+ const objects = [];
460
+ let cursor;
461
+ do {
462
+ const response = await postJson(path, headers, {
463
+ prefix,
464
+ cursor
465
+ });
466
+ if (response.status === 404) throw new Error(`The storage service has no ${path} route, which storage prune needs.`);
467
+ if (!response.ok) throw new Error(`Failed to list storage objects: ${response.statusText}`);
468
+ const page = await response.json();
469
+ for (const object of page.objects) {
470
+ parseStorageUri(object.storageUri, config.protocol);
471
+ objects.push({
472
+ key: object.key,
473
+ storageUri: object.storageUri,
474
+ size: object.size,
475
+ ...object.lastModifiedAt === void 0 ? {} : { lastModifiedAt: new Date(object.lastModifiedAt) }
476
+ });
477
+ }
478
+ cursor = page.cursor;
479
+ } while (cursor !== void 0);
480
+ return objects;
481
+ },
482
+ async deleteObjects(keys) {
483
+ for (let offset = 0; offset < keys.length; offset += DELETE_BATCH_SIZE) {
484
+ const batch = keys.slice(offset, offset + DELETE_BATCH_SIZE);
485
+ const { path, headers } = resolveRoute("deleteObjects", [{ keys: batch }]);
486
+ const response = await postJson(path, headers, { keys: batch });
487
+ if (!response.ok) throw new Error(`Failed to delete storage objects: ${response.statusText}`);
488
+ }
342
489
  }
343
490
  });
344
491
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hot-updater/standalone",
3
- "version": "1.2.0-rc.5",
3
+ "version": "1.2.0-rc.50",
4
4
  "type": "module",
5
5
  "description": "React Native OTA solution for self-hosted",
6
6
  "sideEffects": false,
@@ -42,8 +42,8 @@
42
42
  "access": "public"
43
43
  },
44
44
  "dependencies": {
45
- "@hot-updater/protocol": "1.2.0-rc.5",
46
- "@hot-updater/plugin-core": "1.2.0-rc.5"
45
+ "@hot-updater/protocol": "1.2.0-rc.50",
46
+ "@hot-updater/plugin-core": "1.2.0-rc.50"
47
47
  },
48
48
  "devDependencies": {
49
49
  "mime": "2.6.0",
@@ -52,12 +52,7 @@
52
52
  "msw": "^2.7.0",
53
53
  "verkit": "0.4.0",
54
54
  "vitest": "4.1.4",
55
- "@hot-updater/test-utils": "1.2.0-rc.5"
56
- },
57
- "nx": {
58
- "implicitDependencies": [
59
- "!@hot-updater/test-utils"
60
- ]
55
+ "@hot-updater/test-utils": "1.2.0-rc.50"
61
56
  },
62
57
  "scripts": {
63
58
  "build": "tsdown",