percher 1.4.0 → 1.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.
@@ -4854,7 +4854,7 @@ var package_default;
4854
4854
  var init_package = __esm(() => {
4855
4855
  package_default = {
4856
4856
  name: "@percher/client",
4857
- version: "1.4.0",
4857
+ version: "1.5.0",
4858
4858
  description: "Official TypeScript SDK for Percher: deploy apps, manage env vars, stream logs, and automate hosting workflows.",
4859
4859
  keywords: [
4860
4860
  "percher",
@@ -4895,8 +4895,8 @@ var init_package = __esm(() => {
4895
4895
  typecheck: "tsc --noEmit"
4896
4896
  },
4897
4897
  dependencies: {
4898
- "@percher/shared": "^1.3.0",
4899
- "@percher/toml": "^1.0.5"
4898
+ "@percher/shared": "^1.4.0",
4899
+ "@percher/toml": "^1.1.0"
4900
4900
  },
4901
4901
  devDependencies: {
4902
4902
  "bun-types": "^1.1.0",
@@ -5013,8 +5013,8 @@ class Http {
5013
5013
  get(path, opts) {
5014
5014
  return this.request("GET", path, undefined, opts?.signal);
5015
5015
  }
5016
- post(path, body) {
5017
- return this.request("POST", path, body);
5016
+ post(path, body, opts) {
5017
+ return this.request("POST", path, body, opts?.signal);
5018
5018
  }
5019
5019
  put(path, body) {
5020
5020
  return this.request("PUT", path, body);
@@ -5043,6 +5043,154 @@ class Http {
5043
5043
  throw await this.parseError(res);
5044
5044
  return res;
5045
5045
  }
5046
+ async exportCapability(method, path, capability, signal) {
5047
+ if (!/^pce_[A-Za-z0-9_-]{43}$/.test(capability) || !(method === "GET" && path === "/export/v2/status" || method === "POST" && (path === "/export/v2/prepare" || path === "/export/v2/grants"))) {
5048
+ throw new PercherApiError("Invalid export request.", {
5049
+ status: 400,
5050
+ code: "EXPORT_INVALID_REQUEST"
5051
+ });
5052
+ }
5053
+ const headers = this.buildHeaders();
5054
+ headers.Authorization = `Bearer ${capability}`;
5055
+ const operationSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(30000)]) : AbortSignal.timeout(30000);
5056
+ let res;
5057
+ try {
5058
+ operationSignal.throwIfAborted();
5059
+ res = await this.fetchImpl(`${this.apiUrl}${path}`, {
5060
+ method,
5061
+ headers,
5062
+ signal: operationSignal,
5063
+ redirect: "error"
5064
+ });
5065
+ } catch {
5066
+ signal?.throwIfAborted();
5067
+ throw new NetworkError("Export preparation request failed.");
5068
+ }
5069
+ if (!res.ok) {
5070
+ throw await this.exportError(res, operationSignal, signal, "Export request refused. Check its status before retrying.");
5071
+ }
5072
+ const validStatus = path.endsWith("/grants") ? res.status === 201 : path.endsWith("/prepare") ? res.status === 200 || res.status === 202 : res.status === 200;
5073
+ if (!validStatus || res.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase() !== "application/json" || !res.body) {
5074
+ res.body?.cancel().catch(() => {});
5075
+ throw new PercherApiError("Invalid export response.", {
5076
+ status: 502,
5077
+ code: "EXPORT_INVALID_RESPONSE"
5078
+ });
5079
+ }
5080
+ const reader = res.body.getReader();
5081
+ const abortRead = () => {
5082
+ reader.cancel().catch(() => {});
5083
+ };
5084
+ operationSignal.addEventListener("abort", abortRead, { once: true });
5085
+ if (operationSignal.aborted)
5086
+ abortRead();
5087
+ const chunks = [];
5088
+ let length = 0;
5089
+ try {
5090
+ for (;; ) {
5091
+ operationSignal.throwIfAborted();
5092
+ const part = await reader.read();
5093
+ if (part.done)
5094
+ break;
5095
+ length += part.value.byteLength;
5096
+ if (length > 8192)
5097
+ throw new Error;
5098
+ chunks.push(part.value);
5099
+ }
5100
+ operationSignal.throwIfAborted();
5101
+ const bytes = new Uint8Array(length);
5102
+ let offset = 0;
5103
+ for (const chunk of chunks) {
5104
+ bytes.set(chunk, offset);
5105
+ offset += chunk.byteLength;
5106
+ }
5107
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
5108
+ } catch {
5109
+ reader.cancel().catch(() => {});
5110
+ signal?.throwIfAborted();
5111
+ throw new PercherApiError("Invalid export response.", {
5112
+ status: 502,
5113
+ code: "EXPORT_INVALID_RESPONSE"
5114
+ });
5115
+ } finally {
5116
+ operationSignal.removeEventListener("abort", abortRead);
5117
+ reader.releaseLock();
5118
+ }
5119
+ }
5120
+ async exportDownload(path, signal) {
5121
+ if (!/^\/export\/download\/pcd_[A-Za-z0-9_-]{43}$/.test(path)) {
5122
+ throw new PercherApiError("Invalid export download.", {
5123
+ status: 400,
5124
+ code: "EXPORT_INVALID_REQUEST"
5125
+ });
5126
+ }
5127
+ let res;
5128
+ try {
5129
+ signal?.throwIfAborted();
5130
+ res = await this.fetchImpl(`${this.apiUrl}${path}`, {
5131
+ headers: { ...this.buildHeaders(), Accept: "application/gzip" },
5132
+ signal,
5133
+ redirect: "error"
5134
+ });
5135
+ } catch {
5136
+ signal?.throwIfAborted();
5137
+ throw new NetworkError("Export download failed.");
5138
+ }
5139
+ if (!res.ok) {
5140
+ const operationSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(30000)]) : AbortSignal.timeout(30000);
5141
+ throw await this.exportError(res, operationSignal, signal, "Export download refused. Request a new download grant if it was spent.");
5142
+ }
5143
+ return res;
5144
+ }
5145
+ async exportError(res, operationSignal, callerSignal, message) {
5146
+ const invalid = () => new PercherApiError("Invalid export response.", {
5147
+ status: 502,
5148
+ code: "EXPORT_INVALID_RESPONSE"
5149
+ });
5150
+ if (!res.body)
5151
+ return invalid();
5152
+ const reader = res.body.getReader();
5153
+ const cancel = () => {
5154
+ reader.cancel().catch(() => {});
5155
+ };
5156
+ operationSignal.addEventListener("abort", cancel, { once: true });
5157
+ if (operationSignal.aborted)
5158
+ cancel();
5159
+ try {
5160
+ const chunks = [];
5161
+ let length = 0;
5162
+ for (;; ) {
5163
+ operationSignal.throwIfAborted();
5164
+ const part = await reader.read();
5165
+ if (part.done)
5166
+ break;
5167
+ length += part.value.byteLength;
5168
+ if (length > 8192)
5169
+ throw new Error;
5170
+ chunks.push(part.value);
5171
+ }
5172
+ operationSignal.throwIfAborted();
5173
+ const bytes = new Uint8Array(length);
5174
+ let offset = 0;
5175
+ for (const chunk of chunks) {
5176
+ bytes.set(chunk, offset);
5177
+ offset += chunk.byteLength;
5178
+ }
5179
+ const raw = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
5180
+ const error = raw && typeof raw === "object" && !Array.isArray(raw) ? raw.error : null;
5181
+ const code = error && typeof error === "object" && !Array.isArray(error) ? error.code : null;
5182
+ if (typeof code !== "string" || !EXPORT_ERROR_CODES.has(code))
5183
+ return invalid();
5184
+ return new PercherApiError(message, { status: res.status, code });
5185
+ } catch {
5186
+ cancel();
5187
+ callerSignal?.throwIfAborted();
5188
+ return invalid();
5189
+ } finally {
5190
+ operationSignal.removeEventListener("abort", cancel);
5191
+ reader.releaseLock();
5192
+ }
5193
+ }
5046
5194
  async getBinary(path) {
5047
5195
  const headers = this.buildHeaders();
5048
5196
  let res;
@@ -5166,10 +5314,32 @@ class Http {
5166
5314
  });
5167
5315
  }
5168
5316
  }
5169
- var BODY_SNIPPET_MAX = 120;
5317
+ var BODY_SNIPPET_MAX = 120, EXPORT_ERROR_CODES;
5170
5318
  var init_http = __esm(() => {
5171
5319
  init_package();
5172
5320
  init_errors();
5321
+ EXPORT_ERROR_CODES = new Set([
5322
+ "EXPORT_NOT_FOUND",
5323
+ "EXPORT_CONFLICT",
5324
+ "EXPORT_BUSY",
5325
+ "EXPORT_NOT_READY",
5326
+ "EXPORT_DISPATCH_BUSY",
5327
+ "EXPORT_DELIVERY_BUSY",
5328
+ "EXPORT_DELIVERY_NOT_FOUND",
5329
+ "EXPORT_DELIVERY_EXHAUSTED",
5330
+ "EXPORT_DELIVERY_UNAVAILABLE",
5331
+ "EXPORT_DELIVERY_ABORTED",
5332
+ "EXPORT_GRANT_SPENT",
5333
+ "EXPORT_EXPIRED",
5334
+ "EXPORT_RATE_LIMIT",
5335
+ "EXPORT_CAPACITY",
5336
+ "EXPORT_LEDGER_UNAVAILABLE",
5337
+ "EXPORT_LOCK_UNAVAILABLE",
5338
+ "EXPORT_UNAVAILABLE",
5339
+ "EXPORT_V2_UNAVAILABLE",
5340
+ "UNAUTHORIZED",
5341
+ "FORBIDDEN"
5342
+ ]);
5173
5343
  });
5174
5344
 
5175
5345
  // ../client/dist/resources/account.js
@@ -5244,6 +5414,47 @@ class AnonResource {
5244
5414
  }
5245
5415
  }
5246
5416
 
5417
+ // ../client/dist/resources/app-mcp.js
5418
+ class AppMcpResource {
5419
+ http;
5420
+ constructor(http) {
5421
+ this.http = http;
5422
+ }
5423
+ get(appRef) {
5424
+ return this.http.get(`/apps/${encodeURIComponent(appRef)}/app-mcp`);
5425
+ }
5426
+ accept(appRef, input) {
5427
+ return this.http.post(`/apps/${encodeURIComponent(appRef)}/app-mcp/accept`, input);
5428
+ }
5429
+ disable(appRef) {
5430
+ return this.http.post(`/apps/${encodeURIComponent(appRef)}/app-mcp/disable`, {});
5431
+ }
5432
+ }
5433
+
5434
+ // ../client/dist/resources/apps-publish.js
5435
+ function publishInline(http, input) {
5436
+ const params = new URLSearchParams;
5437
+ params.set("name", input.name);
5438
+ params.set("runtime", input.runtime);
5439
+ if (input.framework)
5440
+ params.set("framework", input.framework);
5441
+ if (input.check)
5442
+ params.set("check", "1");
5443
+ else if (input.type === "preview")
5444
+ params.set("type", "preview");
5445
+ if (input.note)
5446
+ params.set("note", input.note);
5447
+ if (input.noCache)
5448
+ params.set("noCache", "1");
5449
+ const headers = {};
5450
+ if (input.tarballHash)
5451
+ headers["X-Tarball-Hash"] = input.tarballHash;
5452
+ if (input.emitBytes !== undefined && Number.isFinite(input.emitBytes) && input.emitBytes >= 0) {
5453
+ headers["X-Percher-Emit-Bytes"] = String(Math.round(input.emitBytes));
5454
+ }
5455
+ return http.postBinary(`/apps/publish?${params.toString()}`, input.tarball, headers);
5456
+ }
5457
+
5247
5458
  // ../client/dist/resources/apps-types.js
5248
5459
  function isDeployAlreadyInProgress(res) {
5249
5460
  return res.status === "already_in_progress";
@@ -5303,27 +5514,11 @@ class AppsResource {
5303
5514
  }
5304
5515
  return this.http.postBinary(`/apps/${encodeURIComponent(id)}/deploys${qs ? `?${qs}` : ""}`, input.tarball, headers);
5305
5516
  }
5517
+ publishPatch(appRef, input) {
5518
+ return this.http.post(`/apps/${encodeURIComponent(appRef)}/publish/patch`, input);
5519
+ }
5306
5520
  publishInline(input) {
5307
- const params = new URLSearchParams;
5308
- params.set("name", input.name);
5309
- params.set("runtime", input.runtime);
5310
- if (input.framework)
5311
- params.set("framework", input.framework);
5312
- if (input.check)
5313
- params.set("check", "1");
5314
- else if (input.type === "preview")
5315
- params.set("type", "preview");
5316
- if (input.note)
5317
- params.set("note", input.note);
5318
- if (input.noCache)
5319
- params.set("noCache", "1");
5320
- const headers = {};
5321
- if (input.tarballHash)
5322
- headers["X-Tarball-Hash"] = input.tarballHash;
5323
- if (input.emitBytes !== undefined && Number.isFinite(input.emitBytes) && input.emitBytes >= 0) {
5324
- headers["X-Percher-Emit-Bytes"] = String(Math.round(input.emitBytes));
5325
- }
5326
- return this.http.postBinary(`/apps/publish?${params.toString()}`, input.tarball, headers);
5521
+ return publishInline(this.http, input);
5327
5522
  }
5328
5523
  promotePreview(appRef, deployId) {
5329
5524
  return this.http.post(`/apps/${encodeURIComponent(appRef)}/deploys/${encodeURIComponent(deployId)}/promote`, {});
@@ -5825,11 +6020,91 @@ class EnvScanResource {
5825
6020
  }
5826
6021
 
5827
6022
  // ../client/dist/resources/export.js
6023
+ function invalid() {
6024
+ throw new PercherApiError("Server did not provide a valid export v2 response. No legacy export was downloaded.", { status: 502, code: "EXPORT_INVALID_RESPONSE" });
6025
+ }
6026
+ function record2(value, keys) {
6027
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).sort().join("|") !== keys.sort().join("|"))
6028
+ return invalid();
6029
+ return value;
6030
+ }
6031
+ function instant(value) {
6032
+ return typeof value === "string" && value.length === 24 && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
6033
+ }
6034
+ function identifier2(value) {
6035
+ return typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(value);
6036
+ }
6037
+ function status(value) {
6038
+ const v = record2(value, ["operationId", "state", "revision", "deadline", "cleanupReason"]);
6039
+ if (!identifier2(v.operationId) || typeof v.state !== "string" || !["NOT_REQUESTED", "REQUESTED", "PREPARING", "READY", "CLEANUP_REQUIRED"].includes(v.state) || typeof v.revision !== "number" || !Number.isSafeInteger(v.revision) || v.revision < 0 || typeof v.deadline !== "number" || !Number.isSafeInteger(v.deadline) || v.deadline <= 0 || (v.state === "CLEANUP_REQUIRED" ? typeof v.cleanupReason !== "string" || !["INTERRUPTED", "AUTHORITY_LOST", "EXPIRED", "PROCESSOR_FAILED"].includes(v.cleanupReason) : v.cleanupReason !== null))
6040
+ return invalid();
6041
+ return Object.freeze({ ...v });
6042
+ }
6043
+
5828
6044
  class ExportResource {
5829
6045
  http;
5830
6046
  constructor(http) {
5831
6047
  this.http = http;
5832
6048
  }
6049
+ async mintV2(appRef, options) {
6050
+ const value = await this.http.post(`/apps/${encodeURIComponent(appRef)}/export/mint`, { protocolVersion: 2, deliveryKind: options?.deliveryKind ?? "cli" }, { signal: options?.signal });
6051
+ const v = record2(value, [
6052
+ "protocolVersion",
6053
+ "operationId",
6054
+ "tokenId",
6055
+ "preparationToken",
6056
+ "expiresAt",
6057
+ "ttlSeconds",
6058
+ "includeSecrets"
6059
+ ]);
6060
+ if (v.protocolVersion !== 2 || !identifier2(v.operationId) || !identifier2(v.tokenId) || typeof v.preparationToken !== "string" || !/^pce_[A-Za-z0-9_-]{43}$/.test(v.preparationToken) || !instant(v.expiresAt) || Date.parse(v.expiresAt) > Date.now() + 900000 || v.ttlSeconds !== 900 || v.includeSecrets !== false)
6061
+ return invalid();
6062
+ if (Date.parse(v.expiresAt) <= Date.now())
6063
+ throw new PercherApiError("Export preparation expired. Start a new export.", {
6064
+ status: 410,
6065
+ code: "EXPORT_EXPIRED"
6066
+ });
6067
+ return Object.freeze({ ...v });
6068
+ }
6069
+ async prepareV2(capability, signal) {
6070
+ return status(await this.http.exportCapability("POST", "/export/v2/prepare", capability, signal));
6071
+ }
6072
+ async statusV2(capability, signal) {
6073
+ return status(await this.http.exportCapability("GET", "/export/v2/status", capability, signal));
6074
+ }
6075
+ async grantV2(capability, signal, options) {
6076
+ const v = record2(await this.http.exportCapability("POST", "/export/v2/grants", capability, signal), ["downloadUrl", "expiresAt"]);
6077
+ if (typeof v.downloadUrl !== "string" || !instant(v.expiresAt) || Date.parse(v.expiresAt) <= Date.now())
6078
+ return invalid();
6079
+ this.v2DownloadPath(v.downloadUrl, options?.publicDownloadOrigin);
6080
+ return Object.freeze({ downloadUrl: v.downloadUrl, expiresAt: v.expiresAt });
6081
+ }
6082
+ v2DownloadPath(downloadUrl, publicDownloadOrigin) {
6083
+ try {
6084
+ const base = new URL(this.http.baseUrl());
6085
+ const expected = publicDownloadOrigin === undefined ? base.origin : publicDownloadOrigin;
6086
+ const configured = new URL(expected);
6087
+ if (!["http:", "https:"].includes(configured.protocol) || configured.origin !== expected)
6088
+ return invalid();
6089
+ const url = new URL(downloadUrl, configured);
6090
+ if (url.origin !== expected || url.username || url.password || url.search || url.hash || !/^\/export\/download\/pcd_[A-Za-z0-9_-]{43}$/.test(url.pathname))
6091
+ return invalid();
6092
+ return url.pathname;
6093
+ } catch {
6094
+ return invalid();
6095
+ }
6096
+ }
6097
+ async downloadV2(downloadUrl, signal) {
6098
+ const res = await this.http.exportDownload(this.v2DownloadPath(downloadUrl), signal);
6099
+ const size = res.headers.get("x-export-bytes");
6100
+ const contentLength = res.headers.get("content-length");
6101
+ const sha256 = res.headers.get("x-export-sha256");
6102
+ if (res.status !== 200 || res.headers.get("content-type") !== "application/gzip" || !res.body || res.body.locked || !size || !/^[1-9][0-9]*$/.test(size) || !Number.isSafeInteger(Number(size)) || Number(size) > 2 ** 40 || contentLength !== null && contentLength !== size || !sha256 || !/^[a-f0-9]{64}$/.test(sha256) || ![null, "identity"].includes(res.headers.get("content-encoding"))) {
6103
+ res.body?.cancel().catch(() => {});
6104
+ return invalid();
6105
+ }
6106
+ return { response: res, bytes: Number(size), sha256 };
6107
+ }
5833
6108
  mint(appRef, options) {
5834
6109
  return this.http.post(`/apps/${encodeURIComponent(appRef)}/export/mint`, {
5835
6110
  deliveryKind: options?.deliveryKind
@@ -5852,6 +6127,9 @@ class ExportResource {
5852
6127
  return this.http.get(`/apps/${encodeURIComponent(appRef)}/export/git/check`);
5853
6128
  }
5854
6129
  }
6130
+ var init_export = __esm(() => {
6131
+ init_errors();
6132
+ });
5855
6133
 
5856
6134
  // ../client/dist/resources/hooks.js
5857
6135
  class HooksResource {
@@ -6107,6 +6385,79 @@ class InvitesResource {
6107
6385
  }
6108
6386
  }
6109
6387
 
6388
+ // ../client/dist/resources/source.js
6389
+ class SourceResource {
6390
+ http;
6391
+ constructor(http) {
6392
+ this.http = http;
6393
+ }
6394
+ base(appRef, version) {
6395
+ return `/apps/${encodeURIComponent(appRef)}/versions/${encodeURIComponent(version)}`;
6396
+ }
6397
+ listFiles(appRef, version = "live") {
6398
+ return this.http.get(`${this.base(appRef, version)}/files`);
6399
+ }
6400
+ getFile(appRef, path, version = "live") {
6401
+ const qs = new URLSearchParams({ path }).toString();
6402
+ return this.http.get(`${this.base(appRef, version)}/file?${qs}`);
6403
+ }
6404
+ getConfig(appRef, sha) {
6405
+ return this.http.get(`${this.base(appRef, sha)}/config`);
6406
+ }
6407
+ getManifest(appRef, sha) {
6408
+ return this.http.get(`${this.base(appRef, sha)}/manifest`);
6409
+ }
6410
+ }
6411
+
6412
+ // ../client/dist/resources/source-reviews.js
6413
+ class SourceReviewsResource {
6414
+ http;
6415
+ constructor(http) {
6416
+ this.http = http;
6417
+ }
6418
+ base(appRef) {
6419
+ return `/apps/${encodeURIComponent(appRef)}/source-reviews`;
6420
+ }
6421
+ query(options) {
6422
+ const query = new URLSearchParams;
6423
+ if (options?.afterId)
6424
+ query.set("afterId", options.afterId);
6425
+ if (options?.limit !== undefined)
6426
+ query.set("limit", String(options.limit));
6427
+ return query.size ? `?${query}` : "";
6428
+ }
6429
+ list(appRef, options) {
6430
+ return this.http.get(this.base(appRef) + this.query(options));
6431
+ }
6432
+ submit(appRef, assessmentId, findingId, bytes, consent) {
6433
+ if (consent !== "complete-file" || bytes.byteLength > 1024 * 1024)
6434
+ throw new Error("Complete file consent and at most 1 MiB required");
6435
+ return this.http.postBinary(`${this.base(appRef)}/${encodeURIComponent(assessmentId)}/${encodeURIComponent(findingId)}`, bytes, {
6436
+ "X-Percher-Source-Review-Consent": consent
6437
+ });
6438
+ }
6439
+ get(appRef, requestId) {
6440
+ return this.http.get(`${this.base(appRef)}/requests/${encodeURIComponent(requestId)}`);
6441
+ }
6442
+ withdraw(appRef, requestId, revision) {
6443
+ return this.http.post(`${this.base(appRef)}/requests/${encodeURIComponent(requestId)}/withdraw`, { revision });
6444
+ }
6445
+ listAdmin(options) {
6446
+ return this.http.get(`/admin/source-reviews${this.query(options)}`);
6447
+ }
6448
+ open(requestId) {
6449
+ return this.http.post(`/admin/source-reviews/${encodeURIComponent(requestId)}/open`, {});
6450
+ }
6451
+ decide(requestId, decision) {
6452
+ return this.http.post(`/admin/source-reviews/${encodeURIComponent(requestId)}/decide`, decision);
6453
+ }
6454
+ revoke(requestId, revision) {
6455
+ return this.http.post(`/admin/source-reviews/${encodeURIComponent(requestId)}/revoke`, {
6456
+ revision
6457
+ });
6458
+ }
6459
+ }
6460
+
6110
6461
  // ../client/dist/resources/support.js
6111
6462
  class SupportResource {
6112
6463
  http;
@@ -6192,6 +6543,7 @@ class PercherClient {
6192
6543
  sessionId;
6193
6544
  clientVersion;
6194
6545
  apps;
6546
+ appMcp;
6195
6547
  anon;
6196
6548
  data;
6197
6549
  env;
@@ -6210,6 +6562,8 @@ class PercherClient {
6210
6562
  invites;
6211
6563
  transfers;
6212
6564
  support;
6565
+ source;
6566
+ sourceReviews;
6213
6567
  constructor(options = {}) {
6214
6568
  const bothExplicit = options.apiUrl !== undefined && options.token !== undefined;
6215
6569
  const defaults = bothExplicit ? undefined : loadConfig();
@@ -6243,6 +6597,9 @@ class PercherClient {
6243
6597
  this.invites = new InvitesResource(http);
6244
6598
  this.transfers = new TransfersResource(http);
6245
6599
  this.support = new SupportResource(http);
6600
+ this.source = new SourceResource(http);
6601
+ this.sourceReviews = new SourceReviewsResource(http);
6602
+ this.appMcp = new AppMcpResource(http);
6246
6603
  }
6247
6604
  }
6248
6605
  var init_client = __esm(() => {
@@ -6251,6 +6608,7 @@ var init_client = __esm(() => {
6251
6608
  init_apps();
6252
6609
  init_auth();
6253
6610
  init_data();
6611
+ init_export();
6254
6612
  init_logs();
6255
6613
  });
6256
6614
 
@@ -6430,6 +6788,7 @@ var init_dist = __esm(() => {
6430
6788
  init_apps();
6431
6789
  init_auth();
6432
6790
  init_data();
6791
+ init_export();
6433
6792
  init_logs();
6434
6793
  init_telemetry_consent();
6435
6794
  });
@@ -91958,101 +92317,62 @@ function detectCiBranchMessage(env) {
91958
92317
  }
91959
92318
  var MAX_BRANCH_LEN = 80;
91960
92319
 
91961
- // src/env-set-input.ts
91962
- function trimTrailingNewline(s) {
91963
- return s.replace(/\r?\n$/, "");
91964
- }
91965
- function isBareKey(arg) {
91966
- return !arg.includes("=");
91967
- }
91968
- async function resolveEnvSetInputs(opts) {
91969
- const { args, fromStdin, fromFile, fromEnvFile } = opts;
91970
- if (fromEnvFile && fromStdin) {
91971
- throw new EnvSetInputError("Cannot combine --from-env-file and --from-stdin");
91972
- }
91973
- if (fromEnvFile && fromFile) {
91974
- throw new EnvSetInputError("Cannot combine --from-env-file and --from-file");
91975
- }
91976
- if (fromStdin && fromFile) {
91977
- throw new EnvSetInputError("Cannot combine --from-stdin and --from-file");
91978
- }
91979
- if (fromEnvFile) {
91980
- if (args.length > 0) {
91981
- throw new EnvSetInputError("--from-env-file takes no KEY arguments — every KEY=VALUE line in the file is set");
91982
- }
91983
- let raw;
91984
- try {
91985
- raw = await opts.readFile(fromEnvFile);
91986
- } catch (err) {
91987
- const message = err instanceof Error ? err.message : String(err);
91988
- throw new EnvSetInputError(`Couldn't read ${fromEnvFile}: ${message}`);
91989
- }
91990
- const parsed = parseEnvFile(raw);
91991
- if (parsed.invalidLines.length > 0) {
91992
- const listing = parsed.invalidLines.map((l) => {
91993
- const redacted = redactEnvLine(l.text);
91994
- return `line ${l.lineNumber}${redacted ? `: ${redacted}` : ""}`;
91995
- }).join(`
91996
- `);
91997
- throw new EnvSetInputError(`Nothing was set. These lines in ${fromEnvFile} are not NAME=VALUE with a name of A-Z, 0-9 and _ (not starting with a digit, at most 256 characters):
91998
- ${listing}`);
91999
- }
92000
- if (parsed.entries.length === 0) {
92001
- throw new EnvSetInputError(`No KEY=VALUE lines found in ${fromEnvFile}`);
92002
- }
92003
- const out = {};
92004
- for (const entry of parsed.entries) {
92005
- out[entry.key] = entry.value;
92006
- }
92007
- return out;
92320
+ // src/data-oauth-input.ts
92321
+ async function readOauthSecretStdin(input) {
92322
+ const chunks = [];
92323
+ let size = 0;
92324
+ try {
92325
+ for await (const chunk of input) {
92326
+ const bytes = Buffer.from(chunk);
92327
+ size += bytes.length;
92328
+ if (size > MAX_SECRET_BYTES)
92329
+ throw new OauthSecretInputError("Client secret exceeds 64 KiB.");
92330
+ chunks.push(bytes);
92331
+ }
92332
+ } catch (error) {
92333
+ if (error instanceof OauthSecretInputError)
92334
+ throw error;
92335
+ throw new OauthSecretInputError("Could not read client secret from stdin.");
92008
92336
  }
92009
- if (fromStdin || fromFile) {
92010
- if (args.length !== 1) {
92011
- throw new EnvSetInputError("--from-stdin/--from-file expects exactly one KEY (without =VALUE)");
92012
- }
92013
- const key = args[0] ?? "";
92014
- if (!isBareKey(key)) {
92015
- throw new EnvSetInputError("--from-stdin/--from-file expects bare KEY, not KEY=VALUE");
92016
- }
92017
- const raw = fromStdin ? await opts.readStdin() : await opts.readFile(fromFile ?? "");
92018
- const value = trimTrailingNewline(raw);
92019
- if (value.length === 0) {
92020
- throw new EnvSetInputError(`Empty value for ${key}`);
92021
- }
92022
- return { [key]: value };
92337
+ return Buffer.concat(chunks).toString("utf8");
92338
+ }
92339
+ async function resolveOauthSecret(options) {
92340
+ const argv = options.clientSecret !== undefined;
92341
+ const stdin = options.fromStdin === true;
92342
+ const configuring = options.clientId !== undefined;
92343
+ if (argv && stdin)
92344
+ throw new OauthSecretInputError("Choose --client-secret or --client-secret-stdin, not both.");
92345
+ if (options.remove && (configuring || argv || stdin)) {
92346
+ throw new OauthSecretInputError("Do not combine --remove with OAuth credentials.");
92023
92347
  }
92024
- const out = {};
92025
- for (const arg of args) {
92026
- if (isBareKey(arg)) {
92027
- const value = await opts.promptHidden(`Value for ${arg}:`);
92028
- if (value.length === 0) {
92029
- throw new EnvSetInputError(`Empty value for ${arg}`);
92030
- }
92031
- out[arg] = value;
92032
- } else {
92033
- const eqIdx = arg.indexOf("=");
92034
- const key = arg.slice(0, eqIdx);
92035
- const value = arg.slice(eqIdx + 1);
92036
- if (key.length === 0) {
92037
- throw new EnvSetInputError(`Empty key in "${arg}"`);
92038
- }
92039
- if (value.length === 0) {
92040
- throw new EnvSetInputError(`Empty value for ${key}`);
92041
- }
92042
- out[key] = value;
92043
- }
92348
+ if (options.remove)
92349
+ return;
92350
+ if (!configuring) {
92351
+ if (argv || stdin)
92352
+ throw new OauthSecretInputError("--client-id is required when supplying a client secret.");
92353
+ return;
92044
92354
  }
92045
- return out;
92355
+ if (!options.clientId?.trim())
92356
+ throw new OauthSecretInputError("Client ID must not be empty.");
92357
+ let value;
92358
+ try {
92359
+ value = argv ? options.clientSecret : stdin ? (await options.readStdin()).replace(/\r?\n$/, "") : await options.promptHidden("OAuth client secret:");
92360
+ } catch {
92361
+ throw new OauthSecretInputError("Could not read client secret.");
92362
+ }
92363
+ if (!value.length)
92364
+ throw new OauthSecretInputError("Client secret must not be empty.");
92365
+ if (Buffer.byteLength(value, "utf8") > MAX_SECRET_BYTES)
92366
+ throw new OauthSecretInputError("Client secret exceeds 64 KiB.");
92367
+ if (argv)
92368
+ await options.warn();
92369
+ return value;
92046
92370
  }
92047
- var EnvSetInputError;
92048
- var init_env_set_input = __esm(() => {
92049
- init_dist();
92050
- EnvSetInputError = class EnvSetInputError extends Error {
92051
- constructor(message) {
92052
- super(message);
92053
- this.name = "EnvSetInputError";
92054
- }
92371
+ var OauthSecretInputError, MAX_SECRET_BYTES;
92372
+ var init_data_oauth_input = __esm(() => {
92373
+ OauthSecretInputError = class OauthSecretInputError extends Error {
92055
92374
  };
92375
+ MAX_SECRET_BYTES = 64 * 1024;
92056
92376
  });
92057
92377
 
92058
92378
  // src/prompt-hidden.ts
@@ -92148,6 +92468,103 @@ async function promptHidden(question) {
92148
92468
  }
92149
92469
  var init_prompt_hidden = () => {};
92150
92470
 
92471
+ // src/env-set-input.ts
92472
+ function trimTrailingNewline(s) {
92473
+ return s.replace(/\r?\n$/, "");
92474
+ }
92475
+ function isBareKey(arg) {
92476
+ return !arg.includes("=");
92477
+ }
92478
+ async function resolveEnvSetInputs(opts) {
92479
+ const { args, fromStdin, fromFile, fromEnvFile } = opts;
92480
+ if (fromEnvFile && fromStdin) {
92481
+ throw new EnvSetInputError("Cannot combine --from-env-file and --from-stdin");
92482
+ }
92483
+ if (fromEnvFile && fromFile) {
92484
+ throw new EnvSetInputError("Cannot combine --from-env-file and --from-file");
92485
+ }
92486
+ if (fromStdin && fromFile) {
92487
+ throw new EnvSetInputError("Cannot combine --from-stdin and --from-file");
92488
+ }
92489
+ if (fromEnvFile) {
92490
+ if (args.length > 0) {
92491
+ throw new EnvSetInputError("--from-env-file takes no KEY arguments — every KEY=VALUE line in the file is set");
92492
+ }
92493
+ let raw;
92494
+ try {
92495
+ raw = await opts.readFile(fromEnvFile);
92496
+ } catch (err) {
92497
+ const message = err instanceof Error ? err.message : String(err);
92498
+ throw new EnvSetInputError(`Couldn't read ${fromEnvFile}: ${message}`);
92499
+ }
92500
+ const parsed = parseEnvFile(raw);
92501
+ if (parsed.invalidLines.length > 0) {
92502
+ const listing = parsed.invalidLines.map((l) => {
92503
+ const redacted = redactEnvLine(l.text);
92504
+ return `line ${l.lineNumber}${redacted ? `: ${redacted}` : ""}`;
92505
+ }).join(`
92506
+ `);
92507
+ throw new EnvSetInputError(`Nothing was set. These lines in ${fromEnvFile} are not NAME=VALUE with a name of A-Z, 0-9 and _ (not starting with a digit, at most 256 characters):
92508
+ ${listing}`);
92509
+ }
92510
+ if (parsed.entries.length === 0) {
92511
+ throw new EnvSetInputError(`No KEY=VALUE lines found in ${fromEnvFile}`);
92512
+ }
92513
+ const out = {};
92514
+ for (const entry of parsed.entries) {
92515
+ out[entry.key] = entry.value;
92516
+ }
92517
+ return out;
92518
+ }
92519
+ if (fromStdin || fromFile) {
92520
+ if (args.length !== 1) {
92521
+ throw new EnvSetInputError("--from-stdin/--from-file expects exactly one KEY (without =VALUE)");
92522
+ }
92523
+ const key = args[0] ?? "";
92524
+ if (!isBareKey(key)) {
92525
+ throw new EnvSetInputError("--from-stdin/--from-file expects bare KEY, not KEY=VALUE");
92526
+ }
92527
+ const raw = fromStdin ? await opts.readStdin() : await opts.readFile(fromFile ?? "");
92528
+ const value = trimTrailingNewline(raw);
92529
+ if (value.length === 0) {
92530
+ throw new EnvSetInputError(`Empty value for ${key}`);
92531
+ }
92532
+ return { [key]: value };
92533
+ }
92534
+ const out = {};
92535
+ for (const arg of args) {
92536
+ if (isBareKey(arg)) {
92537
+ const value = await opts.promptHidden(`Value for ${arg}:`);
92538
+ if (value.length === 0) {
92539
+ throw new EnvSetInputError(`Empty value for ${arg}`);
92540
+ }
92541
+ out[arg] = value;
92542
+ } else {
92543
+ const eqIdx = arg.indexOf("=");
92544
+ const key = arg.slice(0, eqIdx);
92545
+ const value = arg.slice(eqIdx + 1);
92546
+ if (key.length === 0) {
92547
+ throw new EnvSetInputError(`Empty key in "${arg}"`);
92548
+ }
92549
+ if (value.length === 0) {
92550
+ throw new EnvSetInputError(`Empty value for ${key}`);
92551
+ }
92552
+ out[key] = value;
92553
+ }
92554
+ }
92555
+ return out;
92556
+ }
92557
+ var EnvSetInputError;
92558
+ var init_env_set_input = __esm(() => {
92559
+ init_dist();
92560
+ EnvSetInputError = class EnvSetInputError extends Error {
92561
+ constructor(message) {
92562
+ super(message);
92563
+ this.name = "EnvSetInputError";
92564
+ }
92565
+ };
92566
+ });
92567
+
92151
92568
  // ../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/toml.js
92152
92569
  var exports_toml = {};
92153
92570
  __exportCjs(exports_toml, {
@@ -93006,8 +93423,8 @@ var EMAIL_BRAND_HEADER = `<p style="margin:0 0 20px;line-height:28px;">
93006
93423
  // ../shared/dist/legal.js
93007
93424
  var LEGAL_DOCUMENT_VERSIONS = {
93008
93425
  terms: "1.0.3",
93009
- aup: "1.0.1",
93010
- privacy: "1.0.4",
93426
+ aup: "1.1.1",
93427
+ privacy: "1.1.1",
93011
93428
  cookies: "1.0.4",
93012
93429
  dpa: "1.1",
93013
93430
  subprocessors: "1.2",
@@ -93059,6 +93476,40 @@ var PROXY_LOWERCASE_ALIASES = new Set([
93059
93476
  // ../shared/dist/runtime.js
93060
93477
  var DEFAULT_NODE_VERSION_MAJOR = "24";
93061
93478
  var DEFAULT_NODE_VERSION_LABEL = `${DEFAULT_NODE_VERSION_MAJOR} LTS`;
93479
+ // ../shared/dist/secret-source-paths.js
93480
+ var SECRET_BASENAMES = new Set([
93481
+ ".npmrc",
93482
+ ".pypirc",
93483
+ ".netrc",
93484
+ "_netrc",
93485
+ ".git-credentials",
93486
+ ".htpasswd",
93487
+ ".pgpass",
93488
+ ".my.cnf",
93489
+ ".dev.vars",
93490
+ "id_rsa",
93491
+ "id_dsa",
93492
+ "id_ecdsa",
93493
+ "id_ed25519",
93494
+ "credentials.json",
93495
+ "secrets.toml",
93496
+ "wp-config.php"
93497
+ ]);
93498
+ var SECRET_PREFIXES = [".dev.vars."];
93499
+ var ENV_NAMES = [".env", ".envrc"];
93500
+ var ENV_PREFIXES = [".env.", ".env-", ".env_"];
93501
+ var ENV_FILE_IGNORE_PATTERNS = [
93502
+ ...ENV_NAMES,
93503
+ ...ENV_PREFIXES.map((p) => `${p}*`)
93504
+ ];
93505
+ var SECRET_EXTENSIONS = [".pem", ".key", ".p12", ".pfx", ".jks", ".keystore"];
93506
+ var SECRET_DIRS = new Set([".ssh", ".aws", ".gnupg"]);
93507
+ var SECRET_PATH_SUFFIXES = [".docker/config.json", ".kube/config"];
93508
+ var STATIC_CREDENTIAL_PATH_PATTERN = `(?i)(?:^|/)(?:${[
93509
+ ...[...SECRET_BASENAMES, ...ENV_NAMES, ...SECRET_DIRS, ...SECRET_PATH_SUFFIXES].map((p) => p.replaceAll(".", "[.]")),
93510
+ ...[...ENV_PREFIXES, ...SECRET_PREFIXES].map((p) => `${p.replaceAll(".", "[.]")}[^/]*`),
93511
+ ...SECRET_EXTENSIONS.map((p) => `[^/]*${p.replaceAll(".", "[.]")}`)
93512
+ ].join("|")})(?:/|$)`;
93062
93513
  // ../shared/dist/signup-day.js
93063
93514
  var stockholmDate = new Intl.DateTimeFormat("sv-SE", {
93064
93515
  timeZone: "Europe/Stockholm",
@@ -93076,6 +93527,47 @@ var stockholmClock = new Intl.DateTimeFormat("en-GB", {
93076
93527
  second: "2-digit",
93077
93528
  hourCycle: "h23"
93078
93529
  });
93530
+ // ../shared/dist/static-platform-paths.js
93531
+ var STATIC_PLATFORM_ROOT_PATTERNS = [
93532
+ "percher.toml",
93533
+ ".percherignore",
93534
+ "pb",
93535
+ "Dockerfile",
93536
+ "Caddyfile",
93537
+ ".git",
93538
+ ".env",
93539
+ ".env.*",
93540
+ ".percher-*"
93541
+ ];
93542
+ var STATIC_PLATFORM_PATH_REGEX = `(?i)(?:^/+(?:${STATIC_PLATFORM_ROOT_PATTERNS.map((p) => p.replaceAll(".", "[.]").replaceAll("*", "[^/]*")).join("|")})(?:/|$)|${STATIC_CREDENTIAL_PATH_PATTERN.slice(4)})`;
93543
+ var reserved = new RegExp(STATIC_PLATFORM_PATH_REGEX.slice(4), "i");
93544
+ function isStaticPlatformPath(path) {
93545
+ const segments = [];
93546
+ for (const segment of path.replaceAll("\\", "/").split("/")) {
93547
+ if (!segment || segment === ".")
93548
+ continue;
93549
+ if (segment === "..")
93550
+ segments.pop();
93551
+ else
93552
+ segments.push(segment);
93553
+ }
93554
+ return reserved.test(`/${segments.join("/")}`);
93555
+ }
93556
+ function normalizeStaticOutputDir(output) {
93557
+ const value = output ?? "";
93558
+ if (typeof value !== "string" || value.startsWith("/") || value.includes("\\") || /^[a-z]:/i.test(value) || [...value].some((ch) => ch.charCodeAt(0) < 32 || ch.charCodeAt(0) === 127) || value.split("/").includes(".."))
93559
+ throw new Error("Static output must stay inside the project as a relative directory.");
93560
+ const normalized = value.split("/").filter((p) => p && p !== ".").join("/") || ".";
93561
+ if (isStaticPlatformPath(normalized))
93562
+ throw new Error("Static output cannot select reserved platform content.");
93563
+ return normalized;
93564
+ }
93565
+ function staticPlatformDenyDirectives() {
93566
+ return [
93567
+ `@percher_platform path_regexp percher_platform ${STATIC_PLATFORM_PATH_REGEX}`,
93568
+ "respond @percher_platform 404"
93569
+ ];
93570
+ }
93079
93571
  // ../shared/dist/switches.js
93080
93572
  var ONE = ["1"];
93081
93573
  var TRUE = ["true"];
@@ -93090,6 +93582,11 @@ var bool = (name, readers, purpose, enabled, def = "disabled", disabled = OFF_SP
93090
93582
  default: def
93091
93583
  });
93092
93584
  var SWITCHES = [
93585
+ bool("PERCHER_SOURCE_REVIEW_ENABLED", ["api", "worker", "dashboard"], "accept voluntary source-review submissions and browser staff decisions", ONE, "disabled", ["0"]),
93586
+ bool("PERCHER_PB_CREDENTIAL_LEDGER", ["api", "worker"], "serialize owner PocketBase reset with durable credential evidence", ONE, "disabled"),
93587
+ bool("PERCHER_EXPORT_V2", ["api", "dashboard"], "prepare verified encrypted exports before separate one-use binary delivery", ONE, "disabled"),
93588
+ bool("PERCHER_BACKUP_VOLUME_REQUIRED", ["api", "worker"], "require verified backup Volume identity; missing or invalid state never falls back to root storage", ONE, "disabled", ["0"]),
93589
+ bool("PERCHER_DOCKER_REQUIRE_SECRET_MOUNTS", ["api", "worker"], "refuse private Docker build arguments after owners migrate to secret mounts (rollout gate; default off)", ONE),
93093
93590
  bool("PERCHER_NODE_USE_DOCKERFILE", ["api"], 'Node/Bun apps build through the Percher Dockerfile instead of Nixpacks (default; "0" is the emergency lever)', ONE, "enabled", ["0"]),
93094
93591
  bool("PERCHER_PYTHON_USE_DOCKERFILE", ["api"], 'Python apps build through the Percher Dockerfile instead of Nixpacks (default; "0" is the emergency lever)', ONE, "enabled", ["0"]),
93095
93592
  bool("PERCHER_OPS_BUILD_TRIAGE", ["api"], "append the internal cold-build triage block to build logs", ONE),
@@ -93197,6 +93694,795 @@ var TIMEOUTS = {
93197
93694
  };
93198
93695
  // ../shared/dist/waitlist.js
93199
93696
  var WAITLIST_THROTTLE_WINDOW_MS = 60 * 60 * 1000;
93697
+ // ../../node_modules/.bun/croner@10.0.1/node_modules/croner/dist/croner.js
93698
+ function T(s) {
93699
+ return Date.UTC(s.y, s.m - 1, s.d, s.h, s.i, s.s);
93700
+ }
93701
+ function D(s, e) {
93702
+ return s.y === e.y && s.m === e.m && s.d === e.d && s.h === e.h && s.i === e.i && s.s === e.s;
93703
+ }
93704
+ function A(s, e) {
93705
+ let t = new Date(Date.parse(s));
93706
+ if (isNaN(t))
93707
+ throw new Error("Invalid ISO8601 passed to timezone parser.");
93708
+ let r = s.substring(9);
93709
+ return r.includes("Z") || r.includes("+") || r.includes("-") ? b(t.getUTCFullYear(), t.getUTCMonth() + 1, t.getUTCDate(), t.getUTCHours(), t.getUTCMinutes(), t.getUTCSeconds(), "Etc/UTC") : b(t.getFullYear(), t.getMonth() + 1, t.getDate(), t.getHours(), t.getMinutes(), t.getSeconds(), e);
93710
+ }
93711
+ function v(s, e, t) {
93712
+ return k(A(s, e), t);
93713
+ }
93714
+ function k(s, e) {
93715
+ let t = new Date(T(s)), r = g(t, s.tz), n = T(s), i = T(r), a = n - i, o = new Date(t.getTime() + a), h = g(o, s.tz);
93716
+ if (D(h, s)) {
93717
+ let u = new Date(o.getTime() - 3600000), d = g(u, s.tz);
93718
+ return D(d, s) ? u : o;
93719
+ }
93720
+ let l = new Date(o.getTime() + T(s) - T(h)), y = g(l, s.tz);
93721
+ if (D(y, s))
93722
+ return l;
93723
+ if (e)
93724
+ throw new Error("Invalid date passed to fromTZ()");
93725
+ return o.getTime() > l.getTime() ? o : l;
93726
+ }
93727
+ function g(s, e) {
93728
+ let t, r;
93729
+ try {
93730
+ t = new Intl.DateTimeFormat("en-US", { timeZone: e, year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", second: "numeric", hour12: false }), r = t.formatToParts(s);
93731
+ } catch (i) {
93732
+ let a = i instanceof Error ? i.message : String(i);
93733
+ throw new RangeError(`toTZ: Invalid timezone '${e}' or date. Please provide a valid IANA timezone (e.g., 'America/New_York', 'Europe/Stockholm'). Original error: ${a}`);
93734
+ }
93735
+ let n = { year: 0, month: 0, day: 0, hour: 0, minute: 0, second: 0 };
93736
+ for (let i of r)
93737
+ (i.type === "year" || i.type === "month" || i.type === "day" || i.type === "hour" || i.type === "minute" || i.type === "second") && (n[i.type] = parseInt(i.value, 10));
93738
+ if (isNaN(n.year) || isNaN(n.month) || isNaN(n.day) || isNaN(n.hour) || isNaN(n.minute) || isNaN(n.second))
93739
+ throw new Error(`toTZ: Failed to parse all date components from timezone '${e}'. This may indicate an invalid date or timezone configuration. Parsed components: ${JSON.stringify(n)}`);
93740
+ return n.hour === 24 && (n.hour = 0), { y: n.year, m: n.month, d: n.day, h: n.hour, i: n.minute, s: n.second, tz: e };
93741
+ }
93742
+ function b(s, e, t, r, n, i, a) {
93743
+ return { y: s, m: e, d: t, h: r, i: n, s: i, tz: a };
93744
+ }
93745
+ var O = [1, 2, 4, 8, 16];
93746
+ var C = class {
93747
+ pattern;
93748
+ timezone;
93749
+ mode;
93750
+ alternativeWeekdays;
93751
+ sloppyRanges;
93752
+ second;
93753
+ minute;
93754
+ hour;
93755
+ day;
93756
+ month;
93757
+ dayOfWeek;
93758
+ year;
93759
+ lastDayOfMonth;
93760
+ lastWeekday;
93761
+ nearestWeekdays;
93762
+ starDOM;
93763
+ starDOW;
93764
+ starYear;
93765
+ useAndLogic;
93766
+ constructor(e, t, r) {
93767
+ this.pattern = e, this.timezone = t, this.mode = r?.mode ?? "auto", this.alternativeWeekdays = r?.alternativeWeekdays ?? false, this.sloppyRanges = r?.sloppyRanges ?? false, this.second = Array(60).fill(0), this.minute = Array(60).fill(0), this.hour = Array(24).fill(0), this.day = Array(31).fill(0), this.month = Array(12).fill(0), this.dayOfWeek = Array(7).fill(0), this.year = Array(1e4).fill(0), this.lastDayOfMonth = false, this.lastWeekday = false, this.nearestWeekdays = Array(31).fill(0), this.starDOM = false, this.starDOW = false, this.starYear = false, this.useAndLogic = false, this.parse();
93768
+ }
93769
+ parse() {
93770
+ if (!(typeof this.pattern == "string" || this.pattern instanceof String))
93771
+ throw new TypeError("CronPattern: Pattern has to be of type string.");
93772
+ this.pattern.indexOf("@") >= 0 && (this.pattern = this.handleNicknames(this.pattern).trim());
93773
+ let e = this.pattern.match(/\S+/g) || [""], t = e.length;
93774
+ if (e.length < 5 || e.length > 7)
93775
+ throw new TypeError("CronPattern: invalid configuration format ('" + this.pattern + "'), exactly five, six, or seven space separated parts are required.");
93776
+ if (this.mode !== "auto") {
93777
+ let n;
93778
+ switch (this.mode) {
93779
+ case "5-part":
93780
+ n = 5;
93781
+ break;
93782
+ case "6-part":
93783
+ n = 6;
93784
+ break;
93785
+ case "7-part":
93786
+ n = 7;
93787
+ break;
93788
+ case "5-or-6-parts":
93789
+ n = [5, 6];
93790
+ break;
93791
+ case "6-or-7-parts":
93792
+ n = [6, 7];
93793
+ break;
93794
+ default:
93795
+ n = 0;
93796
+ }
93797
+ if (!(Array.isArray(n) ? n.includes(t) : t === n)) {
93798
+ let a = Array.isArray(n) ? n.join(" or ") : n.toString();
93799
+ throw new TypeError(`CronPattern: mode '${this.mode}' requires exactly ${a} parts, but pattern '${this.pattern}' has ${t} parts.`);
93800
+ }
93801
+ }
93802
+ if (e.length === 5 && e.unshift("0"), e.length === 6 && e.push("*"), e[3].toUpperCase() === "LW" ? (this.lastWeekday = true, e[3] = "") : e[3].toUpperCase().indexOf("L") >= 0 && (e[3] = e[3].replace(/L/gi, ""), this.lastDayOfMonth = true), e[3] == "*" && (this.starDOM = true), e[6] == "*" && (this.starYear = true), e[4].length >= 3 && (e[4] = this.replaceAlphaMonths(e[4])), e[5].length >= 3 && (e[5] = this.alternativeWeekdays ? this.replaceAlphaDaysQuartz(e[5]) : this.replaceAlphaDays(e[5])), e[5].startsWith("+") && (this.useAndLogic = true, e[5] = e[5].substring(1), e[5] === ""))
93803
+ throw new TypeError("CronPattern: Day-of-week field cannot be empty after '+' modifier.");
93804
+ switch (e[5] == "*" && (this.starDOW = true), this.pattern.indexOf("?") >= 0 && (e[0] = e[0].replace(/\?/g, "*"), e[1] = e[1].replace(/\?/g, "*"), e[2] = e[2].replace(/\?/g, "*"), e[3] = e[3].replace(/\?/g, "*"), e[4] = e[4].replace(/\?/g, "*"), e[5] = e[5].replace(/\?/g, "*"), e[6] && (e[6] = e[6].replace(/\?/g, "*"))), this.mode) {
93805
+ case "5-part":
93806
+ e[0] = "0", e[6] = "*";
93807
+ break;
93808
+ case "6-part":
93809
+ e[6] = "*";
93810
+ break;
93811
+ case "5-or-6-parts":
93812
+ e[6] = "*";
93813
+ break;
93814
+ case "6-or-7-parts":
93815
+ break;
93816
+ case "7-part":
93817
+ case "auto":
93818
+ break;
93819
+ }
93820
+ this.throwAtIllegalCharacters(e), this.partToArray("second", e[0], 0, 1), this.partToArray("minute", e[1], 0, 1), this.partToArray("hour", e[2], 0, 1), this.partToArray("day", e[3], -1, 1), this.partToArray("month", e[4], -1, 1);
93821
+ let r = this.alternativeWeekdays ? -1 : 0;
93822
+ this.partToArray("dayOfWeek", e[5], r, 63), this.partToArray("year", e[6], 0, 1), !this.alternativeWeekdays && this.dayOfWeek[7] && (this.dayOfWeek[0] = this.dayOfWeek[7]);
93823
+ }
93824
+ partToArray(e, t, r, n) {
93825
+ let i = this[e], a = e === "day" && this.lastDayOfMonth, o = e === "day" && this.lastWeekday;
93826
+ if (t === "" && !a && !o)
93827
+ throw new TypeError("CronPattern: configuration entry " + e + " (" + t + ") is empty, check for trailing spaces.");
93828
+ if (t === "*")
93829
+ return i.fill(n);
93830
+ let h = t.split(",");
93831
+ if (h.length > 1)
93832
+ for (let l = 0;l < h.length; l++)
93833
+ this.partToArray(e, h[l], r, n);
93834
+ else
93835
+ t.indexOf("-") !== -1 && t.indexOf("/") !== -1 ? this.handleRangeWithStepping(t, e, r, n) : t.indexOf("-") !== -1 ? this.handleRange(t, e, r, n) : t.indexOf("/") !== -1 ? this.handleStepping(t, e, r, n) : t !== "" && this.handleNumber(t, e, r, n);
93836
+ }
93837
+ throwAtIllegalCharacters(e) {
93838
+ for (let t = 0;t < e.length; t++)
93839
+ if ((t === 3 ? /[^/*0-9,\-WwLl]+/ : t === 5 ? /[^/*0-9,\-#Ll]+/ : /[^/*0-9,\-]+/).test(e[t]))
93840
+ throw new TypeError("CronPattern: configuration entry " + t + " (" + e[t] + ") contains illegal characters.");
93841
+ }
93842
+ handleNumber(e, t, r, n) {
93843
+ let i = this.extractNth(e, t), a = e.toUpperCase().includes("W");
93844
+ if (t !== "day" && a)
93845
+ throw new TypeError("CronPattern: Nearest weekday modifier (W) only allowed in day-of-month.");
93846
+ a && (t = "nearestWeekdays");
93847
+ let o = parseInt(i[0], 10) + r;
93848
+ if (isNaN(o))
93849
+ throw new TypeError("CronPattern: " + t + " is not a number: '" + e + "'");
93850
+ this.setPart(t, o, i[1] || n);
93851
+ }
93852
+ setPart(e, t, r) {
93853
+ if (!Object.prototype.hasOwnProperty.call(this, e))
93854
+ throw new TypeError("CronPattern: Invalid part specified: " + e);
93855
+ if (e === "dayOfWeek") {
93856
+ if (t === 7 && (t = 0), t < 0 || t > 6)
93857
+ throw new RangeError("CronPattern: Invalid value for dayOfWeek: " + t);
93858
+ this.setNthWeekdayOfMonth(t, r);
93859
+ return;
93860
+ }
93861
+ if (e === "second" || e === "minute") {
93862
+ if (t < 0 || t >= 60)
93863
+ throw new RangeError("CronPattern: Invalid value for " + e + ": " + t);
93864
+ } else if (e === "hour") {
93865
+ if (t < 0 || t >= 24)
93866
+ throw new RangeError("CronPattern: Invalid value for " + e + ": " + t);
93867
+ } else if (e === "day" || e === "nearestWeekdays") {
93868
+ if (t < 0 || t >= 31)
93869
+ throw new RangeError("CronPattern: Invalid value for " + e + ": " + t);
93870
+ } else if (e === "month") {
93871
+ if (t < 0 || t >= 12)
93872
+ throw new RangeError("CronPattern: Invalid value for " + e + ": " + t);
93873
+ } else if (e === "year" && (t < 1 || t >= 1e4))
93874
+ throw new RangeError("CronPattern: Invalid value for " + e + ": " + t + " (supported range: 1-9999)");
93875
+ this[e][t] = r;
93876
+ }
93877
+ validateNotNaN(e, t) {
93878
+ if (isNaN(e))
93879
+ throw new TypeError(t);
93880
+ }
93881
+ validateRange(e, t, r, n, i) {
93882
+ if (e > t)
93883
+ throw new TypeError("CronPattern: From value is larger than to value: '" + i + "'");
93884
+ if (r !== undefined) {
93885
+ if (r === 0)
93886
+ throw new TypeError("CronPattern: Syntax error, illegal stepping: 0");
93887
+ if (r > this[n].length)
93888
+ throw new TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part (" + this[n].length + ")");
93889
+ }
93890
+ }
93891
+ handleRangeWithStepping(e, t, r, n) {
93892
+ if (e.toUpperCase().includes("W"))
93893
+ throw new TypeError("CronPattern: Syntax error, W is not allowed in ranges with stepping.");
93894
+ let i = this.extractNth(e, t), a = i[0].match(/^(\d+)-(\d+)\/(\d+)$/);
93895
+ if (a === null)
93896
+ throw new TypeError("CronPattern: Syntax error, illegal range with stepping: '" + e + "'");
93897
+ let [, o, h, l] = a, y = parseInt(o, 10) + r, u = parseInt(h, 10) + r, d = parseInt(l, 10);
93898
+ this.validateNotNaN(y, "CronPattern: Syntax error, illegal lower range (NaN)"), this.validateNotNaN(u, "CronPattern: Syntax error, illegal upper range (NaN)"), this.validateNotNaN(d, "CronPattern: Syntax error, illegal stepping: (NaN)"), this.validateRange(y, u, d, t, e);
93899
+ for (let c = y;c <= u; c += d)
93900
+ this.setPart(t, c, i[1] || n);
93901
+ }
93902
+ extractNth(e, t) {
93903
+ let r = e, n;
93904
+ if (r.includes("#")) {
93905
+ if (t !== "dayOfWeek")
93906
+ throw new Error("CronPattern: nth (#) only allowed in day-of-week field");
93907
+ n = r.split("#")[1], r = r.split("#")[0];
93908
+ } else if (r.toUpperCase().endsWith("L")) {
93909
+ if (t !== "dayOfWeek")
93910
+ throw new Error("CronPattern: L modifier only allowed in day-of-week field (use L alone for day-of-month)");
93911
+ n = "L", r = r.slice(0, -1);
93912
+ }
93913
+ return [r, n];
93914
+ }
93915
+ handleRange(e, t, r, n) {
93916
+ if (e.toUpperCase().includes("W"))
93917
+ throw new TypeError("CronPattern: Syntax error, W is not allowed in a range.");
93918
+ let i = this.extractNth(e, t), a = i[0].split("-");
93919
+ if (a.length !== 2)
93920
+ throw new TypeError("CronPattern: Syntax error, illegal range: '" + e + "'");
93921
+ let o = parseInt(a[0], 10) + r, h = parseInt(a[1], 10) + r;
93922
+ this.validateNotNaN(o, "CronPattern: Syntax error, illegal lower range (NaN)"), this.validateNotNaN(h, "CronPattern: Syntax error, illegal upper range (NaN)"), this.validateRange(o, h, undefined, t, e);
93923
+ for (let l = o;l <= h; l++)
93924
+ this.setPart(t, l, i[1] || n);
93925
+ }
93926
+ handleStepping(e, t, r, n) {
93927
+ if (e.toUpperCase().includes("W"))
93928
+ throw new TypeError("CronPattern: Syntax error, W is not allowed in parts with stepping.");
93929
+ let i = this.extractNth(e, t), a = i[0].split("/");
93930
+ if (a.length !== 2)
93931
+ throw new TypeError("CronPattern: Syntax error, illegal stepping: '" + e + "'");
93932
+ if (this.sloppyRanges)
93933
+ a[0] === "" && (a[0] = "*");
93934
+ else {
93935
+ if (a[0] === "")
93936
+ throw new TypeError("CronPattern: Syntax error, stepping with missing prefix ('" + e + "') is not allowed. Use wildcard (*/step) or range (min-max/step) instead.");
93937
+ if (a[0] !== "*")
93938
+ throw new TypeError("CronPattern: Syntax error, stepping with numeric prefix ('" + e + "') is not allowed. Use wildcard (*/step) or range (min-max/step) instead.");
93939
+ }
93940
+ let o = 0;
93941
+ a[0] !== "*" && (o = parseInt(a[0], 10) + r);
93942
+ let h = parseInt(a[1], 10);
93943
+ this.validateNotNaN(h, "CronPattern: Syntax error, illegal stepping: (NaN)"), this.validateRange(0, this[t].length - 1, h, t, e);
93944
+ for (let l = o;l < this[t].length; l += h)
93945
+ this.setPart(t, l, i[1] || n);
93946
+ }
93947
+ replaceAlphaDays(e) {
93948
+ return e.replace(/-sun/gi, "-7").replace(/sun/gi, "0").replace(/mon/gi, "1").replace(/tue/gi, "2").replace(/wed/gi, "3").replace(/thu/gi, "4").replace(/fri/gi, "5").replace(/sat/gi, "6");
93949
+ }
93950
+ replaceAlphaDaysQuartz(e) {
93951
+ return e.replace(/sun/gi, "1").replace(/mon/gi, "2").replace(/tue/gi, "3").replace(/wed/gi, "4").replace(/thu/gi, "5").replace(/fri/gi, "6").replace(/sat/gi, "7");
93952
+ }
93953
+ replaceAlphaMonths(e) {
93954
+ return e.replace(/jan/gi, "1").replace(/feb/gi, "2").replace(/mar/gi, "3").replace(/apr/gi, "4").replace(/may/gi, "5").replace(/jun/gi, "6").replace(/jul/gi, "7").replace(/aug/gi, "8").replace(/sep/gi, "9").replace(/oct/gi, "10").replace(/nov/gi, "11").replace(/dec/gi, "12");
93955
+ }
93956
+ handleNicknames(e) {
93957
+ let t = e.trim().toLowerCase();
93958
+ if (t === "@yearly" || t === "@annually")
93959
+ return "0 0 1 1 *";
93960
+ if (t === "@monthly")
93961
+ return "0 0 1 * *";
93962
+ if (t === "@weekly")
93963
+ return "0 0 * * 0";
93964
+ if (t === "@daily" || t === "@midnight")
93965
+ return "0 0 * * *";
93966
+ if (t === "@hourly")
93967
+ return "0 * * * *";
93968
+ if (t === "@reboot")
93969
+ throw new TypeError("CronPattern: @reboot is not supported in this environment. This is an event-based trigger that requires system startup detection.");
93970
+ return e;
93971
+ }
93972
+ setNthWeekdayOfMonth(e, t) {
93973
+ if (typeof t != "number" && t.toUpperCase() === "L")
93974
+ this.dayOfWeek[e] = this.dayOfWeek[e] | 32;
93975
+ else if (t === 63)
93976
+ this.dayOfWeek[e] = 63;
93977
+ else if (t < 6 && t > 0)
93978
+ this.dayOfWeek[e] = this.dayOfWeek[e] | O[t - 1];
93979
+ else
93980
+ throw new TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${t}, Type: ${typeof t}`);
93981
+ }
93982
+ };
93983
+ var P = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
93984
+ var f = [["month", "year", 0], ["day", "month", -1], ["hour", "day", 0], ["minute", "hour", 0], ["second", "minute", 0]];
93985
+ var m = class s {
93986
+ tz;
93987
+ ms;
93988
+ second;
93989
+ minute;
93990
+ hour;
93991
+ day;
93992
+ month;
93993
+ year;
93994
+ constructor(e, t) {
93995
+ if (this.tz = t, e && e instanceof Date)
93996
+ if (!isNaN(e))
93997
+ this.fromDate(e);
93998
+ else
93999
+ throw new TypeError("CronDate: Invalid date passed to CronDate constructor");
94000
+ else if (e == null)
94001
+ this.fromDate(new Date);
94002
+ else if (e && typeof e == "string")
94003
+ this.fromString(e);
94004
+ else if (e instanceof s)
94005
+ this.fromCronDate(e);
94006
+ else
94007
+ throw new TypeError("CronDate: Invalid type (" + typeof e + ") passed to CronDate constructor");
94008
+ }
94009
+ getLastDayOfMonth(e, t) {
94010
+ return t !== 1 ? P[t] : new Date(Date.UTC(e, t + 1, 0)).getUTCDate();
94011
+ }
94012
+ getLastWeekday(e, t) {
94013
+ let r = this.getLastDayOfMonth(e, t), i = new Date(Date.UTC(e, t, r)).getUTCDay();
94014
+ return i === 0 ? r - 2 : i === 6 ? r - 1 : r;
94015
+ }
94016
+ getNearestWeekday(e, t, r) {
94017
+ let n = this.getLastDayOfMonth(e, t);
94018
+ if (r > n)
94019
+ return -1;
94020
+ let a = new Date(Date.UTC(e, t, r)).getUTCDay();
94021
+ return a === 0 ? r === n ? r - 2 : r + 1 : a === 6 ? r === 1 ? r + 2 : r - 1 : r;
94022
+ }
94023
+ isNthWeekdayOfMonth(e, t, r, n) {
94024
+ let a = new Date(Date.UTC(e, t, r)).getUTCDay(), o = 0;
94025
+ for (let h = 1;h <= r; h++)
94026
+ new Date(Date.UTC(e, t, h)).getUTCDay() === a && o++;
94027
+ if (n & 63 && O[o - 1] & n)
94028
+ return true;
94029
+ if (n & 32) {
94030
+ let h = this.getLastDayOfMonth(e, t);
94031
+ for (let l = r + 1;l <= h; l++)
94032
+ if (new Date(Date.UTC(e, t, l)).getUTCDay() === a)
94033
+ return false;
94034
+ return true;
94035
+ }
94036
+ return false;
94037
+ }
94038
+ fromDate(e) {
94039
+ if (this.tz !== undefined)
94040
+ if (typeof this.tz == "number")
94041
+ this.ms = e.getUTCMilliseconds(), this.second = e.getUTCSeconds(), this.minute = e.getUTCMinutes() + this.tz, this.hour = e.getUTCHours(), this.day = e.getUTCDate(), this.month = e.getUTCMonth(), this.year = e.getUTCFullYear(), this.apply();
94042
+ else
94043
+ try {
94044
+ let t = g(e, this.tz);
94045
+ this.ms = e.getMilliseconds(), this.second = t.s, this.minute = t.i, this.hour = t.h, this.day = t.d, this.month = t.m - 1, this.year = t.y;
94046
+ } catch (t) {
94047
+ let r = t instanceof Error ? t.message : String(t);
94048
+ throw new TypeError(`CronDate: Failed to convert date to timezone '${this.tz}'. This may happen with invalid timezone names or dates. Original error: ${r}`);
94049
+ }
94050
+ else
94051
+ this.ms = e.getMilliseconds(), this.second = e.getSeconds(), this.minute = e.getMinutes(), this.hour = e.getHours(), this.day = e.getDate(), this.month = e.getMonth(), this.year = e.getFullYear();
94052
+ }
94053
+ fromCronDate(e) {
94054
+ this.tz = e.tz, this.year = e.year, this.month = e.month, this.day = e.day, this.hour = e.hour, this.minute = e.minute, this.second = e.second, this.ms = e.ms;
94055
+ }
94056
+ apply() {
94057
+ if (this.month > 11 || this.month < 0 || this.day > P[this.month] || this.day < 1 || this.hour > 59 || this.minute > 59 || this.second > 59 || this.hour < 0 || this.minute < 0 || this.second < 0) {
94058
+ let e = new Date(Date.UTC(this.year, this.month, this.day, this.hour, this.minute, this.second, this.ms));
94059
+ return this.ms = e.getUTCMilliseconds(), this.second = e.getUTCSeconds(), this.minute = e.getUTCMinutes(), this.hour = e.getUTCHours(), this.day = e.getUTCDate(), this.month = e.getUTCMonth(), this.year = e.getUTCFullYear(), true;
94060
+ } else
94061
+ return false;
94062
+ }
94063
+ fromString(e) {
94064
+ if (typeof this.tz == "number") {
94065
+ let t = v(e);
94066
+ this.ms = t.getUTCMilliseconds(), this.second = t.getUTCSeconds(), this.minute = t.getUTCMinutes(), this.hour = t.getUTCHours(), this.day = t.getUTCDate(), this.month = t.getUTCMonth(), this.year = t.getUTCFullYear(), this.apply();
94067
+ } else
94068
+ return this.fromDate(v(e, this.tz));
94069
+ }
94070
+ findNext(e, t, r, n) {
94071
+ return this._findMatch(e, t, r, n, 1);
94072
+ }
94073
+ _findMatch(e, t, r, n, i) {
94074
+ let a = this[t], o;
94075
+ r.lastDayOfMonth && (o = this.getLastDayOfMonth(this.year, this.month));
94076
+ let h = !r.starDOW && t == "day" ? new Date(Date.UTC(this.year, this.month, 1, 0, 0, 0, 0)).getUTCDay() : undefined, l = this[t] + n, y = i === 1 ? (u) => u < r[t].length : (u) => u >= 0;
94077
+ for (let u = l;y(u); u += i) {
94078
+ let d = r[t][u];
94079
+ if (t === "day" && !d) {
94080
+ for (let c = 0;c < r.nearestWeekdays.length; c++)
94081
+ if (r.nearestWeekdays[c]) {
94082
+ let M = this.getNearestWeekday(this.year, this.month, c - n);
94083
+ if (M === -1)
94084
+ continue;
94085
+ if (M === u - n) {
94086
+ d = 1;
94087
+ break;
94088
+ }
94089
+ }
94090
+ }
94091
+ if (t === "day" && r.lastWeekday) {
94092
+ let c = this.getLastWeekday(this.year, this.month);
94093
+ u - n === c && (d = 1);
94094
+ }
94095
+ if (t === "day" && r.lastDayOfMonth && u - n == o && (d = 1), t === "day" && !r.starDOW) {
94096
+ let c = r.dayOfWeek[(h + (u - n - 1)) % 7];
94097
+ if (c && c & 63)
94098
+ c = this.isNthWeekdayOfMonth(this.year, this.month, u - n, c) ? 1 : 0;
94099
+ else if (c)
94100
+ throw new Error(`CronDate: Invalid value for dayOfWeek encountered. ${c}`);
94101
+ r.useAndLogic ? d = d && c : !e.domAndDow && !r.starDOM ? d = d || c : d = d && c;
94102
+ }
94103
+ if (d)
94104
+ return this[t] = u - n, a !== this[t] ? 2 : 1;
94105
+ }
94106
+ return 3;
94107
+ }
94108
+ recurse(e, t, r) {
94109
+ if (r === 0 && !e.starYear) {
94110
+ if (this.year >= 0 && this.year < e.year.length && e.year[this.year] === 0) {
94111
+ let i = -1;
94112
+ for (let a = this.year + 1;a < e.year.length && a < 1e4; a++)
94113
+ if (e.year[a] === 1) {
94114
+ i = a;
94115
+ break;
94116
+ }
94117
+ if (i === -1)
94118
+ return null;
94119
+ this.year = i, this.month = 0, this.day = 1, this.hour = 0, this.minute = 0, this.second = 0, this.ms = 0;
94120
+ }
94121
+ if (this.year >= 1e4)
94122
+ return null;
94123
+ }
94124
+ let n = this.findNext(t, f[r][0], e, f[r][2]);
94125
+ if (n > 1) {
94126
+ let i = r + 1;
94127
+ for (;i < f.length; )
94128
+ this[f[i][0]] = -f[i][2], i++;
94129
+ if (n === 3) {
94130
+ if (this[f[r][1]]++, this[f[r][0]] = -f[r][2], this.apply(), r === 0 && !e.starYear) {
94131
+ for (;this.year >= 0 && this.year < e.year.length && e.year[this.year] === 0 && this.year < 1e4; )
94132
+ this.year++;
94133
+ if (this.year >= 1e4 || this.year >= e.year.length)
94134
+ return null;
94135
+ }
94136
+ return this.recurse(e, t, 0);
94137
+ } else if (this.apply())
94138
+ return this.recurse(e, t, r - 1);
94139
+ }
94140
+ return r += 1, r >= f.length ? this : (e.starYear ? this.year >= 3000 : this.year >= 1e4) ? null : this.recurse(e, t, r);
94141
+ }
94142
+ increment(e, t, r) {
94143
+ return this.second += t.interval !== undefined && t.interval > 1 && r ? t.interval : 1, this.ms = 0, this.apply(), this.recurse(e, t, 0);
94144
+ }
94145
+ decrement(e, t) {
94146
+ return this.second -= t.interval !== undefined && t.interval > 1 ? t.interval : 1, this.ms = 0, this.apply(), this.recurseBackward(e, t, 0, 0);
94147
+ }
94148
+ recurseBackward(e, t, r, n = 0) {
94149
+ if (n > 1e4)
94150
+ return null;
94151
+ if (r === 0 && !e.starYear) {
94152
+ if (this.year >= 0 && this.year < e.year.length && e.year[this.year] === 0) {
94153
+ let a = -1;
94154
+ for (let o = this.year - 1;o >= 0; o--)
94155
+ if (e.year[o] === 1) {
94156
+ a = o;
94157
+ break;
94158
+ }
94159
+ if (a === -1)
94160
+ return null;
94161
+ this.year = a, this.month = 11, this.day = 31, this.hour = 23, this.minute = 59, this.second = 59, this.ms = 0;
94162
+ }
94163
+ if (this.year < 0)
94164
+ return null;
94165
+ }
94166
+ let i = this.findPrevious(t, f[r][0], e, f[r][2]);
94167
+ if (i > 1) {
94168
+ let a = r + 1;
94169
+ for (;a < f.length; ) {
94170
+ let o = f[a][0], h = f[a][2], l = this.getMaxPatternValue(o, e, h);
94171
+ this[o] = l, a++;
94172
+ }
94173
+ if (i === 3) {
94174
+ if (this[f[r][1]]--, r === 0) {
94175
+ let y = this.getLastDayOfMonth(this.year, this.month);
94176
+ this.day > y && (this.day = y);
94177
+ }
94178
+ if (r === 1)
94179
+ if (this.day <= 0)
94180
+ this.day = 1;
94181
+ else {
94182
+ let y = this.year, u = this.month;
94183
+ for (;u < 0; )
94184
+ u += 12, y--;
94185
+ for (;u > 11; )
94186
+ u -= 12, y++;
94187
+ let d = u !== 1 ? P[u] : new Date(Date.UTC(y, u + 1, 0)).getUTCDate();
94188
+ this.day > d && (this.day = d);
94189
+ }
94190
+ this.apply();
94191
+ let o = f[r][0], h = f[r][2], l = this.getMaxPatternValue(o, e, h);
94192
+ if (o === "day") {
94193
+ let y = this.getLastDayOfMonth(this.year, this.month);
94194
+ this[o] = Math.min(l, y);
94195
+ } else
94196
+ this[o] = l;
94197
+ if (this.apply(), r === 0) {
94198
+ let y = f[1][2], u = this.getMaxPatternValue("day", e, y), d = this.getLastDayOfMonth(this.year, this.month), c = Math.min(u, d);
94199
+ c !== this.day && (this.day = c, this.hour = this.getMaxPatternValue("hour", e, f[2][2]), this.minute = this.getMaxPatternValue("minute", e, f[3][2]), this.second = this.getMaxPatternValue("second", e, f[4][2]));
94200
+ }
94201
+ if (r === 0 && !e.starYear) {
94202
+ for (;this.year >= 0 && this.year < e.year.length && e.year[this.year] === 0; )
94203
+ this.year--;
94204
+ if (this.year < 0)
94205
+ return null;
94206
+ }
94207
+ return this.recurseBackward(e, t, 0, n + 1);
94208
+ } else if (this.apply())
94209
+ return this.recurseBackward(e, t, r - 1, n + 1);
94210
+ }
94211
+ return r += 1, r >= f.length ? this : this.year < 0 ? null : this.recurseBackward(e, t, r, n + 1);
94212
+ }
94213
+ getMaxPatternValue(e, t, r) {
94214
+ if (e === "day" && t.lastDayOfMonth)
94215
+ return this.getLastDayOfMonth(this.year, this.month);
94216
+ if (e === "day" && !t.starDOW)
94217
+ return this.getLastDayOfMonth(this.year, this.month);
94218
+ for (let n = t[e].length - 1;n >= 0; n--)
94219
+ if (t[e][n])
94220
+ return n - r;
94221
+ return t[e].length - 1 - r;
94222
+ }
94223
+ findPrevious(e, t, r, n) {
94224
+ return this._findMatch(e, t, r, n, -1);
94225
+ }
94226
+ getDate(e) {
94227
+ return e || this.tz === undefined ? new Date(this.year, this.month, this.day, this.hour, this.minute, this.second, this.ms) : typeof this.tz == "number" ? new Date(Date.UTC(this.year, this.month, this.day, this.hour, this.minute - this.tz, this.second, this.ms)) : k(b(this.year, this.month + 1, this.day, this.hour, this.minute, this.second, this.tz), false);
94228
+ }
94229
+ getTime() {
94230
+ return this.getDate(false).getTime();
94231
+ }
94232
+ match(e, t) {
94233
+ if (!e.starYear && (this.year < 0 || this.year >= e.year.length || e.year[this.year] === 0))
94234
+ return false;
94235
+ for (let r = 0;r < f.length; r++) {
94236
+ let n = f[r][0], i = f[r][2], a = this[n];
94237
+ if (a + i < 0 || a + i >= e[n].length)
94238
+ return false;
94239
+ let o = e[n][a + i];
94240
+ if (n === "day") {
94241
+ if (!o) {
94242
+ for (let h = 0;h < e.nearestWeekdays.length; h++)
94243
+ if (e.nearestWeekdays[h]) {
94244
+ let l = this.getNearestWeekday(this.year, this.month, h - i);
94245
+ if (l !== -1 && l === a) {
94246
+ o = 1;
94247
+ break;
94248
+ }
94249
+ }
94250
+ }
94251
+ if (e.lastWeekday) {
94252
+ let h = this.getLastWeekday(this.year, this.month);
94253
+ a === h && (o = 1);
94254
+ }
94255
+ if (e.lastDayOfMonth) {
94256
+ let h = this.getLastDayOfMonth(this.year, this.month);
94257
+ a === h && (o = 1);
94258
+ }
94259
+ if (!e.starDOW) {
94260
+ let h = new Date(Date.UTC(this.year, this.month, 1, 0, 0, 0, 0)).getUTCDay(), l = e.dayOfWeek[(h + (a - 1)) % 7];
94261
+ l && l & 63 && (l = this.isNthWeekdayOfMonth(this.year, this.month, a, l) ? 1 : 0), e.useAndLogic ? o = o && l : !t.domAndDow && !e.starDOM ? o = o || l : o = o && l;
94262
+ }
94263
+ }
94264
+ if (!o)
94265
+ return false;
94266
+ }
94267
+ return true;
94268
+ }
94269
+ };
94270
+ function R(s) {
94271
+ if (s === undefined && (s = {}), delete s.name, s.legacyMode !== undefined && s.domAndDow === undefined ? s.domAndDow = !s.legacyMode : s.domAndDow === undefined && (s.domAndDow = false), s.legacyMode = !s.domAndDow, s.paused = s.paused === undefined ? false : s.paused, s.maxRuns = s.maxRuns === undefined ? 1 / 0 : s.maxRuns, s.catch = s.catch === undefined ? false : s.catch, s.interval = s.interval === undefined ? 0 : parseInt(s.interval.toString(), 10), s.utcOffset = s.utcOffset === undefined ? undefined : parseInt(s.utcOffset.toString(), 10), s.dayOffset = s.dayOffset === undefined ? 0 : parseInt(s.dayOffset.toString(), 10), s.unref = s.unref === undefined ? false : s.unref, s.mode = s.mode === undefined ? "auto" : s.mode, s.alternativeWeekdays = s.alternativeWeekdays === undefined ? false : s.alternativeWeekdays, s.sloppyRanges = s.sloppyRanges === undefined ? false : s.sloppyRanges, !["auto", "5-part", "6-part", "7-part", "5-or-6-parts", "6-or-7-parts"].includes(s.mode))
94272
+ throw new Error("CronOptions: mode must be one of 'auto', '5-part', '6-part', '7-part', '5-or-6-parts', or '6-or-7-parts'.");
94273
+ if (s.startAt && (s.startAt = new m(s.startAt, s.timezone)), s.stopAt && (s.stopAt = new m(s.stopAt, s.timezone)), s.interval !== null) {
94274
+ if (isNaN(s.interval))
94275
+ throw new Error("CronOptions: Supplied value for interval is not a number");
94276
+ if (s.interval < 0)
94277
+ throw new Error("CronOptions: Supplied value for interval can not be negative");
94278
+ }
94279
+ if (s.utcOffset !== undefined) {
94280
+ if (isNaN(s.utcOffset))
94281
+ throw new Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");
94282
+ if (s.utcOffset < -870 || s.utcOffset > 870)
94283
+ throw new Error("CronOptions: utcOffset out of bounds.");
94284
+ if (s.utcOffset !== undefined && s.timezone)
94285
+ throw new Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.");
94286
+ }
94287
+ if (s.unref !== true && s.unref !== false)
94288
+ throw new Error("CronOptions: Unref should be either true, false or undefined(false).");
94289
+ if (s.dayOffset !== undefined && s.dayOffset !== 0 && isNaN(s.dayOffset))
94290
+ throw new Error("CronOptions: Invalid value passed for dayOffset, should be a number representing days to offset.");
94291
+ return s;
94292
+ }
94293
+ function p(s) {
94294
+ return Object.prototype.toString.call(s) === "[object Function]" || typeof s == "function" || s instanceof Function;
94295
+ }
94296
+ function _(s) {
94297
+ return p(s);
94298
+ }
94299
+ function x(s) {
94300
+ typeof Deno < "u" && typeof Deno.unrefTimer < "u" ? Deno.unrefTimer(s) : s && typeof s.unref < "u" && s.unref();
94301
+ }
94302
+ var W = 30 * 1000;
94303
+ var w = [];
94304
+ var E = class {
94305
+ name;
94306
+ options;
94307
+ _states;
94308
+ fn;
94309
+ getTz() {
94310
+ return this.options.timezone || this.options.utcOffset;
94311
+ }
94312
+ applyDayOffset(e) {
94313
+ if (this.options.dayOffset !== undefined && this.options.dayOffset !== 0) {
94314
+ let t = this.options.dayOffset * 24 * 60 * 60 * 1000;
94315
+ return new Date(e.getTime() + t);
94316
+ }
94317
+ return e;
94318
+ }
94319
+ constructor(e, t, r) {
94320
+ let n, i;
94321
+ if (p(t))
94322
+ i = t;
94323
+ else if (typeof t == "object")
94324
+ n = t;
94325
+ else if (t !== undefined)
94326
+ throw new Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");
94327
+ if (p(r))
94328
+ i = r;
94329
+ else if (typeof r == "object")
94330
+ n = r;
94331
+ else if (r !== undefined)
94332
+ throw new Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");
94333
+ if (this.name = n?.name, this.options = R(n), this._states = { kill: false, blocking: false, previousRun: undefined, currentRun: undefined, once: undefined, currentTimeout: undefined, maxRuns: n ? n.maxRuns : undefined, paused: n ? n.paused : false, pattern: new C("* * * * *", undefined, { mode: "auto" }) }, e && (e instanceof Date || typeof e == "string" && e.indexOf(":") > 0) ? this._states.once = new m(e, this.getTz()) : this._states.pattern = new C(e, this.options.timezone, { mode: this.options.mode, alternativeWeekdays: this.options.alternativeWeekdays, sloppyRanges: this.options.sloppyRanges }), this.name) {
94334
+ if (w.find((o) => o.name === this.name))
94335
+ throw new Error("Cron: Tried to initialize new named job '" + this.name + "', but name already taken.");
94336
+ w.push(this);
94337
+ }
94338
+ return i !== undefined && _(i) && (this.fn = i, this.schedule()), this;
94339
+ }
94340
+ nextRun(e) {
94341
+ let t = this._next(e);
94342
+ return t ? this.applyDayOffset(t.getDate(false)) : null;
94343
+ }
94344
+ nextRuns(e, t) {
94345
+ this._states.maxRuns !== undefined && e > this._states.maxRuns && (e = this._states.maxRuns);
94346
+ let r = t || this._states.currentRun || undefined;
94347
+ return this._enumerateRuns(e, r, "next");
94348
+ }
94349
+ previousRuns(e, t) {
94350
+ return this._enumerateRuns(e, t || undefined, "previous");
94351
+ }
94352
+ _enumerateRuns(e, t, r) {
94353
+ let n = [], i = t ? new m(t, this.getTz()) : null, a = r === "next" ? this._next : this._previous;
94354
+ for (;e--; ) {
94355
+ let o = a.call(this, i);
94356
+ if (!o)
94357
+ break;
94358
+ let h = o.getDate(false);
94359
+ n.push(this.applyDayOffset(h)), i = o;
94360
+ }
94361
+ return n;
94362
+ }
94363
+ match(e) {
94364
+ if (this._states.once) {
94365
+ let r = new m(e, this.getTz());
94366
+ r.ms = 0;
94367
+ let n = new m(this._states.once, this.getTz());
94368
+ return n.ms = 0, r.getTime() === n.getTime();
94369
+ }
94370
+ let t = new m(e, this.getTz());
94371
+ return t.ms = 0, t.match(this._states.pattern, this.options);
94372
+ }
94373
+ getPattern() {
94374
+ if (!this._states.once)
94375
+ return this._states.pattern ? this._states.pattern.pattern : undefined;
94376
+ }
94377
+ getOnce() {
94378
+ return this._states.once ? this._states.once.getDate() : null;
94379
+ }
94380
+ isRunning() {
94381
+ let e = this.nextRun(this._states.currentRun), t = !this._states.paused, r = this.fn !== undefined, n = !this._states.kill;
94382
+ return t && r && n && e !== null;
94383
+ }
94384
+ isStopped() {
94385
+ return this._states.kill;
94386
+ }
94387
+ isBusy() {
94388
+ return this._states.blocking;
94389
+ }
94390
+ currentRun() {
94391
+ return this._states.currentRun ? this._states.currentRun.getDate() : null;
94392
+ }
94393
+ previousRun() {
94394
+ return this._states.previousRun ? this._states.previousRun.getDate() : null;
94395
+ }
94396
+ msToNext(e) {
94397
+ let t = this._next(e);
94398
+ return t ? e instanceof m || e instanceof Date ? t.getTime() - e.getTime() : t.getTime() - new m(e).getTime() : null;
94399
+ }
94400
+ stop() {
94401
+ this._states.kill = true, this._states.currentTimeout && clearTimeout(this._states.currentTimeout);
94402
+ let e = w.indexOf(this);
94403
+ e >= 0 && w.splice(e, 1);
94404
+ }
94405
+ pause() {
94406
+ return this._states.paused = true, !this._states.kill;
94407
+ }
94408
+ resume() {
94409
+ return this._states.paused = false, !this._states.kill;
94410
+ }
94411
+ schedule(e) {
94412
+ if (e && this.fn)
94413
+ throw new Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");
94414
+ e && (this.fn = e);
94415
+ let t = this.msToNext(), r = this.nextRun(this._states.currentRun);
94416
+ return t == null || isNaN(t) || r === null ? this : (t > W && (t = W), this._states.currentTimeout = setTimeout(() => this._checkTrigger(r), t), this._states.currentTimeout && this.options.unref && x(this._states.currentTimeout), this);
94417
+ }
94418
+ async _trigger(e) {
94419
+ this._states.blocking = true, this._states.currentRun = new m(undefined, this.getTz());
94420
+ try {
94421
+ if (this.options.catch)
94422
+ try {
94423
+ this.fn !== undefined && await this.fn(this, this.options.context);
94424
+ } catch (t) {
94425
+ if (p(this.options.catch))
94426
+ try {
94427
+ this.options.catch(t, this);
94428
+ } catch {}
94429
+ }
94430
+ else
94431
+ this.fn !== undefined && await this.fn(this, this.options.context);
94432
+ } finally {
94433
+ this._states.previousRun = new m(e, this.getTz()), this._states.blocking = false;
94434
+ }
94435
+ }
94436
+ async trigger() {
94437
+ await this._trigger();
94438
+ }
94439
+ runsLeft() {
94440
+ return this._states.maxRuns;
94441
+ }
94442
+ _checkTrigger(e) {
94443
+ let t = new Date, r = !this._states.paused && t.getTime() >= e.getTime(), n = this._states.blocking && this.options.protect;
94444
+ r && !n ? (this._states.maxRuns !== undefined && this._states.maxRuns--, this._trigger()) : r && n && p(this.options.protect) && setTimeout(() => this.options.protect(this), 0), this.schedule();
94445
+ }
94446
+ _next(e) {
94447
+ let t = !!(e || this._states.currentRun), r = false;
94448
+ !e && this.options.startAt && this.options.interval && ([e, t] = this._calculatePreviousRun(e, t), r = !e), e = new m(e, this.getTz()), this.options.startAt && e && e.getTime() < this.options.startAt.getTime() && (e = this.options.startAt);
94449
+ let n = this._states.once || new m(e, this.getTz());
94450
+ return !r && n !== this._states.once && (n = n.increment(this._states.pattern, this.options, t)), this._states.once && this._states.once.getTime() <= e.getTime() || n === null || this._states.maxRuns !== undefined && this._states.maxRuns <= 0 || this._states.kill || this.options.stopAt && n.getTime() >= this.options.stopAt.getTime() ? null : n;
94451
+ }
94452
+ _previous(e) {
94453
+ let t = new m(e, this.getTz());
94454
+ this.options.stopAt && t.getTime() > this.options.stopAt.getTime() && (t = this.options.stopAt);
94455
+ let r = new m(t, this.getTz());
94456
+ return this._states.once ? this._states.once.getTime() < t.getTime() ? this._states.once : null : (r = r.decrement(this._states.pattern, this.options), r === null || this.options.startAt && r.getTime() < this.options.startAt.getTime() ? null : r);
94457
+ }
94458
+ _calculatePreviousRun(e, t) {
94459
+ let r = new m(undefined, this.getTz()), n = e;
94460
+ if (this.options.startAt.getTime() <= r.getTime()) {
94461
+ n = this.options.startAt;
94462
+ let i = n.getTime() + this.options.interval * 1000;
94463
+ for (;i <= r.getTime(); )
94464
+ n = new m(n, this.getTz()).increment(this._states.pattern, this.options, true), i = n.getTime() + this.options.interval * 1000;
94465
+ t = true;
94466
+ }
94467
+ return n === null && (n = undefined), [n, t];
94468
+ }
94469
+ };
94470
+
94471
+ // ../toml/dist/cron-schedule.js
94472
+ function cronSchedulePolicy(schedule) {
94473
+ let cron;
94474
+ try {
94475
+ cron = new E(schedule, { timezone: "UTC" });
94476
+ if (cron.getOnce())
94477
+ return "valid";
94478
+ const seconds = new C(schedule, "UTC").second.filter((value) => value !== 0).length;
94479
+ return seconds > 1 ? "subminute" : seconds === 1 ? "valid" : "invalid";
94480
+ } catch {
94481
+ return "invalid";
94482
+ } finally {
94483
+ cron?.stop();
94484
+ }
94485
+ }
93200
94486
  // ../toml/dist/errors.js
93201
94487
  class PercherTomlError extends Error {
93202
94488
  code;
@@ -93228,13 +94514,6 @@ function generateName(input) {
93228
94514
  }
93229
94515
  return result;
93230
94516
  }
93231
- // ../toml/dist/parse.js
93232
- import { readFile } from "node:fs/promises";
93233
-
93234
- // ../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/toml.js
93235
- var $parse = require_parse();
93236
- var $stringify = require_stringify();
93237
-
93238
94517
  // ../../node_modules/.bun/zod@4.3.6/node_modules/zod/v4/core/core.js
93239
94518
  var NEVER = Object.freeze({
93240
94519
  status: "aborted"
@@ -97647,6 +98926,79 @@ var ZodFirstPartyTypeKind;
97647
98926
  (function(ZodFirstPartyTypeKind) {})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
97648
98927
  // ../../node_modules/.bun/zod@4.3.6/node_modules/zod/v4/classic/external.js
97649
98928
  config(en_default());
98929
+ // ../toml/dist/mcp-schema.js
98930
+ var identifier = string2().regex(/^[A-Za-z_][A-Za-z0-9_]{0,63}$/);
98931
+ var collectionId = string2().regex(/^[A-Za-z0-9_]{1,100}$/);
98932
+ var httpsUrl = string2().max(2048).refine((value) => {
98933
+ try {
98934
+ const url = new URL(value);
98935
+ return url.protocol === "https:" && !url.username && !url.password;
98936
+ } catch {
98937
+ return false;
98938
+ }
98939
+ }, "must be an HTTPS URL without credentials");
98940
+ var tool = object({
98941
+ name: identifier,
98942
+ auth_collection_id: collectionId,
98943
+ collection_id: collectionId,
98944
+ owner_field: identifier,
98945
+ fields: array(identifier).min(1).max(32),
98946
+ scope: literal("read"),
98947
+ operations: array(_enum(["list", "view"])).min(1).max(2)
98948
+ }).strict();
98949
+ var mcpSchema = object({
98950
+ version: literal(1),
98951
+ terms_url: httpsUrl,
98952
+ privacy_url: httpsUrl,
98953
+ auth_collection_id: collectionId,
98954
+ tools: array(tool).min(1).max(32)
98955
+ }).strict().superRefine((value, ctx) => {
98956
+ const names = new Set;
98957
+ const contexts = new Map;
98958
+ for (const [i, entry] of value.tools.entries()) {
98959
+ const issue = (message) => ctx.addIssue({ code: "custom", path: ["tools", i], message });
98960
+ if (names.has(entry.name))
98961
+ issue("duplicate tool name");
98962
+ names.add(entry.name);
98963
+ if (entry.auth_collection_id !== value.auth_collection_id)
98964
+ issue("tool auth collection must match login");
98965
+ if (new Set(entry.fields).size !== entry.fields.length)
98966
+ issue("duplicate field");
98967
+ if (new Set(entry.operations).size !== entry.operations.length)
98968
+ issue("duplicate operation");
98969
+ const context = JSON.stringify([entry.auth_collection_id, entry.owner_field]);
98970
+ if (contexts.has(entry.collection_id) && contexts.get(entry.collection_id) !== context)
98971
+ issue("conflicting collection context");
98972
+ contexts.set(entry.collection_id, context);
98973
+ }
98974
+ if (new TextEncoder().encode(serializeMcpDeclaration(value)).byteLength > 32768) {
98975
+ ctx.addIssue({ code: "custom", message: "MCP declaration exceeds 32 KiB" });
98976
+ }
98977
+ });
98978
+ function serializeMcpDeclaration(value) {
98979
+ return JSON.stringify({
98980
+ version: value.version,
98981
+ terms_url: value.terms_url,
98982
+ privacy_url: value.privacy_url,
98983
+ auth_collection_id: value.auth_collection_id,
98984
+ tools: [...value.tools].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0).map((entry) => ({
98985
+ name: entry.name,
98986
+ auth_collection_id: entry.auth_collection_id,
98987
+ collection_id: entry.collection_id,
98988
+ owner_field: entry.owner_field,
98989
+ fields: [...entry.fields].sort(),
98990
+ scope: entry.scope,
98991
+ operations: [...entry.operations].sort()
98992
+ }))
98993
+ });
98994
+ }
98995
+ // ../toml/dist/parse.js
98996
+ import { readFile } from "node:fs/promises";
98997
+
98998
+ // ../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/toml.js
98999
+ var $parse = require_parse();
99000
+ var $stringify = require_stringify();
99001
+
97650
99002
  // ../toml/dist/schema.js
97651
99003
  var appSchema = object({
97652
99004
  name: string2().regex(APP_NAME_RE, "must be 3–40 chars, lowercase, start with a letter, [a-z0-9-] only"),
@@ -97734,8 +99086,16 @@ var dataSchema = object({
97734
99086
  mode: _enum(["pocketbase", "postgres", "sqlite", "convex", "supabase", "external", "none"]),
97735
99087
  file: string2().min(1).optional(),
97736
99088
  convex: convexConfigSchema.optional(),
97737
- supabase: supabaseConfigSchema.optional()
99089
+ supabase: supabaseConfigSchema.optional(),
99090
+ superuser_env: boolean2().optional()
97738
99091
  }).strict().superRefine((value, ctx) => {
99092
+ if (value.superuser_env !== undefined && value.mode !== "pocketbase") {
99093
+ ctx.addIssue({
99094
+ code: "custom",
99095
+ path: ["superuser_env"],
99096
+ message: "Only supported when mode = 'pocketbase'."
99097
+ });
99098
+ }
97739
99099
  if (value.mode === "sqlite" && !value.file) {
97740
99100
  ctx.addIssue({
97741
99101
  code: ZodIssueCode.custom,
@@ -97891,7 +99251,14 @@ var devSchema = object({
97891
99251
  }).strict();
97892
99252
  var requiredEnvSchema = record(string2(), _enum(["secret", "url", "string"]));
97893
99253
  var cronSchema = object({
97894
- schedule: string2().min(1),
99254
+ schedule: string2().min(1).superRefine((value, ctx) => {
99255
+ const policy = cronSchedulePolicy(value);
99256
+ if (policy !== "valid")
99257
+ ctx.addIssue({
99258
+ code: "custom",
99259
+ message: policy === "subminute" ? "Recurring cron schedules must be at least one minute apart." : "Invalid cron schedule."
99260
+ });
99261
+ }),
97895
99262
  command: string2().min(1),
97896
99263
  description: string2().max(200).optional()
97897
99264
  }).strict();
@@ -98048,6 +99415,7 @@ var percherConfigSchema = object({
98048
99415
  build: buildSchema.optional(),
98049
99416
  web: webSchema.optional(),
98050
99417
  data: dataSchema.optional(),
99418
+ mcp: mcpSchema.optional(),
98051
99419
  env: envSchema.optional(),
98052
99420
  domain: domainSchema.optional(),
98053
99421
  resources: resourcesSchema.optional(),
@@ -98521,7 +99889,7 @@ function classifyFile(projectRoot, template, manifest) {
98521
99889
  var CLAUDE_MD = {
98522
99890
  id: "claude-md",
98523
99891
  path: "CLAUDE.md",
98524
- version: "1.3.0",
99892
+ version: "1.4.0",
98525
99893
  content: `# CLAUDE.md — Percher publishing instructions
98526
99894
 
98527
99895
  This project is hosted on **Percher** (https://percher.app). Apps run
@@ -98539,6 +99907,17 @@ This single command:
98539
99907
  - Packages, uploads, builds, deploys
98540
99908
  - Returns the live URL
98541
99909
 
99910
+ ## PocketBase admin credentials
99911
+
99912
+ Managed PocketBase injects admin credentials by default. If your server does not
99913
+ use POCKETBASE_ADMIN_*, set [data] superuser_env = false. False persists across
99914
+ omission and old-version redeploys; only superuser_env = true in a new live
99915
+ publish re-enables it. Percher data tools and reset-superuser --reveal still work.
99916
+ This does not erase copied credentials or old processes. Reset after suspected
99917
+ exposure; reset does not re-enable app injection. Rollback to a version deployed while admin env was on is refused: redeploy its
99918
+ retained source or publish it again. Rotation makes the old admin password stop
99919
+ working; it does not revoke other secrets your app holds.
99920
+
98542
99921
  ## Setting secrets
98543
99922
 
98544
99923
  Never put secret values in \`percher.toml\` or anywhere in source.
@@ -99232,7 +100611,7 @@ import { join as join9, resolve as resolve5 } from "node:path";
99232
100611
  // ../core/dist/templates.js
99233
100612
  import { existsSync as existsSync5, mkdirSync as mkdirSync6, readdirSync, readFileSync as readFileSync6, statSync, writeFileSync as writeFileSync6 } from "node:fs";
99234
100613
  import { basename as basename2, join as join8, normalize, relative as relative2, resolve as resolve4 } from "node:path";
99235
- var __dirname = "C:\\dev\\Percher-npm-1.4.0-20261023\\packages\\core\\dist";
100614
+ var __dirname = "/mnt/c/dev/Percher-lc-evidence/hardening-20261102/release963/worktree/packages/core/dist";
99236
100615
  var TEMPLATES_DIR = resolve4(import.meta.dirname ?? __dirname, "../templates");
99237
100616
  var PLACEHOLDER = "__APP_NAME__";
99238
100617
  function listTemplates() {
@@ -99621,6 +101000,30 @@ init_dist();
99621
101000
 
99622
101001
  // ../core/dist/structured-error-codes.js
99623
101002
  var MAPPINGS = {
101003
+ APP_IMAGE_VOLUME_UNSUPPORTED: {
101004
+ errorClass: "app_image_volume_unsupported",
101005
+ phase: "start",
101006
+ cause: "app_image_volume_unsupported",
101007
+ title: "Unsupported image volumes",
101008
+ explanation: () => "The image declares volumes outside Percher's managed mount destinations.",
101009
+ suggestion: "Check the Dockerfile and base image. Use an image that declares VOLUME only at /app/data, /tmp or /var/tmp. /app/data is persistent; /tmp and /var/tmp are bounded temporary storage. Remove other declarations or choose another base image, then publish again."
101010
+ },
101011
+ IMAGE_MOUNT_ATTESTATION_UNAVAILABLE: {
101012
+ errorClass: "infra_unavailable",
101013
+ phase: "infra",
101014
+ cause: "image_mount_attestation_unavailable",
101015
+ title: "Image mount verification unavailable",
101016
+ explanation: () => "Percher could not verify the image and managed mounts. This is a platform failure.",
101017
+ suggestion: "Retry later. If it persists, contact support."
101018
+ },
101019
+ BUILD_SECRETS_MIGRATION_REQUIRED: {
101020
+ errorClass: "build_secret_migration",
101021
+ phase: "build",
101022
+ cause: "docker_build_secret_migration",
101023
+ title: "Migrate Dockerfile build secrets",
101024
+ explanation: () => "Percher refused private Docker build arguments because they can persist in image history and cache.",
101025
+ suggestion: "Replace private ARG/ENV consumers with RUN --mount=type=secret,id=KEY,env=KEY,required=true. Add # percher: build-secrets=mount after all parser directives, before the first instruction; keep the keys in [build] pass_env. Do not print or save values. See https://percher.app/docs/env-vars#build-time."
101026
+ },
99624
101027
  SECURITY_GATE_BLOCKED: {
99625
101028
  errorClass: "security_blocked",
99626
101029
  phase: "build",
@@ -100063,6 +101466,16 @@ function unprovenPlatformClaim(failure) {
100063
101466
  }
100064
101467
  function recoveryFromErrorClass(errorClass, failure) {
100065
101468
  switch (errorClass) {
101469
+ case "app_image_volume_unsupported":
101470
+ return recoveryAsk({
101471
+ prompt: "The image declares unsupported volumes. Check the Dockerfile and base image: VOLUME may name only /app/data, /tmp or /var/tmp. /app/data is persistent; /tmp and /var/tmp are bounded temporary storage. Remove other declarations or choose another base image before publishing again.",
101472
+ reasonCode: "app_image_volume_unsupported"
101473
+ });
101474
+ case "build_secret_migration":
101475
+ return recoveryAsk({
101476
+ prompt: "This Dockerfile needs build-secret migration. Replace each private ARG/ENV consumer with RUN --mount=type=secret,id=KEY,env=KEY,required=true, then add # percher: build-secrets=mount after all parser directives, before the first instruction. Keep the keys in [build] pass_env. Do not print or save secret values. Review https://percher.app/docs/env-vars#build-time before publishing again.",
101477
+ reasonCode: "build_failed"
101478
+ });
100066
101479
  case "security_blocked":
100067
101480
  return recoveryAsk({
100068
101481
  prompt: "Publication was blocked by security policy. Review the vulnerability details, update affected app dependencies or wait for Percher's platform fix before publishing again.",
@@ -100367,6 +101780,15 @@ function replacedDeploymentResult(app, deployment) {
100367
101780
  };
100368
101781
  }
100369
101782
 
101783
+ // ../core/dist/pb-superuser-env-note.js
101784
+ function pbSuperuserEnvNote(deployment) {
101785
+ if (deployment.pocketbaseSuperuserEnv !== false)
101786
+ return;
101787
+ if (deployment.pocketbaseSuperuserEnvOptInSuperseded)
101788
+ return "PocketBase admin env stays off: another publish changed the policy before this opt-in completed. Publish again with superuser_env = true to re-enable it.";
101789
+ return deployment.pocketbaseSuperuserEnvInherited ? "PocketBase admin env is still off from an earlier publish. Set [data] superuser_env = true in a new live publish to re-enable it." : "PocketBase admin env is off. Set [data] superuser_env = true in a new live publish to re-enable it.";
101790
+ }
101791
+
100370
101792
  // ../core/dist/poll-deployment.js
100371
101793
  init_dist();
100372
101794
  class DeployPollLostContactError extends PercherCoreError {
@@ -101085,12 +102507,12 @@ import { existsSync as existsSync8 } from "node:fs";
101085
102507
  import { join as join13 } from "node:path";
101086
102508
 
101087
102509
  // ../core/dist/tarball.js
101088
- var import_ignore = __toESM(require_ignore(), 1);
101089
102510
  import { createHash as createHash2 } from "node:crypto";
101090
- import { existsSync as existsSync6, readdirSync as readdirSync2, readFileSync as readFileSync7, statSync as statSync2 } from "node:fs";
101091
- import { join as join11, relative as relative4, sep as sep2 } from "node:path";
102511
+ import { closeSync as closeSync2, constants, existsSync as existsSync6, fstatSync, lstatSync as lstatSync2, openSync as openSync2, readdirSync as readdirSync2, readFileSync as readFileSync7, realpathSync } from "node:fs";
102512
+ import { isAbsolute as isAbsolute2, join as join11, relative as relative4, sep as sep2 } from "node:path";
101092
102513
  import { Readable } from "node:stream";
101093
102514
  import { createGzip } from "node:zlib";
102515
+ var import_ignore = __toESM(require_ignore(), 1);
101094
102516
  function isFilesOptions(options) {
101095
102517
  return "files" in options;
101096
102518
  }
@@ -101102,13 +102524,37 @@ var DEFAULT_IGNORE = [
101102
102524
  ".svelte-kit",
101103
102525
  "build",
101104
102526
  "coverage",
101105
- ".env",
101106
- ".env.*",
102527
+ ...ENV_FILE_IGNORE_PATTERNS,
101107
102528
  ".bun",
101108
102529
  "*.log",
101109
102530
  ".DS_Store"
101110
102531
  ];
101111
- var ALWAYS_IGNORE_SECRETS = [".env", ".env.*"];
102532
+ var ALWAYS_IGNORE_SECRETS = ENV_FILE_IGNORE_PATTERNS;
102533
+ function inspectSourcePath(root, path, entry = lstatSync2(path)) {
102534
+ if (entry.isSymbolicLink()) {
102535
+ throw new Error(`Refusing symlink in publish source: ${relative4(root, path)}`);
102536
+ }
102537
+ const rel = relative4(root, realpathSync(path));
102538
+ if (isAbsolute2(rel) || rel === ".." || rel.startsWith(`..${sep2}`)) {
102539
+ throw new Error("Publish source must stay inside the selected project");
102540
+ }
102541
+ return entry;
102542
+ }
102543
+ function readSourceFile(root, path) {
102544
+ const entry = inspectSourcePath(root, path);
102545
+ if (!entry.isFile())
102546
+ throw new Error("Publish source must contain regular files");
102547
+ const fd = openSync2(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
102548
+ try {
102549
+ const opened = fstatSync(fd);
102550
+ if (!opened.isFile() || opened.dev !== entry.dev || opened.ino !== entry.ino) {
102551
+ throw new Error("Publish source changed while packaging");
102552
+ }
102553
+ return readFileSync7(fd);
102554
+ } finally {
102555
+ closeSync2(fd);
102556
+ }
102557
+ }
101112
102558
  function* walk(dir, baseDir, ig) {
101113
102559
  const entries = readdirSync2(dir);
101114
102560
  for (const name of entries) {
@@ -101116,10 +102562,11 @@ function* walk(dir, baseDir, ig) {
101116
102562
  const rel = relative4(baseDir, full).split(sep2).join("/");
101117
102563
  if (ig.ignores(rel))
101118
102564
  continue;
101119
- const stats = statSync2(full);
102565
+ const stats = lstatSync2(full);
102566
+ if ((stats.isDirectory() || stats.isSymbolicLink()) && ig.ignores(`${rel}/`))
102567
+ continue;
102568
+ inspectSourcePath(baseDir, full, stats);
101120
102569
  if (stats.isDirectory()) {
101121
- if (ig.ignores(`${rel}/`))
101122
- continue;
101123
102570
  yield* walk(full, baseDir, ig);
101124
102571
  } else if (stats.isFile()) {
101125
102572
  yield rel;
@@ -101147,7 +102594,7 @@ function normalizeInlinePath(raw) {
101147
102594
  }
101148
102595
  return cleaned;
101149
102596
  }
101150
- function buildTarball(fileBuffers) {
102597
+ function buildTarball(fileBuffers, emptyDirs = []) {
101151
102598
  fileBuffers.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
101152
102599
  const totalBytes = fileBuffers.reduce((sum, f) => sum + f.size, 0);
101153
102600
  const contentHasher = createHash2("sha256");
@@ -101155,17 +102602,32 @@ function buildTarball(fileBuffers) {
101155
102602
  contentHasher.update(`PATH:${f.path.length}:${f.path}
101156
102603
  `);
101157
102604
  contentHasher.update(`SIZE:${f.size}
102605
+ `);
102606
+ if (f.mode !== undefined)
102607
+ contentHasher.update(`MODE:${f.mode.toString(8)}
101158
102608
  `);
101159
102609
  contentHasher.update(f.data);
101160
102610
  contentHasher.update(`
101161
102611
  `);
101162
102612
  }
102613
+ for (const dir of emptyDirs)
102614
+ contentHasher.update(`DIR:${dir.length}:${dir}
102615
+ `);
101163
102616
  const contentHash = contentHasher.digest("hex");
101164
102617
  const pack = $pack();
101165
102618
  (async () => {
101166
102619
  for (const file of fileBuffers) {
101167
102620
  await new Promise((resolve, reject) => {
101168
- pack.entry({ name: file.path, size: file.data.length }, file.data, (err) => err ? reject(err) : resolve());
102621
+ pack.entry({
102622
+ name: file.path,
102623
+ size: file.data.length,
102624
+ ...file.mode !== undefined ? { mode: file.mode } : {}
102625
+ }, file.data, (err) => err ? reject(err) : resolve());
102626
+ });
102627
+ }
102628
+ for (const dir of emptyDirs) {
102629
+ await new Promise((resolve, reject) => {
102630
+ pack.entry({ name: `${dir}/`, type: "directory" }, (err) => err ? reject(err) : resolve());
101169
102631
  });
101170
102632
  }
101171
102633
  pack.finalize();
@@ -101199,27 +102661,28 @@ async function createTarball(options) {
101199
102661
  if (isFilesOptions(options)) {
101200
102662
  return createTarballFromFiles(options.files, options.config);
101201
102663
  }
102664
+ const root = realpathSync(options.cwd);
101202
102665
  const ig = import_ignore.default();
101203
102666
  ig.add(DEFAULT_IGNORE);
101204
- const gitignorePath = join11(options.cwd, ".gitignore");
102667
+ const gitignorePath = join11(root, ".gitignore");
101205
102668
  if (existsSync6(gitignorePath)) {
101206
- ig.add(readFileSync7(gitignorePath, "utf8"));
102669
+ ig.add(readSourceFile(root, gitignorePath).toString("utf8"));
101207
102670
  }
101208
- const percherignorePath = join11(options.cwd, ".percherignore");
102671
+ const percherignorePath = join11(root, ".percherignore");
101209
102672
  if (existsSync6(percherignorePath)) {
101210
- ig.add(readFileSync7(percherignorePath, "utf8"));
102673
+ ig.add(readSourceFile(root, percherignorePath).toString("utf8"));
101211
102674
  }
101212
102675
  if (options.extraIgnore)
101213
102676
  ig.add(options.extraIgnore);
101214
102677
  ig.add(ALWAYS_IGNORE_SECRETS);
101215
102678
  const fileBuffers = [];
101216
- for (const rel of walk(options.cwd, options.cwd, ig)) {
101217
- const data = readFileSync7(join11(options.cwd, rel));
102679
+ for (const rel of walk(root, root, ig)) {
102680
+ const data = readSourceFile(root, join11(root, rel));
101218
102681
  fileBuffers.push({ path: rel, size: data.length, data });
101219
102682
  }
101220
102683
  return buildTarball(fileBuffers);
101221
102684
  }
101222
- function createTarballFromFiles(files, _config) {
102685
+ function createTarballFromFiles(files, _config, options = {}) {
101223
102686
  const seen = new Set;
101224
102687
  const fileBuffers = [];
101225
102688
  for (const file of files) {
@@ -101229,15 +102692,26 @@ function createTarballFromFiles(files, _config) {
101229
102692
  }
101230
102693
  seen.add(path);
101231
102694
  const data = Buffer.from(file.data);
101232
- fileBuffers.push({ path, size: data.length, data });
102695
+ if (file.mode !== undefined && file.mode !== 420 && file.mode !== 493)
102696
+ throw new Error("unsupported source file mode");
102697
+ fileBuffers.push({
102698
+ path,
102699
+ size: data.length,
102700
+ data,
102701
+ ...file.mode !== undefined ? { mode: file.mode } : {}
102702
+ });
101233
102703
  }
101234
- return buildTarball(fileBuffers);
102704
+ const emptyDirs = (options.emptyDirs ?? []).map(normalizeInlinePath).sort();
102705
+ if (new Set(emptyDirs).size !== emptyDirs.length) {
102706
+ throw new Error("duplicate empty directory in inline source");
102707
+ }
102708
+ return buildTarball(fileBuffers, emptyDirs);
101235
102709
  }
101236
102710
 
101237
102711
  // ../core/dist/watcher.js
101238
- var import_ignore2 = __toESM(require_ignore(), 1);
101239
- import { existsSync as existsSync7, lstatSync as lstatSync2, readFileSync as readFileSync8, watch } from "node:fs";
102712
+ import { existsSync as existsSync7, lstatSync as lstatSync3, readFileSync as readFileSync8, watch } from "node:fs";
101240
102713
  import { join as join12, sep as sep3 } from "node:path";
102714
+ var import_ignore2 = __toESM(require_ignore(), 1);
101241
102715
  var DEFAULT_IGNORE2 = [
101242
102716
  "node_modules",
101243
102717
  ".git",
@@ -101246,8 +102720,7 @@ var DEFAULT_IGNORE2 = [
101246
102720
  ".svelte-kit",
101247
102721
  "build",
101248
102722
  "coverage",
101249
- ".env",
101250
- ".env.*",
102723
+ ...ENV_FILE_IGNORE_PATTERNS,
101251
102724
  ".bun",
101252
102725
  "*.log",
101253
102726
  ".DS_Store",
@@ -101272,7 +102745,7 @@ function createWatcher(options) {
101272
102745
  if (ig.ignores(rel))
101273
102746
  return;
101274
102747
  try {
101275
- if (lstatSync2(join12(options.cwd, rel)).isDirectory() && ig.ignores(`${rel}/`))
102748
+ if (lstatSync3(join12(options.cwd, rel)).isDirectory() && ig.ignores(`${rel}/`))
101276
102749
  return;
101277
102750
  } catch {}
101278
102751
  pending.add(rel);
@@ -101618,6 +103091,7 @@ async function waitForDeploy(ctx, input, opts) {
101618
103091
  const rc = deployment.runtimeCapture;
101619
103092
  return {
101620
103093
  status: "live",
103094
+ pocketbaseSuperuserEnvNote: pbSuperuserEnvNote(deployment),
101621
103095
  app: { id: app.id, name: app.name, url: app.url },
101622
103096
  deployment,
101623
103097
  url,
@@ -101843,6 +103317,10 @@ async function doctor(ctx, input = {}) {
101843
103317
  checks.push({ name: "App", status: "skip", message: reason });
101844
103318
  return summarize(checks, { appProvided: !!input.app, tomlProblems });
101845
103319
  }
103320
+ return doctorServer(ctx, { ...input, app: appName }, checks, !!input.app);
103321
+ }
103322
+ async function doctorServer(ctx, input, checks = [], appProvided = true) {
103323
+ const appName = input.app;
101846
103324
  let appStatus;
101847
103325
  let lastDeployStatus;
101848
103326
  let lastDeployId;
@@ -102112,7 +103590,7 @@ ${rc.errors.map((e) => ` • [${e.kind}] ${e.text}${e.url ? ` (${e.url}${e.line
102112
103590
  }
102113
103591
  return summarize(checks, {
102114
103592
  appName,
102115
- appProvided: !!input.app,
103593
+ appProvided,
102116
103594
  appStatus,
102117
103595
  lastDeployStatus,
102118
103596
  lastDeployId,
@@ -102684,10 +104162,11 @@ async function envList(ctx, input = {}) {
102684
104162
  return { values, detailed };
102685
104163
  }
102686
104164
  // ../core/dist/commands/export.js
102687
- import { randomUUID as randomUUID2 } from "node:crypto";
104165
+ init_dist();
104166
+ import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
102688
104167
  import { createWriteStream as createWriteStream2 } from "node:fs";
102689
104168
  import { rename as rename2, unlink as unlink2 } from "node:fs/promises";
102690
- import { isAbsolute as isAbsolute2, resolve as resolvePath } from "node:path";
104169
+ import { isAbsolute as isAbsolute3, resolve as resolvePath } from "node:path";
102691
104170
  var exportInputSchema = object({
102692
104171
  app: string2().optional(),
102693
104172
  out: string2().optional(),
@@ -102707,9 +104186,10 @@ function resolveAppName3(ctx, provided) {
102707
104186
  }
102708
104187
  return name;
102709
104188
  }
102710
- async function streamToFile(outPath, source) {
104189
+ async function streamToFile(outPath, source, options) {
104190
+ options?.signal?.throwIfAborted();
102711
104191
  const tmpPath = `${outPath}.part-${randomUUID2()}`;
102712
- const out = createWriteStream2(tmpPath);
104192
+ const out = createWriteStream2(tmpPath, { flags: "wx", mode: 384 });
102713
104193
  const reader = source.getReader();
102714
104194
  const closed = new Promise((resolve) => out.once("close", () => resolve()));
102715
104195
  let onWriteError;
@@ -102718,14 +104198,31 @@ async function streamToFile(outPath, source) {
102718
104198
  });
102719
104199
  out.once("error", onWriteError);
102720
104200
  writeFailed.catch(() => {});
104201
+ const hash = options ? createHash3("sha256") : undefined;
104202
+ const abort = () => {
104203
+ const reason = options?.signal?.reason instanceof Error ? options.signal.reason : new Error("Export aborted");
104204
+ out.destroy(reason);
104205
+ reader.cancel(reason).catch(() => {});
104206
+ };
104207
+ options?.signal?.addEventListener("abort", abort, { once: true });
104208
+ if (options?.signal?.aborted)
104209
+ abort();
102721
104210
  let bytes = 0;
102722
104211
  try {
102723
104212
  for (;; ) {
102724
104213
  const { done, value } = await Promise.race([reader.read(), writeFailed]);
104214
+ options?.signal?.throwIfAborted();
102725
104215
  if (done)
102726
104216
  break;
102727
104217
  if (value && value.byteLength > 0) {
104218
+ if (options && value.byteLength > options.bytes - bytes)
104219
+ throw new PercherApiError("Export size did not match its verified header.", {
104220
+ status: 502,
104221
+ code: "EXPORT_INTEGRITY_FAILED"
104222
+ });
102728
104223
  bytes += value.byteLength;
104224
+ hash?.update(value);
104225
+ options?.signal?.throwIfAborted();
102729
104226
  if (!out.write(value)) {
102730
104227
  await Promise.race([
102731
104228
  new Promise((resolve) => out.once("drain", resolve)),
@@ -102734,15 +104231,24 @@ async function streamToFile(outPath, source) {
102734
104231
  }
102735
104232
  }
102736
104233
  }
104234
+ options?.signal?.throwIfAborted();
102737
104235
  await new Promise((resolve, reject) => {
102738
104236
  out.end((err) => err ? reject(err) : resolve());
102739
104237
  });
102740
104238
  await closed;
104239
+ options?.signal?.throwIfAborted();
104240
+ if (options && (bytes !== options.bytes || hash?.digest("hex") !== options.sha256))
104241
+ throw new PercherApiError("Export checksum or size verification failed. The previous file was preserved.", { status: 502, code: "EXPORT_INTEGRITY_FAILED" });
102741
104242
  } catch (err) {
104243
+ reader.cancel().catch(() => {});
102742
104244
  out.destroy();
102743
104245
  await closed;
102744
104246
  await unlink2(tmpPath).catch(() => {});
104247
+ options?.signal?.throwIfAborted();
102745
104248
  throw err;
104249
+ } finally {
104250
+ options?.signal?.removeEventListener("abort", abort);
104251
+ reader.releaseLock();
102746
104252
  }
102747
104253
  try {
102748
104254
  await rename2(tmpPath, outPath);
@@ -102753,35 +104259,93 @@ async function streamToFile(outPath, source) {
102753
104259
  return { bytes };
102754
104260
  }
102755
104261
  function resolveOutPath(ctxCwd, filename) {
102756
- if (isAbsolute2(filename))
104262
+ if (isAbsolute3(filename))
102757
104263
  return filename;
102758
104264
  return resolvePath(ctxCwd, filename);
102759
104265
  }
102760
104266
  async function exportApp(ctx, input) {
102761
104267
  const name = resolveAppName3(ctx, input.app);
102762
- const mint = await ctx.client.export.mint(name, { deliveryKind: input.deliveryKind });
102763
- const dl = await ctx.client.export.download(mint.downloadUrl);
102764
- if (!dl.body) {
102765
- throw new PercherCoreError("Export download returned an empty body", {
102766
- code: "export.empty-body",
102767
- hint: "Try again — the link is single-use, so a new mint is required."
104268
+ const started = Date.now();
104269
+ const controller = new AbortController;
104270
+ const expired = () => controller.abort(new PercherApiError("Export preparation expired. Start a new export.", {
104271
+ status: 410,
104272
+ code: "EXPORT_EXPIRED"
104273
+ }));
104274
+ let timer = setTimeout(expired, 900000);
104275
+ let response;
104276
+ try {
104277
+ const mint = await ctx.client.export.mintV2(name, {
104278
+ deliveryKind: input.deliveryKind,
104279
+ signal: controller.signal
102768
104280
  });
104281
+ const originalDeadline = Date.parse(mint.expiresAt);
104282
+ const localDeadline = Math.min(originalDeadline, started + 900000);
104283
+ clearTimeout(timer);
104284
+ if (localDeadline <= Date.now())
104285
+ expired();
104286
+ else
104287
+ timer = setTimeout(expired, localDeadline - Date.now());
104288
+ controller.signal.throwIfAborted();
104289
+ let state = await ctx.client.export.prepareV2(mint.preparationToken, controller.signal);
104290
+ let revision = -1;
104291
+ let polls = 0;
104292
+ for (;; ) {
104293
+ controller.signal.throwIfAborted();
104294
+ if (Date.now() >= localDeadline) {
104295
+ expired();
104296
+ controller.signal.throwIfAborted();
104297
+ }
104298
+ if (state.operationId !== mint.operationId || state.deadline !== originalDeadline || state.revision < revision)
104299
+ throw new PercherApiError("Export preparation status changed unexpectedly.", {
104300
+ status: 502,
104301
+ code: "EXPORT_INVALID_RESPONSE"
104302
+ });
104303
+ revision = state.revision;
104304
+ if (state.state === "READY")
104305
+ break;
104306
+ if (state.state === "CLEANUP_REQUIRED")
104307
+ throw new PercherApiError("Export preparation requires cleanup. Contact support before retrying.", { status: 409, code: "EXPORT_CLEANUP_REQUIRED" });
104308
+ if (state.state === "NOT_REQUESTED")
104309
+ throw new PercherApiError("Export preparation was not queued. Retry later.", {
104310
+ status: 409,
104311
+ code: "EXPORT_NOT_REQUESTED"
104312
+ });
104313
+ if (++polls > 900) {
104314
+ expired();
104315
+ controller.signal.throwIfAborted();
104316
+ }
104317
+ await abortableSleep(Math.min(1000, localDeadline - Date.now()), controller.signal);
104318
+ controller.signal.throwIfAborted();
104319
+ state = await ctx.client.export.statusV2(mint.preparationToken, controller.signal);
104320
+ }
104321
+ const grant = await ctx.client.export.grantV2(mint.preparationToken, controller.signal);
104322
+ if (Date.parse(grant.expiresAt) > originalDeadline)
104323
+ throw new PercherApiError("Export grant exceeded the preparation deadline.", {
104324
+ status: 502,
104325
+ code: "EXPORT_INVALID_RESPONSE"
104326
+ });
104327
+ const download = await ctx.client.export.downloadV2(grant.downloadUrl, controller.signal);
104328
+ response = download.response;
104329
+ if (!response.body)
104330
+ throw new PercherCoreError("Export download returned an empty body", {
104331
+ code: "export.empty-body"
104332
+ });
104333
+ const headerName = response.headers.get("Content-Disposition")?.match(/filename="?([^";]+)"?/)?.[1];
104334
+ const safeHeader = headerName && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(headerName) ? headerName : undefined;
104335
+ const fallback = `${name.replace(/[^A-Za-z0-9._-]/g, "_")}-export.tar.gz`;
104336
+ const outPath = resolveOutPath(ctx.cwd, input.out ?? safeHeader ?? fallback);
104337
+ const { bytes } = await streamToFile(outPath, response.body, {
104338
+ signal: controller.signal,
104339
+ bytes: download.bytes,
104340
+ sha256: download.sha256
104341
+ });
104342
+ return { appName: name, outPath, bytes, expiresAt: mint.expiresAt, includedSecrets: false };
104343
+ } finally {
104344
+ clearTimeout(timer);
104345
+ controller.abort();
104346
+ if (response?.body && !response.body.locked)
104347
+ response.body.cancel().catch(() => {});
102769
104348
  }
102770
- const filenameFromHeader = (() => {
102771
- const cd = dl.headers.get("Content-Disposition") ?? "";
102772
- const m = cd.match(/filename="?([^";]+)"?/);
102773
- return m?.[1];
102774
- })();
102775
- const filename = input.out ?? filenameFromHeader ?? `${name}-export.tar.gz`;
102776
- const outPath = resolveOutPath(ctx.cwd, filename);
102777
- const { bytes } = await streamToFile(outPath, dl.body);
102778
- return {
102779
- appName: name,
102780
- outPath,
102781
- bytes,
102782
- expiresAt: mint.expiresAt,
102783
- includedSecrets: false
102784
- };
102785
104349
  }
102786
104350
  async function exportGitBundle(ctx, input) {
102787
104351
  const name = resolveAppName3(ctx, input.app);
@@ -103136,6 +104700,16 @@ var INIT_TEMPLATE_FRAMEWORKS = new Set([
103136
104700
  "vite"
103137
104701
  ]);
103138
104702
  function renderStaticFrameworkDockerfile(input) {
104703
+ const outputDir = normalizeStaticOutputDir(input.outputDir);
104704
+ const sanitize = [
104705
+ 'const fs=require("node:fs"),path=require("node:path")',
104706
+ "const root=fs.realpathSync(process.argv[1]),dir=fs.realpathSync(process.argv[2]),dest=process.argv[3]",
104707
+ `const deny=new RegExp(${JSON.stringify(STATIC_PLATFORM_PATH_REGEX.slice(4))},"i")`,
104708
+ 'const reserved=p=>deny.test("/"+p.split(path.sep).join("/"))',
104709
+ 'if((dir!==root&&!dir.startsWith(root+path.sep))||reserved(path.relative(root,dir)))throw Error("Static output escapes the project or selects platform content")',
104710
+ 'if(fs.existsSync(dest))throw Error("Reserved static staging directory already exists")',
104711
+ 'fs.cpSync(dir,dest,{recursive:true,filter:p=>{if(reserved(path.relative(dir,p))||reserved(path.relative(root,p)))return false;if(fs.lstatSync(p).isSymbolicLink()){console.error("Static content cannot contain symlinks");process.exit(1)};return true}})'
104712
+ ].join(";");
103139
104713
  return `# Multi-stage build: a Bun stage compiles the static bundle, then a
103140
104714
  # minimal Caddy image serves it. This project uses runtime = "docker"
103141
104715
  # (not "static") because Percher's static runtime serves pre-built
@@ -103148,27 +104722,26 @@ WORKDIR /app
103148
104722
  COPY . .
103149
104723
  RUN bun install && bun run build
103150
104724
 
104725
+ # Preserve build inputs for deployment; only this filtered copy reaches /srv.
104726
+ FROM build AS static-content
104727
+ RUN bun -e ${shellQuote(sanitize)} '/app' ${shellQuote(`/app/${outputDir}`)} '/percher-static-content'
104728
+
103151
104729
  # --- Serve stage: minimal Caddy image --------------------------------
103152
104730
  # Build pinned Caddy source with refreshed security modules. The scratch
103153
104731
  # runtime carries no shell, package manager, or file capabilities and listens
103154
104732
  # on the unprivileged port :${STATIC_DOCKER_PORT}.
103155
104733
  FROM golang:1.26.10-alpine3.23@sha256:0525c952defebc693cdaf62cdf43afa32be5a7f377e99260642ea19c240c708e AS caddy-source
103156
- ADD --checksum=sha256:78e660d838e45c0b8c89338b325946238f153641aa9925df9ef2ad5e8eced31b \\
103157
- https://github.com/caddyserver/caddy/commit/b2693fb63a30e6d7be0972c3645e9a2c0a500e93.patch /tmp/caddy-cel-go.patch
103158
- RUN go mod download github.com/caddyserver/caddy/v2@v2.11.4 \\
103159
- && cp -R /go/pkg/mod/github.com/caddyserver/caddy/v2@v2.11.4 /src \\
104734
+ RUN go mod download github.com/caddyserver/caddy/v2@v2.11.7 \\
104735
+ && cp -R /go/pkg/mod/github.com/caddyserver/caddy/v2@v2.11.7 /src \\
103160
104736
  && chmod -R u+w /src
103161
104737
  WORKDIR /src
103162
- RUN apk add --no-cache patch \\
103163
- && patch -p1 < /tmp/caddy-cel-go.patch \\
103164
- && go get github.com/go-chi/chi/v5@v5.3.0 github.com/google/cel-go@v0.29.2 \\
103165
- github.com/klauspost/compress@v1.18.7 go.opentelemetry.io/otel@v1.45.0 \\
103166
- go.opentelemetry.io/otel/sdk/log@v0.21.0 \\
103167
- go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc@v0.21.0 \\
103168
- go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp@v0.21.0 \\
103169
- go.opentelemetry.io/otel/exporters/stdout/stdoutlog@v0.21.0 \\
103170
- go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc@v1.45.0 \\
103171
- go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp@v1.45.0 \\
104738
+ RUN go get github.com/go-jose/go-jose/v4@v4.1.6 github.com/go-chi/chi/v5@v5.3.2 github.com/klauspost/compress@v1.20.1 \\
104739
+ go.opentelemetry.io/otel@v1.46.0 go.opentelemetry.io/otel/sdk/log@v0.22.0 \\
104740
+ go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc@v0.22.0 \\
104741
+ go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp@v0.22.0 \\
104742
+ go.opentelemetry.io/otel/exporters/stdout/stdoutlog@v0.22.0 \\
104743
+ go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc@v1.46.0 \\
104744
+ go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp@v1.46.0 \\
103172
104745
  golang.org/x/crypto@v0.57.0 golang.org/x/net@v0.60.0 \\
103173
104746
  golang.org/x/text@v0.42.0 google.golang.org/grpc@v1.83.2 \\
103174
104747
  && go mod tidy \\
@@ -103184,7 +104757,7 @@ COPY --from=caddy-source /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-ce
103184
104757
  COPY --from=caddy-source /out/caddy /usr/bin/caddy
103185
104758
  COPY --from=caddy-source /out/percher-healthcheck /usr/bin/percher-healthcheck
103186
104759
  COPY Caddyfile /etc/caddy/Caddyfile
103187
- COPY --from=build /app/${input.outputDir} /srv
104760
+ COPY --from=static-content /percher-static-content /srv
103188
104761
  LABEL dev.percher.health-client="static-http-v1"
103189
104762
  # HOME points at the writable tmpfs so non-root Caddy can persist its
103190
104763
  # XDG state (storage-clean lock, config autosave) under Percher's
@@ -103196,11 +104769,17 @@ CMD ["caddy", "run", "--config", "/etc/caddy/Caddyfile", "--adapter", "caddyfile
103196
104769
  `;
103197
104770
  }
103198
104771
  function renderStaticFrameworkCaddyfile(input) {
103199
- const directives = ["bind 0.0.0.0", "root * /srv", "encode gzip zstd"];
104772
+ const directives = [
104773
+ "bind 0.0.0.0",
104774
+ "root * /srv",
104775
+ "encode gzip zstd",
104776
+ "route {",
104777
+ ...staticPlatformDenyDirectives().map((line) => ` ${line}`)
104778
+ ];
103200
104779
  if (input.spa) {
103201
- directives.push("try_files {path} /index.html");
104780
+ directives.push("\ttry_files {path} /index.html");
103202
104781
  }
103203
- directives.push("file_server");
104782
+ directives.push("\tfile_server", "}");
103204
104783
  const body = directives.map((d) => ` ${d}`).join(`
103205
104784
  `);
103206
104785
  return `:${STATIC_DOCKER_PORT} {
@@ -103217,6 +104796,9 @@ function readGoPins(dockerfile) {
103217
104796
  }
103218
104797
  return { go: /^FROM golang:(\d+\.\d+\.\d+)/m.exec(dockerfile)?.[1] ?? null, modules };
103219
104798
  }
104799
+ function shellQuote(value) {
104800
+ return "'" + value.replaceAll("'", "'\\''") + "'";
104801
+ }
103220
104802
 
103221
104803
  // ../core/dist/commands/import-project.js
103222
104804
  var importInputSchema = object({
@@ -106509,7 +108091,7 @@ function applyRewrite(path, replacement, kind, pattern, note, flags, state) {
106509
108091
  // ../core/dist/commands/migrate-supabase-walker.js
106510
108092
  var import_ignore3 = __toESM(require_ignore(), 1);
106511
108093
  import { mkdir as mkdir2, readdir, readFile as readFile3, stat as stat2, writeFile as writeFile2 } from "node:fs/promises";
106512
- import { dirname as dirname6, isAbsolute as isAbsolute3, join as join19, relative as relative5, resolve as resolve7, sep as sep4 } from "node:path";
108094
+ import { dirname as dirname6, isAbsolute as isAbsolute4, join as join19, relative as relative5, resolve as resolve7, sep as sep4 } from "node:path";
106513
108095
  var REWRITABLE_EXTENSIONS = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"]);
106514
108096
  var DEFAULT_EXCLUDES = [
106515
108097
  "node_modules",
@@ -106820,7 +108402,7 @@ async function writeWalkResult(input) {
106820
108402
  const abs = resolve7(targetAbs, file.relativePath);
106821
108403
  const rel = relative5(targetAbs, abs);
106822
108404
  const isParentTraversal = rel === ".." || rel.startsWith(`..${sep4}`) || rel.startsWith("../");
106823
- if (rel.length === 0 || isParentTraversal || isAbsolute3(rel)) {
108405
+ if (rel.length === 0 || isParentTraversal || isAbsolute4(rel)) {
106824
108406
  throw new Error(`writeWalkResult refused path-traversing file "${file.relativePath}" → "${abs}" (would escape targetDir "${targetAbs}").`);
106825
108407
  }
106826
108408
  await mkdir2(dirname6(abs), { recursive: true });
@@ -107557,7 +109139,7 @@ function failure3(rootAbs, mode, err, suggestion) {
107557
109139
  }
107558
109140
  // ../core/dist/commands/migrate-supabase-schema.js
107559
109141
  import { mkdir as mkdir4, writeFile as writeFile4 } from "node:fs/promises";
107560
- import { isAbsolute as isAbsolute4, join as join22, relative as relative8, resolve as resolve10 } from "node:path";
109142
+ import { isAbsolute as isAbsolute5, join as join22, relative as relative8, resolve as resolve10 } from "node:path";
107561
109143
 
107562
109144
  // ../core/dist/commands/migrate-supabase-scripts.js
107563
109145
  function generateDataImportScripts(preview) {
@@ -108070,7 +109652,7 @@ async function migrateSupabaseSchema(ctx, input) {
108070
109652
  }
108071
109653
  function resolveOutputDir(cwd, requested) {
108072
109654
  const raw = requested ?? "./migration-preview";
108073
- return isAbsolute4(raw) ? raw : resolve10(cwd, raw);
109655
+ return isAbsolute5(raw) ? raw : resolve10(cwd, raw);
108074
109656
  }
108075
109657
  async function writePreviewFiles(ctx, outputDir, preview) {
108076
109658
  await mkdir4(outputDir, { recursive: true });
@@ -108316,9 +109898,9 @@ import { existsSync as existsSync15 } from "node:fs";
108316
109898
  import { join as join25 } from "node:path";
108317
109899
 
108318
109900
  // ../shared/dist/pow.js
108319
- import { createHash as createHash3 } from "node:crypto";
109901
+ import { createHash as createHash4 } from "node:crypto";
108320
109902
  function digest(nonce, solution) {
108321
- return createHash3("sha256").update(`${nonce}:${solution}`).digest("hex");
109903
+ return createHash4("sha256").update(`${nonce}:${solution}`).digest("hex");
108322
109904
  }
108323
109905
  function leadingZeroBits(hexDigest) {
108324
109906
  let bits = 0;
@@ -108717,7 +110299,7 @@ async function runDeployWithRetry(opts) {
108717
110299
 
108718
110300
  // ../core/dist/commands/env-scan.js
108719
110301
  init_dist();
108720
- import { readdirSync as readdirSync3, readFileSync as readFileSync11, statSync as statSync3 } from "node:fs";
110302
+ import { readdirSync as readdirSync3, readFileSync as readFileSync11, statSync as statSync2 } from "node:fs";
108721
110303
  import { join as join23 } from "node:path";
108722
110304
  function platformInjectedClientEnvKeys(config) {
108723
110305
  const data = config.data;
@@ -108811,7 +110393,7 @@ function* walkDir(dir, base) {
108811
110393
  const full = join23(dir, name);
108812
110394
  let st;
108813
110395
  try {
108814
- st = statSync3(full);
110396
+ st = statSync2(full);
108815
110397
  } catch {
108816
110398
  continue;
108817
110399
  }
@@ -110005,6 +111587,7 @@ async function finalizeDeploy(opts) {
110005
111587
  });
110006
111588
  return {
110007
111589
  status: "live",
111590
+ pocketbaseSuperuserEnvNote: pbSuperuserEnvNote(deployment),
110008
111591
  url,
110009
111592
  qrDataUri,
110010
111593
  app,
@@ -110290,6 +111873,19 @@ var publishInlineInputSchema = object({
110290
111873
  noCache: boolean2().optional().describe("Skip the image cache and force a fresh build."),
110291
111874
  waitForLive: boolean2().optional().describe("If true (default), block until the deploy is live or failed. If false, return as soon as it is queued so the agent can resume with percher_wait_for_deploy.")
110292
111875
  });
111876
+ // ../core/dist/commands/publish-patch.js
111877
+ var publishPatchInputSchema = object({
111878
+ app: string2().min(1).describe("Explicit app name or id. No local-state fallback."),
111879
+ expectedBase: string2().regex(/^[0-9a-f]{40}$/).describe("Full live version commit from percher_versions; prefixes and branch names are refused."),
111880
+ files: array(object({
111881
+ path: string2().min(1).max(1024),
111882
+ content: string2(),
111883
+ encoding: _enum(["utf8", "base64"]).optional()
111884
+ }).strict()).max(2000),
111885
+ delete: array(string2().min(1).max(1024)).max(2000),
111886
+ dryRun: boolean2().optional().describe("Classify requested changes without creating a deployment or returning unchanged source."),
111887
+ confirm: boolean2().optional().describe("Required true for publishing, after the user requested the change.")
111888
+ }).strict().refine((input) => input.dryRun === true || input.confirm === true, "Publishing requires confirm: true.");
110293
111889
  // ../core/dist/commands/push.js
110294
111890
  init_dist();
110295
111891
  import { existsSync as existsSync16 } from "node:fs";
@@ -110908,6 +112504,7 @@ async function redeploy(ctx, input = {}) {
110908
112504
  const cacheTag = cacheHit ? "cached, " : "";
110909
112505
  return {
110910
112506
  status: "live",
112507
+ pocketbaseSuperuserEnvNote: pbSuperuserEnvNote(deployment),
110911
112508
  app,
110912
112509
  deployment,
110913
112510
  url,
@@ -111511,7 +113108,7 @@ async function sleep(ctx, input = {}) {
111511
113108
  var statusInputSchema = object({
111512
113109
  json: boolean2().optional()
111513
113110
  });
111514
- async function status(ctx, _input = {}) {
113111
+ async function status2(ctx, _input = {}) {
111515
113112
  let health;
111516
113113
  try {
111517
113114
  health = await ctx.client.platform.health();
@@ -112027,6 +113624,10 @@ async function writeStageTimeline(ctx, events) {
112027
113624
  await writeLine2(ctx, ` ${r.stage.padEnd(stageW)} ${dur} ${mark}`);
112028
113625
  }
112029
113626
  }
113627
+ async function printPbSuperuserEnvNote(ctx, result) {
113628
+ if (result.pocketbaseSuperuserEnvNote)
113629
+ await writeLine2(ctx, result.pocketbaseSuperuserEnvNote);
113630
+ }
112030
113631
  async function printSuperuserResetResult(ctx, result) {
112031
113632
  await writeLine2(ctx, `${import_picocolors.default.green("✓")} ${result.message}`);
112032
113633
  if (result.password) {
@@ -112696,6 +114297,7 @@ async function handlePublishResult(ctx, result, options = {}) {
112696
114297
  case "live": {
112697
114298
  const timing = result.timing ? ` (${result.timing.totalSeconds}s)` : "";
112698
114299
  await writeLine2(ctx, `${import_picocolors5.default.green("✓")} Published to ${result.url}${timing}`);
114300
+ await printPbSuperuserEnvNote(ctx, result);
112699
114301
  if (result.traceId) {
112700
114302
  await writeLine2(ctx, import_picocolors5.default.dim(` Trace: ${result.traceId}`));
112701
114303
  }
@@ -112846,6 +114448,7 @@ function registerAppsCommands(cli, ctx) {
112846
114448
  }
112847
114449
  throw new SilentExitError;
112848
114450
  }
114451
+ await printPbSuperuserEnvNote(ctx, result);
112849
114452
  const timing = result.timing ? ` (${result.timing.totalSeconds.toFixed(0)}s)` : "";
112850
114453
  await writeLine2(ctx, `${import_picocolors5.default.green("✓")} Redeployed to ${result.url}${timing}`);
112851
114454
  });
@@ -112895,6 +114498,7 @@ function registerAppsCommands(cli, ctx) {
112895
114498
  await writeLine2(ctx, import_picocolors5.default.dim(`${lastStatus}...`));
112896
114499
  }
112897
114500
  if (result.status === "live") {
114501
+ await printPbSuperuserEnvNote(ctx, result);
112898
114502
  await writeLine2(ctx, `${import_picocolors5.default.green("✓")} ${result.summary}`);
112899
114503
  return;
112900
114504
  }
@@ -113304,7 +114908,7 @@ var DATA_VALUE_FLAGS = new Set([
113304
114908
  "--client-secret"
113305
114909
  ]);
113306
114910
  function registerDataCommands(cli, ctx, argv) {
113307
- cli.command("data [app] [...rest]", "Show app data status and collections").option("--json", "Output as JSON").option("--reveal", "(reset-superuser only) also print the plaintext password once").option("--out <path>", "(export only) Output file (default: ./<app>-pb-<timestamp>.tar.gz)").option("--provider <name>", "(oauth only) OAuth provider (default: google)").option("--app <name>", "Target app (default: read percher.toml); names an app called like a subcommand, e.g. `data --app get`").option("--client-id <id>", "(oauth only) OAuth client id").option("--client-secret <secret>", "(oauth only) OAuth client secret (a command-line value lands in shell history)").option("--remove", "(oauth only) remove the provider instead of setting it").option("--filter <expr>", "(query only) filter over the collection's fields").option("--sort <fields>", "(query only) comma-separated fields, - for descending (write --sort=-field)").option("--page <n>", "(query only) page number").option("--per-page <n>", "(query only) records per page (max 100)").option("--fields <fields>", "(query only) comma-separated fields to return").option("--data <json>", "(create, update) field values as a JSON object").option("--id <id>", "(create only) id for the new record").option("--if-updated <timestamp>", "(update only) refuse if the record changed since").action(async (app, _rest, options) => {
114911
+ cli.command("data [app] [...rest]", "Show app data status and collections").option("--json", "Output as JSON").option("--reveal", "(reset-superuser only) also print the plaintext password once").option("--out <path>", "(export only) Output file (default: ./<app>-pb-<timestamp>.tar.gz)").option("--provider <name>", "(oauth only) OAuth provider (default: google)").option("--app <name>", "Target app (default: read percher.toml); names an app called like a subcommand, e.g. `data --app get`").option("--client-id <id>", "(oauth only) OAuth client id").option("--client-secret <secret>", "(oauth only, deprecated) Client secret; prefer the hidden prompt or --client-secret-stdin").option("--client-secret-stdin", "(oauth only) Read client secret from stdin").option("--remove", "(oauth only) remove the provider instead of setting it").option("--filter <expr>", "(query only) filter over the collection's fields").option("--sort <fields>", "(query only) comma-separated fields, - for descending (write --sort=-field)").option("--page <n>", "(query only) page number").option("--per-page <n>", "(query only) records per page (max 100)").option("--fields <fields>", "(query only) comma-separated fields to return").option("--data <json>", "(create, update) field values as a JSON object").option("--id <id>", "(create only) id for the new record").option("--if-updated <timestamp>", "(update only) refuse if the record changed since").action(async (app, _rest, options) => {
113308
114912
  if (app !== undefined && DATA_RECORD_SUBCOMMANDS.has(app)) {
113309
114913
  await runDataRecordCommand(ctx, argv, app, _rest, options);
113310
114914
  return;
@@ -113331,11 +114935,30 @@ function registerDataCommands(cli, ctx, argv) {
113331
114935
  if (app === "oauth") {
113332
114936
  const idx = argv.indexOf("oauth");
113333
114937
  const provider = (idx >= 0 ? firstNonFlagAfter(argv, idx, DATA_VALUE_FLAGS) : undefined) ?? options.provider ?? "google";
114938
+ await Promise.resolve().then(() => init_data_oauth_input());
114939
+ await Promise.resolve().then(() => init_prompt_hidden());
114940
+ let clientSecret;
114941
+ try {
114942
+ clientSecret = await resolveOauthSecret({
114943
+ clientId: options.clientId,
114944
+ clientSecret: options.clientSecret,
114945
+ fromStdin: argv.includes("--client-secret-stdin"),
114946
+ remove: options.remove,
114947
+ readStdin: () => readOauthSecretStdin(process.stdin),
114948
+ promptHidden,
114949
+ warn: () => writeLine2(ctx, "Warning: --client-secret exposes the value in process arguments and shell history. Use the hidden prompt or --client-secret-stdin.")
114950
+ });
114951
+ } catch (error) {
114952
+ if (!(error instanceof OauthSecretInputError))
114953
+ throw error;
114954
+ await writeLine2(ctx, error.message);
114955
+ throw new SilentExitError;
114956
+ }
113334
114957
  const result = await dataOauth(ctx, {
113335
114958
  app: options.app,
113336
114959
  provider,
113337
114960
  clientId: options.clientId,
113338
- clientSecret: options.clientSecret,
114961
+ clientSecret,
113339
114962
  remove: options.remove
113340
114963
  });
113341
114964
  if (result.action === "removed") {
@@ -113385,11 +115008,11 @@ function registerDataCommands(cli, ctx, argv) {
113385
115008
  }
113386
115009
  });
113387
115010
  registerDataRecordHelp(cli);
113388
- cli.command("data reset-superuser [app]", "Reset PocketBase superuser and inject new credentials").option("--reveal", "Also print the plaintext password once (default: hidden)").action(async (app, options) => {
115011
+ cli.command("data reset-superuser [app]", "Rotate PocketBase superuser credentials (app injection follows its policy)").option("--reveal", "Also print the plaintext password once (default: hidden)").action(async (app, options) => {
113389
115012
  const result = await resetSuperuser(ctx, { app, reveal: options.reveal });
113390
115013
  await printSuperuserResetResult(ctx, result);
113391
115014
  });
113392
- cli.command("data oauth [provider]", "Configure capsule OAuth sign-in (e.g. `data oauth google --client-id … --client-secret …`)").action(async () => {});
115015
+ cli.command("data oauth [provider]", "Configure capsule OAuth sign-in: data oauth google --client-id <id> (hidden secret prompt)").action(async () => {});
113393
115016
  cli.command("data export [app]", "Download a snapshot of your app's PocketBase data as a .tar.gz").action(async () => {});
113394
115017
  cli.command("backups [app]", "List available backups for an app").action(async (app) => {
113395
115018
  const { backups, skipped } = await listBackups(ctx, { app });
@@ -114242,7 +115865,7 @@ function registerSharingCommands(cli, ctx) {
114242
115865
  var import_picocolors15 = __toESM(require_picocolors(), 1);
114243
115866
  function registerStatusCommands(cli, ctx) {
114244
115867
  cli.command("status", "Show Percher platform status (API + worker health)").option("--json", "Output JSON instead of formatted text").action(async (options) => {
114245
- const result = await status(ctx, { json: Boolean(options.json) });
115868
+ const result = await status2(ctx, { json: Boolean(options.json) });
114246
115869
  if (options.json) {
114247
115870
  await writeLine2(ctx, JSON.stringify(result, null, 2));
114248
115871
  if (result.verdict === "unreachable")
@@ -114291,7 +115914,7 @@ import { createInterface } from "node:readline";
114291
115914
  // package.json
114292
115915
  var package_default2 = {
114293
115916
  name: "percher",
114294
- version: "1.4.0",
115917
+ version: "1.5.0",
114295
115918
  description: "CLI for the Percher hosting platform — publish apps with one command",
114296
115919
  type: "module",
114297
115920
  bin: {
@@ -114319,10 +115942,10 @@ var package_default2 = {
114319
115942
  typecheck: "tsc --noEmit"
114320
115943
  },
114321
115944
  dependencies: {
114322
- "@percher/shared": "^1.3.0",
114323
- "@percher/client": "^1.4.0",
114324
- "@percher/core": "^1.4.0",
114325
- "@percher/toml": "^1.0.5",
115945
+ "@percher/shared": "^1.4.0",
115946
+ "@percher/client": "^1.5.0",
115947
+ "@percher/core": "^1.5.0",
115948
+ "@percher/toml": "^1.1.0",
114326
115949
  cac: "^7.0.0",
114327
115950
  picocolors: "^1.1.1"
114328
115951
  },