target-supabase-sdk 0.2.24 → 0.3.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.
Files changed (81) hide show
  1. package/dist/browser.d.ts +3 -2
  2. package/dist/browser.d.ts.map +1 -1
  3. package/dist/browser.js +3 -2
  4. package/dist/browser.js.map +1 -1
  5. package/dist/chunks/{list.api-BzbTJBsM.js → config-BNxsVKR4.js} +163 -10
  6. package/dist/chunks/config-BNxsVKR4.js.map +1 -0
  7. package/dist/chunks/{enable-C7lFooTG.js → enable-CF77OsXr.js} +20 -238
  8. package/dist/chunks/enable-CF77OsXr.js.map +1 -0
  9. package/dist/chunks/{task-queue-C_nUaM2S.js → task-queue-BL-KwAGW.js} +39 -13
  10. package/dist/chunks/task-queue-BL-KwAGW.js.map +1 -0
  11. package/dist/node/{node-runtime.base.d.ts → base-node-runtime.d.ts} +4 -1
  12. package/dist/node/base-node-runtime.d.ts.map +1 -0
  13. package/dist/node/node-liveness.d.ts +2 -0
  14. package/dist/node/node-liveness.d.ts.map +1 -1
  15. package/dist/node/node-service-id.d.ts +3 -0
  16. package/dist/node/node-service-id.d.ts.map +1 -0
  17. package/dist/node/node.api.d.ts +9 -1
  18. package/dist/node/node.api.d.ts.map +1 -1
  19. package/dist/node/node.interface.d.ts +9 -2
  20. package/dist/node/node.interface.d.ts.map +1 -1
  21. package/dist/node/service-guard/run-service-guard-tick.d.ts.map +1 -1
  22. package/dist/node/service-guard/service-guard-node.d.ts +3 -1
  23. package/dist/node/service-guard/service-guard-node.d.ts.map +1 -1
  24. package/dist/node/service-host/service-host.d.ts.map +1 -1
  25. package/dist/node/service-host/single-process-service.d.ts.map +1 -1
  26. package/dist/node.d.ts +2 -2
  27. package/dist/node.d.ts.map +1 -1
  28. package/dist/node.js +244 -198
  29. package/dist/node.js.map +1 -1
  30. package/dist/preload.js +3 -3
  31. package/dist/service/service.interface.d.ts +2 -2
  32. package/dist/service/service.interface.d.ts.map +1 -1
  33. package/dist/shared/log/core/log-batch.d.ts +4 -4
  34. package/dist/shared/log/core/log-batch.d.ts.map +1 -1
  35. package/dist/shared/log/index.d.ts +2 -1
  36. package/dist/shared/log/index.d.ts.map +1 -1
  37. package/dist/shared/log/spool/collector.d.ts +1 -1
  38. package/dist/shared/log/spool/collector.d.ts.map +1 -1
  39. package/dist/shared/log/spool/file.d.ts +2 -8
  40. package/dist/shared/log/spool/file.d.ts.map +1 -1
  41. package/dist/shared/log/spool/writer.d.ts.map +1 -1
  42. package/dist/shared/log/upload/flush.d.ts.map +1 -1
  43. package/dist/shared/log/upload/interface.d.ts +3 -11
  44. package/dist/shared/log/upload/interface.d.ts.map +1 -1
  45. package/dist/task/task-node.d.ts +3 -1
  46. package/dist/task/task-node.d.ts.map +1 -1
  47. package/dist/trigger/trigger-manager.d.ts +1 -1
  48. package/dist/trigger/trigger-node.d.ts +3 -1
  49. package/dist/trigger/trigger-node.d.ts.map +1 -1
  50. package/dist/trigger/trigger.api.d.ts +10 -10
  51. package/package.json +1 -1
  52. package/src/browser.ts +4 -3
  53. package/src/node/{node-runtime.base.ts → base-node-runtime.ts} +11 -2
  54. package/src/node/node-liveness.ts +6 -1
  55. package/src/node/node-service-id.ts +12 -0
  56. package/src/node/node.api.ts +7 -5
  57. package/src/node/node.interface.ts +10 -2
  58. package/src/node/service-guard/run-service-guard-tick.ts +12 -6
  59. package/src/node/service-guard/service-guard-node.ts +6 -1
  60. package/src/node/service-host/service-host.ts +2 -1
  61. package/src/node/service-host/single-process-service.ts +3 -0
  62. package/src/node.ts +2 -2
  63. package/src/service/service.interface.ts +2 -2
  64. package/src/shared/log/README.md +2 -3
  65. package/src/shared/log/core/log-batch.ts +12 -10
  66. package/src/shared/log/index.ts +2 -1
  67. package/src/shared/log/spool/collector.ts +46 -20
  68. package/src/shared/log/spool/file.ts +12 -25
  69. package/src/shared/log/spool/writer.ts +2 -7
  70. package/src/shared/log/upload/flush.ts +23 -38
  71. package/src/shared/log/upload/interface.ts +3 -12
  72. package/src/task/task-node.ts +6 -1
  73. package/src/trigger/trigger-manager.ts +1 -1
  74. package/src/trigger/trigger-node.ts +6 -1
  75. package/dist/chunks/enable-C7lFooTG.js.map +0 -1
  76. package/dist/chunks/list.api-BzbTJBsM.js.map +0 -1
  77. package/dist/chunks/task-queue-C_nUaM2S.js.map +0 -1
  78. package/dist/node/node-runtime.base.d.ts.map +0 -1
  79. package/dist/shared/log/upload/batch-id.d.ts +0 -13
  80. package/dist/shared/log/upload/batch-id.d.ts.map +0 -1
  81. package/src/shared/log/upload/batch-id.ts +0 -43
@@ -1,76 +1,8 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { resolve, dirname, join } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
- import { g as createLogger, c as LOG_PERSIST_LOADER_KEY, a as CategoryList, D as postLogListCreate, q as isCreateTargetAlreadyExistsError, W as registerLogPersistOffer } from './list.api-BzbTJBsM.js';
4
+ import { W as envBool, f as createLogger, L as LOG_BATCH_LIST_VALUE, a as CategoryList, A as postListCreate, X as DEFAULT_LOG_SPOOL_CONFIG, Y as resolveLogSpoolConfig, Z as randomLogSpoolShortId, _ as buildLogSpoolBatchBaseName, $ as registerLogPersistOffer, a0 as LOG_SPOOL_SERVICE_ID_ENV, a1 as logSpoolServiceIdFromEnv, a2 as logSpoolConfigFromEnv } from './config-BNxsVKR4.js';
5
5
  import { mkdir, writeFile, rename } from 'node:fs/promises';
6
- import { createHash } from 'node:crypto';
7
-
8
- function readEnv(name, env = process.env) {
9
- const value = env[name]?.trim();
10
- if (value == null || value === "") {
11
- return undefined;
12
- }
13
- return value;
14
- }
15
- function requireEnv(name, env = process.env) {
16
- const value = readEnv(name, env);
17
- if (value == null) {
18
- throw new Error(`Missing required environment variable: ${name}`);
19
- }
20
- return value;
21
- }
22
-
23
- function envInt(name, defaultValue, options) {
24
- const env = options?.env ?? process.env;
25
- const raw = readEnv(name, env);
26
- if (raw == null) {
27
- return defaultValue;
28
- }
29
- const value = Number(raw);
30
- if (!Number.isInteger(value)) {
31
- throw new Error(`Invalid ${name}: ${raw}`);
32
- }
33
- const min = options?.min;
34
- if (min != null && value < min) {
35
- throw new Error(`Invalid ${name}: ${raw}`);
36
- }
37
- const max = options?.max;
38
- if (max != null && value > max) {
39
- throw new Error(`Invalid ${name}: ${raw}`);
40
- }
41
- return value;
42
- }
43
- function envMs(name, defaultMs, options) {
44
- return envInt(name, defaultMs, { ...options, min: options?.min ?? 1 });
45
- }
46
- function envPort(defaultPort = 3100, options) {
47
- const envKey = options?.envKey ?? "PORT";
48
- return envInt(envKey, defaultPort, { ...options, min: 1, max: 65535 });
49
- }
50
- function envNumber(name, defaultValue, options) {
51
- const env = options?.env ?? process.env;
52
- const raw = readEnv(name, env);
53
- if (raw == null) {
54
- return defaultValue;
55
- }
56
- const value = Number(raw);
57
- if (!Number.isFinite(value)) {
58
- throw new Error(`Invalid ${name}: ${raw}`);
59
- }
60
- const min = options?.min;
61
- const resolved = options?.floor === true ? Math.floor(value) : value;
62
- if (min != null && resolved < min) {
63
- throw new Error(`Invalid ${name}: ${raw}`);
64
- }
65
- return resolved;
66
- }
67
- function envBool(name, defaultValue = false, env = process.env) {
68
- const raw = readEnv(name, env)?.toLowerCase();
69
- if (raw == null) {
70
- return defaultValue;
71
- }
72
- return raw === "1" || raw === "true" || raw === "yes";
73
- }
74
6
 
75
7
  const DEFAULT_ENV_FILES = [".env.local", ".env"];
76
8
  const PROD_ENV_FILES = [".env.prod"];
@@ -233,56 +165,6 @@ function isLogPersistInternalTopic(topic) {
233
165
  return topic === LOG_PERSIST_INTERNAL_TOPIC;
234
166
  }
235
167
 
