@dragonmastery/tamer 0.1.2 → 0.29.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.
- package/README.md +570 -18
- package/dist/CFApiClient-DhbyyV71.mjs +868 -0
- package/dist/CFApiClient-DhbyyV71.mjs.map +1 -0
- package/dist/StateManager-DTqtLLVX.mjs +760 -0
- package/dist/StateManager-DTqtLLVX.mjs.map +1 -0
- package/dist/apply-BOABC3UB.mjs +423 -0
- package/dist/apply-BOABC3UB.mjs.map +1 -0
- package/dist/applyTarget-GWDEOXeY.mjs +152 -0
- package/dist/applyTarget-GWDEOXeY.mjs.map +1 -0
- package/dist/bootstrap-BxwxC_2Z.mjs +33 -0
- package/dist/bootstrap-BxwxC_2Z.mjs.map +1 -0
- package/dist/buildDispatchUploadForm-BoUB93b3.mjs +38 -0
- package/dist/buildDispatchUploadForm-BoUB93b3.mjs.map +1 -0
- package/dist/cloudflareSnapshot-DzPuCRTh.mjs +163 -0
- package/dist/cloudflareSnapshot-DzPuCRTh.mjs.map +1 -0
- package/dist/deploy-C0edCpn9.mjs +119 -0
- package/dist/deploy-C0edCpn9.mjs.map +1 -0
- package/dist/destroy-DzgA4lCA.mjs +215 -0
- package/dist/destroy-DzgA4lCA.mjs.map +1 -0
- package/dist/destroy-tenant-U0t7BeJ0.mjs +103 -0
- package/dist/destroy-tenant-U0t7BeJ0.mjs.map +1 -0
- package/dist/dev-CZbKfdFw.mjs +103 -0
- package/dist/dev-CZbKfdFw.mjs.map +1 -0
- package/dist/dns-records.resolve-C2T0m4NG.mjs +3 -0
- package/dist/dns-records.resolve-DwBR_1WI.mjs +47 -0
- package/dist/dns-records.resolve-DwBR_1WI.mjs.map +1 -0
- package/dist/dns-records.sync-Bpzz9H0s.mjs +75 -0
- package/dist/dns-records.sync-Bpzz9H0s.mjs.map +1 -0
- package/dist/doctor-C_hs7k2D.mjs +34 -0
- package/dist/doctor-C_hs7k2D.mjs.map +1 -0
- package/dist/drift-B5bpkI0i.mjs +323 -0
- package/dist/drift-B5bpkI0i.mjs.map +1 -0
- package/dist/drift-BNa92AK5.mjs +10 -0
- package/dist/events-BIznt8Sj.mjs +68 -0
- package/dist/events-BIznt8Sj.mjs.map +1 -0
- package/dist/fetchStackImports-C-1THPYL.mjs +3826 -0
- package/dist/fetchStackImports-C-1THPYL.mjs.map +1 -0
- package/dist/generator-Ba-vqyBG.mjs +77 -0
- package/dist/generator-Ba-vqyBG.mjs.map +1 -0
- package/dist/import-B0dlwKoQ.mjs +164 -0
- package/dist/import-B0dlwKoQ.mjs.map +1 -0
- package/dist/index.d.mts +5673 -1290
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +18 -1
- package/dist/index.mjs.map +1 -0
- package/dist/loader-DAvCKLTT.mjs +518 -0
- package/dist/loader-DAvCKLTT.mjs.map +1 -0
- package/dist/logpush-job-DsRkOORJ.mjs +1106 -0
- package/dist/logpush-job-DsRkOORJ.mjs.map +1 -0
- package/dist/migrate-BpW6JkIg.mjs +87 -0
- package/dist/migrate-BpW6JkIg.mjs.map +1 -0
- package/dist/normalize-DVSTRZhO.mjs +253 -0
- package/dist/normalize-DVSTRZhO.mjs.map +1 -0
- package/dist/plan-Do5rE-c5.mjs +453 -0
- package/dist/plan-Do5rE-c5.mjs.map +1 -0
- package/dist/planFormat-CJw8Kq2s.mjs +119 -0
- package/dist/planFormat-CJw8Kq2s.mjs.map +1 -0
- package/dist/provision-tenant-Wfck-2Oa.mjs +192 -0
- package/dist/provision-tenant-Wfck-2Oa.mjs.map +1 -0
- package/dist/r2S3EmptyBucket-DD81ZWQ7.mjs +92 -0
- package/dist/r2S3EmptyBucket-DD81ZWQ7.mjs.map +1 -0
- package/dist/stackOutputs-CQQHtdPA.mjs +69 -0
- package/dist/stackOutputs-CQQHtdPA.mjs.map +1 -0
- package/dist/status-D5GLpWyn.mjs +198 -0
- package/dist/status-D5GLpWyn.mjs.map +1 -0
- package/dist/sync-B_pyPi7Z.mjs +90 -0
- package/dist/sync-B_pyPi7Z.mjs.map +1 -0
- package/dist/tamer.d.mts +1 -0
- package/dist/tamer.mjs +4553 -0
- package/dist/tamer.mjs.map +1 -0
- package/dist/tamerArtifactsR2-Ccgplu2Q.mjs +52 -0
- package/dist/tamerArtifactsR2-Ccgplu2Q.mjs.map +1 -0
- package/dist/types-JrdlG7Dy.mjs +44 -0
- package/dist/types-JrdlG7Dy.mjs.map +1 -0
- package/dist/verifyPlanFile-ah_4tvTu.mjs +33 -0
- package/dist/verifyPlanFile-ah_4tvTu.mjs.map +1 -0
- package/dist/wfp-delete-BhuUrBUA.mjs +36 -0
- package/dist/wfp-delete-BhuUrBUA.mjs.map +1 -0
- package/dist/wfp-put-DL0mJNNz.mjs +52 -0
- package/dist/wfp-put-DL0mJNNz.mjs.map +1 -0
- package/dist/worker-route-CMbtozNa.mjs +263 -0
- package/dist/worker-route-CMbtozNa.mjs.map +1 -0
- package/dist/workers-C-oeZhdD.mjs +87 -0
- package/dist/workers-C-oeZhdD.mjs.map +1 -0
- package/dist/wranglerSpawn-DmEz0ldT.mjs +24 -0
- package/dist/wranglerSpawn-DmEz0ldT.mjs.map +1 -0
- package/dist/zoneResolver-VoxLHM4N.mjs +32 -0
- package/dist/zoneResolver-VoxLHM4N.mjs.map +1 -0
- package/package.json +38 -3
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { f as getDispatchNamespaces, p as getDnsRecords } from "./normalize-DVSTRZhO.mjs";
|
|
2
|
+
import { n as loadConfig, t as getWorkers } from "./loader-DAvCKLTT.mjs";
|
|
3
|
+
import { n as cloudflareAccountIdFromEnv, t as CFApiClient } from "./CFApiClient-DhbyyV71.mjs";
|
|
4
|
+
import { _ as namingFromConfig, a as resourceModules, o as logicalNamesForResourceKind } from "./fetchStackImports-C-1THPYL.mjs";
|
|
5
|
+
import { f as stackNameForConfig, l as destroyTamerStateDatabase, s as isEphemeralEnv, t as StateManager } from "./StateManager-DTqtLLVX.mjs";
|
|
6
|
+
import "./r2S3EmptyBucket-DD81ZWQ7.mjs";
|
|
7
|
+
import { n as logpushJobDestroy } from "./logpush-job-DsRkOORJ.mjs";
|
|
8
|
+
import { n as workerRoutesDestroy } from "./worker-route-CMbtozNa.mjs";
|
|
9
|
+
import { runSync } from "./sync-B_pyPi7Z.mjs";
|
|
10
|
+
import { i as hashCloudflareSnapshot, t as buildCloudflareSnapshot } from "./cloudflareSnapshot-DzPuCRTh.mjs";
|
|
11
|
+
import { t as verifyPlanFile } from "./verifyPlanFile-ah_4tvTu.mjs";
|
|
12
|
+
import { t as destroyTamerArtifactsBucket } from "./tamerArtifactsR2-Ccgplu2Q.mjs";
|
|
13
|
+
import { n as workersDestroy } from "./workers-C-oeZhdD.mjs";
|
|
14
|
+
|
|
15
|
+
//#region src/features/dispatch-namespace/dispatch-namespace.destroy.ts
|
|
16
|
+
/**
|
|
17
|
+
* Tear down every dispatch namespace recorded in state.
|
|
18
|
+
*
|
|
19
|
+
* Cloudflare refuses to delete a namespace that still contains scripts, so we
|
|
20
|
+
* enumerate `/dispatch/namespaces/{ns}/scripts` and delete each (with `force`
|
|
21
|
+
* so dependents like service-bind targets don't block the removal). This
|
|
22
|
+
* covers tenant scripts uploaded by `tamer wfp put` / `provision-workflow`
|
|
23
|
+
* that aren't otherwise tracked in Tamer state.
|
|
24
|
+
*/
|
|
25
|
+
async function dispatchNamespaceDestroy(env, state, api, config, _force) {
|
|
26
|
+
const allowedLogical = new Set(getDispatchNamespaces(config).map((d) => d.logicalName));
|
|
27
|
+
if (allowedLogical.size === 0) return;
|
|
28
|
+
for (const [key, entry] of Object.entries(state.getAll())) {
|
|
29
|
+
if (entry.type !== "dispatch_namespace") continue;
|
|
30
|
+
const ns = entry;
|
|
31
|
+
if (!allowedLogical.has(ns.logicalName)) continue;
|
|
32
|
+
const isSharedEphemeral = ns.derivedName.endsWith("-ephemeral");
|
|
33
|
+
try {
|
|
34
|
+
const scripts = await api.dispatchNamespaceScriptList(ns.derivedName);
|
|
35
|
+
for (const s of scripts) {
|
|
36
|
+
if (isEphemeralEnv(env, config.tenant) && isSharedEphemeral) {
|
|
37
|
+
if (!s.id.endsWith(`-${env}`)) continue;
|
|
38
|
+
}
|
|
39
|
+
try {
|
|
40
|
+
await api.dispatchNamespaceScriptDelete(ns.derivedName, s.id, { force: true });
|
|
41
|
+
console.log(`Deleted tenant script "${s.id}" from namespace ${ns.derivedName}.`);
|
|
42
|
+
} catch (err) {
|
|
43
|
+
console.warn(`Failed to delete tenant script ${s.id} in ${ns.derivedName}:`, err instanceof Error ? err.message : err);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (isEphemeralEnv(env, config.tenant) && isSharedEphemeral) {
|
|
47
|
+
console.log(`Left shared dispatch namespace ${ns.derivedName} (removed only scripts suffixed -${env}).`);
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
await api.dispatchNamespaceDelete(ns.derivedName);
|
|
51
|
+
state.delete(key);
|
|
52
|
+
} catch (err) {
|
|
53
|
+
console.warn(`Failed to delete dispatch namespace ${ns.derivedName}:`, err instanceof Error ? err.message : err);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
//#endregion
|
|
59
|
+
//#region src/features/dns-records/dns-records.destroy.ts
|
|
60
|
+
/**
|
|
61
|
+
* Tear down every DNS record this stack owns. Restricted to records
|
|
62
|
+
* whose `logicalName` is declared in the current `CfiConfig.dnsRecords`
|
|
63
|
+
* (matches `runDestroy` semantics for shared state rows). Records flagged
|
|
64
|
+
* `preserveOnDestroy: true` are left in place but still dropped from
|
|
65
|
+
* state — the operator is responsible for re-importing them later.
|
|
66
|
+
*/
|
|
67
|
+
async function dnsRecordDestroy(env, state, api, config, _force) {
|
|
68
|
+
if (env === "local") return;
|
|
69
|
+
const declared = getDnsRecords(config);
|
|
70
|
+
if (declared.length === 0) return;
|
|
71
|
+
const preserve = new Map(declared.map((c) => [c.logicalName, !!c.preserveOnDestroy]));
|
|
72
|
+
const allowedLogical = new Set(declared.map((c) => c.logicalName));
|
|
73
|
+
for (const [key, entry] of Object.entries(state.getAll())) {
|
|
74
|
+
if (entry.type !== "dns_record") continue;
|
|
75
|
+
const rec = entry;
|
|
76
|
+
if (!allowedLogical.has(rec.logicalName)) continue;
|
|
77
|
+
if (preserve.get(rec.logicalName)) {
|
|
78
|
+
console.log(`Preserved DNS record ${rec.recordType} ${rec.name} (preserveOnDestroy).`);
|
|
79
|
+
state.delete(key);
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
await api.zoneDnsRecordDelete(rec.zoneId, rec.recordId);
|
|
84
|
+
state.delete(key);
|
|
85
|
+
} catch (err) {
|
|
86
|
+
console.warn(`Failed to delete DNS record ${rec.recordType} ${rec.name}:`, err instanceof Error ? err.message : err);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
//#endregion
|
|
92
|
+
//#region src/cli/destroyGuard.ts
|
|
93
|
+
/** Shared envs where destroy must be confirmed with `--confirm-env <same>`. */
|
|
94
|
+
const SHARED_ENV_DESTROY = [
|
|
95
|
+
"dev",
|
|
96
|
+
"staging",
|
|
97
|
+
"prod",
|
|
98
|
+
"production"
|
|
99
|
+
];
|
|
100
|
+
/**
|
|
101
|
+
* @param force When true, skips the typed confirmation (break-glass).
|
|
102
|
+
*/
|
|
103
|
+
function assertDestroyEnvAllowed(env, force, confirmEnv) {
|
|
104
|
+
if (force) return;
|
|
105
|
+
if (!SHARED_ENV_DESTROY.includes(env)) return;
|
|
106
|
+
if (confirmEnv !== env) throw new Error(`Destroying shared environment "${env}" requires --confirm-env ${env}`);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
//#endregion
|
|
110
|
+
//#region src/cli/commands/destroy.ts
|
|
111
|
+
async function runDestroy(options) {
|
|
112
|
+
const { env, force = false, skipWorkers = false, confirmEnv, configPath, wipeMetadata = false } = options;
|
|
113
|
+
const baseDir = process.cwd();
|
|
114
|
+
assertDestroyEnvAllowed(env, force, confirmEnv);
|
|
115
|
+
const config = await loadConfig(configPath, { env });
|
|
116
|
+
const accountId = config.account_id ?? cloudflareAccountIdFromEnv();
|
|
117
|
+
if (!accountId) throw new Error("account_id required in config or CLOUDFLARE_ACCOUNT_ID env var");
|
|
118
|
+
if (options.planFile) {
|
|
119
|
+
const verifyApi = new CFApiClient(accountId);
|
|
120
|
+
const verifyState = new StateManager(config.tenant.id, env, stackNameForConfig(config));
|
|
121
|
+
await verifyState.hydrate(verifyApi);
|
|
122
|
+
const liveSnapshot = env === "local" ? void 0 : await buildCloudflareSnapshot({
|
|
123
|
+
config,
|
|
124
|
+
env,
|
|
125
|
+
api: verifyApi,
|
|
126
|
+
baseDir
|
|
127
|
+
});
|
|
128
|
+
verifyPlanFile({
|
|
129
|
+
planPath: options.planFile,
|
|
130
|
+
command: "destroy",
|
|
131
|
+
expectedMode: "destroy",
|
|
132
|
+
env,
|
|
133
|
+
tenantId: config.tenant.id,
|
|
134
|
+
config,
|
|
135
|
+
stateAtPlanCheck: verifyState.load(),
|
|
136
|
+
liveCloudflareHash: liveSnapshot ? hashCloudflareSnapshot(liveSnapshot) : void 0,
|
|
137
|
+
allowStale: !!options.allowStale
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
if (env !== "local") {
|
|
141
|
+
console.log(`Syncing state from Cloudflare for env: ${env}...`);
|
|
142
|
+
await runSync({
|
|
143
|
+
env,
|
|
144
|
+
configPath
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
const api = new CFApiClient(accountId);
|
|
148
|
+
const naming = namingFromConfig(config);
|
|
149
|
+
const state = new StateManager(config.tenant.id, env, stackNameForConfig(config));
|
|
150
|
+
await state.hydrate(api);
|
|
151
|
+
state.beginOperation("destroy", wipeMetadata ? "wipe-metadata" : void 0);
|
|
152
|
+
try {
|
|
153
|
+
await state.persist(api);
|
|
154
|
+
} catch {}
|
|
155
|
+
try {
|
|
156
|
+
if (!skipWorkers) {
|
|
157
|
+
await workerRoutesDestroy(env, config, baseDir, state, api);
|
|
158
|
+
await state.persist(api);
|
|
159
|
+
await workersDestroy(env, baseDir, accountId, config, state, api, force);
|
|
160
|
+
}
|
|
161
|
+
const ownedByKind = await Promise.all(resourceModules.map((m) => logicalNamesForResourceKind(config, baseDir, m.kind).then((set) => ({
|
|
162
|
+
mod: m,
|
|
163
|
+
owned: set
|
|
164
|
+
}))));
|
|
165
|
+
const workers = await getWorkers(config, baseDir);
|
|
166
|
+
await logpushJobDestroy(env, state, api, config);
|
|
167
|
+
await state.persist(api);
|
|
168
|
+
for (const { mod, owned } of ownedByKind) {
|
|
169
|
+
if (owned.size === 0) continue;
|
|
170
|
+
const resources = workers.flatMap(([, wc]) => mod.pickResources(wc));
|
|
171
|
+
await mod.destroy({
|
|
172
|
+
resources,
|
|
173
|
+
tenant: config.tenant,
|
|
174
|
+
env,
|
|
175
|
+
api,
|
|
176
|
+
state,
|
|
177
|
+
naming,
|
|
178
|
+
config,
|
|
179
|
+
baseDir,
|
|
180
|
+
force
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
if (getDispatchNamespaces(config).length > 0) await dispatchNamespaceDestroy(env, state, api, config, force);
|
|
184
|
+
if (getDnsRecords(config).length > 0) await dnsRecordDestroy(env, state, api, config, force);
|
|
185
|
+
state.replaceStackOutputs({});
|
|
186
|
+
if (env !== "local" && wipeMetadata) {
|
|
187
|
+
if (await destroyTamerStateDatabase(api, env)) console.log(`Deleted Tamer metadata database tamer-state-${env}.`);
|
|
188
|
+
try {
|
|
189
|
+
if (await destroyTamerArtifactsBucket(api, env)) console.log(`Deleted Tamer artifacts bucket tamer-artifacts-${env}.`);
|
|
190
|
+
} catch (err) {
|
|
191
|
+
console.warn(`Failed to delete Tamer artifacts bucket tamer-artifacts-${env} (likely non-empty; remove objects and re-run with --wipe-metadata):`, err instanceof Error ? err.message : err);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (env !== "local" && !wipeMetadata) {
|
|
195
|
+
state.finishOperation();
|
|
196
|
+
try {
|
|
197
|
+
await state.persist(api);
|
|
198
|
+
} catch {}
|
|
199
|
+
}
|
|
200
|
+
state.clearDirty();
|
|
201
|
+
console.log(`Destroyed all resources for env: ${env}`);
|
|
202
|
+
} catch (err) {
|
|
203
|
+
if (env !== "local") {
|
|
204
|
+
state.failOperation(err instanceof Error ? err.message : String(err));
|
|
205
|
+
try {
|
|
206
|
+
await state.persist(api);
|
|
207
|
+
} catch {}
|
|
208
|
+
}
|
|
209
|
+
throw err;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
//#endregion
|
|
214
|
+
export { runDestroy };
|
|
215
|
+
//# sourceMappingURL=destroy-DzgA4lCA.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"destroy-DzgA4lCA.mjs","names":[],"sources":["../src/features/dispatch-namespace/dispatch-namespace.destroy.ts","../src/features/dns-records/dns-records.destroy.ts","../src/cli/destroyGuard.ts","../src/cli/commands/destroy.ts"],"sourcesContent":["import type { CfiConfig } from \"../../types.js\";\nimport { getDispatchNamespaces } from \"../../types.js\";\nimport type { StateManager } from \"../../core/state/StateManager.js\";\nimport type { CFApiClient } from \"../../core/api/CFApiClient.js\";\nimport type { DispatchNamespaceStateEntry } from \"../../types.js\";\nimport { isEphemeralEnv } from \"./dispatch-namespace.resolve.js\";\n\n/**\n * Tear down every dispatch namespace recorded in state.\n *\n * Cloudflare refuses to delete a namespace that still contains scripts, so we\n * enumerate `/dispatch/namespaces/{ns}/scripts` and delete each (with `force`\n * so dependents like service-bind targets don't block the removal). This\n * covers tenant scripts uploaded by `tamer wfp put` / `provision-workflow`\n * that aren't otherwise tracked in Tamer state.\n */\nexport async function dispatchNamespaceDestroy(\n env: string,\n state: StateManager,\n api: CFApiClient,\n config: CfiConfig,\n _force?: boolean,\n): Promise<void> {\n const allowedLogical = new Set(\n getDispatchNamespaces(config).map((d) => d.logicalName),\n );\n if (allowedLogical.size === 0) return;\n\n for (const [key, entry] of Object.entries(state.getAll())) {\n if (entry.type !== \"dispatch_namespace\") continue;\n const ns = entry as DispatchNamespaceStateEntry;\n if (!allowedLogical.has(ns.logicalName)) continue;\n const isSharedEphemeral = ns.derivedName.endsWith(\"-ephemeral\");\n try {\n const scripts = await api.dispatchNamespaceScriptList(ns.derivedName);\n for (const s of scripts) {\n if (isEphemeralEnv(env, config.tenant) && isSharedEphemeral) {\n if (!s.id.endsWith(`-${env}`)) continue;\n }\n try {\n await api.dispatchNamespaceScriptDelete(ns.derivedName, s.id, {\n force: true,\n });\n console.log(\n `Deleted tenant script \"${s.id}\" from namespace ${ns.derivedName}.`,\n );\n } catch (err) {\n console.warn(\n `Failed to delete tenant script ${s.id} in ${ns.derivedName}:`,\n err instanceof Error ? err.message : err,\n );\n }\n }\n if (isEphemeralEnv(env, config.tenant) && isSharedEphemeral) {\n console.log(\n `Left shared dispatch namespace ${ns.derivedName} (removed only scripts suffixed -${env}).`,\n );\n continue;\n }\n await api.dispatchNamespaceDelete(ns.derivedName);\n state.delete(key);\n } catch (err) {\n console.warn(\n `Failed to delete dispatch namespace ${ns.derivedName}:`,\n err instanceof Error ? err.message : err,\n );\n }\n }\n}\n","import type { CfiConfig, DnsRecordStateEntry } from \"../../types.js\";\nimport { getDnsRecords } from \"../../types.js\";\nimport type { CFApiClient } from \"../../core/api/CFApiClient.js\";\nimport type { StateManager } from \"../../core/state/StateManager.js\";\n\n/**\n * Tear down every DNS record this stack owns. Restricted to records\n * whose `logicalName` is declared in the current `CfiConfig.dnsRecords`\n * (matches `runDestroy` semantics for shared state rows). Records flagged\n * `preserveOnDestroy: true` are left in place but still dropped from\n * state — the operator is responsible for re-importing them later.\n */\nexport async function dnsRecordDestroy(\n env: string,\n state: StateManager,\n api: CFApiClient,\n config: CfiConfig,\n _force?: boolean,\n): Promise<void> {\n if (env === \"local\") return;\n const declared = getDnsRecords(config);\n if (declared.length === 0) return;\n const preserve = new Map<string, boolean>(\n declared.map((c) => [c.logicalName, !!c.preserveOnDestroy]),\n );\n const allowedLogical = new Set(declared.map((c) => c.logicalName));\n\n for (const [key, entry] of Object.entries(state.getAll())) {\n if (entry.type !== \"dns_record\") continue;\n const rec = entry as DnsRecordStateEntry;\n if (!allowedLogical.has(rec.logicalName)) continue;\n if (preserve.get(rec.logicalName)) {\n console.log(\n `Preserved DNS record ${rec.recordType} ${rec.name} (preserveOnDestroy).`,\n );\n state.delete(key);\n continue;\n }\n try {\n await api.zoneDnsRecordDelete(rec.zoneId, rec.recordId);\n state.delete(key);\n } catch (err) {\n console.warn(\n `Failed to delete DNS record ${rec.recordType} ${rec.name}:`,\n err instanceof Error ? err.message : err,\n );\n }\n }\n}\n","/** Shared envs where destroy must be confirmed with `--confirm-env <same>`. */\nexport const SHARED_ENV_DESTROY = [\n \"dev\",\n \"staging\",\n \"prod\",\n \"production\",\n] as const;\n\n/**\n * @param force When true, skips the typed confirmation (break-glass).\n */\nexport function assertDestroyEnvAllowed(\n env: string,\n force: boolean,\n confirmEnv?: string,\n): void {\n if (force) return;\n if (!SHARED_ENV_DESTROY.includes(env as (typeof SHARED_ENV_DESTROY)[number])) {\n return;\n }\n if (confirmEnv !== env) {\n throw new Error(\n `Destroying shared environment \"${env}\" requires --confirm-env ${env}`,\n );\n }\n}\n","import { loadConfig, getWorkers } from \"../../core/config/loader.js\";\nimport { logicalNamesForResourceKind } from \"../../core/config/resourcesFromConfig.js\";\nimport { cloudflareAccountIdFromEnv } from \"../../core/cloudflareEnv.js\";\nimport { CFApiClient } from \"../../core/api/CFApiClient.js\";\nimport { StateManager } from \"../../core/state/StateManager.js\";\nimport { stackNameForConfig } from \"../../core/state/stackName.js\";\nimport { destroyTamerStateDatabase } from \"../../core/state/tamerStateDb.js\";\nimport { destroyTamerArtifactsBucket } from \"../../core/state/tamerArtifactsR2.js\";\nimport { getDispatchNamespaces, getDnsRecords } from \"../../types.js\";\nimport { logpushJobDestroy } from \"../../features/logpush-job/index.js\";\nimport { assertDestroyEnvAllowed } from \"../destroyGuard.js\";\nimport { dispatchNamespaceDestroy } from \"../../features/dispatch-namespace/index.js\";\nimport { dnsRecordDestroy } from \"../../features/dns-records/index.js\";\nimport { workersDestroy } from \"../../features/workers/index.js\";\nimport { workerRoutesDestroy } from \"../../features/worker-route/index.js\";\nimport { runSync } from \"./sync.js\";\nimport { resourceModules } from \"../../core/registry/registry.js\";\nimport { namingFromConfig } from \"../../core/config/namingFromConfig.js\";\nimport { verifyPlanFile } from \"../../core/plan/verifyPlanFile.js\";\nimport { hashCloudflareSnapshot } from \"../../core/plan/planFile.js\";\nimport { buildCloudflareSnapshot } from \"../../core/plan/cloudflareSnapshot.js\";\n\nexport async function runDestroy(options: {\n env: string;\n force?: boolean;\n skipWorkers?: boolean;\n confirmEnv?: string;\n configPath?: string;\n /** When true, delete the shared `tamer-state-{env}` D1 after other resources (use on last stack teardown). */\n wipeMetadata?: boolean;\n /**\n * Path to a destroy plan file from `tamer plan --destroy --out`. Destroy\n * recomputes the `(config, state, cloudflare)` attestation hashes and\n * refuses to proceed if any drifted (override with `allowStale`). The\n * pinned plan ensures the operator destroys exactly what they reviewed.\n */\n planFile?: string;\n allowStale?: boolean;\n}): Promise<void> {\n const {\n env,\n force = false,\n skipWorkers = false,\n confirmEnv,\n configPath,\n wipeMetadata = false,\n } = options;\n const baseDir = process.cwd();\n\n assertDestroyEnvAllowed(env, force, confirmEnv);\n\n const config = await loadConfig(configPath, { env });\n const accountId =\n config.account_id ?? cloudflareAccountIdFromEnv();\n if (!accountId) {\n throw new Error(\n \"account_id required in config or CLOUDFLARE_ACCOUNT_ID env var\",\n );\n }\n\n if (options.planFile) {\n const verifyApi = new CFApiClient(accountId);\n const verifyState = new StateManager(\n config.tenant.id,\n env,\n stackNameForConfig(config),\n );\n await verifyState.hydrate(verifyApi);\n const liveSnapshot =\n env === \"local\"\n ? undefined\n : await buildCloudflareSnapshot({\n config,\n env,\n api: verifyApi,\n baseDir,\n });\n verifyPlanFile({\n planPath: options.planFile,\n command: \"destroy\",\n expectedMode: \"destroy\",\n env,\n tenantId: config.tenant.id,\n config,\n stateAtPlanCheck: verifyState.load(),\n liveCloudflareHash: liveSnapshot\n ? hashCloudflareSnapshot(liveSnapshot)\n : undefined,\n allowStale: !!options.allowStale,\n });\n }\n\n if (env !== \"local\") {\n console.log(`Syncing state from Cloudflare for env: ${env}...`);\n await runSync({ env, configPath });\n }\n\n const api = new CFApiClient(accountId);\n const naming = namingFromConfig(config);\n const state = new StateManager(\n config.tenant.id,\n env,\n stackNameForConfig(config),\n );\n await state.hydrate(api);\n state.beginOperation(\"destroy\", wipeMetadata ? \"wipe-metadata\" : undefined);\n try {\n await state.persist(api);\n } catch {\n /* in-progress marker best-effort */\n }\n\n try {\n if (!skipWorkers) {\n await workerRoutesDestroy(env, config, baseDir, state, api);\n await state.persist(api);\n await workersDestroy(env, baseDir, accountId, config, state, api, force);\n }\n\n const ownedByKind = await Promise.all(\n resourceModules.map((m) =>\n logicalNamesForResourceKind(config, baseDir, m.kind).then((set) => ({\n mod: m,\n owned: set,\n })),\n ),\n );\n const workers = await getWorkers(config, baseDir);\n\n // Always run Logpush + Pipelines teardown: state may still hold\n // `logpush_pipelines` even if logpush was removed from tamer.config.ts,\n // and destroy must still delete the Pipelines stream/sink in that case.\n await logpushJobDestroy(env, state, api, config);\n await state.persist(api);\n\n for (const { mod, owned } of ownedByKind) {\n if (owned.size === 0) continue;\n // Aggregate this kind's resources across all workers in the config — the\n // destroy hook only needs them for stack-scope filtering and may walk\n // state directly. Empty array is acceptable when state holds entries\n // owned by another stack we still want to filter against `owned`.\n const resources = workers.flatMap(([, wc]) => mod.pickResources(wc));\n await mod.destroy({\n resources,\n tenant: config.tenant,\n env,\n api,\n state,\n naming,\n config,\n baseDir,\n force,\n });\n }\n\n if (getDispatchNamespaces(config).length > 0) {\n await dispatchNamespaceDestroy(env, state, api, config, force);\n }\n\n if (getDnsRecords(config).length > 0) {\n await dnsRecordDestroy(env, state, api, config, force);\n }\n\n // Clear `stackOutputs` after every successful destroy — the values\n // pointed at resources we just deleted, so leaving them in state would\n // mislead a future `tamer status` and (post-imports) leak dangling\n // refs into sibling stacks. The state row itself is dropped further\n // below when `wipeMetadata` is set.\n state.replaceStackOutputs({});\n\n if (env !== \"local\" && wipeMetadata) {\n const deletedDb = await destroyTamerStateDatabase(api, env);\n if (deletedDb) {\n console.log(`Deleted Tamer metadata database tamer-state-${env}.`);\n }\n try {\n const deletedBucket = await destroyTamerArtifactsBucket(api, env);\n if (deletedBucket) {\n console.log(\n `Deleted Tamer artifacts bucket tamer-artifacts-${env}.`,\n );\n }\n } catch (err) {\n console.warn(\n `Failed to delete Tamer artifacts bucket tamer-artifacts-${env} (likely non-empty; remove objects and re-run with --wipe-metadata):`,\n err instanceof Error ? err.message : err,\n );\n }\n }\n\n if (env !== \"local\" && !wipeMetadata) {\n state.finishOperation();\n try {\n await state.persist(api);\n } catch {\n /* state row may have been wiped by sub-steps */\n }\n }\n state.clearDirty();\n console.log(`Destroyed all resources for env: ${env}`);\n } catch (err) {\n if (env !== \"local\") {\n state.failOperation(err instanceof Error ? err.message : String(err));\n try {\n await state.persist(api);\n } catch {\n /* swallow secondary persist failure */\n }\n }\n throw err;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAgBA,eAAsB,yBACpB,KACA,OACA,KACA,QACA,QACe;CACf,MAAM,iBAAiB,IAAI,IACzB,sBAAsB,OAAO,CAAC,KAAK,MAAM,EAAE,YAAY,CACxD;AACD,KAAI,eAAe,SAAS,EAAG;AAE/B,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,QAAQ,CAAC,EAAE;AACzD,MAAI,MAAM,SAAS,qBAAsB;EACzC,MAAM,KAAK;AACX,MAAI,CAAC,eAAe,IAAI,GAAG,YAAY,CAAE;EACzC,MAAM,oBAAoB,GAAG,YAAY,SAAS,aAAa;AAC/D,MAAI;GACF,MAAM,UAAU,MAAM,IAA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iB,KAAK,OAAO,KAAK,QAAQ,MAAM;AAQxD,QAAM,oBAAoB,EAAE,CAAC;AAE7B,MAAI,QAAQ,WAAW,cAAc;AAEnC,OADkB,MAAM,0BAA0B,KAAK,IAAI,CAEzD,SAAQ,IAAI,+CAA+C,IAAI,GAAG;AAEpE,OAAI;AAEF,QADsB,MAAM,4BAA4B,KAAK,IAAI,CAE/D,SAAQ,IACN,kDAAkD,IAAI,GACvD;YAEI,KAAK;AACZ,YAAQ,KACN,2DAA2D,IAAI,uEAC/D,eAAe,QAAQ,IAAI,UAAU,IACtC;;;AAIL,MAAI,QAAQ,WAAW,CAAC,cAAc;AACpC,SAAM,iBAAiB;AACvB,OAAI;AACF,UAAM,MAAM,QAAQ,IAAI;WAClB;;AAIV,QAAM,YAAY;AAClB,UAAQ,IAAI,oCAAoC,MAAM;UAC/C,KAAK;AACZ,MAAI,QAAQ,SAAS;AACnB,SAAM,cAAc,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI,CAAC;AACrE,OAAI;AACF,UAAM,MAAM,QAAQ,IAAI;WAClB;;AAIV,QAAM"}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { n as loadConfig } from "./loader-DAvCKLTT.mjs";
|
|
2
|
+
import { n as cloudflareAccountIdFromEnv, t as CFApiClient } from "./CFApiClient-DhbyyV71.mjs";
|
|
3
|
+
import { a as tenantStateKey, f as stackNameForConfig, t as StateManager } from "./StateManager-DTqtLLVX.mjs";
|
|
4
|
+
|
|
5
|
+
//#region src/core/env/protectedEnvs.ts
|
|
6
|
+
/**
|
|
7
|
+
* Default set of envs that require explicit confirmation before
|
|
8
|
+
* `destroy-tenant` will run. Used when the loaded config doesn't pin
|
|
9
|
+
* `tenant.protectedEnvs` — these two names are universal-enough across
|
|
10
|
+
* accounts that "destroying prod by accident" stays guarded by default,
|
|
11
|
+
* but the operator is free to override the list (e.g. a multi-region
|
|
12
|
+
* account with `production-eu` / `production-us` / `canary` adds those
|
|
13
|
+
* here, and a personal account passes `[]` to disable the prompt).
|
|
14
|
+
*/
|
|
15
|
+
const DEFAULT_PROTECTED_ENVS = ["prod", "production"];
|
|
16
|
+
/**
|
|
17
|
+
* `true` when `env` is in `tenant.protectedEnvs` from the loaded
|
|
18
|
+
* `tamer.config.ts` (or in the default set when the config doesn't
|
|
19
|
+
* pin its own list). Single source of truth for the destroy
|
|
20
|
+
* confirmation check — call this **after** `loadConfig` so the
|
|
21
|
+
* config-pinned list is honored.
|
|
22
|
+
*/
|
|
23
|
+
function isProtectedEnv(env, config) {
|
|
24
|
+
return (config.tenant.protectedEnvs ?? DEFAULT_PROTECTED_ENVS).includes(env);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
//#endregion
|
|
28
|
+
//#region src/cli/commands/destroy-tenant.ts
|
|
29
|
+
async function runDestroyTenant(options) {
|
|
30
|
+
const env = options.env;
|
|
31
|
+
if (env === "local") throw new Error("destroy-tenant requires a non-local --env.");
|
|
32
|
+
const config = await loadConfig(options.configPath, { env });
|
|
33
|
+
if (isProtectedEnv(env, config) && !options.force) {
|
|
34
|
+
if (options.confirmTenant !== options.workspace) throw new Error(`destroy-tenant: env "${env}" is in tenant.protectedEnvs (or the default ["prod","production"]); pass --confirm-tenant ${options.workspace} (must match --workspace) or use --force`);
|
|
35
|
+
}
|
|
36
|
+
const accountId = config.account_id ?? cloudflareAccountIdFromEnv();
|
|
37
|
+
if (!accountId) throw new Error("account_id required in config or CLOUDFLARE_ACCOUNT_ID env var");
|
|
38
|
+
const api = new CFApiClient(accountId);
|
|
39
|
+
const state = new StateManager(config.tenant.id, env, stackNameForConfig(config));
|
|
40
|
+
await state.hydrate(api);
|
|
41
|
+
const t = state.getTenant(options.product, options.workspace);
|
|
42
|
+
if (!t) {
|
|
43
|
+
if (!options.force) throw new Error(`No tenant state for ${tenantStateKey(options.product, options.workspace)}; pass --force to skip state check`);
|
|
44
|
+
console.log("No tenant record in state; nothing to remove.");
|
|
45
|
+
if (options.json) {
|
|
46
|
+
const result = {
|
|
47
|
+
status: "noop",
|
|
48
|
+
tenantKey: tenantStateKey(options.product, options.workspace),
|
|
49
|
+
product: options.product,
|
|
50
|
+
workspace: options.workspace,
|
|
51
|
+
env,
|
|
52
|
+
removed: { shards: [] },
|
|
53
|
+
errors: []
|
|
54
|
+
};
|
|
55
|
+
process.stdout.write(JSON.stringify(result) + "\n");
|
|
56
|
+
}
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
const errors = [];
|
|
60
|
+
try {
|
|
61
|
+
await api.dispatchNamespaceScriptDelete(t.dispatchNamespaceName, t.scriptName, { force: true });
|
|
62
|
+
} catch (err) {
|
|
63
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
64
|
+
console.warn(`[destroy-tenant] script delete: ${msg}`);
|
|
65
|
+
errors.push(`script:${t.scriptName}:${msg}`);
|
|
66
|
+
}
|
|
67
|
+
const removedShards = [];
|
|
68
|
+
for (const shard of t.d1Shards ?? []) try {
|
|
69
|
+
await api.d1Delete(shard.cfId);
|
|
70
|
+
removedShards.push({
|
|
71
|
+
role: shard.role,
|
|
72
|
+
derivedName: shard.derivedName,
|
|
73
|
+
cfId: shard.cfId
|
|
74
|
+
});
|
|
75
|
+
} catch (err) {
|
|
76
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
77
|
+
console.warn(`[destroy-tenant] D1 ${shard.derivedName}: ${msg}`);
|
|
78
|
+
errors.push(`d1:${shard.derivedName}:${msg}`);
|
|
79
|
+
}
|
|
80
|
+
state.deleteTenant(options.product, options.workspace);
|
|
81
|
+
await state.persist(api);
|
|
82
|
+
console.log(`Destroyed tenant ${tenantStateKey(options.product, options.workspace)}`);
|
|
83
|
+
if (options.json) {
|
|
84
|
+
const result = {
|
|
85
|
+
status: "destroyed",
|
|
86
|
+
tenantKey: tenantStateKey(options.product, options.workspace),
|
|
87
|
+
product: options.product,
|
|
88
|
+
workspace: options.workspace,
|
|
89
|
+
env,
|
|
90
|
+
removed: {
|
|
91
|
+
scriptName: t.scriptName,
|
|
92
|
+
dispatchNamespaceName: t.dispatchNamespaceName,
|
|
93
|
+
shards: removedShards
|
|
94
|
+
},
|
|
95
|
+
errors
|
|
96
|
+
};
|
|
97
|
+
process.stdout.write(JSON.stringify(result) + "\n");
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
//#endregion
|
|
102
|
+
export { runDestroyTenant };
|
|
103
|
+
//# sourceMappingURL=destroy-tenant-U0t7BeJ0.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"destroy-tenant-U0t7BeJ0.mjs","names":["DEFAULT_PROTECTED_ENVS: readonly string[]","result: DestroyTenantResult","errors: string[]","removedShards: { role: string; derivedName: string; cfId: string }[]"],"sources":["../src/core/env/protectedEnvs.ts","../src/cli/commands/destroy-tenant.ts"],"sourcesContent":["import type { CfiConfig } from \"../../types.js\";\n\n/**\n * Default set of envs that require explicit confirmation before\n * `destroy-tenant` will run. Used when the loaded config doesn't pin\n * `tenant.protectedEnvs` — these two names are universal-enough across\n * accounts that \"destroying prod by accident\" stays guarded by default,\n * but the operator is free to override the list (e.g. a multi-region\n * account with `production-eu` / `production-us` / `canary` adds those\n * here, and a personal account passes `[]` to disable the prompt).\n */\nconst DEFAULT_PROTECTED_ENVS: readonly string[] = [\"prod\", \"production\"];\n\n/**\n * `true` when `env` is in `tenant.protectedEnvs` from the loaded\n * `tamer.config.ts` (or in the default set when the config doesn't\n * pin its own list). Single source of truth for the destroy\n * confirmation check — call this **after** `loadConfig` so the\n * config-pinned list is honored.\n */\nexport function isProtectedEnv(env: string, config: CfiConfig): boolean {\n const list = config.tenant.protectedEnvs ?? DEFAULT_PROTECTED_ENVS;\n return list.includes(env);\n}\n\nexport { DEFAULT_PROTECTED_ENVS };\n","import { loadConfig } from \"../../core/config/loader.js\";\nimport { cloudflareAccountIdFromEnv } from \"../../core/cloudflareEnv.js\";\nimport { CFApiClient } from \"../../core/api/CFApiClient.js\";\nimport { StateManager } from \"../../core/state/StateManager.js\";\nimport { stackNameForConfig } from \"../../core/state/stackName.js\";\nimport { tenantStateKey } from \"../../core/tenant/tenantKeys.js\";\nimport { isProtectedEnv } from \"../../core/env/protectedEnvs.js\";\n\n/**\n * Machine-readable result envelope emitted on the final stdout line\n * when `--json` is passed. Mirrors `ProvisionTenantResult` so the\n * Cloudflare Container caller (`provision-workflow`, see\n * `docs/handoff.md` §7) can consume both commands with the same\n * parsing path. `removed.shards` lists every D1 we attempted to\n * delete; `errors` lists any best-effort delete failures so the\n * Workflow can surface them without re-parsing logs.\n */\nexport interface DestroyTenantResult {\n status: \"destroyed\" | \"noop\" | \"failed\";\n tenantKey: string;\n product: string;\n workspace: string;\n env: string;\n removed: {\n scriptName?: string;\n dispatchNamespaceName?: string;\n shards: { role: string; derivedName: string; cfId: string }[];\n };\n errors: string[];\n error?: string;\n}\n\nexport async function runDestroyTenant(options: {\n env: string;\n product: string;\n workspace: string;\n force?: boolean;\n confirmTenant?: string;\n configPath?: string;\n json?: boolean;\n}): Promise<void> {\n const env = options.env;\n if (env === \"local\") {\n throw new Error(\"destroy-tenant requires a non-local --env.\");\n }\n\n // Load config FIRST so the protection prompt can read\n // `tenant.protectedEnvs` from `tamer.config.ts`. This intentionally\n // ignores `--force` so a misconfigured CLI invocation can't\n // bypass even the load step — we want the parsed config in hand\n // before we accept any confirmation flag.\n const config = await loadConfig(options.configPath, { env });\n\n if (isProtectedEnv(env, config) && !options.force) {\n if (options.confirmTenant !== options.workspace) {\n throw new Error(\n `destroy-tenant: env \"${env}\" is in tenant.protectedEnvs ` +\n `(or the default [\"prod\",\"production\"]); pass ` +\n `--confirm-tenant ${options.workspace} (must match --workspace) or use --force`,\n );\n }\n }\n\n const accountId = config.account_id ?? cloudflareAccountIdFromEnv();\n if (!accountId) {\n throw new Error(\n \"account_id required in config or CLOUDFLARE_ACCOUNT_ID env var\",\n );\n }\n\n const api = new CFApiClient(accountId);\n const state = new StateManager(\n config.tenant.id,\n env,\n stackNameForConfig(config),\n );\n await state.hydrate(api);\n\n const t = state.getTenant(options.product, options.workspace);\n if (!t) {\n if (!options.force) {\n throw new Error(\n `No tenant state for ${tenantStateKey(options.product, options.workspace)}; pass --force to skip state check`,\n );\n }\n console.log(\"No tenant record in state; nothing to remove.\");\n if (options.json) {\n const result: DestroyTenantResult = {\n status: \"noop\",\n tenantKey: tenantStateKey(options.product, options.workspace),\n product: options.product,\n workspace: options.workspace,\n env,\n removed: { shards: [] },\n errors: [],\n };\n process.stdout.write(JSON.stringify(result) + \"\\n\");\n }\n return;\n }\n\n const errors: string[] = [];\n try {\n await api.dispatchNamespaceScriptDelete(\n t.dispatchNamespaceName,\n t.scriptName,\n { force: true },\n );\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.warn(`[destroy-tenant] script delete: ${msg}`);\n errors.push(`script:${t.scriptName}:${msg}`);\n }\n\n const removedShards: { role: string; derivedName: string; cfId: string }[] =\n [];\n for (const shard of t.d1Shards ?? []) {\n try {\n await api.d1Delete(shard.cfId);\n removedShards.push({\n role: shard.role,\n derivedName: shard.derivedName,\n cfId: shard.cfId,\n });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.warn(`[destroy-tenant] D1 ${shard.derivedName}: ${msg}`);\n errors.push(`d1:${shard.derivedName}:${msg}`);\n }\n }\n\n state.deleteTenant(options.product, options.workspace);\n await state.persist(api);\n\n console.log(\n `Destroyed tenant ${tenantStateKey(options.product, options.workspace)}`,\n );\n\n if (options.json) {\n const result: DestroyTenantResult = {\n status: \"destroyed\",\n tenantKey: tenantStateKey(options.product, options.workspace),\n product: options.product,\n workspace: options.workspace,\n env,\n removed: {\n scriptName: t.scriptName,\n dispatchNamespaceName: t.dispatchNamespaceName,\n shards: removedShards,\n },\n errors,\n };\n process.stdout.write(JSON.stringify(result) + \"\\n\");\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAWA,MAAMA,yBAA4C,CAAC,QAAQ,aAAa;;;;;;;;AASxE,SAAgB,eAA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M,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI;AAC5D,UAAQ,KAAK,mCAAmC,MAAM;AACtD,SAAO,KAAK,UAAU,EAAE,WAAW,GAAG,MAAM;;CAG9C,MAAMC,gBACJ,EAAE;AACJ,MAAK,MAAM,SAAS,EAAE,YAAY,EAAE,CAClC,KAAI;AACF,QAAM,IAAI,SAAS,MAAM,KAAK;AAC9B,gBAAc,KAAK;GACjB,MAAM,MAAM;GACZ,aAAa,MAAM;GACnB,MAAM,MAAM;GACb,CAAC;UACK,KAAK;EACZ,MAAM,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI;AAC5D,UAAQ,KAAK,uBAAuB,MAAM,YAAY,IAAI,MAAM;AAChE,SAAO,KAAK,MAAM,MAAM,YAAY,GAAG,MAAM;;AAIjD,OAAM,aAAa,QAAQ,SAAS,QAAQ,UAAU;AACtD,OAAM,MAAM,QAAQ,IAAI;AAExB,SAAQ,IACN,oBAAoB,eAAe,QAAQ,SAAS,QAAQ,UAAU,GACvE;AAED,KAAI,QAAQ,MAAM;EAChB,MAAMF,SAA8B;GAClC,QAAQ;GACR,WAAW,eAAe,QAAQ,SAAS,QAAQ,UAAU;GAC7D,SAAS,QAAQ;GACjB,WAAW,QAAQ;GACnB;GACA,SAAS;IACP,YAAY,EAAE;IACd,uBAAuB,EAAE;IACzB,QAAQ;IACT;GACD;GACD;AACD,UAAQ,OAAO,MAAM,KAAK,UAAU,OAAO,GAAG,KAAK"}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { n as loadConfig, t as getWorkers } from "./loader-DAvCKLTT.mjs";
|
|
2
|
+
import { n as cloudflareAccountIdFromEnv, t as CFApiClient } from "./CFApiClient-DhbyyV71.mjs";
|
|
3
|
+
import { _ as namingFromConfig, g as wranglerConfigCliArgs, p as resolveWorkerConfig, t as fetchStackImports } from "./fetchStackImports-C-1THPYL.mjs";
|
|
4
|
+
import { f as stackNameForConfig, t as StateManager } from "./StateManager-DTqtLLVX.mjs";
|
|
5
|
+
import "./r2S3EmptyBucket-DD81ZWQ7.mjs";
|
|
6
|
+
import { n as writeWranglerJson, t as generateWranglerConfig } from "./generator-Ba-vqyBG.mjs";
|
|
7
|
+
import "./logpush-job-DsRkOORJ.mjs";
|
|
8
|
+
import "./worker-route-CMbtozNa.mjs";
|
|
9
|
+
import { runSync } from "./sync-B_pyPi7Z.mjs";
|
|
10
|
+
import { spawn } from "child_process";
|
|
11
|
+
|
|
12
|
+
//#region src/cli/commands/dev.ts
|
|
13
|
+
async function runDev(options) {
|
|
14
|
+
const workerFilter = options.worker;
|
|
15
|
+
const env = options.env ?? "local";
|
|
16
|
+
const configPath = options.configPath;
|
|
17
|
+
const baseDir = process.cwd();
|
|
18
|
+
const config = await loadConfig(configPath, { env });
|
|
19
|
+
const accountId = config.account_id ?? cloudflareAccountIdFromEnv();
|
|
20
|
+
if (!accountId) throw new Error("account_id required in config or CLOUDFLARE_ACCOUNT_ID env var");
|
|
21
|
+
const naming = namingFromConfig(config);
|
|
22
|
+
const api = new CFApiClient(accountId);
|
|
23
|
+
const state = new StateManager(config.tenant.id, env, stackNameForConfig(config));
|
|
24
|
+
await state.hydrate(api);
|
|
25
|
+
if (env !== "local" && Object.keys(state.load().resources).length === 0) {
|
|
26
|
+
console.log("Tamer state is empty; running sync...");
|
|
27
|
+
await runSync({
|
|
28
|
+
env,
|
|
29
|
+
configPath
|
|
30
|
+
});
|
|
31
|
+
state.reset();
|
|
32
|
+
await state.hydrate(api);
|
|
33
|
+
}
|
|
34
|
+
const imports = await fetchStackImports(api, config, env);
|
|
35
|
+
const workers = await getWorkers(config, baseDir);
|
|
36
|
+
const toRun = workerFilter ? workers.filter(([k]) => k === workerFilter) : workers;
|
|
37
|
+
if (toRun.length === 0) throw new Error(workerFilter ? `Worker "${workerFilter}" not found` : "No workers configured");
|
|
38
|
+
for (const [workerKey$1, workerConfig$1] of toRun) {
|
|
39
|
+
const resolved$1 = await resolveWorkerConfig(config, workerKey$1, workerConfig$1, env, baseDir, accountId, naming, state, { imports });
|
|
40
|
+
const wranglerConfig = generateWranglerConfig(resolved$1, state, naming);
|
|
41
|
+
writeWranglerJson(resolved$1.workerDir, wranglerConfig, resolved$1.wranglerOutFile);
|
|
42
|
+
}
|
|
43
|
+
if (options.all && toRun.length > 0) {
|
|
44
|
+
const basePort = Number(process.env.TAMER_DEV_BASE_PORT) || 8787;
|
|
45
|
+
const children = [];
|
|
46
|
+
for (let i = 0; i < toRun.length; i++) {
|
|
47
|
+
const [workerKey$1, workerConfig$1] = toRun[i];
|
|
48
|
+
const resolved$1 = await resolveWorkerConfig(config, workerKey$1, workerConfig$1, env, baseDir, accountId, naming, state, { imports });
|
|
49
|
+
const port = basePort + i;
|
|
50
|
+
const devArgs = [
|
|
51
|
+
"wrangler",
|
|
52
|
+
...wranglerConfigCliArgs(resolved$1.wranglerOutFile),
|
|
53
|
+
"dev",
|
|
54
|
+
"--port",
|
|
55
|
+
String(port)
|
|
56
|
+
];
|
|
57
|
+
console.log(`Starting ${workerKey$1} on http://127.0.0.1:${port}`);
|
|
58
|
+
const proc = spawn("bunx", devArgs, {
|
|
59
|
+
cwd: resolved$1.workerDir,
|
|
60
|
+
stdio: "inherit",
|
|
61
|
+
shell: true
|
|
62
|
+
});
|
|
63
|
+
children.push(proc);
|
|
64
|
+
}
|
|
65
|
+
const shutdown = () => {
|
|
66
|
+
for (const c of children) if (!c.killed) c.kill("SIGTERM");
|
|
67
|
+
};
|
|
68
|
+
process.once("SIGINT", () => {
|
|
69
|
+
shutdown();
|
|
70
|
+
process.exit(0);
|
|
71
|
+
});
|
|
72
|
+
process.once("SIGTERM", () => {
|
|
73
|
+
shutdown();
|
|
74
|
+
process.exit(0);
|
|
75
|
+
});
|
|
76
|
+
await new Promise((resolve) => {
|
|
77
|
+
let remaining = children.length;
|
|
78
|
+
for (const c of children) c.on("exit", () => {
|
|
79
|
+
remaining -= 1;
|
|
80
|
+
if (remaining <= 0) resolve();
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
const [workerKey, workerConfig] = toRun[0];
|
|
86
|
+
const resolved = await resolveWorkerConfig(config, workerKey, workerConfig, env, baseDir, accountId, naming, state, { imports });
|
|
87
|
+
console.log(`Starting wrangler dev for ${workerKey}...`);
|
|
88
|
+
spawn("bunx", [
|
|
89
|
+
"wrangler",
|
|
90
|
+
...wranglerConfigCliArgs(resolved.wranglerOutFile),
|
|
91
|
+
"dev"
|
|
92
|
+
], {
|
|
93
|
+
cwd: resolved.workerDir,
|
|
94
|
+
stdio: "inherit",
|
|
95
|
+
shell: true
|
|
96
|
+
}).on("exit", (code) => {
|
|
97
|
+
process.exit(code ?? 0);
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
//#endregion
|
|
102
|
+
export { runDev };
|
|
103
|
+
//# sourceMappingURL=dev-CZbKfdFw.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dev-CZbKfdFw.mjs","names":["workerKey","workerConfig","resolved","children: ChildProcess[]"],"sources":["../src/cli/commands/dev.ts"],"sourcesContent":["import type { ChildProcess } from \"child_process\";\nimport { spawn } from \"child_process\";\nimport { loadConfig, getWorkers } from \"../../core/config/loader.js\";\nimport { cloudflareAccountIdFromEnv } from \"../../core/cloudflareEnv.js\";\nimport { namingFromConfig } from \"../../core/config/namingFromConfig.js\";\nimport { wranglerConfigCliArgs } from \"../../core/wrangler/wranglerOutFile.js\";\nimport { StateManager } from \"../../core/state/StateManager.js\";\nimport { stackNameForConfig } from \"../../core/state/stackName.js\";\nimport { CFApiClient } from \"../../core/api/CFApiClient.js\";\nimport { resolveWorkerConfig } from \"../../core/config/resolver.js\";\nimport {\n generateWranglerConfig,\n writeWranglerJson,\n} from \"../../core/wrangler/generator.js\";\nimport { runSync } from \"./sync.js\";\nimport { fetchStackImports } from \"../../core/imports/fetchStackImports.js\";\n\nexport async function runDev(options: {\n worker?: string;\n env?: string;\n configPath?: string;\n /** Run every selected worker as a separate `wrangler dev` on incrementing ports (from TAMER_DEV_BASE_PORT or 8787). */\n all?: boolean;\n}): Promise<void> {\n const workerFilter = options.worker;\n const env = options.env ?? \"local\";\n const configPath = options.configPath;\n const baseDir = process.cwd();\n\n const config = await loadConfig(configPath, { env });\n const accountId =\n config.account_id ?? cloudflareAccountIdFromEnv();\n if (!accountId) {\n throw new Error(\n \"account_id required in config or CLOUDFLARE_ACCOUNT_ID env var\",\n );\n }\n\n const naming = namingFromConfig(config);\n const api = new CFApiClient(accountId);\n const state = new StateManager(\n config.tenant.id,\n env,\n stackNameForConfig(config),\n );\n await state.hydrate(api);\n\n if (\n env !== \"local\" &&\n Object.keys(state.load().resources).length === 0\n ) {\n console.log(\"Tamer state is empty; running sync...\");\n await runSync({ env, configPath });\n state.reset();\n await state.hydrate(api);\n }\n\n // Pre-fetch sibling stack outputs so worker `vars` / `tamerRoutes`\n // can reference `${tamer:import:<stack>.<output>}` even in dev mode.\n // No-op in local env (returns `{}`); when missing in non-local, the\n // import resolver will throw with a clear \"run apply on <stack>\" hint.\n const imports = await fetchStackImports(api, config, env);\n\n const workers = await getWorkers(config, baseDir);\n const toRun = workerFilter\n ? workers.filter(([k]) => k === workerFilter)\n : workers;\n\n if (toRun.length === 0) {\n throw new Error(\n workerFilter\n ? `Worker \"${workerFilter}\" not found`\n : \"No workers configured\",\n );\n }\n\n for (const [workerKey, workerConfig] of toRun) {\n const resolved = await resolveWorkerConfig(\n config,\n workerKey,\n workerConfig,\n env,\n baseDir,\n accountId,\n naming,\n state,\n { imports },\n );\n const wranglerConfig = generateWranglerConfig(resolved, state, naming);\n writeWranglerJson(resolved.workerDir, wranglerConfig, resolved.wranglerOutFile);\n }\n\n if (options.all && toRun.length > 0) {\n const basePort = Number(process.env.TAMER_DEV_BASE_PORT) || 8787;\n const children: ChildProcess[] = [];\n\n for (let i = 0; i < toRun.length; i++) {\n const [workerKey, workerConfig] = toRun[i];\n const resolved = await resolveWorkerConfig(\n config,\n workerKey,\n workerConfig,\n env,\n baseDir,\n accountId,\n naming,\n state,\n { imports },\n );\n const port = basePort + i;\n const devArgs = [\n \"wrangler\",\n ...wranglerConfigCliArgs(resolved.wranglerOutFile),\n \"dev\",\n \"--port\",\n String(port),\n ];\n console.log(`Starting ${workerKey} on http://127.0.0.1:${port}`);\n const proc = spawn(\"bunx\", devArgs, {\n cwd: resolved.workerDir,\n stdio: \"inherit\",\n shell: true,\n });\n children.push(proc);\n }\n\n const shutdown = () => {\n for (const c of children) {\n if (!c.killed) c.kill(\"SIGTERM\");\n }\n };\n process.once(\"SIGINT\", () => {\n shutdown();\n process.exit(0);\n });\n process.once(\"SIGTERM\", () => {\n shutdown();\n process.exit(0);\n });\n\n await new Promise<void>((resolve) => {\n let remaining = children.length;\n for (const c of children) {\n c.on(\"exit\", () => {\n remaining -= 1;\n if (remaining <= 0) resolve();\n });\n }\n });\n return;\n }\n\n const [workerKey, workerConfig] = toRun[0];\n const resolved = await resolveWorkerConfig(\n config,\n workerKey,\n workerConfig,\n env,\n baseDir,\n accountId,\n naming,\n state,\n { imports },\n );\n\n console.log(`Starting wrangler dev for ${workerKey}...`);\n const devArgs = [\n \"wrangler\",\n ...wranglerConfigCliArgs(resolved.wranglerOutFile),\n \"dev\",\n ];\n const proc = spawn(\"bunx\", devArgs, {\n cwd: resolved.workerDir,\n stdio: \"inherit\",\n shell: true,\n });\n\n proc.on(\"exit\", (code) => {\n process.exit(code ?? 0);\n });\n}\n"],"mappings":";;;;;;;;;;;;AAiBA,eAAsB,OAAO,SAMX;CAChB,MAAM,eAAe,QAAQ;CAC7B,MAAM,MAAM,QAAQ,OAAO;CAC3B,MAAM,aAAa,QAAQ;CAC3B,MAAM,UAAU,QAAQ,KAAK;CAE7B,MAAM,SAAS,MAAM,WAAW,YAAY,EAAE,KAAK,CAAC;CACpD,MAAM,YACJ,OAAO,cAAc,4BAA4B;AACnD,KAAI,CAAC,UACH,OAAM,IAAI,MACR,iEAC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sBC,WAAS,gBAAgB;IAClD;IACA;IACA,OAAO,KAAK;IACb;AACD,WAAQ,IAAI,YAAYF,YAAU,uBAAuB,OAAO;GAChE,MAAM,OAAO,MAAM,QAAQ,SAAS;IAClC,KAAKE,WAAS;IACd,OAAO;IACP,OAAO;IACR,CAAC;AACF,YAAS,KAAK,KAAK;;EAGrB,MAAM,iBAAiB;AACrB,QAAK,MAAM,KAAK,SACd,KAAI,CAAC,EAAE,OAAQ,GAAE,KAAK,UAAU;;AAGpC,UAAQ,KAAK,gBAAgB;AAC3B,aAAU;AACV,WAAQ,KAAK,EAAE;IACf;AACF,UAAQ,KAAK,iBAAiB;AAC5B,aAAU;AACV,WAAQ,KAAK,EAAE;IACf;AAEF,QAAM,IAAI,SAAe,YAAY;GACnC,IAAI,YAAY,SAAS;AACzB,QAAK,MAAM,KAAK,SACd,GAAE,GAAG,cAAc;AACjB,iBAAa;AACb,QAAI,aAAa,EAAG,UAAS;KAC7B;IAEJ;AACF;;CAGF,MAAM,CAAC,WAAW,gBAAgB,MAAM;CACxC,MAAM,WAAW,MAAM,oBACrB,QACA,WACA,cACA,KACA,SACA,WACA,QACA,OACA,EAAE,SAAS,CACZ;AAED,SAAQ,IAAI,6BAA6B,UAAU,KAAK;AAYxD,CANa,MAAM,QALH;EACd;EACA,GAAG,sBAAsB,SAAS,gBAAgB;EAClD;EACD,EACmC;EAClC,KAAK,SAAS;EACd,OAAO;EACP,OAAO;EACR,CAAC,CAEG,GAAG,SAAS,SAAS;AACxB,UAAQ,KAAK,QAAQ,EAAE;GACvB"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
//#region src/features/dns-records/dns-records.resolve.ts
|
|
2
|
+
/**
|
|
3
|
+
* Default skip list — `local` is always implicitly skipped on top of any
|
|
4
|
+
* envs the user lists in `skipEnvs`. Wrangler dev does not own real DNS;
|
|
5
|
+
* Tamer never reaches into Cloudflare for `local` apply/destroy.
|
|
6
|
+
*/
|
|
7
|
+
const ALWAYS_SKIPPED = new Set(["local"]);
|
|
8
|
+
/** Whether the record should be created/updated/destroyed for `env`. */
|
|
9
|
+
function dnsRecordAppliesToEnv(config, env) {
|
|
10
|
+
if (ALWAYS_SKIPPED.has(env)) return false;
|
|
11
|
+
return !(config.skipEnvs ?? []).includes(env);
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Stable comment marker Tamer attaches to every record it creates so
|
|
15
|
+
* `tamer sync` and `tamer import` can rediscover orphans after state
|
|
16
|
+
* loss. Format: `tamer:<tenantId>:<env>:<logicalName>` followed by the
|
|
17
|
+
* user's own free-form comment when set.
|
|
18
|
+
*/
|
|
19
|
+
function dnsRecordCommentMarker(tenant, env, logicalName) {
|
|
20
|
+
return `tamer:${tenant.id}:${env}:${logicalName}`;
|
|
21
|
+
}
|
|
22
|
+
/** Compose the comment Tamer writes (marker + optional user-supplied tail). */
|
|
23
|
+
function effectiveDnsRecordComment(config, tenant, env) {
|
|
24
|
+
const marker = dnsRecordCommentMarker(tenant, env, config.logicalName);
|
|
25
|
+
if (!config.comment) return marker;
|
|
26
|
+
return `${marker} ${config.comment}`;
|
|
27
|
+
}
|
|
28
|
+
/** TTL default — `1` is Cloudflare's "auto" sentinel. */
|
|
29
|
+
function effectiveDnsRecordTtl(config) {
|
|
30
|
+
return config.ttl ?? 1;
|
|
31
|
+
}
|
|
32
|
+
/** Proxied default — `false`, since most managed records (TXT, MX, NS, etc.) cannot be proxied. */
|
|
33
|
+
function effectiveDnsRecordProxied(config) {
|
|
34
|
+
return config.proxied ?? false;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* State key for one DNS record. Includes zone + type + name so multiple
|
|
38
|
+
* records of different types on the same hostname (e.g. A + AAAA + TXT)
|
|
39
|
+
* each get their own row.
|
|
40
|
+
*/
|
|
41
|
+
function dnsRecordStateKey(zoneId, type, name) {
|
|
42
|
+
return `dns_record:${zoneId}:${type}:${name}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
//#endregion
|
|
46
|
+
export { effectiveDnsRecordProxied as a, effectiveDnsRecordComment as i, dnsRecordCommentMarker as n, effectiveDnsRecordTtl as o, dnsRecordStateKey as r, dnsRecordAppliesToEnv as t };
|
|
47
|
+
//# sourceMappingURL=dns-records.resolve-DwBR_1WI.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dns-records.resolve-DwBR_1WI.mjs","names":[],"sources":["../src/features/dns-records/dns-records.resolve.ts"],"sourcesContent":["import type { DnsRecordResourceConfig, TenantMeta } from \"../../types.js\";\n\n/**\n * Default skip list — `local` is always implicitly skipped on top of any\n * envs the user lists in `skipEnvs`. Wrangler dev does not own real DNS;\n * Tamer never reaches into Cloudflare for `local` apply/destroy.\n */\nconst ALWAYS_SKIPPED = new Set([\"local\"]);\n\n/** Whether the record should be created/updated/destroyed for `env`. */\nexport function dnsRecordAppliesToEnv(\n config: DnsRecordResourceConfig,\n env: string,\n): boolean {\n if (ALWAYS_SKIPPED.has(env)) return false;\n return !(config.skipEnvs ?? []).includes(env);\n}\n\n/**\n * Stable comment marker Tamer attaches to every record it creates so\n * `tamer sync` and `tamer import` can rediscover orphans after state\n * loss. Format: `tamer:<tenantId>:<env>:<logicalName>` followed by the\n * user's own free-form comment when set.\n */\nexport function dnsRecordCommentMarker(\n tenant: TenantMeta,\n env: string,\n logicalName: string,\n): string {\n return `tamer:${tenant.id}:${env}:${logicalName}`;\n}\n\n/** Compose the comment Tamer writes (marker + optional user-supplied tail). */\nexport function effectiveDnsRecordComment(\n config: DnsRecordResourceConfig,\n tenant: TenantMeta,\n env: string,\n): string {\n const marker = dnsRecordCommentMarker(tenant, env, config.logicalName);\n if (!config.comment) return marker;\n return `${marker} ${config.comment}`;\n}\n\n/** TTL default — `1` is Cloudflare's \"auto\" sentinel. */\nexport function effectiveDnsRecordTtl(config: DnsRecordResourceConfig): number {\n return config.ttl ?? 1;\n}\n\n/** Proxied default — `false`, since most managed records (TXT, MX, NS, etc.) cannot be proxied. */\nexport function effectiveDnsRecordProxied(\n config: DnsRecordResourceConfig,\n): boolean {\n return config.proxied ?? false;\n}\n\n/**\n * State key for one DNS record. Includes zone + type + name so multiple\n * records of different types on the same hostname (e.g. A + AAAA + TXT)\n * each get their own row.\n */\nexport function dnsRecordStateKey(\n zoneId: string,\n type: string,\n name: string,\n): string {\n return `dns_record:${zoneId}:${type}:${name}`;\n}\n"],"mappings":";;;;;;AAOA,MAAM,iBAAiB,IAAI,IAAI,CAAC,QAAQ,CAAC;;AAGzC,SAAgB,sBACd,QACA,KACS;AACT,KAAI,eAAe,IAAI,IAAI,CAAE,QAAO;AACpC,QAAO,EAAE,OAAO,YAAY,EAAE,EAAE,SAAS,IAAI;;;;;;;;AAS/C,SAAgB,uBACd,QACA,KACA,aACQ;AACR,QAAO,SAAS,OAAO,GAAG,GAAG,IAAI,GAAG;;;AAItC,SAAgB,0BACd,QACA,QACA,KACQ;CACR,MAAM,SAAS,uBAAuB,QAAQ,KAAK,OAAO,YAAY;AACtE,KAAI,CAAC,OAAO,QAAS,QAAO;AAC5B,QAAO,GAAG,OAAO,GAAG,OAAO;;;AAI7B,SAAgB,sBAAsB,QAAyC;AAC7E,QAAO,OAAO,OAAO;;;AAIvB,SAAgB,0BACd,QACS;AACT,QAAO,OAAO,WAAW;;;;;;;AAQ3B,SAAgB,kBACd,QACA,MACA,MACQ;AACR,QAAO,cAAc,OAAO,GAAG,KAAK,GAAG"}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { o as effectiveDispatchNamespaceName } from "./StateManager-DTqtLLVX.mjs";
|
|
2
|
+
import { n as dnsRecordCommentMarker, r as dnsRecordStateKey, t as dnsRecordAppliesToEnv } from "./dns-records.resolve-DwBR_1WI.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/features/dispatch-namespace/dispatch-namespace.sync.ts
|
|
5
|
+
async function dispatchNamespaceSync(resources, tenant, env, api, state) {
|
|
6
|
+
if (resources.length === 0) return;
|
|
7
|
+
if (env === "local") return;
|
|
8
|
+
const list = await api.dispatchNamespaceListAll();
|
|
9
|
+
const names = new Set(list.map((n) => n.namespace_name));
|
|
10
|
+
for (const config of resources) {
|
|
11
|
+
const resolved = effectiveDispatchNamespaceName(config, env, tenant);
|
|
12
|
+
const key = `dispatch_ns:${resolved}`;
|
|
13
|
+
if (!names.has(resolved)) continue;
|
|
14
|
+
state.set(key, {
|
|
15
|
+
type: "dispatch_namespace",
|
|
16
|
+
logicalName: config.logicalName,
|
|
17
|
+
derivedName: resolved,
|
|
18
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
19
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
//#endregion
|
|
25
|
+
//#region src/features/dns-records/dns-records.sync.ts
|
|
26
|
+
/**
|
|
27
|
+
* Re-adopt every Tamer-attributed DNS record found on the live zones into
|
|
28
|
+
* state. Mirrors the dispatch-namespace sync pattern: Tamer never
|
|
29
|
+
* **destroys** records here, just imports rows that match its
|
|
30
|
+
* attribution comment so a `apply` straight after `sync` is a no-op when
|
|
31
|
+
* Cloudflare and config agree.
|
|
32
|
+
*
|
|
33
|
+
* Records on Cloudflare without Tamer's marker comment are ignored even
|
|
34
|
+
* if they happen to match the declared `(zone, type, name)` — they are
|
|
35
|
+
* presumed to be hand-managed and surface in `tamer drift` as
|
|
36
|
+
* `unrecordedInState` so the operator can decide.
|
|
37
|
+
*/
|
|
38
|
+
async function dnsRecordSync(resources, tenant, env, api, state) {
|
|
39
|
+
if (resources.length === 0) return;
|
|
40
|
+
const applicable = resources.filter((r) => dnsRecordAppliesToEnv(r, env));
|
|
41
|
+
if (applicable.length === 0) return;
|
|
42
|
+
const zoneCache = /* @__PURE__ */ new Map();
|
|
43
|
+
for (const config of applicable) {
|
|
44
|
+
let live = zoneCache.get(config.zoneId);
|
|
45
|
+
if (!live) {
|
|
46
|
+
live = await api.zoneDnsRecordListAll(config.zoneId);
|
|
47
|
+
zoneCache.set(config.zoneId, live);
|
|
48
|
+
}
|
|
49
|
+
const marker = dnsRecordCommentMarker(tenant, env, config.logicalName);
|
|
50
|
+
const adopted = live.find((r) => r.type === config.type && typeof r.comment === "string" && r.comment.startsWith(marker));
|
|
51
|
+
if (!adopted) continue;
|
|
52
|
+
const stateKey = dnsRecordStateKey(config.zoneId, config.type, config.name);
|
|
53
|
+
const ts = (/* @__PURE__ */ new Date()).toISOString();
|
|
54
|
+
const entry = {
|
|
55
|
+
type: "dns_record",
|
|
56
|
+
logicalName: config.logicalName,
|
|
57
|
+
zoneId: config.zoneId,
|
|
58
|
+
recordType: config.type,
|
|
59
|
+
name: adopted.name,
|
|
60
|
+
content: adopted.content,
|
|
61
|
+
ttl: adopted.ttl ?? 1,
|
|
62
|
+
proxied: adopted.proxied ?? false,
|
|
63
|
+
priority: adopted.priority,
|
|
64
|
+
comment: adopted.comment ?? marker,
|
|
65
|
+
recordId: adopted.id,
|
|
66
|
+
createdAt: state.get(stateKey)?.type === "dns_record" ? state.get(stateKey).createdAt : ts,
|
|
67
|
+
updatedAt: ts
|
|
68
|
+
};
|
|
69
|
+
state.set(stateKey, entry);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
//#endregion
|
|
74
|
+
export { dispatchNamespaceSync as n, dnsRecordSync as t };
|
|
75
|
+
//# sourceMappingURL=dns-records.sync-Bpzz9H0s.mjs.map
|