@redcenterstudio/deno-audit 0.0.0-stage → 1.0.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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +61 -2
  3. package/dist/bin.js +1419 -0
  4. package/package.json +39 -4
package/dist/bin.js ADDED
@@ -0,0 +1,1419 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/bin.ts
4
+ import { existsSync } from "node:fs";
5
+ import { resolve as resolve2 } from "node:path";
6
+
7
+ // src/index.ts
8
+ import { readdirSync, readFileSync, statSync } from "node:fs";
9
+ import { basename, join, relative, resolve, sep } from "node:path";
10
+
11
+ // ../core/src/oak-specifier.ts
12
+ function isOakSpecifier(spec, importMap) {
13
+ const mapped = importMap[spec] ?? spec;
14
+ const test = (s) => s === "oak" || s === "@oak/oak" || s === "@oakserver/oak" || s.startsWith("jsr:@oak/oak") || s.startsWith("npm:@oakserver/oak") || s.startsWith("@oak/oak/") || s.includes("deno.land/x/oak");
15
+ return test(spec) || test(mapped);
16
+ }
17
+
18
+ // ../core/src/scanner.ts
19
+ import ts3 from "typescript";
20
+
21
+ // ../core/src/parse-cache.ts
22
+ import ts from "typescript";
23
+ var active = null;
24
+ function parseSource(path, content, kind) {
25
+ const cache = active;
26
+ if (cache) {
27
+ const hit = cache.get(`${kind ?? ""}|${path}`);
28
+ if (hit && hit.kind === kind && hit.content === content) return hit.sf;
29
+ }
30
+ const sf = ts.createSourceFile(path, content, ts.ScriptTarget.Latest, true, kind);
31
+ if (cache) cache.set(`${kind ?? ""}|${path}`, { content, kind, sf });
32
+ return sf;
33
+ }
34
+
35
+ // ../core/src/cost-calculator.ts
36
+ function roundUsd(value) {
37
+ return Math.round(value * 100) / 100;
38
+ }
39
+ function calculateCostComparison(input) {
40
+ const requests = Math.max(0, input.monthlyRequests);
41
+ const egressGb = Math.max(0, input.egressGb);
42
+ const kvReadsMillions = Math.max(0, input.kvReadsMillions);
43
+ const kvWritesMillions = Math.max(0, input.kvWritesMillions);
44
+ const storageGb = Math.max(0, input.storageGb);
45
+ const denoBase = requests <= 1e5 && !input.usesDurableObjectKv ? 0 : 20;
46
+ const denoReqOverage = Math.max(0, (requests - 5e6) / 1e6) * 2;
47
+ const denoEgressOverage = Math.max(0, egressGb - 100) * 0.3;
48
+ const denoKvReads = Math.max(0, kvReadsMillions - 1) * 0.2;
49
+ const denoKvWrites = Math.max(0, kvWritesMillions - 0.5) * 1;
50
+ const denoStorageOverage = Math.max(0, storageGb - 5) * 0.75;
51
+ const denoComputeAndRequestsUsd = roundUsd(denoBase + denoReqOverage);
52
+ const denoEgressAndKvUsd = roundUsd(
53
+ denoEgressOverage + denoKvReads + denoKvWrites + denoStorageOverage
54
+ );
55
+ const denoDeployMonthlyUsd = roundUsd(denoComputeAndRequestsUsd + denoEgressAndKvUsd);
56
+ const cfBase = 5;
57
+ const cfReqOverage = Math.max(0, (requests - 1e7) / 1e6) * 0.3;
58
+ const cfWorkersUsd = roundUsd(cfBase + cfReqOverage);
59
+ let cfKvOrDoUsd = 0;
60
+ if (input.usesDurableObjectKv) {
61
+ const doRequestsM = Math.max(0, kvReadsMillions + kvWritesMillions - 1) * 0.15;
62
+ const doRowsRead = kvReadsMillions * 1e-3;
63
+ const doRowsWritten = Math.max(0, kvWritesMillions - 0.05) * 1;
64
+ const doStorage = Math.max(0, storageGb - 5) * 0.2;
65
+ cfKvOrDoUsd = roundUsd(doRequestsM + doRowsRead + doRowsWritten + doStorage);
66
+ } else {
67
+ const kvReadOverage = Math.max(0, kvReadsMillions - 10) * 0.5;
68
+ const kvWriteOverage = Math.max(0, kvWritesMillions - 1) * 5;
69
+ const kvStorageOverage = Math.max(0, storageGb - 1) * 0.5;
70
+ cfKvOrDoUsd = roundUsd(kvReadOverage + kvWriteOverage + kvStorageOverage);
71
+ }
72
+ const cloudflareMonthlyUsd = roundUsd(cfWorkersUsd + cfKvOrDoUsd);
73
+ const monthlySavingsUsd = roundUsd(denoDeployMonthlyUsd - cloudflareMonthlyUsd);
74
+ const annualSavingsUsd = roundUsd(monthlySavingsUsd * 12);
75
+ return {
76
+ usage: {
77
+ monthlyRequests: requests,
78
+ egressGb,
79
+ kvReadsMillions,
80
+ kvWritesMillions,
81
+ storageGb,
82
+ usesDurableObjectKv: input.usesDurableObjectKv
83
+ },
84
+ denoDeployMonthlyUsd,
85
+ cloudflareMonthlyUsd,
86
+ monthlySavingsUsd,
87
+ annualSavingsUsd,
88
+ breakdown: {
89
+ denoComputeAndRequestsUsd,
90
+ denoEgressAndKvUsd,
91
+ cfWorkersUsd,
92
+ cfKvOrDoUsd
93
+ },
94
+ assumptionsNote: "Comparison uses Deno Deploy Pro ($20/mo base) vs Cloudflare Workers Paid ($5/mo base, zero standard egress fees) with SQLite Durable Objects or Workers KV."
95
+ };
96
+ }
97
+
98
+ // ../core/src/deno-forms.ts
99
+ import ts2 from "typescript";
100
+ var hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
101
+ function resolveImportMapSpecifier(spec, map) {
102
+ if (hasOwn(map, spec)) return map[spec];
103
+ let best = null;
104
+ for (const key of Object.keys(map)) {
105
+ if (key.endsWith("/") && spec.startsWith(key) && (best === null || key.length > best.length)) {
106
+ best = key;
107
+ }
108
+ }
109
+ if (best !== null) return map[best] + spec.slice(best.length);
110
+ return spec;
111
+ }
112
+ var STD_HTTP_URL = /^https:\/\/deno\.land\/std(@[^/]+)?\/http\/(server|mod)\.ts$/;
113
+ function isStdHttpServerSpecifier(resolved) {
114
+ return STD_HTTP_URL.test(resolved) || /^jsr:@std\/http(@[^/]+)?(\/server)?$/.test(resolved);
115
+ }
116
+ function nativeDependency(spec) {
117
+ if (/^(jsr:@db\/|@jsr\/db__)/.test(spec)) {
118
+ return { name: "@db/sqlite", suggestion: "Use Cloudflare D1 (SQLite) instead." };
119
+ }
120
+ if (/^(npm:)?(better-sqlite3|sqlite3)(@[^/]*)?(\/.*)?$/.test(spec)) {
121
+ return { name: spec.replace(/^npm:/, "").replace(/@[^/]*$/, ""), suggestion: "Use Cloudflare D1 (SQLite) instead." };
122
+ }
123
+ if (/deno\.land\/x\/(sqlite3?|sqlite_native)(@|\/)/.test(spec)) {
124
+ return { name: "deno.land/x/sqlite", suggestion: "Use Cloudflare D1 (SQLite) instead." };
125
+ }
126
+ const tcp = /deno\.land\/x\/(postgres|mysql|mongo|redis)(@|\/)/.exec(spec);
127
+ if (tcp) {
128
+ return {
129
+ name: `deno.land/x/${tcp[1]}`,
130
+ suggestion: "It opens raw TCP sockets with Deno.connect. Use Cloudflare Hyperdrive or D1, or call the database over HTTP."
131
+ };
132
+ }
133
+ if (/^(jsr:@deno\/kv-oauth|@jsr\/deno__kv-oauth)/.test(spec)) {
134
+ return { name: "@deno/kv-oauth", suggestion: "It stores sessions in Deno KV and uses Deno-only APIs. Use Hono's OAuth middleware with D1 or a Durable Object." };
135
+ }
136
+ if (/^(npm:)?(sharp|canvas|bcrypt)(@[^/]*)?$/.test(spec)) {
137
+ return { name: spec.replace(/^npm:/, "").replace(/@[^/]*$/, ""), suggestion: "It is a native addon. Use Cloudflare Images or a pure JavaScript or WebAssembly alternative." };
138
+ }
139
+ return null;
140
+ }
141
+ function findStdServeBindings(sf, importMap) {
142
+ const out = { names: /* @__PURE__ */ new Map(), namespaces: /* @__PURE__ */ new Set(), decls: [] };
143
+ for (const stmt of sf.statements) {
144
+ if (!ts2.isImportDeclaration(stmt) || !ts2.isStringLiteral(stmt.moduleSpecifier)) continue;
145
+ const resolved = resolveImportMapSpecifier(stmt.moduleSpecifier.text, importMap);
146
+ if (!isStdHttpServerSpecifier(resolved)) continue;
147
+ const nb = stmt.importClause?.namedBindings;
148
+ if (!nb) continue;
149
+ let hit = false;
150
+ if (ts2.isNamedImports(nb)) {
151
+ for (const el of nb.elements) {
152
+ const imported = (el.propertyName ?? el.name).text;
153
+ if (imported === "serve" || imported === "listenAndServe") {
154
+ out.names.set(el.name.text, imported);
155
+ hit = true;
156
+ }
157
+ }
158
+ } else if (ts2.isNamespaceImport(nb)) {
159
+ out.namespaces.add(nb.name.text);
160
+ hit = true;
161
+ }
162
+ if (hit) out.decls.push(stmt);
163
+ }
164
+ return out;
165
+ }
166
+ function stdServeCallKind(call, std) {
167
+ const c = call.expression;
168
+ if (ts2.isIdentifier(c)) return std.names.get(c.text) ?? null;
169
+ if (ts2.isPropertyAccessExpression(c) && ts2.isIdentifier(c.expression) && std.namespaces.has(c.expression.text) && (c.name.text === "serve" || c.name.text === "listenAndServe")) {
170
+ return c.name.text;
171
+ }
172
+ return null;
173
+ }
174
+ function unwrapExpr(expr) {
175
+ let e = expr;
176
+ while (ts2.isParenthesizedExpression(e) || ts2.isAsExpression(e) || ts2.isSatisfiesExpression(e) || ts2.isNonNullExpression(e) || ts2.isTypeAssertionExpression(e)) {
177
+ e = e.expression;
178
+ }
179
+ return e;
180
+ }
181
+ function cronField(init, sf) {
182
+ if (!init) return "*";
183
+ const e = unwrapExpr(init);
184
+ if (ts2.isNumericLiteral(e)) return e.text;
185
+ if (!ts2.isObjectLiteralExpression(e)) return null;
186
+ let exact = null;
187
+ let start = null;
188
+ let end = null;
189
+ let every = null;
190
+ for (const p of e.properties) {
191
+ if (!ts2.isPropertyAssignment(p) || !ts2.isIdentifier(p.name)) return null;
192
+ const v = unwrapExpr(p.initializer);
193
+ switch (p.name.text) {
194
+ case "exact":
195
+ if (ts2.isNumericLiteral(v)) exact = v.text;
196
+ else if (ts2.isArrayLiteralExpression(v) && v.elements.every((x) => ts2.isNumericLiteral(x))) {
197
+ exact = v.elements.map((x) => x.text).join(",");
198
+ } else return null;
199
+ break;
200
+ case "start":
201
+ if (!ts2.isNumericLiteral(v)) return null;
202
+ start = v.text;
203
+ break;
204
+ case "end":
205
+ if (!ts2.isNumericLiteral(v)) return null;
206
+ end = v.text;
207
+ break;
208
+ case "every":
209
+ if (!ts2.isNumericLiteral(v)) return null;
210
+ every = v.text;
211
+ break;
212
+ default:
213
+ return null;
214
+ }
215
+ }
216
+ void sf;
217
+ if (exact !== null) return start || end || every ? null : exact;
218
+ if (start !== null || end !== null) {
219
+ if (start === null || end === null) return null;
220
+ return every ? `${start}-${end}/${every}` : `${start}-${end}`;
221
+ }
222
+ if (every !== null) return `*/${every}`;
223
+ return null;
224
+ }
225
+ function constStringInitializer(name, sf) {
226
+ for (const stmt of sf.statements) {
227
+ if (!ts2.isVariableStatement(stmt)) continue;
228
+ if ((stmt.declarationList.flags & ts2.NodeFlags.Const) === 0) continue;
229
+ for (const d of stmt.declarationList.declarations) {
230
+ if (ts2.isIdentifier(d.name) && d.name.text === name && d.initializer) return d.initializer;
231
+ }
232
+ }
233
+ return null;
234
+ }
235
+ function resolveStringExpr(expr, sf) {
236
+ if (!expr) return null;
237
+ const e = unwrapExpr(expr);
238
+ if (ts2.isStringLiteral(e) || ts2.isNoSubstitutionTemplateLiteral(e)) return e.text;
239
+ if (ts2.isIdentifier(e)) {
240
+ const init = constStringInitializer(e.text, sf);
241
+ if (init) {
242
+ const u = unwrapExpr(init);
243
+ if (ts2.isStringLiteral(u) || ts2.isNoSubstitutionTemplateLiteral(u)) return u.text;
244
+ }
245
+ }
246
+ return null;
247
+ }
248
+ function resolveCronSchedule(expr, sf) {
249
+ if (!expr) return { ok: false, reason: "no schedule argument" };
250
+ const str = resolveStringExpr(expr, sf);
251
+ if (str !== null) return { ok: true, schedule: str };
252
+ const e = unwrapExpr(expr);
253
+ if (ts2.isObjectLiteralExpression(e)) {
254
+ const fields = {};
255
+ for (const p of e.properties) {
256
+ if (!ts2.isPropertyAssignment(p) || !ts2.isIdentifier(p.name)) {
257
+ return { ok: false, reason: "the object schedule uses a form that is not a plain literal" };
258
+ }
259
+ fields[p.name.text] = p.initializer;
260
+ }
261
+ const allowed = /* @__PURE__ */ new Set(["minute", "hour", "dayOfMonth", "month", "dayOfWeek"]);
262
+ if (Object.keys(fields).some((k) => !allowed.has(k))) {
263
+ return { ok: false, reason: "the object schedule has an unknown field" };
264
+ }
265
+ const parts = [];
266
+ for (const k of ["minute", "hour", "dayOfMonth", "month", "dayOfWeek"]) {
267
+ const f = cronField(fields[k], sf);
268
+ if (f === null) return { ok: false, reason: `the object schedule field ${k} could not be converted exactly` };
269
+ parts.push(f);
270
+ }
271
+ return { ok: true, schedule: parts.join(" ") };
272
+ }
273
+ return { ok: false, reason: "the schedule is not a string literal, a constant or a plain object" };
274
+ }
275
+ function parseCronCall(call) {
276
+ const a = call.arguments;
277
+ if (a.length >= 4) return { name: a[0], schedule: a[1], options: a[2], handler: a[3] };
278
+ if (a.length === 3) return { name: a[0], schedule: a[1], options: void 0, handler: a[2] };
279
+ return { name: a[0], schedule: a[1], options: void 0, handler: void 0 };
280
+ }
281
+
282
+ // ../core/src/scanner.ts
283
+ var FS_METHODS = /* @__PURE__ */ new Set([
284
+ "readFile",
285
+ "readTextFile",
286
+ "writeFile",
287
+ "writeTextFile",
288
+ "readFileSync",
289
+ "readTextFileSync",
290
+ "writeFileSync",
291
+ "writeTextFileSync",
292
+ "readDir",
293
+ "readDirSync",
294
+ "open",
295
+ "openSync",
296
+ "stat",
297
+ "statSync",
298
+ "lstat",
299
+ "mkdir",
300
+ "mkdirSync",
301
+ "remove",
302
+ "removeSync",
303
+ "rename",
304
+ "makeTempFile",
305
+ "makeTempDir",
306
+ "copyFile"
307
+ ]);
308
+ var SUNSET_DATE = "2027-04";
309
+ var RUNTIME_MAINTENANCE_DATE = "2027-10";
310
+ var SUNSET_UTC_MS = Date.parse("2027-04-30T23:59:59.000Z");
311
+ function stripJsoncComments(input) {
312
+ let out = "";
313
+ let inString = false;
314
+ let escaped = false;
315
+ let inLineComment = false;
316
+ let inBlockComment = false;
317
+ for (let i = 0; i < input.length; i++) {
318
+ const ch = input[i];
319
+ const next = i + 1 < input.length ? input[i + 1] : "";
320
+ if (inLineComment) {
321
+ if (ch === "\n") {
322
+ inLineComment = false;
323
+ out += ch;
324
+ }
325
+ continue;
326
+ }
327
+ if (inBlockComment) {
328
+ if (ch === "*" && next === "/") {
329
+ inBlockComment = false;
330
+ i += 1;
331
+ } else if (ch === "\n") {
332
+ out += "\n";
333
+ }
334
+ continue;
335
+ }
336
+ if (inString) {
337
+ out += ch;
338
+ if (escaped) {
339
+ escaped = false;
340
+ } else if (ch === "\\") {
341
+ escaped = true;
342
+ } else if (ch === '"') {
343
+ inString = false;
344
+ }
345
+ continue;
346
+ }
347
+ if (ch === '"') {
348
+ inString = true;
349
+ out += ch;
350
+ continue;
351
+ }
352
+ if (ch === "/" && next === "/") {
353
+ inLineComment = true;
354
+ i += 1;
355
+ continue;
356
+ }
357
+ if (ch === "/" && next === "*") {
358
+ inBlockComment = true;
359
+ i += 1;
360
+ continue;
361
+ }
362
+ out += ch;
363
+ }
364
+ return out;
365
+ }
366
+ function parseDenoConfig(files) {
367
+ const merged = { imports: {}, tasks: {} };
368
+ const denoFile = files.find(
369
+ (f) => f.path === "deno.json" || f.path === "deno.jsonc"
370
+ );
371
+ if (denoFile) {
372
+ try {
373
+ const parsed = JSON.parse(stripJsoncComments(denoFile.content));
374
+ if (parsed.name) merged.name = parsed.name;
375
+ if (parsed.imports) merged.imports = { ...parsed.imports };
376
+ if (parsed.tasks) merged.tasks = { ...parsed.tasks };
377
+ if (parsed.compilerOptions && typeof parsed.compilerOptions === "object") merged.compilerOptions = { ...parsed.compilerOptions };
378
+ } catch {
379
+ }
380
+ }
381
+ const importMapFile = files.find((f) => f.path === "import_map.json");
382
+ if (importMapFile) {
383
+ try {
384
+ const parsed = JSON.parse(stripJsoncComments(importMapFile.content));
385
+ if (parsed.imports) {
386
+ merged.imports = { ...merged.imports, ...parsed.imports };
387
+ }
388
+ } catch {
389
+ }
390
+ }
391
+ return merged;
392
+ }
393
+ function getLineCol(sf, pos) {
394
+ const lc = sf.getLineAndCharacterOfPosition(pos);
395
+ return { line: lc.line + 1, column: lc.character + 1 };
396
+ }
397
+ function classifySpecifier(rawSpecifier, importMap) {
398
+ const mapped = resolveImportMapSpecifier(rawSpecifier, importMap);
399
+ if (mapped.startsWith("jsr:")) {
400
+ return { resolved: mapped, kind: "jsr" };
401
+ }
402
+ if (mapped.startsWith("npm:")) {
403
+ return { resolved: mapped, kind: "npm" };
404
+ }
405
+ if (mapped.startsWith("https://deno.land/x/")) {
406
+ return { resolved: mapped, kind: "deno_x" };
407
+ }
408
+ if (mapped.startsWith("https://deno.land/std")) {
409
+ return { resolved: mapped, kind: "std" };
410
+ }
411
+ if (mapped.startsWith("https://") || mapped.startsWith("http://")) {
412
+ return { resolved: mapped, kind: "https" };
413
+ }
414
+ if (mapped === "oak" || mapped === "@oak/oak") {
415
+ return { resolved: mapped, kind: "jsr" };
416
+ }
417
+ return null;
418
+ }
419
+ function isTsSourceFile(path) {
420
+ return /\.(ts|tsx|mts|js|jsx|mjs)$/i.test(path);
421
+ }
422
+ function detectStaticAssetsDir(files) {
423
+ const candidates = ["public", "static", "assets"];
424
+ for (const dir of candidates) {
425
+ const prefix = `${dir}/`;
426
+ if (files.some((f) => f.path.startsWith(prefix))) {
427
+ return `./${dir}`;
428
+ }
429
+ }
430
+ return null;
431
+ }
432
+ function isInsideFunctionLike(node) {
433
+ let curr = node.parent;
434
+ while (curr) {
435
+ if (ts3.isFunctionDeclaration(curr) || ts3.isFunctionExpression(curr) || ts3.isArrowFunction(curr) || ts3.isMethodDeclaration(curr)) {
436
+ return true;
437
+ }
438
+ curr = curr.parent;
439
+ }
440
+ return false;
441
+ }
442
+ function getRootIdentifierName(expr) {
443
+ if (ts3.isIdentifier(expr)) return expr.text;
444
+ if (ts3.isPropertyAccessExpression(expr)) return getRootIdentifierName(expr.expression);
445
+ if (ts3.isElementAccessExpression(expr)) return getRootIdentifierName(expr.expression);
446
+ return null;
447
+ }
448
+ var KV_ONLY_METHODS = /* @__PURE__ */ new Set(["atomic", "getMany", "enqueue", "listenQueue", "watch", "check", "sum", "min", "max", "commit"]);
449
+ function isKvSelectorArg(arg) {
450
+ if (!arg || !ts3.isObjectLiteralExpression(arg)) return false;
451
+ return arg.properties.some(
452
+ (p) => (ts3.isPropertyAssignment(p) || ts3.isShorthandPropertyAssignment(p)) && ts3.isIdentifier(p.name) && (p.name.text === "prefix" || p.name.text === "start" || p.name.text === "end")
453
+ );
454
+ }
455
+ function isDenoKvTypeNode(type) {
456
+ if (!type) return false;
457
+ if (ts3.isTypeReferenceNode(type)) {
458
+ if (ts3.isQualifiedName(type.typeName) && ts3.isIdentifier(type.typeName.left) && type.typeName.left.text === "Deno") {
459
+ return type.typeName.right.text === "Kv";
460
+ }
461
+ if (ts3.isIdentifier(type.typeName) && type.typeName.text === "Promise" && type.typeArguments?.[0]) {
462
+ return isDenoKvTypeNode(type.typeArguments[0]);
463
+ }
464
+ }
465
+ if (ts3.isUnionTypeNode(type)) return type.types.some(isDenoKvTypeNode);
466
+ return false;
467
+ }
468
+ function isOpenKvCallExpr(expr) {
469
+ let e = expr;
470
+ while (e && (ts3.isAwaitExpression(e) || ts3.isParenthesizedExpression(e) || ts3.isNonNullExpression(e) || ts3.isAsExpression(e))) e = e.expression;
471
+ if (!e) return false;
472
+ if (ts3.isBinaryExpression(e) && e.operatorToken.kind === ts3.SyntaxKind.QuestionQuestionEqualsToken) return isOpenKvCallExpr(e.right);
473
+ if (ts3.isBinaryExpression(e) && e.operatorToken.kind === ts3.SyntaxKind.QuestionQuestionToken) return isOpenKvCallExpr(e.right);
474
+ return ts3.isCallExpression(e) && ts3.isPropertyAccessExpression(e.expression) && ts3.isIdentifier(e.expression.expression) && e.expression.expression.text === "Deno" && e.expression.name.text === "openKv";
475
+ }
476
+ function collectKvNames(files) {
477
+ const names = /* @__PURE__ */ new Set(["kv"]);
478
+ let projectUsesKv = false;
479
+ for (const f of files) {
480
+ if (!isTsSourceFile(f.path)) continue;
481
+ if (!/\bDeno\.(openKv|Kv\w*|AtomicOperation)\b/.test(f.content)) continue;
482
+ projectUsesKv = true;
483
+ const sf = parseSource(f.path, f.content);
484
+ const walk = (n) => {
485
+ if (ts3.isVariableDeclaration(n) && ts3.isIdentifier(n.name) && (isOpenKvCallExpr(n.initializer) || isDenoKvTypeNode(n.type))) {
486
+ names.add(n.name.text);
487
+ }
488
+ if ((ts3.isParameter(n) || ts3.isPropertyDeclaration(n) || ts3.isPropertySignature(n)) && ts3.isIdentifier(n.name) && isDenoKvTypeNode(n.type)) {
489
+ names.add(n.name.text);
490
+ }
491
+ if (ts3.isBinaryExpression(n) && (n.operatorToken.kind === ts3.SyntaxKind.EqualsToken || n.operatorToken.kind === ts3.SyntaxKind.QuestionQuestionEqualsToken) && isOpenKvCallExpr(n.right)) {
492
+ if (ts3.isIdentifier(n.left)) names.add(n.left.text);
493
+ else if (ts3.isPropertyAccessExpression(n.left)) names.add(n.left.name.text);
494
+ }
495
+ ts3.forEachChild(n, walk);
496
+ };
497
+ walk(sf);
498
+ }
499
+ return { names, projectUsesKv };
500
+ }
501
+ function isKvChainReceiver(expr, kv, kvVars) {
502
+ if (ts3.isNonNullExpression(expr) || ts3.isParenthesizedExpression(expr)) {
503
+ return isKvChainReceiver(expr.expression, kv, kvVars);
504
+ }
505
+ if (ts3.isIdentifier(expr)) {
506
+ return kvVars.has(expr.text) || kv.names.has(expr.text);
507
+ }
508
+ if (ts3.isPropertyAccessExpression(expr)) {
509
+ return kv.names.has(expr.name.text);
510
+ }
511
+ if (ts3.isCallExpression(expr) && ts3.isPropertyAccessExpression(expr.expression)) {
512
+ const method = expr.expression.name.text;
513
+ if (method === "atomic" || method === "check" || method === "set" || method === "delete" || method === "sum" || method === "min" || method === "max" || method === "mutate") {
514
+ return isKvChainReceiver(expr.expression.expression, kv, kvVars) || kv.projectUsesKv && method !== "set" && method !== "delete" && KV_ONLY_METHODS.has(method);
515
+ }
516
+ if (ts3.isIdentifier(expr.expression.expression) && expr.expression.expression.text === "Deno" && method === "openKv") {
517
+ return true;
518
+ }
519
+ }
520
+ return false;
521
+ }
522
+ var FRESH_UNSUPPORTED_MESSAGE = "Fresh projects are not supported by the automated migration yet. Contact us for a manual migration.";
523
+ function detectFreshProject(files, importMap) {
524
+ const genFile = files.find((f) => /(^|\/)fresh\.gen\.ts$/.test(f.path.split("\\").join("/")));
525
+ if (genFile) return genFile.path;
526
+ for (const [key, value] of Object.entries(importMap)) {
527
+ if (key.startsWith("$fresh") || /deno\.land\/x\/fresh|jsr:@fresh\/core|@fresh\/core/.test(value)) {
528
+ return "deno.json";
529
+ }
530
+ }
531
+ for (const f of files) {
532
+ if (!/\.(ts|tsx|js|jsx|mts|mjs)$/i.test(f.path)) continue;
533
+ if (/from\s+["'](\$fresh\/|jsr:@fresh\/core|https:\/\/deno\.land\/x\/fresh)/.test(f.content)) {
534
+ return f.path;
535
+ }
536
+ }
537
+ const norm = files.map((f) => f.path.split("\\").join("/"));
538
+ const hasRoutes = norm.some((p) => /(^|\/)routes\/.+\.(tsx|ts|jsx|js)$/.test(p));
539
+ const hasIslands = norm.some((p) => /(^|\/)islands\/.+\.(tsx|ts|jsx|js)$/.test(p));
540
+ if (hasRoutes && hasIslands) return norm.find((p) => /(^|\/)islands\//.test(p)) ?? "routes/";
541
+ return null;
542
+ }
543
+ function collectOakVars(files, importMap) {
544
+ const result = /* @__PURE__ */ new Map();
545
+ const exported = /* @__PURE__ */ new Set();
546
+ const parsed = [];
547
+ for (const f of files) {
548
+ if (!isTsSourceFile(f.path)) continue;
549
+ const sf = parseSource(f.path, f.content);
550
+ const ctorNames = /* @__PURE__ */ new Set();
551
+ for (const st of sf.statements) {
552
+ if (ts3.isImportDeclaration(st) && ts3.isStringLiteral(st.moduleSpecifier) && isOakSpecifier(st.moduleSpecifier.text, importMap)) {
553
+ const nb = st.importClause?.namedBindings;
554
+ if (nb && ts3.isNamedImports(nb)) {
555
+ for (const el of nb.elements) {
556
+ const orig = (el.propertyName ?? el.name).text;
557
+ if (orig === "Router" || orig === "Application") ctorNames.add(el.name.text);
558
+ }
559
+ }
560
+ }
561
+ }
562
+ parsed.push({ path: f.path, sf, oakNames: ctorNames });
563
+ if (ctorNames.size === 0) continue;
564
+ const vars = /* @__PURE__ */ new Set();
565
+ const rootIsCtor = (e) => {
566
+ let cur = e;
567
+ for (; ; ) {
568
+ if (ts3.isParenthesizedExpression(cur) || ts3.isAwaitExpression(cur) || ts3.isAsExpression(cur)) cur = cur.expression;
569
+ else if (ts3.isCallExpression(cur) && ts3.isPropertyAccessExpression(cur.expression)) cur = cur.expression.expression;
570
+ else break;
571
+ }
572
+ return ts3.isNewExpression(cur) && ts3.isIdentifier(cur.expression) && ctorNames.has(cur.expression.text);
573
+ };
574
+ const walk = (n) => {
575
+ if (ts3.isVariableDeclaration(n) && ts3.isIdentifier(n.name)) {
576
+ if (n.initializer && rootIsCtor(n.initializer)) vars.add(n.name.text);
577
+ else if (n.type && ts3.isTypeReferenceNode(n.type) && ts3.isIdentifier(n.type.typeName) && ctorNames.has(n.type.typeName.text)) vars.add(n.name.text);
578
+ }
579
+ if (ts3.isParameter(n) && ts3.isIdentifier(n.name) && n.type && ts3.isTypeReferenceNode(n.type) && ts3.isIdentifier(n.type.typeName) && ctorNames.has(n.type.typeName.text)) {
580
+ vars.add(n.name.text);
581
+ }
582
+ ts3.forEachChild(n, walk);
583
+ };
584
+ walk(sf);
585
+ result.set(f.path, vars);
586
+ for (const st of sf.statements) {
587
+ if (ts3.isVariableStatement(st) && st.modifiers?.some((m) => m.kind === ts3.SyntaxKind.ExportKeyword)) {
588
+ for (const d of st.declarationList.declarations) if (ts3.isIdentifier(d.name) && vars.has(d.name.text)) exported.add(d.name.text);
589
+ }
590
+ if (ts3.isExportDeclaration(st) && st.exportClause && ts3.isNamedExports(st.exportClause)) {
591
+ for (const el of st.exportClause.elements) if (vars.has((el.propertyName ?? el.name).text)) exported.add(el.name.text);
592
+ }
593
+ if (ts3.isExportAssignment(st) && ts3.isIdentifier(st.expression) && vars.has(st.expression.text)) exported.add("default");
594
+ }
595
+ }
596
+ for (const p of parsed) {
597
+ for (const st of p.sf.statements) {
598
+ if (!ts3.isImportDeclaration(st) || !st.importClause) continue;
599
+ const spec = st.moduleSpecifier;
600
+ if (!ts3.isStringLiteral(spec) || !(spec.text.startsWith(".") || importMap[spec.text]?.startsWith("./"))) continue;
601
+ const add = (n) => {
602
+ if (!result.has(p.path)) result.set(p.path, /* @__PURE__ */ new Set());
603
+ result.get(p.path).add(n);
604
+ };
605
+ if (st.importClause.name && exported.has("default")) add(st.importClause.name.text);
606
+ const nb = st.importClause.namedBindings;
607
+ if (nb && ts3.isNamedImports(nb)) {
608
+ for (const el of nb.elements) if (exported.has((el.propertyName ?? el.name).text)) add(el.name.text);
609
+ }
610
+ }
611
+ }
612
+ return result;
613
+ }
614
+ function isTrackedOakReceiver(recv, vars) {
615
+ let cur = recv;
616
+ for (; ; ) {
617
+ if (ts3.isParenthesizedExpression(cur)) cur = cur.expression;
618
+ else if (ts3.isCallExpression(cur) && ts3.isPropertyAccessExpression(cur.expression)) cur = cur.expression.expression;
619
+ else break;
620
+ }
621
+ if (ts3.isNewExpression(cur)) return ts3.isIdentifier(cur.expression) && /^(Router|Application)$/.test(cur.expression.text);
622
+ return ts3.isIdentifier(cur) && vars.has(cur.text);
623
+ }
624
+ function scanProject(files, options) {
625
+ const now = options?.now ?? /* @__PURE__ */ new Date();
626
+ const sourceLabel = options?.sourceLabel ?? "deno-project";
627
+ const denoConfig = parseDenoConfig(files);
628
+ const importMap = denoConfig.imports ?? {};
629
+ const findings = [];
630
+ const kvCallSites = [];
631
+ const detectedEnvVars = /* @__PURE__ */ new Set();
632
+ const detectedEntrypoints = /* @__PURE__ */ new Set();
633
+ const detectedCrons = [];
634
+ const detectedDependencies = [];
635
+ const seenDeps = /* @__PURE__ */ new Set();
636
+ let routeCount = 0;
637
+ let usesOak = false;
638
+ let findingSeq = 0;
639
+ const kvCounts = {
640
+ openKv: 0,
641
+ atomic: 0,
642
+ versionstamp: 0,
643
+ expireIn: 0,
644
+ kvU64: 0,
645
+ list: 0,
646
+ simpleReadWrite: 0
647
+ };
648
+ const addFinding = (item) => {
649
+ findingSeq += 1;
650
+ findings.push({ id: `f-${findingSeq}`, ...item });
651
+ };
652
+ const oakVarsByFile = collectOakVars(files, importMap);
653
+ const kvNames = collectKvNames(files);
654
+ let usesKvTypes = false;
655
+ for (const file of files) {
656
+ if (!isTsSourceFile(file.path)) continue;
657
+ const sf = parseSource(file.path, file.content);
658
+ const oakVars = oakVarsByFile.get(file.path) ?? /* @__PURE__ */ new Set();
659
+ const stdServe = findStdServeBindings(sf, importMap);
660
+ const kvVars = /* @__PURE__ */ new Set(["kv"]);
661
+ const mutableTopLevelKind = /* @__PURE__ */ new Map();
662
+ const flaggedLeaks = /* @__PURE__ */ new Set();
663
+ const nonKvContainers = /* @__PURE__ */ new Set();
664
+ let fileImportsOak = false;
665
+ for (const stmt of sf.statements) {
666
+ if (ts3.isImportDeclaration(stmt) && ts3.isStringLiteral(stmt.moduleSpecifier)) {
667
+ const spec = stmt.moduleSpecifier.text;
668
+ const classified = classifySpecifier(spec, importMap);
669
+ if (classified) {
670
+ const depKey = `${file.path}:${spec}`;
671
+ if (!seenDeps.has(depKey)) {
672
+ seenDeps.add(depKey);
673
+ detectedDependencies.push({
674
+ specifier: spec,
675
+ resolvedName: classified.resolved,
676
+ kind: classified.kind,
677
+ file: file.path
678
+ });
679
+ }
680
+ const lc = getLineCol(sf, stmt.getStart(sf));
681
+ const native = nativeDependency(classified.resolved);
682
+ if (native) {
683
+ addFinding({
684
+ file: file.path,
685
+ line: lc.line,
686
+ column: lc.column,
687
+ category: "native-dependency",
688
+ severity: "critical",
689
+ symbol: spec,
690
+ message: `${native.name} needs native code, FFI, raw TCP or Deno-only APIs, so it cannot run on Cloudflare Workers.`,
691
+ recommendation: native.suggestion,
692
+ autoMigratable: false
693
+ });
694
+ }
695
+ const isOakSpec = isOakSpecifier(spec, importMap) || classified.resolved.includes("oak") || spec === "oak" || spec === "@oak/oak";
696
+ if (isOakSpec) {
697
+ usesOak = true;
698
+ fileImportsOak = true;
699
+ addFinding({
700
+ file: file.path,
701
+ line: lc.line,
702
+ column: lc.column,
703
+ category: "oak",
704
+ severity: "warning",
705
+ symbol: spec,
706
+ message: `Oak framework import '${spec}' is not natively supported in Workers; auto-rewrites to Hono.`,
707
+ recommendation: "Convert Oak Application/Router and standard routes to Hono<{ Bindings: Env }>.",
708
+ autoMigratable: true
709
+ });
710
+ } else {
711
+ addFinding({
712
+ file: file.path,
713
+ line: lc.line,
714
+ column: lc.column,
715
+ category: "import",
716
+ severity: !isStdHttpServerSpecifier(classified.resolved) && (classified.kind === "https" || classified.kind === "deno_x" || classified.kind === "std") ? "warning" : "info",
717
+ symbol: spec,
718
+ message: `Deno dependency specifier '${spec}' (${classified.kind}) requires npm/package.json resolution.`,
719
+ recommendation: "Resolve specifier into package.json or replace with Web Standard / Node compat equivalent.",
720
+ autoMigratable: isStdHttpServerSpecifier(classified.resolved) || !(classified.kind === "https" || classified.kind === "deno_x" || classified.kind === "std")
721
+ });
722
+ }
723
+ }
724
+ }
725
+ if (ts3.isVariableStatement(stmt)) {
726
+ const flags = ts3.getCombinedNodeFlags(stmt.declarationList);
727
+ const isMutableBinding = Boolean(flags & ts3.NodeFlags.Let) || (stmt.declarationList.flags & ts3.NodeFlags.Const) === 0;
728
+ for (const decl of stmt.declarationList.declarations) {
729
+ if (!ts3.isIdentifier(decl.name)) continue;
730
+ const varName = decl.name.text;
731
+ if (kvNames.names.has(varName)) continue;
732
+ const lc = getLineCol(sf, decl.getStart(sf));
733
+ const init = decl.initializer;
734
+ if (init) {
735
+ if (ts3.isNewExpression(init) && ts3.isIdentifier(init.expression)) {
736
+ const ctor = init.expression.text;
737
+ if (ctor === "Map" || ctor === "Set") {
738
+ mutableTopLevelKind.set(varName, { kind: `new ${ctor}()`, line: lc.line, column: lc.column });
739
+ nonKvContainers.add(varName);
740
+ }
741
+ } else if (ts3.isArrayLiteralExpression(init)) {
742
+ mutableTopLevelKind.set(varName, { kind: "top-level array", line: lc.line, column: lc.column });
743
+ } else if (isMutableBinding) {
744
+ mutableTopLevelKind.set(varName, { kind: "mutable let/var binding", line: lc.line, column: lc.column });
745
+ }
746
+ } else if (isMutableBinding) {
747
+ mutableTopLevelKind.set(varName, { kind: "mutable let/var binding", line: lc.line, column: lc.column });
748
+ }
749
+ }
750
+ }
751
+ }
752
+ const visit = (node) => {
753
+ if (ts3.isVariableDeclaration(node) && ts3.isIdentifier(node.name) && node.initializer) {
754
+ let initExpr = node.initializer;
755
+ if (ts3.isAwaitExpression(initExpr)) initExpr = initExpr.expression;
756
+ if (ts3.isCallExpression(initExpr) && ts3.isPropertyAccessExpression(initExpr.expression) && ts3.isIdentifier(initExpr.expression.expression) && initExpr.expression.expression.text === "Deno" && initExpr.expression.name.text === "openKv") {
757
+ kvVars.add(node.name.text);
758
+ }
759
+ if (ts3.isNewExpression(initExpr) && ts3.isIdentifier(initExpr.expression)) {
760
+ const cName = initExpr.expression.text;
761
+ if (cName === "Map" || cName === "Set") {
762
+ nonKvContainers.add(node.name.text);
763
+ }
764
+ }
765
+ }
766
+ if (fileImportsOak && (ts3.isFunctionDeclaration(node) || ts3.isFunctionExpression(node) || ts3.isArrowFunction(node)) && node.parameters.length === 2) {
767
+ const p1Type = node.parameters[0]?.type?.getText(sf) ?? "";
768
+ const p2Type = node.parameters[1]?.type?.getText(sf) ?? "";
769
+ const bodyText = node.body?.getText(sf) ?? "";
770
+ if (p1Type.includes("Context") && p2Type.includes("Next") || bodyText.includes("ctx.state") && bodyText.includes("next()")) {
771
+ const lc = getLineCol(sf, node.getStart(sf));
772
+ const fnName = ts3.isFunctionDeclaration(node) && node.name ? node.name.text : "middleware";
773
+ addFinding({
774
+ file: file.path,
775
+ line: lc.line,
776
+ column: lc.column,
777
+ category: "oak",
778
+ severity: "warning",
779
+ symbol: fnName,
780
+ message: `Custom Oak middleware '${fnName}' uses ctx.state or post-next() hooks that require manual verification.`,
781
+ recommendation: "Review generated TODO(redcenter-migrator) stub and map ctx.state to Hono c.set()/c.get().",
782
+ autoMigratable: false
783
+ });
784
+ }
785
+ }
786
+ if ((ts3.isBinaryExpression(node) || ts3.isCallExpression(node)) && isInsideFunctionLike(node)) {
787
+ if (ts3.isBinaryExpression(node) && node.operatorToken.kind >= ts3.SyntaxKind.FirstAssignment && node.operatorToken.kind <= ts3.SyntaxKind.LastAssignment) {
788
+ const root = getRootIdentifierName(node.left);
789
+ if (root && mutableTopLevelKind.has(root) && !flaggedLeaks.has(root)) {
790
+ flaggedLeaks.add(root);
791
+ const decl = mutableTopLevelKind.get(root);
792
+ addFinding({
793
+ file: file.path,
794
+ line: decl.line,
795
+ column: decl.column,
796
+ category: "isolate-leak",
797
+ severity: "warning",
798
+ symbol: root,
799
+ message: `Top-level mutable ${decl.kind} '${root}' is mutated inside a request handler and will not persist across Cloudflare Workers isolates.`,
800
+ recommendation: "Move shared mutable state to Durable Objects or Workers KV.",
801
+ autoMigratable: false
802
+ });
803
+ }
804
+ }
805
+ if (ts3.isCallExpression(node) && ts3.isPropertyAccessExpression(node.expression)) {
806
+ const method = node.expression.name.text;
807
+ const recv = node.expression.expression;
808
+ if (ts3.isIdentifier(recv) && mutableTopLevelKind.has(recv.text) && ["set", "add", "delete", "clear", "push", "pop", "shift", "unshift", "splice"].includes(method) && !flaggedLeaks.has(recv.text)) {
809
+ flaggedLeaks.add(recv.text);
810
+ const decl = mutableTopLevelKind.get(recv.text);
811
+ addFinding({
812
+ file: file.path,
813
+ line: decl.line,
814
+ column: decl.column,
815
+ category: "isolate-leak",
816
+ severity: "warning",
817
+ symbol: recv.text,
818
+ message: `Top-level mutable ${decl.kind} '${recv.text}' (${method}()) loses state between Cloudflare Workers isolates and risks cross-request leakage.`,
819
+ recommendation: "Replace in-memory cache/state with Durable Object storage or Cache API.",
820
+ autoMigratable: false
821
+ });
822
+ }
823
+ }
824
+ }
825
+ if (ts3.isQualifiedName(node) && ts3.isIdentifier(node.left) && node.left.text === "Deno" && (node.right.text.startsWith("Kv") || node.right.text === "AtomicOperation")) {
826
+ usesKvTypes = true;
827
+ }
828
+ if (ts3.isQualifiedName(node) && ts3.isIdentifier(node.left) && node.left.text === "Deno" && node.right.text === "KvU64") {
829
+ const lc = getLineCol(sf, node.getStart(sf));
830
+ kvCounts.kvU64 += 1;
831
+ kvCallSites.push({
832
+ file: file.path,
833
+ line: lc.line,
834
+ column: lc.column,
835
+ operation: "KvU64",
836
+ detail: "Deno.KvU64 type annotation"
837
+ });
838
+ }
839
+ if (ts3.isPropertyAccessExpression(node)) {
840
+ const objText = node.expression.getText(sf);
841
+ const prop = node.name.text;
842
+ const lc = getLineCol(sf, node.getStart(sf));
843
+ if (objText === "Deno" && prop === "KvU64") {
844
+ kvCounts.kvU64 += 1;
845
+ kvCallSites.push({
846
+ file: file.path,
847
+ line: lc.line,
848
+ column: lc.column,
849
+ operation: "KvU64",
850
+ detail: "Deno.KvU64 64-bit unsigned atomic counter type"
851
+ });
852
+ addFinding({
853
+ file: file.path,
854
+ line: lc.line,
855
+ column: lc.column,
856
+ category: "kv",
857
+ severity: "critical",
858
+ symbol: "Deno.KvU64",
859
+ message: "Deno.KvU64 requires atomic 64-bit counter semantics unavailable in Workers KV.",
860
+ recommendation: "Use SQLite Durable Object DenoKvU64 adapter.",
861
+ autoMigratable: true
862
+ });
863
+ } else if (prop === "versionstamp") {
864
+ kvCounts.versionstamp += 1;
865
+ kvCallSites.push({
866
+ file: file.path,
867
+ line: lc.line,
868
+ column: lc.column,
869
+ operation: "versionstamp",
870
+ detail: "Optimistic concurrency versionstamp read/check"
871
+ });
872
+ addFinding({
873
+ file: file.path,
874
+ line: lc.line,
875
+ column: lc.column,
876
+ category: "kv",
877
+ severity: "critical",
878
+ symbol: "versionstamp",
879
+ message: "KV versionstamp optimistic concurrency requires strongly consistent SQLite Durable Objects.",
880
+ recommendation: "Route KV reads and atomic checks through DenoKvDurableObject.",
881
+ autoMigratable: true
882
+ });
883
+ }
884
+ }
885
+ if ((ts3.isPropertyAssignment(node) || ts3.isShorthandPropertyAssignment(node)) && ts3.isIdentifier(node.name) && node.name.text === "expireIn") {
886
+ const lc = getLineCol(sf, node.getStart(sf));
887
+ kvCounts.expireIn += 1;
888
+ kvCallSites.push({
889
+ file: file.path,
890
+ line: lc.line,
891
+ column: lc.column,
892
+ operation: "expireIn",
893
+ detail: `TTL expiration option (${node.getText(sf)})`
894
+ });
895
+ addFinding({
896
+ file: file.path,
897
+ line: lc.line,
898
+ column: lc.column,
899
+ category: "kv",
900
+ severity: "warning",
901
+ symbol: "expireIn",
902
+ message: "Deno KV expireIn millisecond TTL maps to Durable Object SQLite expires_at + alarm() cleanup.",
903
+ recommendation: "Preserve exact millisecond TTL via DenoKvDurableObject alarms.",
904
+ autoMigratable: true
905
+ });
906
+ }
907
+ if (ts3.isCallExpression(node)) {
908
+ const lc = getLineCol(sf, node.getStart(sf));
909
+ if (stdServeCallKind(node, stdServe)) {
910
+ detectedEntrypoints.add(file.path);
911
+ addFinding({
912
+ file: file.path,
913
+ line: lc.line,
914
+ column: lc.column,
915
+ category: "entrypoint",
916
+ severity: "info",
917
+ symbol: "std http serve",
918
+ message: "std http serve() HTTP entrypoint converts to Cloudflare Worker fetch().",
919
+ recommendation: "Transform to export default { async fetch(request, env, ctx) }.",
920
+ autoMigratable: true
921
+ });
922
+ }
923
+ if (ts3.isPropertyAccessExpression(node.expression)) {
924
+ const recv = node.expression.expression;
925
+ const recvText = recv.getText(sf);
926
+ const method = node.expression.name.text;
927
+ if (recvText === "Deno") {
928
+ if (method === "serve") {
929
+ detectedEntrypoints.add(file.path);
930
+ addFinding({
931
+ file: file.path,
932
+ line: lc.line,
933
+ column: lc.column,
934
+ category: "entrypoint",
935
+ severity: "info",
936
+ symbol: "Deno.serve",
937
+ message: "Deno.serve HTTP entrypoint converts deterministically to Cloudflare Worker fetch().",
938
+ recommendation: "Transform to export default { async fetch(request, env, ctx) }.",
939
+ autoMigratable: true
940
+ });
941
+ } else if (method === "cron") {
942
+ const cronParts = parseCronCall(node);
943
+ const cronName = resolveStringExpr(cronParts.name, sf) ?? "unnamed-cron";
944
+ const sched = resolveCronSchedule(cronParts.schedule, sf);
945
+ if (sched.ok) {
946
+ detectedCrons.push({ name: cronName, schedule: sched.schedule, file: file.path, line: lc.line });
947
+ }
948
+ addFinding({
949
+ file: file.path,
950
+ line: lc.line,
951
+ column: lc.column,
952
+ category: "cron",
953
+ severity: sched.ok ? "info" : "warning",
954
+ symbol: `Deno.cron(${cronName})`,
955
+ message: sched.ok ? `Deno.cron '${cronName}' (${sched.schedule}) maps to wrangler.jsonc triggers.crons + scheduled().` : `Deno.cron '${cronName}' has a schedule that could not be resolved (${sched.reason}). No trigger is generated.`,
956
+ recommendation: sched.ok ? "Extract cron handler to Worker scheduled() entrypoint." : "Write the schedule as a cron string and add it to wrangler.jsonc triggers.crons by hand.",
957
+ autoMigratable: sched.ok
958
+ });
959
+ } else if (method === "openKv") {
960
+ kvCounts.openKv += 1;
961
+ kvCallSites.push({
962
+ file: file.path,
963
+ line: lc.line,
964
+ column: lc.column,
965
+ operation: "openKv",
966
+ detail: "Deno.openKv() database handle"
967
+ });
968
+ } else if (FS_METHODS.has(method)) {
969
+ addFinding({
970
+ file: file.path,
971
+ line: lc.line,
972
+ column: lc.column,
973
+ category: "filesystem",
974
+ severity: "warning",
975
+ symbol: `Deno.${method}`,
976
+ message: `Deno.${method}() accesses local disk which is unavailable inside Cloudflare Workers isolates.`,
977
+ recommendation: "Replace static asset reads with env.ASSETS.fetch() or dynamic blobs with R2.",
978
+ autoMigratable: false
979
+ });
980
+ }
981
+ } else if (recvText === "Deno.env" && method === "get") {
982
+ const firstArg = node.arguments[0];
983
+ if (firstArg && ts3.isStringLiteral(firstArg)) {
984
+ detectedEnvVars.add(firstArg.text);
985
+ addFinding({
986
+ file: file.path,
987
+ line: lc.line,
988
+ column: lc.column,
989
+ category: "env",
990
+ severity: "info",
991
+ symbol: `Deno.env.get("${firstArg.text}")`,
992
+ message: `Environment secret '${firstArg.text}' maps to Cloudflare env.${firstArg.text} and .dev.vars.`,
993
+ recommendation: "Bind via Env interface and set secrets via wrangler secret put.",
994
+ autoMigratable: true
995
+ });
996
+ }
997
+ } else if ((fileImportsOak || oakVars.size > 0) && ["get", "post", "put", "patch", "delete", "all", "options", "head"].includes(method) && isTrackedOakReceiver(recv, oakVars)) {
998
+ usesOak = true;
999
+ routeCount += 1;
1000
+ } else if ((fileImportsOak || oakVars.size > 0) && method === "listen" && isTrackedOakReceiver(recv, oakVars)) {
1001
+ detectedEntrypoints.add(file.path);
1002
+ } else if ((isKvChainReceiver(recv, kvNames, kvVars) || kvNames.projectUsesKv && (method === "atomic" && node.arguments.length === 0 || method === "getMany" || method === "list" && isKvSelectorArg(node.arguments[0]))) && !nonKvContainers.has(recvText)) {
1003
+ const kvOps = [
1004
+ "atomic",
1005
+ "check",
1006
+ "sum",
1007
+ "min",
1008
+ "max",
1009
+ "commit",
1010
+ "list",
1011
+ "get",
1012
+ "getMany",
1013
+ "set",
1014
+ "delete"
1015
+ ];
1016
+ if (kvOps.includes(method)) {
1017
+ const op = method;
1018
+ kvCallSites.push({
1019
+ file: file.path,
1020
+ line: lc.line,
1021
+ column: lc.column,
1022
+ operation: op,
1023
+ detail: `${recvText}.${op}()`
1024
+ });
1025
+ if (op === "atomic") {
1026
+ kvCounts.atomic += 1;
1027
+ addFinding({
1028
+ file: file.path,
1029
+ line: lc.line,
1030
+ column: lc.column,
1031
+ category: "kv",
1032
+ severity: "critical",
1033
+ symbol: `${recvText}.atomic()`,
1034
+ message: "kv.atomic() cannot run safely on eventually consistent Workers KV and causes race conditions.",
1035
+ recommendation: "Migrate to SQLite Durable Object DenoKvDurableObject synchronous transactionSync().",
1036
+ autoMigratable: true
1037
+ });
1038
+ } else if (op === "list") {
1039
+ kvCounts.list += 1;
1040
+ addFinding({
1041
+ file: file.path,
1042
+ line: lc.line,
1043
+ column: lc.column,
1044
+ category: "kv",
1045
+ severity: "warning",
1046
+ symbol: `${recvText}.list()`,
1047
+ message: "kv.list() requires FoundationDB tuple key ordering across types, which JSON-stringified KV keys break.",
1048
+ recommendation: "Use binary tuple key encoding in SQLite Durable Objects for exact range/prefix parity.",
1049
+ autoMigratable: true
1050
+ });
1051
+ } else if (op === "get" || op === "getMany" || op === "set" || op === "delete") {
1052
+ kvCounts.simpleReadWrite += 1;
1053
+ }
1054
+ }
1055
+ }
1056
+ }
1057
+ }
1058
+ if (!fileImportsOak && ts3.isBinaryExpression(node) && node.operatorToken.kind === ts3.SyntaxKind.EqualsEqualsEqualsToken && node.left.getText(sf).endsWith("pathname") && ts3.isStringLiteral(node.right)) {
1059
+ routeCount += 1;
1060
+ }
1061
+ ts3.forEachChild(node, visit);
1062
+ };
1063
+ visit(sf);
1064
+ }
1065
+ if (routeCount === 0 && detectedEntrypoints.size > 0) {
1066
+ routeCount = 1;
1067
+ }
1068
+ const usesKv = kvCounts.openKv > 0 || kvCounts.atomic > 0 || kvCounts.versionstamp > 0 || kvCounts.kvU64 > 0 || kvCounts.list > 0 || kvCounts.simpleReadWrite > 0 || usesKvTypes;
1069
+ const needsStrongConsistency = kvCounts.atomic > 0 || kvCounts.versionstamp > 0 || kvCounts.kvU64 > 0;
1070
+ const needsOrderingOrTtl = kvCounts.list > 0 || kvCounts.expireIn > 0;
1071
+ let riskLevel = "none";
1072
+ let recommendedTarget = "none";
1073
+ let kvSummary = "No Deno.openKv() usage detected. Stateless Worker deployment recommended.";
1074
+ if (usesKv) {
1075
+ if (needsStrongConsistency) {
1076
+ riskLevel = "critical";
1077
+ recommendedTarget = "durable_objects_sqlite";
1078
+ kvSummary = "Critical KV consistency requirements detected (atomic/versionstamp/KvU64). SQLite Durable Object adapter required to eliminate Workers KV race conditions.";
1079
+ } else if (needsOrderingOrTtl) {
1080
+ riskLevel = "medium";
1081
+ recommendedTarget = "durable_objects_sqlite";
1082
+ kvSummary = "Ordered prefix scans (kv.list) or millisecond TTL (expireIn) detected. SQLite Durable Object adapter recommended for exact tuple sort parity.";
1083
+ } else {
1084
+ riskLevel = "low";
1085
+ recommendedTarget = "durable_objects_sqlite";
1086
+ kvSummary = "Deno KV reads and writes detected. They run on the SQLite Durable Object adapter, which keeps Deno KV value types, strong consistency and versionstamps (Workers KV does not).";
1087
+ }
1088
+ }
1089
+ const kvAudit = {
1090
+ usesKv,
1091
+ riskLevel,
1092
+ recommendedTarget,
1093
+ summary: kvSummary,
1094
+ whyWorkersKvFails: "Cloudflare Workers KV is an eventually consistent global cache with up to 60 seconds of propagation lag and no compare-and-set versionstamp transactions, FoundationDB tuple prefix sorting, or atomic uint64 counters. Migrating kv.atomic().check(), versionstamp, or kv.list() onto Workers KV causes silent write races and double-booking bugs. SQLite-backed Durable Objects execute ctx.storage.sql inside single-threaded ACID transactions and preserve exact Deno KV tuple ordering.",
1095
+ counts: kvCounts,
1096
+ callSites: kvCallSites
1097
+ };
1098
+ const freshFile = detectFreshProject(files, importMap);
1099
+ if (freshFile) {
1100
+ addFinding({
1101
+ file: freshFile,
1102
+ line: 1,
1103
+ column: 1,
1104
+ category: "unsupported",
1105
+ severity: "critical",
1106
+ symbol: "Fresh",
1107
+ message: FRESH_UNSUPPORTED_MESSAGE,
1108
+ recommendation: "Contact us for a manual migration of this Fresh project.",
1109
+ autoMigratable: false
1110
+ });
1111
+ }
1112
+ let score = 98;
1113
+ for (const f of findings) {
1114
+ if (!f.autoMigratable) {
1115
+ if (f.category === "isolate-leak") score -= 10;
1116
+ else if (f.category === "filesystem") score -= 12;
1117
+ else if (f.category === "oak") score -= 7;
1118
+ else score -= 8;
1119
+ } else if (f.category === "kv" && f.severity === "critical") {
1120
+ score -= 4;
1121
+ } else if (f.category === "import" && f.severity === "warning") {
1122
+ score -= 5;
1123
+ }
1124
+ }
1125
+ if (usesOak) score -= 2;
1126
+ if (findings.some((f) => f.category === "native-dependency")) score = Math.min(score, 40);
1127
+ const readinessScore = freshFile ? 0 : Math.max(15, Math.min(98, score));
1128
+ const daysUntilSunset = Math.max(
1129
+ 0,
1130
+ Math.ceil((SUNSET_UTC_MS - now.getTime()) / (1e3 * 60 * 60 * 24))
1131
+ );
1132
+ const staticAssetsDir = detectStaticAssetsDir(files);
1133
+ const estimatedTier = recommendedTarget === "durable_objects_sqlite" || routeCount > 15 ? "pro" : "starter";
1134
+ const costEstimate = calculateCostComparison({
1135
+ monthlyRequests: usesKv ? 5e6 : 2e6,
1136
+ egressGb: staticAssetsDir ? 120 : 40,
1137
+ kvReadsMillions: usesKv ? 12 : 0,
1138
+ kvWritesMillions: usesKv ? 2.5 : 0,
1139
+ storageGb: usesKv ? 2 : 0.2,
1140
+ usesDurableObjectKv: recommendedTarget === "durable_objects_sqlite"
1141
+ });
1142
+ return {
1143
+ sourceLabel,
1144
+ scannedAt: now.toISOString(),
1145
+ sunsetDate: SUNSET_DATE,
1146
+ runtimeMaintenanceDate: RUNTIME_MAINTENANCE_DATE,
1147
+ daysUntilSunset,
1148
+ readinessScore,
1149
+ estimatedTier,
1150
+ routeCount,
1151
+ detectedEntrypoints: [...detectedEntrypoints],
1152
+ detectedEnvVars: [...detectedEnvVars].sort(),
1153
+ detectedCrons,
1154
+ detectedDependencies,
1155
+ hasStaticAssets: staticAssetsDir !== null,
1156
+ staticAssetsDir,
1157
+ kvAudit,
1158
+ findings,
1159
+ costEstimate,
1160
+ unconvertedCount: 0,
1161
+ unconvertedItems: [],
1162
+ unsupportedFramework: freshFile ? "fresh" : null
1163
+ };
1164
+ }
1165
+
1166
+ // ../core/src/partition.ts
1167
+ import ts4 from "typescript";
1168
+ function normPath(p) {
1169
+ return p.split("\\").join("/");
1170
+ }
1171
+ function joinPosix(dir, rel) {
1172
+ const parts = (dir === "" ? [] : dir.split("/")).concat(rel.split("/"));
1173
+ const out = [];
1174
+ for (const part of parts) {
1175
+ if (part === "" || part === ".") continue;
1176
+ if (part === "..") {
1177
+ if (out.length === 0) return null;
1178
+ out.pop();
1179
+ } else out.push(part);
1180
+ }
1181
+ return out.join("/");
1182
+ }
1183
+ function resolveLocalImport(from, spec, importMap, paths) {
1184
+ const mapped = resolveImportMapSpecifier(spec, importMap);
1185
+ let rel;
1186
+ if (mapped.startsWith("./") || mapped.startsWith("../")) {
1187
+ const viaMap = mapped !== spec;
1188
+ const dir = viaMap ? "" : from.includes("/") ? from.slice(0, from.lastIndexOf("/")) : "";
1189
+ rel = joinPosix(dir, mapped);
1190
+ } else if (mapped.startsWith("/")) {
1191
+ rel = joinPosix("", mapped);
1192
+ } else {
1193
+ return null;
1194
+ }
1195
+ if (rel === null) return null;
1196
+ for (const cand of [
1197
+ rel,
1198
+ rel.replace(/\.js$/, ".ts"),
1199
+ rel.replace(/\.js$/, ".tsx"),
1200
+ `${rel}.ts`,
1201
+ `${rel}/mod.ts`,
1202
+ `${rel}/index.ts`
1203
+ ]) {
1204
+ if (paths.has(cand)) return cand;
1205
+ }
1206
+ return null;
1207
+ }
1208
+ var EDITOR_DIR = /(^|\/)(\.vscode|\.idea|\.github|\.devcontainer|\.gitlab)\//;
1209
+ var TEST_NAME = /(^|\/)[^/]*(_test|\.test|_bench|\.bench)\.(ts|tsx|mts|js|jsx|mjs)$/;
1210
+ var TOOLING_DIR = /(^|\/)(tests?|__tests__|bench|benchmarks|tools|scripts)\//;
1211
+ var TOOLING_NAME = /(^|\/)scripts\.config\.(ts|js|mjs)$/;
1212
+ var CODE_FILE = /\.(ts|tsx|mts|js|jsx|mjs)$/i;
1213
+ function partitionProject(files) {
1214
+ const excluded = [];
1215
+ const candidates = /* @__PURE__ */ new Map();
1216
+ const keptNow = [];
1217
+ for (const f of files) {
1218
+ const p = normPath(f.path);
1219
+ if (EDITOR_DIR.test(p)) {
1220
+ excluded.push({ path: f.path, reason: "editor or CI settings" });
1221
+ continue;
1222
+ }
1223
+ if (CODE_FILE.test(p)) {
1224
+ if (TEST_NAME.test(p) || /\bDeno\.(test|bench)\s*\(/.test(f.content)) {
1225
+ candidates.set(p, "Deno test or benchmark");
1226
+ continue;
1227
+ }
1228
+ if (TOOLING_DIR.test(p) || TOOLING_NAME.test(p)) {
1229
+ candidates.set(p, "tooling script or test helper");
1230
+ continue;
1231
+ }
1232
+ }
1233
+ keptNow.push(f);
1234
+ }
1235
+ if (candidates.size > 0) {
1236
+ const codeFiles = files.filter((f) => CODE_FILE.test(f.path) && !EDITOR_DIR.test(normPath(f.path)));
1237
+ const importMap = parseDenoConfig(files).imports ?? {};
1238
+ const paths = new Set(codeFiles.map((f) => normPath(f.path)));
1239
+ const edges = /* @__PURE__ */ new Map();
1240
+ for (const f of codeFiles) {
1241
+ const from = normPath(f.path);
1242
+ const deps = /* @__PURE__ */ new Set();
1243
+ const sf = parseSource(f.path, f.content);
1244
+ for (const st of sf.statements) {
1245
+ if ((ts4.isImportDeclaration(st) || ts4.isExportDeclaration(st)) && st.moduleSpecifier && ts4.isStringLiteral(st.moduleSpecifier)) {
1246
+ const target = resolveLocalImport(from, st.moduleSpecifier.text, importMap, paths);
1247
+ if (target && target !== from) deps.add(target);
1248
+ }
1249
+ }
1250
+ edges.set(from, deps);
1251
+ }
1252
+ const rescued = /* @__PURE__ */ new Set();
1253
+ const queue = keptNow.filter((f) => CODE_FILE.test(f.path)).map((f) => normPath(f.path));
1254
+ while (queue.length > 0) {
1255
+ const cur = queue.pop();
1256
+ for (const dep of edges.get(cur) ?? []) {
1257
+ if (candidates.has(dep) && !rescued.has(dep)) {
1258
+ rescued.add(dep);
1259
+ queue.push(dep);
1260
+ }
1261
+ }
1262
+ }
1263
+ const byNorm = new Map(files.map((f) => [normPath(f.path), f]));
1264
+ for (const [p, reason] of candidates) {
1265
+ if (rescued.has(p)) keptNow.push(byNorm.get(p));
1266
+ else excluded.push({ path: byNorm.get(p).path, reason });
1267
+ }
1268
+ }
1269
+ const order = new Map(files.map((f, i) => [f.path, i]));
1270
+ keptNow.sort((a, b) => order.get(a.path) - order.get(b.path));
1271
+ return { kept: keptNow, excluded };
1272
+ }
1273
+
1274
+ // src/index.ts
1275
+ var IGNORED_DIRS = /* @__PURE__ */ new Set([
1276
+ "node_modules",
1277
+ ".git",
1278
+ "dist",
1279
+ ".wrangler",
1280
+ ".deno",
1281
+ "coverage"
1282
+ ]);
1283
+ var INCLUDE_EXT = /\.(ts|tsx|mts|cts|js|jsx|mjs|cjs|json|jsonc|html|css|svg)$/i;
1284
+ function collectDirectoryFiles(rootDir) {
1285
+ const absRoot = resolve(rootDir);
1286
+ const files = [];
1287
+ const walk = (dir) => {
1288
+ let entries;
1289
+ try {
1290
+ entries = readdirSync(dir);
1291
+ } catch {
1292
+ return;
1293
+ }
1294
+ for (const entry of entries) {
1295
+ if (IGNORED_DIRS.has(entry)) continue;
1296
+ const full = join(dir, entry);
1297
+ try {
1298
+ const stat = statSync(full);
1299
+ if (stat.isDirectory()) {
1300
+ walk(full);
1301
+ } else if (stat.size <= 2 * 1024 * 1024 && INCLUDE_EXT.test(entry)) {
1302
+ files.push({
1303
+ path: relative(absRoot, full).split(sep).join("/"),
1304
+ content: readFileSync(full, "utf8")
1305
+ });
1306
+ }
1307
+ } catch {
1308
+ }
1309
+ }
1310
+ };
1311
+ walk(absRoot);
1312
+ return files;
1313
+ }
1314
+ function scanDirectoryWithExcluded(targetDir) {
1315
+ const absRoot = resolve(targetDir);
1316
+ const files = collectDirectoryFiles(absRoot);
1317
+ const { kept, excluded } = partitionProject(files);
1318
+ return {
1319
+ report: scanProject(kept, { sourceLabel: basename(absRoot) }),
1320
+ excludedFiles: excluded
1321
+ };
1322
+ }
1323
+ function formatExcludedFiles(excludedFiles) {
1324
+ const lines = [`NOT PART OF THE WORKER (${excludedFiles.length}):`];
1325
+ if (excludedFiles.length === 0) {
1326
+ lines.push(" No files were left out.");
1327
+ } else {
1328
+ lines.push(" These files are not copied into the generated project, and nothing imports them:");
1329
+ for (const f of excludedFiles) lines.push(` ${f.path} (${f.reason})`);
1330
+ }
1331
+ lines.push("");
1332
+ return lines;
1333
+ }
1334
+ function padRight(value, width) {
1335
+ if (value.length >= width) return value.slice(0, width - 1) + " ";
1336
+ return value + " ".repeat(width - value.length);
1337
+ }
1338
+ function formatAuditReport(report, excludedFiles) {
1339
+ const lines = [];
1340
+ const hr = "------------------------------------------------------------------------";
1341
+ lines.push("RED CENTER STUDIO: DENO DEPLOY & DENO.OPENKV() MIGRATION AUDIT");
1342
+ lines.push(hr);
1343
+ lines.push(`Project : ${report.sourceLabel}`);
1344
+ lines.push("Deno Deploy : scheduled to sunset in April 2027 (Deno gives the month only)");
1345
+ lines.push(`Readiness Score : ${report.readinessScore}/100 (static estimate, nothing was converted)`);
1346
+ lines.push(`Recommended Tier : ${report.estimatedTier.toUpperCase()} (${report.routeCount} detected routes)`);
1347
+ lines.push(`KV Risk Level : ${report.kvAudit.riskLevel.toUpperCase()} -> Target: ${report.kvAudit.recommendedTarget}`);
1348
+ lines.push(hr);
1349
+ lines.push("KV & CONSISTENCY AUDIT:");
1350
+ lines.push(
1351
+ ` openKv=${report.kvAudit.counts.openKv} atomic=${report.kvAudit.counts.atomic} versionstamp=${report.kvAudit.counts.versionstamp} expireIn=${report.kvAudit.counts.expireIn} KvU64=${report.kvAudit.counts.kvU64} list=${report.kvAudit.counts.list}`
1352
+ );
1353
+ lines.push(` ${report.kvAudit.summary}`);
1354
+ if (report.kvAudit.recommendedTarget === "durable_objects_sqlite") {
1355
+ lines.push(" NOTE: Standard Workers KV is eventually consistent; SQLite Durable Objects are required.");
1356
+ }
1357
+ lines.push("");
1358
+ lines.push(`LINE-BY-LINE FINDINGS (${report.findings.length}):`);
1359
+ if (report.findings.length === 0) {
1360
+ lines.push(" No migration issues detected.");
1361
+ } else {
1362
+ lines.push(
1363
+ ` ${padRight("SEVERITY", 10)}${padRight("LOCATION", 26)}${padRight("SYMBOL", 24)}AUTO`
1364
+ );
1365
+ for (const f of report.findings) {
1366
+ const loc = `${f.file}:${f.line}:${f.column}`;
1367
+ lines.push(
1368
+ ` ${padRight(f.severity.toUpperCase(), 10)}${padRight(loc, 26)}${padRight(f.symbol, 24)}${f.autoMigratable ? "YES" : "REVIEW"}`
1369
+ );
1370
+ lines.push(` -> ${f.message}`);
1371
+ }
1372
+ }
1373
+ lines.push("");
1374
+ if (excludedFiles) lines.push(...formatExcludedFiles(excludedFiles));
1375
+ lines.push("ESTIMATED MONTHLY INFRASTRUCTURE COST:");
1376
+ lines.push(
1377
+ ` Deno Deploy Pro : $${report.costEstimate.denoDeployMonthlyUsd.toFixed(2)}/mo`
1378
+ );
1379
+ lines.push(
1380
+ ` Cloudflare Stack: $${report.costEstimate.cloudflareMonthlyUsd.toFixed(2)}/mo (Est. savings: $${report.costEstimate.monthlySavingsUsd.toFixed(2)}/mo)`
1381
+ );
1382
+ lines.push(hr);
1383
+ lines.push("This is a local static scan. Your code never leaves this machine.");
1384
+ lines.push("The score is an estimate: no conversion is run and no build is checked.");
1385
+ lines.push("For a free diff preview and the paid migration (code conversion, KV on Durable Objects, GitHub PR):");
1386
+ lines.push(" https://deno.redcenterstudio.com");
1387
+ return lines.join("\n");
1388
+ }
1389
+
1390
+ // src/bin.ts
1391
+ function main() {
1392
+ const args = process.argv.slice(2);
1393
+ let targetPath = ".";
1394
+ let jsonMode = false;
1395
+ for (const arg of args) {
1396
+ if (arg === "--json") {
1397
+ jsonMode = true;
1398
+ } else if (arg === "--help" || arg === "-h") {
1399
+ console.log("Usage: deno-audit [directory] [--json]");
1400
+ console.log("Local static readiness scan for Deno Deploy projects moving to Cloudflare Workers.");
1401
+ console.log("More: https://deno.redcenterstudio.com");
1402
+ process.exit(0);
1403
+ } else if (!arg.startsWith("-")) {
1404
+ targetPath = arg;
1405
+ }
1406
+ }
1407
+ const absTarget = resolve2(targetPath);
1408
+ if (!existsSync(absTarget)) {
1409
+ console.error(`Target path does not exist: ${absTarget}`);
1410
+ process.exit(1);
1411
+ }
1412
+ const { report, excludedFiles } = scanDirectoryWithExcluded(absTarget);
1413
+ if (jsonMode) {
1414
+ console.log(JSON.stringify({ ...report, excludedFiles, scoreIsStaticEstimate: true }, null, 2));
1415
+ } else {
1416
+ console.log(formatAuditReport(report, excludedFiles));
1417
+ }
1418
+ }
1419
+ main();