236
- const LOG_SPOOL_SERVICE_ID_ENV = "LOG_SPOOL_SERVICE_ID";
237
- const DEFAULT_LOG_SPOOL_CONFIG = {
238
- writer: {
239
- maxEntries: 2000,
240
- maxBytes: 2 * 1024 * 1024,
241
- flushDebounceMs: 3_000,
242
- maxAgeMs: 60_000,
243
- postTimeoutMs: 30_000,
244
- },
245
- gc: {
246
- intervalMs: 24 * 60 * 60 * 1000,
247
- syncedRetentionMs: 7 * 24 * 60 * 60 * 1000,
248
- tmpRetentionMs: 7 * 24 * 60 * 60 * 1000,
249
- },
250
- collectIntervalMs: 60_000,
251
- };
252
- function resolveLogSpoolConfig(partial) {
253
- const defaults = DEFAULT_LOG_SPOOL_CONFIG;
254
- return {
255
- writer: { ...defaults.writer, ...partial?.writer },
256
- gc: { ...defaults.gc, ...partial?.gc },
257
- collectIntervalMs: partial?.collectIntervalMs ?? defaults.collectIntervalMs,
258
- };
259
- }
260
- function logSpoolConfigFromEnv(env = process.env) {
261
- return resolveLogSpoolConfig({
262
- writer: {
263
- maxEntries: envInt("LOG_SPOOL_MAX_ENTRIES", DEFAULT_LOG_SPOOL_CONFIG.writer.maxEntries, { env, min: 1 }),
264
- maxBytes: envInt("LOG_SPOOL_MAX_BYTES", DEFAULT_LOG_SPOOL_CONFIG.writer.maxBytes, { env, min: 1 }),
265
- flushDebounceMs: envMs("LOG_SPOOL_FLUSH_DEBOUNCE_MS", DEFAULT_LOG_SPOOL_CONFIG.writer.flushDebounceMs, {
266
- env,
267
- }),
268
- maxAgeMs: envMs("LOG_SPOOL_MAX_AGE_MS", DEFAULT_LOG_SPOOL_CONFIG.writer.maxAgeMs, { env }),
269
- postTimeoutMs: envMs("LOG_PERSIST_POST_TIMEOUT_MS", DEFAULT_LOG_SPOOL_CONFIG.writer.postTimeoutMs, { env }),
270
- },
271
- gc: {
272
- intervalMs: envMs("LOG_SPOOL_GC_INTERVAL_MS", DEFAULT_LOG_SPOOL_CONFIG.gc.intervalMs, { env }),
273
- syncedRetentionMs: envMs("LOG_SPOOL_SYNCED_RETENTION_MS", DEFAULT_LOG_SPOOL_CONFIG.gc.syncedRetentionMs, {
274
- env,
275
- }),
276
- tmpRetentionMs: envMs("LOG_SPOOL_TMP_RETENTION_MS", DEFAULT_LOG_SPOOL_CONFIG.gc.tmpRetentionMs, { env }),
277
- },
278
- collectIntervalMs: envMs("LOG_SPOOL_COLLECT_INTERVAL_MS", DEFAULT_LOG_SPOOL_CONFIG.collectIntervalMs, { env }),
279
- });
280
- }
281
- function logSpoolServiceIdFromEnv(env = process.env) {
282
- const raw = env[LOG_SPOOL_SERVICE_ID_ENV]?.trim();
283
- return raw != null && raw !== "" ? raw : undefined;
284
- }
285
-
286
168
  const LOG_SPOOL_DIR_NAME = "log-spool";
287
169
  function resolveLogSpoolRoot(explicit) {
288
170
  if (explicit != null && explicit.trim() !== "") {
@@ -374,18 +256,17 @@ function estimateEntriesBytes(entries) {
374
256
  }
375
257
  }
376
258
  function buildLogListDraft(input) {
377
- const { service, process, lane, idempotencyKey, entries } = input;
378
- // TODO: `lane` is legacy transport metadata — scheduled for removal; callers still pass a fixed value for decode compatibility.
259
+ const { service, process, lane, entries } = input;
379
260
  const first = entries[0];
380
261
  const last = entries[entries.length - 1];
381
262
  return {
382
- name: `log-batch:${service}:${process}:${lane}`,
383
- value: idempotencyKey,
263
+ name: service,
264
+ value: LOG_BATCH_LIST_VALUE,
384
265
  category: CategoryList.LIST,
385
266
  tagList: ["log", lane, service],
386
267
  details: {
387
268
  manifestVersion: 0,
388
- loaderKey: LOG_PERSIST_LOADER_KEY,
269
+ loaderKey: LOG_BATCH_LIST_VALUE,
389
270
  meta: {
390
271
  service,
391
272
  process,
@@ -395,7 +276,6 @@ function buildLogListDraft(input) {
395
276
  from: first?.timestamp ?? null,
396
277
  to: last?.timestamp ?? null,
397
278
  flushedAt: Date.now(),
398
- idempotencyKey,
399
279
  },
400
280
  preview: first?.message ?? "",
401
281
  items: entries,
@@ -421,32 +301,19 @@ async function withTimeout(promise, timeoutMs, label) {
421
301
  }
422
302
  }
423
303
  async function postLogBatch(draft, postTimeoutMs) {
424
- try {
425
- const result = await withTimeout(postLogListCreate({
304
+ const result = await withTimeout(postListCreate({
305
+ name: draft.name,
306
+ value: draft.value,
307
+ category: draft.category,
308
+ details: draft.details,
309
+ }), postTimeoutMs, "postListCreate");
310
+ if (!result.success) {
311
+ const message = result.error?.message ?? "postListCreate failed";
312
+ persistLogger.error("post log batch failed", {
426
313
  name: draft.name,
427
- value: draft.value,
428
- category: draft.category,
429
- details: draft.details,
430
- }), postTimeoutMs, "postLogListCreate");
431
- if (!result.success) {
432
- const message = result.error?.message ?? "postLogListCreate failed";
433
- persistLogger.error("post log batch failed", {
434
- idempotencyKey: draft.value,
435
- name: draft.name,
436
- error: message,
437
- });
438
- throw new Error(message);
439
- }
440
- }
441
- catch (error) {
442
- if (isCreateTargetAlreadyExistsError(error)) {
443
- persistLogger.error("post log batch idempotent duplicate — treating as success", {
444
- idempotencyKey: draft.value,
445
- name: draft.name,
446
- });
447
- return;
448
- }
449
- throw error;
314
+ error: message,
315
+ });
316
+ throw new Error(message);
450
317
  }
451
318
  }
452
319
  /** Take a prefix of entries that fits within maxBytes. */
@@ -474,86 +341,6 @@ function takeEntriesWithinBytes(entries, maxBytes) {
474
341
  return result;
475
342
  }
476
343
 
477
- const BATCH_ID_VERSION = 1;
478
- /** Stable subset of LogEntry for idempotency hashing (same batch → same key). */
479
- function canonicalLogEntry(entry) {
480
- return {
481
- timestamp: entry.timestamp,
482
- level: entry.level,
483
- message: entry.message,
484
- topic: entry.topic,
485
- module: entry.module,
486
- traceId: entry.traceId,
487
- traceParentId: entry.traceParentId ?? null,
488
- extra: entry.extra ?? null,
489
- data: entry.data ?? null,
490
- labels: entry.labels ?? null,
491
- };
492
- }
493
- /**
494
- * Deterministic List.value for a log batch — retries after timeout map to the same row key.
495
- * SHA-256 over canonical JSON (service + process + lane + entries in order).
496
- */
497
- function computeLogBatchIdempotencyKey(input) {
498
- const payload = {
499
- v: BATCH_ID_VERSION,
500
- service: input.service,
501
- process: input.process,
502
- lane: input.lane,
503
- entries: input.entries.map(canonicalLogEntry),
504
- };
505
- const hash = createHash("sha256").update(JSON.stringify(payload), "utf8").digest("hex");
506
- return `${hash.slice(0, 32)}`;
507
- }
508
-
509
- /** `role.timestamp.hash.tmp|json` — role is lowercase alphanumeric + hyphen. */
510
- const BATCH_FILE_PATTERN = /^([a-z][a-z0-9-]*)\.(\d{14})\.([a-f0-9]{8})\.(tmp|json)$/;
511
- function formatLogSpoolBatchTimestamp(ms) {
512
- const d = new Date(ms);
513
- const pad = (n) => String(n).padStart(2, "0");
514
- return (`${d.getFullYear()}` +
515
- `${pad(d.getMonth() + 1)}` +
516
- `${pad(d.getDate())}` +
517
- `${pad(d.getHours())}` +
518
- `${pad(d.getMinutes())}` +
519
- `${pad(d.getSeconds())}`);
520
- }
521
- function computeLogSpoolShortHash(input) {
522
- const processKey = `${input.serviceId}:${input.processRole}`;
523
- const idempotencyKey = computeLogBatchIdempotencyKey({
524
- service: input.serviceValue,
525
- process: processKey,
526
- lane: "slow",
527
- entries: input.entries,
528
- });
529
- return idempotencyKey.slice(0, 8);
530
- }
531
- function buildLogSpoolBatchBaseName(input) {
532
- const ts = formatLogSpoolBatchTimestamp(input.firstEntryTimestamp);
533
- return `${input.processRole}.${ts}.${input.shortHash}`;
534
- }
535
- function parseLogSpoolBatchFilename(filename) {
536
- const match = BATCH_FILE_PATTERN.exec(filename);
537
- if (match == null) {
538
- return null;
539
- }
540
- const processRole = match[1];
541
- const tsRaw = match[2];
542
- const shortHash = match[3];
543
- const extension = match[4];
544
- const year = Number(tsRaw.slice(0, 4));
545
- const month = Number(tsRaw.slice(4, 6));
546
- const day = Number(tsRaw.slice(6, 8));
547
- const hour = Number(tsRaw.slice(8, 10));
548
- const minute = Number(tsRaw.slice(10, 12));
549
- const second = Number(tsRaw.slice(12, 14));
550
- const timestampMs = Date.UTC(year, month - 1, day, hour, minute, second);
551
- if (!Number.isFinite(timestampMs)) {
552
- return null;
553
- }
554
- return { processRole, timestampMs, shortHash, extension };
555
- }
556
-
557
344
  class LogSpoolWriter {
558
345
  static instance = null;
559
346
  enabled = false;
@@ -734,12 +521,7 @@ class LogSpoolWriter {
734
521
  }
735
522
  async writeBatchTmp(input) {
736
523
  const first = input.entries[0];
737
- const shortHash = computeLogSpoolShortHash({
738
- serviceValue: input.serviceValue,
739
- serviceId: input.serviceId,
740
- processRole: input.processRole,
741
- entries: input.entries,
742
- });
524
+ const shortHash = randomLogSpoolShortId();
743
525
  const baseName = buildLogSpoolBatchBaseName({
744
526
  processRole: input.processRole,
745
527
  firstEntryTimestamp: first.timestamp,
@@ -870,5 +652,5 @@ function validateLogSpoolPreloadEnv(env = process.env) {
870
652
  }
871
653
  }
872
654
 
873
- export { envMs as A, envNumber as B, CLI_PROD_FLAG as C, envPort as D, envProfileFromProcess as E, resolveDefaultEnvFiles as F, resolveProjectRootFromModule as G, LOG_SPOOL_SERVICE_ID_ENV as L, SERVICE_ENV_PROFILE_ENV_KEY as S, logSpoolEnabledFromEnv as a, readEnv as b, requireEnv as c, resolveLogSpoolSpawnEnvForLabel as d, resolveLogSpoolConfig as e, resolveLogSpoolRoot as f, resolveAllLogSpoolProcessRoles as g, logSpoolProcessDir as h, parseLogSpoolBatchFilename as i, computeLogBatchIdempotencyKey as j, buildLogListDraft as k, loadEnvFiles as l, mergeLogSpoolExtraProcessRolesEnv as m, postLogBatch as n, logSpoolConfigFromEnv as o, pinEnvProfileFromArgv as p, ensureLogSpoolFromEnv as q, resolveProjectRootByPackageName as r, spoolLogger as s, shutdownLogSpoolFromEnv as t, getLogSpoolStats as u, validateLogSpoolPreloadEnv as v, SERVICE_ENV_PROFILE_PROD as w, buildLogSpoolSpawnEnv as x, envBool as y, envInt as z };
874
- //# sourceMappingURL=enable-C7lFooTG.js.map
655
+ export { CLI_PROD_FLAG as C, SERVICE_ENV_PROFILE_ENV_KEY as S, logSpoolEnabledFromEnv as a, resolveLogSpoolSpawnEnvForLabel as b, resolveLogSpoolRoot as c, resolveAllLogSpoolProcessRoles as d, logSpoolProcessDir as e, buildLogListDraft as f, postLogBatch as g, ensureLogSpoolFromEnv as h, shutdownLogSpoolFromEnv as i, getLogSpoolStats as j, SERVICE_ENV_PROFILE_PROD as k, loadEnvFiles as l, mergeLogSpoolExtraProcessRolesEnv as m, buildLogSpoolSpawnEnv as n, envProfileFromProcess as o, pinEnvProfileFromArgv as p, resolveDefaultEnvFiles as q, resolveProjectRootByPackageName as r, spoolLogger as s, resolveProjectRootFromModule as t, validateLogSpoolPreloadEnv as v };
656
+ //# sourceMappingURL=enable-CF77OsXr.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"enable-CF77OsXr.js","sources":["../../src/node/env/load-env.ts","../../src/node/env/project-root.ts","../../src/shared/log/upload/env.ts","../../src/shared/log/upload/logger.ts","../../src/shared/log/spool/paths.ts","../../src/shared/log/spool/process-roles.ts","../../src/shared/log/upload/flush.ts","../../src/shared/log/spool/writer.ts","../../src/shared/log/spool/enable.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\nconst DEFAULT_ENV_FILES = [\".env.local\", \".env\"] as const;\nconst PROD_ENV_FILES = [\".env.prod\"] as const;\n\nexport const SERVICE_ENV_PROFILE_ENV_KEY = \"SERVICE_ENV_PROFILE\" as const;\nexport const SERVICE_ENV_PROFILE_PROD = \"prod\" as const;\nexport const CLI_PROD_FLAG = \"--prod\" as const;\n\nexport interface EnvProfileFromProcessOptions {\n env?: NodeJS.ProcessEnv;\n argv?: readonly string[];\n}\n\n/** Resolve active env profile from `SERVICE_ENV_PROFILE` or `--prod` on argv. */\nexport function envProfileFromProcess(options?: EnvProfileFromProcessOptions): string | undefined {\n const env = options?.env ?? process.env;\n const argv = options?.argv ?? process.argv;\n const fromEnv = env[SERVICE_ENV_PROFILE_ENV_KEY]?.trim();\n if (fromEnv != null && fromEnv !== \"\") {\n return fromEnv;\n }\n if (argv.includes(CLI_PROD_FLAG)) {\n return SERVICE_ENV_PROFILE_PROD;\n }\n return undefined;\n}\n\n/** Default env file list for a profile (`prod` → `.env.prod`; otherwise `.env.local` → `.env`). */\nexport function resolveDefaultEnvFiles(profile?: string): readonly string[] {\n if (profile === SERVICE_ENV_PROFILE_PROD) {\n return PROD_ENV_FILES;\n }\n return DEFAULT_ENV_FILES;\n}\n\n/** Pin `SERVICE_ENV_PROFILE=prod` when `--prod` is on argv (for child process inheritance). */\nexport function pinEnvProfileFromArgv(\n env: NodeJS.ProcessEnv = process.env,\n argv: readonly string[] = process.argv,\n): void {\n if (env[SERVICE_ENV_PROFILE_ENV_KEY]?.trim()) {\n return;\n }\n if (argv.includes(CLI_PROD_FLAG)) {\n env[SERVICE_ENV_PROFILE_ENV_KEY] = SERVICE_ENV_PROFILE_PROD;\n }\n}\n\nexport interface LoadEnvFilesOptions {\n /** Files to load in order (later files do not override existing env). */\n files?: readonly string[];\n env?: NodeJS.ProcessEnv;\n /** Called after all files are merged (e.g. legacy alias normalization). */\n afterLoad?: () => void;\n}\n\nfunction stripQuotes(value: string): string {\n return value.replace(/^[\"']|[\"']$/g, \"\");\n}\n\n/** Parse one KEY=VALUE line; returns null if line should be skipped. */\nexport function parseEnvLine(line: string): { key: string; value: string } | null {\n const trimmed = line.trim();\n if (trimmed === \"\" || trimmed.startsWith(\"#\")) {\n return null;\n }\n\n const eq = trimmed.indexOf(\"=\");\n if (eq === -1) {\n return null;\n }\n\n const key = trimmed.slice(0, eq).trim();\n const raw = trimmed.slice(eq + 1).trim();\n return { key, value: stripQuotes(raw) };\n}\n\nexport function parseEnvFileContent(content: string, env: NodeJS.ProcessEnv): void {\n for (const line of content.split(\"\\n\")) {\n const parsed = parseEnvLine(line);\n if (parsed == null) {\n continue;\n }\n if (env[parsed.key] == null || env[parsed.key] === \"\") {\n env[parsed.key] = parsed.value;\n }\n }\n}\n\nexport function parseEnvFile(filePath: string, env: NodeJS.ProcessEnv): void {\n if (!existsSync(filePath)) {\n return;\n }\n parseEnvFileContent(readFileSync(filePath, \"utf8\"), env);\n}\n\n/**\n * Load env files into `process.env` (or `options.env`).\n * Default files: `.env.local` → `.env`, or `.env.prod` when profile is `prod` / `--prod`.\n * Existing non-empty env values are not overwritten.\n */\nexport function loadEnvFiles(root: string, options?: LoadEnvFilesOptions): void {\n const env = options?.env ?? process.env;\n const files = options?.files ?? resolveDefaultEnvFiles(envProfileFromProcess({ env }));\n\n for (const name of files) {\n parseEnvFile(resolve(root, name), env);\n }\n\n options?.afterLoad?.();\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/**\n * Resolve project root from a module URL (typically `import.meta.url`).\n * @param relativePath Path relative to the module file (default `\"..\"` = parent directory).\n */\nexport function resolveProjectRootFromModule(importMetaUrl: string, relativePath = \"..\"): string {\n return resolve(fileURLToPath(new URL(relativePath, importMetaUrl)));\n}\n\n/**\n * Walk upward from `importMetaUrl` until a `package.json` with matching `name` is found.\n * Use for esbuild bundles under `dist/` where a single `..` hop lands in `dist/`, not repo root.\n */\nexport function resolveProjectRootByPackageName(importMetaUrl: string, packageName: string): string {\n let dir = dirname(fileURLToPath(importMetaUrl));\n for (;;) {\n const packageJsonPath = resolve(dir, \"package.json\");\n if (existsSync(packageJsonPath)) {\n const pkg = JSON.parse(readFileSync(packageJsonPath, \"utf8\")) as { name?: string };\n if (pkg.name === packageName) {\n return dir;\n }\n }\n const parent = dirname(dir);\n if (parent === dir) {\n break;\n }\n dir = parent;\n }\n throw new Error(`Could not find package root for \"${packageName}\" from ${importMetaUrl}`);\n}\n","import { envBool } from \"../../../node/env/env-parsers\";\n\n/** Master switch — env name kept for compatibility (`LOG_PERSIST_ENABLED`). */\nexport function logSpoolEnabledFromEnv(env: NodeJS.ProcessEnv = process.env): boolean {\n return envBool(\"LOG_PERSIST_ENABLED\", false, env);\n}\n\nexport function logPersistServiceFromEnv(env: NodeJS.ProcessEnv = process.env): string | undefined {\n const raw = env.LOG_PERSIST_SERVICE?.trim();\n return raw != null && raw !== \"\" ? raw : undefined;\n}\n\nexport function logPersistProcessFromEnv(env: NodeJS.ProcessEnv = process.env): string | undefined {\n const raw = env.LOG_PERSIST_PROCESS?.trim();\n return raw != null && raw !== \"\" ? raw : undefined;\n}\n\n/** `LOG_PERSIST_REGISTRY_DIR` or `RUNTIME_DATA_DIR`. */\nexport function runtimeDataDirFromEnv(env: NodeJS.ProcessEnv = process.env): string | undefined {\n const configured = env.LOG_PERSIST_REGISTRY_DIR?.trim();\n if (configured != null && configured !== \"\") {\n return configured;\n }\n const runtime = env.RUNTIME_DATA_DIR?.trim();\n return runtime != null && runtime !== \"\" ? runtime : undefined;\n}\n","import { createLogger } from \"../core/create-logger\";\n\n/** User-facing / lifecycle logs — may be persisted like normal app logs. */\nexport const LOG_PERSIST_TOPIC = \"log-persist\";\n\n/** Operational logs from the persist pipeline — never re-offered to avoid feedback loops. */\nexport const LOG_PERSIST_INTERNAL_TOPIC = \"log-persist-internal\";\n\ntype PipelineLogData = Record<string, unknown>;\n\nfunction createPipelineLogger(module: string) {\n const logger = createLogger({ module });\n\n function write(level: \"debug\" | \"info\" | \"warn\" | \"error\", message: string, data?: PipelineLogData): void {\n logger[level](message, {\n topic: LOG_PERSIST_INTERNAL_TOPIC,\n ...(data != null ? { data } : {}),\n });\n }\n\n return {\n debug: (message: string, data?: PipelineLogData) => write(\"debug\", message, data),\n info: (message: string, data?: PipelineLogData) => write(\"info\", message, data),\n warn: (message: string, data?: PipelineLogData) => write(\"warn\", message, data),\n error: (message: string, data?: PipelineLogData) => write(\"error\", message, data),\n };\n}\n\n/** Supabase upload path (`postLogBatch`). */\nexport const persistLogger = createPipelineLogger(\"log-upload\");\n\n/** File spool writer + collector. */\nexport const spoolLogger = createPipelineLogger(\"log-spool\");\n\nexport function isLogPersistInternalTopic(topic: string | undefined): boolean {\n return topic === LOG_PERSIST_INTERNAL_TOPIC;\n}\n","import { join } from \"node:path\";\nimport { runtimeDataDirFromEnv } from \"../upload/env\";\nimport type { LogSpoolProcessRole } from \"./interface\";\n\nexport const LOG_SPOOL_DIR_NAME = \"log-spool\";\n\nexport function resolveLogSpoolRoot(explicit?: string): string {\n if (explicit != null && explicit.trim() !== \"\") {\n return explicit;\n }\n const configured = process.env.LOG_SPOOL_DIR?.trim();\n if (configured != null && configured !== \"\") {\n return configured;\n }\n const runtimeDir = runtimeDataDirFromEnv();\n if (runtimeDir == null) {\n throw new Error(\n \"[LogSpool] spool root required: set LOG_SPOOL_DIR or LOG_PERSIST_REGISTRY_DIR / RUNTIME_DATA_DIR\",\n );\n }\n return join(runtimeDir, LOG_SPOOL_DIR_NAME);\n}\n\nexport function logSpoolServiceDir(spoolRoot: string, serviceId: string): string {\n return join(spoolRoot, serviceId);\n}\n\nexport function logSpoolProcessDir(spoolRoot: string, serviceId: string, processRole: LogSpoolProcessRole): string {\n return join(spoolRoot, serviceId, processRole);\n}\n","/** Four-process L3 blueprint roles — always scanned by collect-log. */\nexport const LOG_SPOOL_CORE_PROCESS_ROLES = [\"main\", \"guard\", \"scheduler\", \"worker\"] as const;\n\nexport type LogSpoolCoreProcessRole = (typeof LOG_SPOOL_CORE_PROCESS_ROLES)[number];\n\n/** Spool directory / `LOG_PERSIST_PROCESS` name — core or service-specific extra. */\nexport type LogSpoolProcessRole = LogSpoolCoreProcessRole | string;\n\nexport const LOG_SPOOL_EXTRA_PROCESS_ROLES_ENV = \"LOG_SPOOL_EXTRA_PROCESS_ROLES\";\n\nconst EXTRA_ROLE_PATTERN = /^[a-z][a-z0-9-]*$/;\n\nfunction parseRoleList(raw: string | undefined): string[] {\n if (raw == null || raw.trim() === \"\") {\n return [];\n }\n return raw\n .split(\",\")\n .map((part) => part.trim())\n .filter((part) => part !== \"\");\n}\n\n/** Parse comma-separated extra roles from env (e.g. `chrome-sidecar`). */\nexport function logSpoolExtraProcessRolesFromEnv(env: NodeJS.ProcessEnv = process.env): string[] {\n return parseRoleList(env[LOG_SPOOL_EXTRA_PROCESS_ROLES_ENV]);\n}\n\n/** Core + extras, deduped, stable order (core first). */\nexport function resolveAllLogSpoolProcessRoles(env: NodeJS.ProcessEnv = process.env): LogSpoolProcessRole[] {\n const extras = logSpoolExtraProcessRolesFromEnv(env);\n const seen = new Set<string>(LOG_SPOOL_CORE_PROCESS_ROLES);\n const all: LogSpoolProcessRole[] = [...LOG_SPOOL_CORE_PROCESS_ROLES];\n for (const role of extras) {\n if (!seen.has(role)) {\n seen.add(role);\n all.push(role);\n }\n }\n return all;\n}\n\nexport function isLogSpoolCoreProcessRole(value: string): value is LogSpoolCoreProcessRole {\n return (LOG_SPOOL_CORE_PROCESS_ROLES as readonly string[]).includes(value);\n}\n\n/** Whether `value` is a known spool role (core or configured extra). */\nexport function isKnownLogSpoolProcessRole(value: string, env: NodeJS.ProcessEnv = process.env): boolean {\n if (isLogSpoolCoreProcessRole(value)) {\n return true;\n }\n return logSpoolExtraProcessRolesFromEnv(env).includes(value);\n}\n\n/** Validate extra role token — lowercase alphanumeric + hyphen, not a duplicate core name. */\nexport function assertValidLogSpoolExtraProcessRole(role: string): void {\n if (role === \"\" || !EXTRA_ROLE_PATTERN.test(role)) {\n throw new Error(\n `[LogSpool] invalid extra process role \"${role}\" — use lowercase letters, digits, hyphen (e.g. chrome-sidecar)`,\n );\n }\n if (isLogSpoolCoreProcessRole(role)) {\n throw new Error(`[LogSpool] extra process role \"${role}\" duplicates a core role`);\n }\n}\n\nexport function mergeLogSpoolExtraProcessRolesEnv(env: NodeJS.ProcessEnv, extraRoles: readonly string[]): void {\n if (extraRoles.length === 0) {\n return;\n }\n for (const role of extraRoles) {\n assertValidLogSpoolExtraProcessRole(role);\n }\n const merged = new Set([...logSpoolExtraProcessRolesFromEnv(env), ...extraRoles]);\n env[LOG_SPOOL_EXTRA_PROCESS_ROLES_ENV] = [...merged].join(\",\");\n}\n","import { postListCreate } from \"../../../list/list.api\";\nimport { CategoryList } from \"../../../list/list.interface\";\nimport type { LogEntry } from \"../core/log-manager\";\nimport type { BuildLogListDraftInput, LogListDraft } from \"./interface\";\nimport { LOG_BATCH_LIST_VALUE } from \"./interface\";\nimport { persistLogger } from \"./logger\";\n\nexport function estimateEntriesBytes(entries: LogEntry[]): number {\n if (entries.length === 0) {\n return 0;\n }\n try {\n return Buffer.byteLength(JSON.stringify(entries), \"utf8\");\n } catch {\n return entries.length * 512;\n }\n}\n\nexport function buildLogListDraft(input: BuildLogListDraftInput): LogListDraft {\n const { service, process, lane, entries } = input;\n const first = entries[0];\n const last = entries[entries.length - 1];\n\n return {\n name: service,\n value: LOG_BATCH_LIST_VALUE,\n category: CategoryList.LIST,\n tagList: [\"log\", lane, service],\n details: {\n manifestVersion: 0,\n loaderKey: LOG_BATCH_LIST_VALUE,\n meta: {\n service,\n process,\n pid: globalThis.process.pid,\n lane,\n count: entries.length,\n from: first?.timestamp ?? null,\n to: last?.timestamp ?? null,\n flushedAt: Date.now(),\n },\n preview: first?.message ?? \"\",\n items: entries,\n },\n };\n}\n\nasync function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | null = null;\n try {\n return await Promise.race([\n promise,\n new Promise<T>((_resolve, reject) => {\n timer = setTimeout(() => {\n reject(new Error(`${label} timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n }),\n ]);\n } finally {\n if (timer != null) {\n clearTimeout(timer);\n }\n }\n}\n\nexport async function postLogBatch(draft: LogListDraft, postTimeoutMs: number): Promise<void> {\n const result = await withTimeout(\n postListCreate({\n name: draft.name,\n value: draft.value,\n category: draft.category,\n details: draft.details,\n }),\n postTimeoutMs,\n \"postListCreate\",\n );\n\n if (!result.success) {\n const message = result.error?.message ?? \"postListCreate failed\";\n persistLogger.error(\"post log batch failed\", {\n name: draft.name,\n error: message,\n });\n throw new Error(message);\n }\n}\n\n/** Take a prefix of entries that fits within maxBytes. */\nexport function takeEntriesWithinBytes(entries: LogEntry[], maxBytes: number): LogEntry[] {\n if (entries.length === 0) {\n return [];\n }\n\n const taken: LogEntry[] = [];\n for (const entry of entries) {\n const candidate = [...taken, entry];\n if (taken.length > 0 && estimateEntriesBytes(candidate) > maxBytes) {\n break;\n }\n taken.push(entry);\n }\n\n const result = taken.length > 0 ? taken : [entries[0]];\n if (result.length < entries.length) {\n persistLogger.warn(\"trimmed batch to maxBytes\", {\n requested: entries.length,\n taken: result.length,\n maxBytes,\n takenBytes: estimateEntriesBytes(result),\n });\n }\n\n return result;\n}\n","import { mkdir, rename, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { LogEntry } from \"../core/log-manager\";\nimport { estimateEntriesBytes, takeEntriesWithinBytes } from \"../upload/flush\";\nimport { registerLogPersistOffer } from \"../upload/hook\";\nimport { isLogPersistInternalTopic, spoolLogger } from \"../upload/logger\";\nimport { DEFAULT_LOG_SPOOL_CONFIG, resolveLogSpoolConfig } from \"./config\";\nimport { buildLogSpoolBatchBaseName, randomLogSpoolShortId } from \"./file\";\nimport type { EnableLogSpoolOptions, LogSpoolBatchFile, LogSpoolProcessRole, LogSpoolWriterStats } from \"./interface\";\nimport { logSpoolProcessDir, resolveLogSpoolRoot } from \"./paths\";\n\nclass LogSpoolWriter {\n private static instance: LogSpoolWriter | null = null;\n\n private enabled = false;\n private buffer: LogEntry[] = [];\n private flushInProgress = false;\n private debounceTimer: ReturnType<typeof setTimeout> | null = null;\n private ageTimer: ReturnType<typeof setTimeout> | null = null;\n private serviceId: string | null = null;\n private processRole: LogSpoolProcessRole | null = null;\n private serviceValue: string | null = null;\n private spoolRoot: string | null = null;\n private config = DEFAULT_LOG_SPOOL_CONFIG.writer;\n\n static getInstance(): LogSpoolWriter {\n LogSpoolWriter.instance ??= new LogSpoolWriter();\n return LogSpoolWriter.instance;\n }\n\n async enable(options: EnableLogSpoolOptions): Promise<void> {\n if (this.enabled) {\n spoolLogger.warn(\"log spool writer already enabled\", {\n serviceId: this.serviceId,\n processRole: this.processRole,\n });\n return;\n }\n\n this.serviceId = options.serviceId;\n this.processRole = options.processRole;\n this.serviceValue = options.serviceValue;\n this.spoolRoot = options.spoolRoot ?? resolveLogSpoolRoot();\n this.config = resolveLogSpoolConfig(options.config).writer;\n this.enabled = true;\n\n registerLogPersistOffer((entry) => this.offer(entry));\n\n spoolLogger.info(\"log spool writer enabled\", {\n serviceId: options.serviceId,\n processRole: options.processRole,\n serviceValue: options.serviceValue,\n spoolRoot: this.spoolRoot,\n config: this.config,\n });\n }\n\n async shutdown(): Promise<void> {\n this.cancelDebounce();\n this.cancelAgeFlush();\n registerLogPersistOffer(null);\n this.enabled = false;\n\n while (this.buffer.length > 0) {\n await this.flushChunk({ reason: \"shutdown\" });\n }\n\n spoolLogger.info(\"log spool writer shutdown complete\", {\n serviceId: this.serviceId,\n processRole: this.processRole,\n });\n }\n\n getStats(): LogSpoolWriterStats {\n return {\n enabled: this.enabled,\n bufferedEntries: this.buffer.length,\n bufferedBytes: estimateEntriesBytes(this.buffer),\n flushInProgress: this.flushInProgress,\n debouncePending: this.debounceTimer != null,\n ageFlushPending: this.ageTimer != null,\n serviceId: this.serviceId,\n processRole: this.processRole,\n };\n }\n\n offer(entry: LogEntry): void {\n if (isLogPersistInternalTopic(entry.topic)) {\n return;\n }\n\n if (!this.enabled) {\n return;\n }\n\n if (this.buffer.length === 0) {\n this.scheduleAgeFlush();\n }\n\n this.buffer.push(entry);\n\n if (this.shouldScheduleDebouncedFlush()) {\n this.scheduleDebouncedFlush();\n }\n }\n\n private shouldScheduleDebouncedFlush(): boolean {\n return (\n this.buffer.length >= this.config.maxEntries || estimateEntriesBytes(this.buffer) >= this.config.maxBytes\n );\n }\n\n private scheduleDebouncedFlush(): void {\n if (this.debounceTimer != null) {\n return;\n }\n\n spoolLogger.debug(\"log spool flush debounce scheduled\", {\n debounceMs: this.config.flushDebounceMs,\n bufferedEntries: this.buffer.length,\n });\n\n this.debounceTimer = setTimeout(() => {\n this.debounceTimer = null;\n void this.flushChunk({ reason: \"debounce\" });\n }, this.config.flushDebounceMs);\n this.debounceTimer.unref?.();\n }\n\n private scheduleAgeFlush(): void {\n if (this.ageTimer != null) {\n return;\n }\n\n spoolLogger.debug(\"log spool age flush scheduled\", {\n maxAgeMs: this.config.maxAgeMs,\n });\n\n this.ageTimer = setTimeout(() => {\n this.ageTimer = null;\n void this.flushChunk({ reason: \"maxAge\" });\n }, this.config.maxAgeMs);\n this.ageTimer.unref?.();\n }\n\n private cancelDebounce(): void {\n if (this.debounceTimer != null) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n }\n }\n\n private cancelAgeFlush(): void {\n if (this.ageTimer != null) {\n clearTimeout(this.ageTimer);\n this.ageTimer = null;\n }\n }\n\n private async flushChunk(input: { reason: string }): Promise<void> {\n if (this.flushInProgress || this.buffer.length === 0) {\n return;\n }\n if (this.serviceId == null || this.processRole == null || this.serviceValue == null || this.spoolRoot == null) {\n return;\n }\n\n this.cancelDebounce();\n this.cancelAgeFlush();\n this.flushInProgress = true;\n try {\n const byCount = this.buffer.slice(0, this.config.maxEntries);\n const entries = takeEntriesWithinBytes(byCount, this.config.maxBytes);\n this.buffer = this.buffer.slice(entries.length);\n\n if (entries.length === 0) {\n if (this.buffer.length > 0) {\n this.scheduleAgeFlush();\n } else {\n this.cancelAgeFlush();\n }\n return;\n }\n\n const batchFile = await this.writeBatchTmp({\n entries,\n serviceId: this.serviceId,\n processRole: this.processRole,\n serviceValue: this.serviceValue,\n spoolRoot: this.spoolRoot,\n });\n\n spoolLogger.info(\"log spool flushed to tmp\", {\n reason: input.reason,\n fileName: batchFile.fileName,\n entryCount: entries.length,\n remainingBuffered: this.buffer.length,\n });\n\n if (this.buffer.length > 0) {\n this.scheduleAgeFlush();\n if (this.shouldScheduleDebouncedFlush()) {\n this.scheduleDebouncedFlush();\n }\n } else {\n this.cancelAgeFlush();\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n spoolLogger.error(\"log spool flush failed\", { reason: input.reason, error: message });\n if (this.buffer.length > 0) {\n this.scheduleAgeFlush();\n }\n } finally {\n this.flushInProgress = false;\n }\n }\n\n private async writeBatchTmp(input: {\n entries: LogEntry[];\n serviceId: string;\n processRole: LogSpoolProcessRole;\n serviceValue: string;\n spoolRoot: string;\n }): Promise<{ fileName: string; tmpPath: string }> {\n const first = input.entries[0];\n const shortHash = randomLogSpoolShortId();\n const baseName = buildLogSpoolBatchBaseName({\n processRole: input.processRole,\n firstEntryTimestamp: first.timestamp,\n shortHash,\n });\n const fileName = `${baseName}.tmp`;\n const processDir = logSpoolProcessDir(input.spoolRoot, input.serviceId, input.processRole);\n await mkdir(processDir, { recursive: true });\n\n const tmpPath = join(processDir, fileName);\n const partPath = `${tmpPath}.part`;\n const payload: LogSpoolBatchFile = {\n entries: input.entries,\n meta: {\n serviceId: input.serviceId,\n processRole: input.processRole,\n serviceValue: input.serviceValue,\n },\n };\n const content = `${JSON.stringify(payload)}\\n`;\n\n await writeFile(partPath, content, \"utf8\");\n await rename(partPath, tmpPath);\n\n return { fileName, tmpPath };\n }\n}\n\nexport { LogSpoolWriter };\n\nexport async function enableLogSpoolWriter(options: EnableLogSpoolOptions): Promise<void> {\n await LogSpoolWriter.getInstance().enable(options);\n}\n\nexport async function shutdownLogSpoolWriter(): Promise<void> {\n await LogSpoolWriter.getInstance().shutdown();\n}\n\nexport function getLogSpoolWriterStats(): LogSpoolWriterStats {\n return LogSpoolWriter.getInstance().getStats();\n}\n","import { createLogger } from \"../core/create-logger\";\nimport { logPersistProcessFromEnv, logPersistServiceFromEnv, logSpoolEnabledFromEnv } from \"../upload/env\";\nimport { registerLogPersistOffer } from \"../upload/hook\";\nimport { LOG_PERSIST_TOPIC } from \"../upload/logger\";\nimport { LOG_SPOOL_SERVICE_ID_ENV, logSpoolConfigFromEnv, logSpoolServiceIdFromEnv } from \"./config\";\nimport type { EnsureLogSpoolFromEnvOptions, LogSpoolProcessRole } from \"./interface\";\nimport { resolveLogSpoolRoot } from \"./paths\";\nimport {\n assertValidLogSpoolExtraProcessRole,\n isKnownLogSpoolProcessRole,\n LOG_SPOOL_EXTRA_PROCESS_ROLES_ENV,\n} from \"./process-roles\";\nimport { enableLogSpoolWriter, getLogSpoolWriterStats, shutdownLogSpoolWriter } from \"./writer\";\n\nexport { logSpoolEnabledFromEnv };\n\nexport function resolveLogSpoolProcessRole(explicit?: string): LogSpoolProcessRole {\n const raw = explicit ?? logPersistProcessFromEnv();\n if (raw == null || raw === \"\") {\n throw new Error(\"[LogSpool] LOG_PERSIST_PROCESS is required when LOG_PERSIST_ENABLED=true\");\n }\n if (!isKnownLogSpoolProcessRole(raw)) {\n throw new Error(\n `[LogSpool] invalid LOG_PERSIST_PROCESS: ${raw} (not a core role and not listed in ${LOG_SPOOL_EXTRA_PROCESS_ROLES_ENV})`,\n );\n }\n return raw;\n}\n\n/**\n * Env vars for child spawn after main claims registry slot.\n * Optional when using {@link ManagedChildProcesses.spawn} — auto-injected from parent env.\n */\nexport function buildLogSpoolSpawnEnv(input: {\n serviceId: string;\n processRole: LogSpoolProcessRole;\n}): Record<string, string> {\n return {\n [LOG_SPOOL_SERVICE_ID_ENV]: input.serviceId,\n LOG_PERSIST_PROCESS: input.processRole,\n };\n}\n\n/**\n * When persistence is enabled and parent has `LOG_SPOOL_SERVICE_ID`, map spawn `label`\n * to spool env when `label` is a known core or extra process role.\n */\nexport function resolveLogSpoolSpawnEnvForLabel(\n label: string,\n env: NodeJS.ProcessEnv = process.env,\n): Record<string, string> {\n if (!logSpoolEnabledFromEnv(env)) {\n return {};\n }\n const serviceId = env[LOG_SPOOL_SERVICE_ID_ENV]?.trim();\n if (serviceId == null || serviceId === \"\") {\n return {};\n }\n if (!isKnownLogSpoolProcessRole(label, env)) {\n return {};\n }\n return buildLogSpoolSpawnEnv({ serviceId, processRole: label });\n}\n\nexport async function ensureLogSpoolFromEnv(options: EnsureLogSpoolFromEnvOptions = {}): Promise<boolean> {\n if (!logSpoolEnabledFromEnv()) {\n registerLogPersistOffer(null);\n return false;\n }\n\n const serviceId = options.serviceId ?? logSpoolServiceIdFromEnv();\n const serviceValue = options.serviceValue ?? logPersistServiceFromEnv();\n const processRole = resolveLogSpoolProcessRole(options.processRole);\n\n if (serviceId == null || serviceId === \"\") {\n throw new Error(\n \"[LogSpool] LOG_SPOOL_SERVICE_ID is required when LOG_PERSIST_ENABLED=true (set after registry claim or pass serviceId)\",\n );\n }\n if (serviceValue == null || serviceValue === \"\") {\n throw new Error(\"[LogSpool] LOG_PERSIST_SERVICE is required when LOG_PERSIST_ENABLED=true\");\n }\n\n const spoolRoot = options.spoolRoot ?? resolveLogSpoolRoot();\n\n await enableLogSpoolWriter({\n serviceId,\n processRole,\n serviceValue,\n spoolRoot,\n config: options.config ?? logSpoolConfigFromEnv(),\n });\n\n const lifecycleLogger = createLogger({ module: \"log-spool\" });\n lifecycleLogger.info(\"log spool enabled from env\", {\n topic: LOG_PERSIST_TOPIC,\n data: { serviceId, processRole, serviceValue, spoolRoot },\n });\n\n return true;\n}\n\nexport async function shutdownLogSpoolFromEnv(): Promise<void> {\n await shutdownLogSpoolWriter();\n}\n\nexport function getLogSpoolStats(): ReturnType<typeof getLogSpoolWriterStats> {\n return getLogSpoolWriterStats();\n}\n\nexport function validateLogSpoolPreloadEnv(env: NodeJS.ProcessEnv = process.env): void {\n if (!logSpoolEnabledFromEnv(env)) {\n return;\n }\n\n const missing: string[] = [];\n if (env.LOG_PERSIST_SERVICE?.trim() == null || env.LOG_PERSIST_SERVICE.trim() === \"\") {\n missing.push(\"LOG_PERSIST_SERVICE\");\n }\n const runtimeDir = env.LOG_PERSIST_REGISTRY_DIR?.trim() || env.RUNTIME_DATA_DIR?.trim();\n if (runtimeDir == null || runtimeDir === \"\") {\n missing.push(\"LOG_PERSIST_REGISTRY_DIR or RUNTIME_DATA_DIR\");\n }\n\n if (missing.length > 0) {\n throw new Error(`[LogSpool] preload env incomplete: ${missing.join(\", \")}`);\n }\n\n for (const role of env[LOG_SPOOL_EXTRA_PROCESS_ROLES_ENV]?.split(\",\") ?? []) {\n const trimmed = role.trim();\n if (trimmed === \"\") {\n continue;\n }\n assertValidLogSpoolExtraProcessRole(trimmed);\n }\n}\n"],"names":[],"mappings":";;;;;;AAGA,MAAM,iBAAiB,GAAG,CAAC,YAAY,EAAE,MAAM,CAAU;AACzD,MAAM,cAAc,GAAG,CAA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C,mBAAmB,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;AAClF,QAAA,OAAO,CAAC,IAAI,CAAC,qBAAqB,CAAC;IACvC;AACA,IAAA,MAAM,UAAU,GAAG,GAAG,CAAC,wBAAwB,EAAE,IAAI,EAAE,IAAI,GAAG,CAAC,gBAAgB,EAAE,IAAI,EAAE;IACvF,IAAI,UAAU,IAAI,IAAI,IAAI,UAAU,KAAK,EAAE,EAAE;AACzC,QAAA,OAAO,CAAC,IAAI,CAAC,8CAA8C,CAAC;IAChE;AAEA,IAAA,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE;AACpB,QAAA,MAAM,IAAI,KAAK,CAAC,CAAA,mCAAA,EAAsC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA,CAAE,CAAC;IAC/E;AAEA,IAAA,KAAK,MAAM,IAAI,IAAI,GAAG,CAAC,iCAAiC,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE;AACzE,QAAA,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,EAAE;AAC3B,QAAA,IAAI,OAAO,KAAK,EAAE,EAAE;YAChB;QACJ;QACA,mCAAmC,CAAC,OAAO,CAAC;IAChD;AACJ;;;;"}
@@ -1,5 +1,6 @@
1
- import { V as validateWithSchema, m as getTarget, l as getPossibleTarget, c as LOG_PERSIST_LOADER_KEY, k as generateResponse, R as updateTargetDetails, g as createLogger, h as createTarget, q as isCreateTargetAlreadyExistsError, J as scanTargetList, B as BaseValidator, a as CategoryList, i as deleteTarget, s as isOptimisticLockError, n as getTargetList, f as OPTIMISTIC_LOCK_FAILED_MESSAGE, O as OPTIMISTIC_LOCK_ERROR_CODE, K as supabase, w as logManager } from './list.api-BzbTJBsM.js';
1
+ import { V as validateWithSchema, m as getTarget, l as getPossibleTarget, L as LOG_BATCH_LIST_VALUE, k as generateResponse, R as updateTargetDetails, f as createLogger, g as createTarget, q as isCreateTargetAlreadyExistsError, J as scanTargetList, B as BaseValidator, a as CategoryList, a0 as LOG_SPOOL_SERVICE_ID_ENV, h as deleteTarget, s as isOptimisticLockError, n as getTargetList, e as OPTIMISTIC_LOCK_FAILED_MESSAGE, O as OPTIMISTIC_LOCK_ERROR_CODE, K as supabase, w as logManager } from './config-BNxsVKR4.js';
2
2
  import { z } from 'zod';
3
+ import 'node:crypto';
3
4
 
4
5
  var CategoryConfig;
5
6
  (function (CategoryConfig) {
@@ -92,8 +93,7 @@ function parseLogBatchMeta(rawMeta) {
92
93
  const service = asString(source.service);
93
94
  const processName = asString(source.process);
94
95
  const laneRaw = asString(source.lane);
95
- const idempotencyKey = asString(source.idempotencyKey);
96
- if (service == null || processName == null || laneRaw == null || !LANES.has(laneRaw) || idempotencyKey == null) {
96
+ if (service == null || processName == null || laneRaw == null || !LANES.has(laneRaw)) {
97
97
  return null;
98
98
  }
99
99
  return {
@@ -105,7 +105,6 @@ function parseLogBatchMeta(rawMeta) {
105
105
  from: asFiniteNumber$1(source.from),
106
106
  to: asFiniteNumber$1(source.to),
107
107
  flushedAt: asFiniteNumber$1(source.flushedAt) ?? 0,
108
- idempotencyKey,
109
108
  };
110
109
  }
111
110
  /** Structural guard for a persisted {@link LogEntry}. */
@@ -119,9 +118,9 @@ function isLogEntry(value) {
119
118
  typeof record.module === "string" &&
120
119
  typeof record.traceId === "string");
121
120
  }
122
- /** Is this List a persisted log batch (by loaderKey)? */
121
+ /** Is this List a persisted log batch (by `value`)? */
123
122
  function isLogBatchList(list) {
124
- return list.details?.loaderKey === LOG_PERSIST_LOADER_KEY;
123
+ return list.value === LOG_BATCH_LIST_VALUE;
125
124
  }
126
125
  /**
127
126
  * Decode a `List` row into a {@link DecodedLogBatch}. Returns null when the row
@@ -131,6 +130,10 @@ function decodeLogBatch(list) {
131
130
  if (!isLogBatchList(list)) {
132
131
  return null;
133
132
  }
133
+ const loaderKey = list.details?.loaderKey;
134
+ if (typeof loaderKey === "string" && loaderKey.endsWith(".bad")) {
135
+ return null;
136
+ }
134
137
  const meta = parseLogBatchMeta(list.details?.meta);
135
138
  if (meta == null) {
136
139
  return null;
@@ -163,7 +166,7 @@ function flattenLogBatch(batch) {
163
166
  process: batch.meta.process,
164
167
  lane: batch.meta.lane,
165
168
  pid: batch.meta.pid,
166
- batchId: batch.meta.idempotencyKey,
169
+ listId: batch.listId,
167
170
  }));
168
171
  }
169
172
  /** Flatten many batches into a single flat entry list. */
@@ -470,12 +473,22 @@ var CategoryNode;
470
473
  (function (CategoryNode) {
471
474
  CategoryNode["NODE"] = "node";
472
475
  })(CategoryNode || (CategoryNode = {}));
476
+ /** Node role — stored in {@link Node.value}. */
477
+ var NodeKind;
478
+ (function (NodeKind) {
479
+ NodeKind["TASK"] = "node.task";
480
+ NodeKind["TRIGGER"] = "node.trigger";
481
+ NodeKind["GUARD"] = "node.guard";
482
+ NodeKind["OTHER"] = "node.other";
483
+ })(NodeKind || (NodeKind = {}));
473
484
 
474
485
  const NODE_STATUS_FIELD = "details->>status";
475
486
  const nodeIdSchema$1 = z.string().trim().min(1);
476
487
  const traceIdSchema$2 = z.string().trim().min(1).optional();
477
488
  // ─── Zod schemas ─────────────────────────────────────────────────────────────
478
489
  const postRegisterNodeSchema = z.object({
490
+ serviceId: nodeIdSchema$1,
491
+ kind: z.nativeEnum(NodeKind),
479
492
  traceId: traceIdSchema$2,
480
493
  });
481
494
  const patchNodeHeartBeatSchema = z.object({
@@ -498,9 +511,9 @@ function lockOnNodeStatus(status) {
498
511
  return [{ field: NODE_STATUS_FIELD, operator: "eq", value: status }];
499
512
  }
500
513
  // ─── postRegisterNode ────────────────────────────────────────────────────────
501
- const postRegisterNode = validateWithSchema(postRegisterNodeSchema, "postRegisterNodeSchema")(async (payload) => {
514
+ const postRegisterNode = validateWithSchema(postRegisterNodeSchema, "postRegisterNodeSchema")(async ({ serviceId, kind, ...payload }) => {
502
515
  return createTarget({
503
- payload,
516
+ payload: { serviceId, kind, ...payload },
504
517
  createFn: () => {
505
518
  const details = {
506
519
  manifestVersion: 0,
@@ -508,9 +521,9 @@ const postRegisterNode = validateWithSchema(postRegisterNodeSchema, "postRegiste
508
521
  lastHeartBeat: Date.now(),
509
522
  };
510
523
  return {
511
- name: "",
524
+ name: serviceId,
512
525
  category: CategoryNode.NODE,
513
- value: "",
526
+ value: kind,
514
527
  tagList: [],
515
528
  details,
516
529
  };
@@ -569,6 +582,10 @@ const patchChangeNodeStatus = validateWithSchema(patchChangeNodeStatusSchema, "p
569
582
  function isBusyWithHeartbeat(node) {
570
583
  return node.details.status === NodeStatus.BUSY && typeof node.details.lastHeartBeat === "number";
571
584
  }
585
+ /** Subset used for worker liveness (Guard / observability) — {@link NodeKind.TASK} only. */
586
+ function nodesForTaskLiveness(nodes) {
587
+ return nodes.filter((node) => node.value === NodeKind.TASK);
588
+ }
572
589
  /** Evaluate TaskNode liveness from a scanned node list (no I/O). */
573
590
  function evaluateBusyNodeLiveness(nodes, options) {
574
591
  const now = options.now ?? Date.now();
@@ -602,6 +619,15 @@ function evaluateBusyNodeLiveness(nodes, options) {
602
619
  };
603
620
  }
604
621
 
622
+ /** Service instance id required for {@link postRegisterNode} (same env as log spool after registry claim). */
623
+ function requireNodeServiceIdFromEnv(env = process.env) {
624
+ const serviceId = env[LOG_SPOOL_SERVICE_ID_ENV]?.trim();
625
+ if (serviceId == null || serviceId === "") {
626
+ throw new Error(`[Node] ${LOG_SPOOL_SERVICE_ID_ENV} must be set before registering a node (claim the registry slot on the service host first)`);
627
+ }
628
+ return serviceId;
629
+ }
630
+
605
631
  function resolveFetchUrl(input) {
606
632
  if (typeof input === "string") {
607
633
  return input;
@@ -3871,5 +3897,5 @@ function summarizeTaskQueue(tasks, taskType, statuses) {
3871
3897
  return tasks.filter((task) => task.value === taskType && statuses.includes(task.details.status)).length;
3872
3898
  }
3873
3899
 
3874
- export { createStorageProviderRegistry as $, ApiMethod as A, buildFeedLinkName as B, CategoryConfig as C, DEFAULT_SYSTEM_REGISTRY_SEED_SLOTS as D, EMPTY_REGISTRY_SLOT_RUNTIME_STATE as E, FEED_VALUES as F, buildIdeaImageLinkDraft as G, buildIdeaLinkDraft as H, IDEA_IMAGE_LINK_NAME as I, buildLinkTargetDraft as J, buildListTargetDraft as K, LINK_MANIFEST_VERSION as L, MEDIA_CONTENT_HASH_ALGORITHM as M, NodeStatus as N, buildMediaLinkDraft as O, POST_TASK_DEFAULT_MAX_ATTEMPTS as P, buildMediaNameFromLocator as Q, ResultCode as R, ServiceLifecycleStatus as S, TARGET_SYSTEM_REGISTRY_KEY as T, buildReviewLinkDraft as U, buildSystemRegistryConfigDetails as V, claimServiceRegistrySlot as W, classifyNetworkError as X, countTasksByType as Y, createActiveServiceLifecycle as Z, createClaimedRegistrySlotRuntimeState as _, CategoryExtraction as a, patchServiceRuntime as a$, createUploadTracker as a0, decodeLogBatch as a1, decodeLogBatchList as a2, defaultL3ServiceDetails as a3, deleteParcel as a4, deleteParcelSchema as a5, escapeIlikePattern as a6, evaluateBusyNodeLiveness as a7, feedLinkDedupFilters as a8, fetchBinaryWithRetry as a9, isIdeaImageLinkName as aA, isLocalFilesystemPath as aB, isLogBatchList as aC, isLogEntry as aD, isMediaValue as aE, isOpaqueChunkUrl as aF, isRetryableHttpStatus as aG, linkDedupFilters as aH, linkTargetDraftBuildInputSchema as aI, mediaLinkDedupFilters as aJ, normalizeStringList as aK, parcelDetailsSchema as aL, parseIdeaOriginal as aM, parseLogBatchMeta as aN, parseProviderPrefixedUrl as aO, parseServiceSlot as aP, parseServiceSlots as aQ, patchChangeNodeStatus as aR, patchChangeNodeStatusSchema as aS, patchChangeTaskStatus as aT, patchChangeTaskStatusSchema as aU, patchClaimTask as aV, patchClaimTaskSchema as aW, patchExtractionObjects as aX, patchExtractionObjectsSchema as aY, patchNodeHeartBeat as aZ, patchNodeHeartBeatSchema as a_, fetchWithRetry as aa, fieldDefinitionSchema as ab, flattenLogBatch as ac, flattenLogBatches as ad, formatNetworkError as ae, getApi as af, getApiSchema as ag, getConfig as ah, getConfigSchema as ai, getExtraction as aj, getExtractionSchema as ak, getParcel as al, getParcelSchema as am, getScanRemoteRepoValues as an, getScanRemoteRepoValuesSchema as ao, getService as ap, getServiceSchema as aq, getTargetSystemRegistry as ar, getValueAtPath as as, guessMediaMime as at, ideaCreateSchema as au, ideaLinkValueFilters as av, ideaUpdateSchema as aw, installChunkFetchRegistry as ax, isFeedValue as ay, isHttpUrl as az, CategoryLink as b, patchStopNode as b0, patchStopNodeSchema as b1, patchTaskProgress as b2, patchTaskProgressSchema as b3, postApi as b4, postApiSchema as b5, postExtraction as b6, postExtractionSchema as b7, postLinkCreate as b8, postParcel as b9, runRegistrySlotGuardCheck as bA, sanitizeFileName as bB, sanitizeParcelFileName as bC, scanExtractionList as bD, scanExtractionListSchema as bE, schemaDefinitionSchema as bF, serviceDetailsSchema as bG, serviceLifecycleSchema as bH, serviceNodeSnapshotSchema as bI, serviceRuntimeSchema as bJ, sha256Hex as bK, summarizeTaskQueue as bL, systemRegistrySeedSlotSchema as bM, toPostgrestTextArrayLiteral as bN, unregisterService as bO, unregisterServiceAtShutdown as bP, getErrorMessage as bQ, LOG_TOPIC_NODE as bR, isFeedIngestSource as bS, resolveFeedOriginalStorageProvider as bT, buildFeedTagList as bU, LOG_TOPIC_TASK as bV, CRITICAL_UNKNOWN_TASK_TRACE_ID as bW, toError as bX, createTaskRow as bY, FEED_INGEST_SOURCES as bZ, postParcelSchema as ba, postRegisterNode as bb, postRegisterNodeSchema as bc, postService as bd, postServiceInstance as be, postServiceSchema as bf, postSystemRegistryConfig as bg, postSystemRegistryConfigSchema as bh, postTask as bi, postTaskSchema as bj, postTaskWithRetry as bk, publishParcel as bl, registerProviderChunkResolver as bm, registerService as bn, registerServiceAtStartup as bo, registrySlotRuntimePatchFromGuardResult as bp, releaseSystemRegistrySlots as bq, releaseSystemRegistrySlotsByServiceId as br, requestHasBody as bs, resetSystemRegistryConfig as bt, resetSystemRegistryConfigSchema as bu, resolveActiveRegistryServiceId as bv, resolveFetchUrl as bw, restoreParcel as bx, restoreParcelById as by, reviewLinksForNameFilters as bz, CategoryNode as c, CategoryParcel as d, CategoryRepo as e, CategoryService as f, CategoryTask as g, IDEA_IMAGE_TAG_RAW as h, IDEA_IMAGE_TEMP_DIR as i, IDEA_LINK_VALUE as j, LIST_MANIFEST_VERSION as k, MEDIA_CONTENT_HASH_PREFIX_LENGTH as l, MEDIA_VALUES as m, ParcelManager as n, PostLinkValidator as o, ServiceRegistryError as p, ServiceSlotStatus as q, TASK_REPO_USAGE as r, TaskStatus as s, TaskStatusAction as t, apiDetailsSchema as u, appendSystemRegistryEmptySlots as v, assertRegistrySlotAvailable as w, assertRegistrySlotOwner as x, buildEmptyServiceSlots as y, buildFeedLinkDraft as z };
3875
- //# sourceMappingURL=task-queue-C_nUaM2S.js.map
3900
+ export { createClaimedRegistrySlotRuntimeState as $, ApiMethod as A, buildFeedLinkDraft as B, CategoryConfig as C, DEFAULT_SYSTEM_REGISTRY_SEED_SLOTS as D, EMPTY_REGISTRY_SLOT_RUNTIME_STATE as E, FEED_VALUES as F, buildFeedLinkName as G, buildIdeaImageLinkDraft as H, IDEA_IMAGE_LINK_NAME as I, buildIdeaLinkDraft as J, buildLinkTargetDraft as K, LINK_MANIFEST_VERSION as L, MEDIA_CONTENT_HASH_ALGORITHM as M, NodeKind as N, buildListTargetDraft as O, POST_TASK_DEFAULT_MAX_ATTEMPTS as P, buildMediaLinkDraft as Q, ResultCode as R, ServiceLifecycleStatus as S, TARGET_SYSTEM_REGISTRY_KEY as T, buildMediaNameFromLocator as U, buildReviewLinkDraft as V, buildSystemRegistryConfigDetails as W, claimServiceRegistrySlot as X, classifyNetworkError as Y, countTasksByType as Z, createActiveServiceLifecycle as _, CategoryExtraction as a, patchNodeHeartBeat as a$, createStorageProviderRegistry as a0, createUploadTracker as a1, decodeLogBatch as a2, decodeLogBatchList as a3, defaultL3ServiceDetails as a4, deleteParcel as a5, deleteParcelSchema as a6, escapeIlikePattern as a7, evaluateBusyNodeLiveness as a8, feedLinkDedupFilters as a9, isHttpUrl as aA, isIdeaImageLinkName as aB, isLocalFilesystemPath as aC, isLogBatchList as aD, isLogEntry as aE, isMediaValue as aF, isOpaqueChunkUrl as aG, isRetryableHttpStatus as aH, linkDedupFilters as aI, linkTargetDraftBuildInputSchema as aJ, mediaLinkDedupFilters as aK, nodesForTaskLiveness as aL, normalizeStringList as aM, parcelDetailsSchema as aN, parseIdeaOriginal as aO, parseLogBatchMeta as aP, parseProviderPrefixedUrl as aQ, parseServiceSlot as aR, parseServiceSlots as aS, patchChangeNodeStatus as aT, patchChangeNodeStatusSchema as aU, patchChangeTaskStatus as aV, patchChangeTaskStatusSchema as aW, patchClaimTask as aX, patchClaimTaskSchema as aY, patchExtractionObjects as aZ, patchExtractionObjectsSchema as a_, fetchBinaryWithRetry as aa, fetchWithRetry as ab, fieldDefinitionSchema as ac, flattenLogBatch as ad, flattenLogBatches as ae, formatNetworkError as af, getApi as ag, getApiSchema as ah, getConfig as ai, getConfigSchema as aj, getExtraction as ak, getExtractionSchema as al, getParcel as am, getParcelSchema as an, getScanRemoteRepoValues as ao, getScanRemoteRepoValuesSchema as ap, getService as aq, getServiceSchema as ar, getTargetSystemRegistry as as, getValueAtPath as at, guessMediaMime as au, ideaCreateSchema as av, ideaLinkValueFilters as aw, ideaUpdateSchema as ax, installChunkFetchRegistry as ay, isFeedValue as az, CategoryLink as b, createTaskRow as b$, patchNodeHeartBeatSchema as b0, patchServiceRuntime as b1, patchStopNode as b2, patchStopNodeSchema as b3, patchTaskProgress as b4, patchTaskProgressSchema as b5, postApi as b6, postApiSchema as b7, postExtraction as b8, postExtractionSchema as b9, restoreParcel as bA, restoreParcelById as bB, reviewLinksForNameFilters as bC, runRegistrySlotGuardCheck as bD, sanitizeFileName as bE, sanitizeParcelFileName as bF, scanExtractionList as bG, scanExtractionListSchema as bH, schemaDefinitionSchema as bI, serviceDetailsSchema as bJ, serviceLifecycleSchema as bK, serviceNodeSnapshotSchema as bL, serviceRuntimeSchema as bM, sha256Hex as bN, summarizeTaskQueue as bO, systemRegistrySeedSlotSchema as bP, toPostgrestTextArrayLiteral as bQ, unregisterService as bR, unregisterServiceAtShutdown as bS, getErrorMessage as bT, LOG_TOPIC_NODE as bU, isFeedIngestSource as bV, resolveFeedOriginalStorageProvider as bW, buildFeedTagList as bX, LOG_TOPIC_TASK as bY, CRITICAL_UNKNOWN_TASK_TRACE_ID as bZ, toError as b_, postLinkCreate as ba, postParcel as bb, postParcelSchema as bc, postRegisterNode as bd, postRegisterNodeSchema as be, postService as bf, postServiceInstance as bg, postServiceSchema as bh, postSystemRegistryConfig as bi, postSystemRegistryConfigSchema as bj, postTask as bk, postTaskSchema as bl, postTaskWithRetry as bm, publishParcel as bn, registerProviderChunkResolver as bo, registerService as bp, registerServiceAtStartup as bq, registrySlotRuntimePatchFromGuardResult as br, releaseSystemRegistrySlots as bs, releaseSystemRegistrySlotsByServiceId as bt, requestHasBody as bu, requireNodeServiceIdFromEnv as bv, resetSystemRegistryConfig as bw, resetSystemRegistryConfigSchema as bx, resolveActiveRegistryServiceId as by, resolveFetchUrl as bz, CategoryNode as c, FEED_INGEST_SOURCES as c0, CategoryParcel as d, CategoryRepo as e, CategoryService as f, CategoryTask as g, IDEA_IMAGE_TAG_RAW as h, IDEA_IMAGE_TEMP_DIR as i, IDEA_LINK_VALUE as j, LIST_MANIFEST_VERSION as k, MEDIA_CONTENT_HASH_PREFIX_LENGTH as l, MEDIA_VALUES as m, NodeStatus as n, ParcelManager as o, PostLinkValidator as p, ServiceRegistryError as q, ServiceSlotStatus as r, TASK_REPO_USAGE as s, TaskStatus as t, TaskStatusAction as u, apiDetailsSchema as v, appendSystemRegistryEmptySlots as w, assertRegistrySlotAvailable as x, assertRegistrySlotOwner as y, buildEmptyServiceSlots as z };
3901
+ //# sourceMappingURL=task-queue-BL-KwAGW.js.map