check-work-order-migration.mjs
14.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
import { access, readFile, readdir, stat } from 'node:fs/promises'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const scriptDir = path.dirname(fileURLToPath(import.meta.url))
const defaultProjectRoot = path.resolve(scriptDir, '..')
const ENTRY_FILES = [
'pages/tab/workspace/workspace.js',
'pages/tab/workspace/workspace.json',
'pages/tab/workspace/workspace.wxml',
'pages/tab/workspace/workspace.sass',
'pages/tabWorkOrder/pages/index/index.js',
'pages/tabWorkOrder/pages/index/index.json',
'pages/tabWorkOrder/pages/index/index.wxml',
'pages/tabWorkOrder/pages/index/index.sass',
'tabWorkOrder/pages/index/index.js',
'tabWorkOrder/pages/index/index.json',
'tabWorkOrder/pages/index/index.wxml',
'tabWorkOrder/pages/index/index.sass',
'tabWorkOrder/pages/createOrder/createOrder.js',
'tabWorkOrder/pages/createOrder/createOrder.json',
'tabWorkOrder/pages/createOrder/createOrder.wxml',
'tabWorkOrder/pages/createOrder/createOrder.sass',
'tabWorkOrder/pages/confirmOrder/confirmOrder.js',
'tabWorkOrder/pages/confirmOrder/confirmOrder.json',
'tabWorkOrder/pages/confirmOrder/confirmOrder.wxml',
'tabWorkOrder/pages/confirmOrder/confirmOrder.wxss',
'tabWorkOrder/pages/orderDetail/orderDetail.js',
'tabWorkOrder/pages/orderDetail/orderDetail.json',
'tabWorkOrder/pages/orderDetail/orderDetail.wxml',
'tabWorkOrder/pages/orderDetail/orderDetail.sass',
'tabWorkOrder/pages/ocr/ocr.js',
'tabWorkOrder/pages/ocr/ocr.json',
'tabWorkOrder/pages/ocr/ocr.wxml',
'tabWorkOrder/pages/ocr/ocr.wxss'
]
const SCRIPT_EXTENSIONS = ['.js', '.mjs', '.wxs']
const STYLE_EXTENSIONS = ['.sass', '.scss', '.wxss', '.css']
const RESOLVABLE_EXTENSIONS = [
'.js',
'.mjs',
'.json',
'.wxs',
'.wxml',
'.sass',
'.scss',
'.wxss',
'.css'
]
const IMAGE_EXTENSION_PATTERN = /\.(?:png|jpe?g|gif|svg|webp)$/i
const FORBIDDEN_ROUTE_PATTERN =
/(?:tabWorkOrder\.)?(?:constructionOrderDetail|defeatOrder|orderSignature|updateOrderInfo|invoiceResult|invoiceCode|createAConstructionOrder)|tabDate\.userPortrait/
function toPosix(value) {
return value.split(path.sep).join('/')
}
async function exists(filePath) {
try {
await access(filePath)
return true
} catch {
return false
}
}
function isExternalSpecifier(specifier) {
return (
!specifier ||
specifier.startsWith('@') ||
(!specifier.startsWith('.') &&
!specifier.startsWith('/') &&
!specifier.startsWith('~/'))
)
}
function resolveBase(projectRoot, fromFile, specifier) {
if (specifier.startsWith('~/')) {
return path.join(projectRoot, specifier.slice(2))
}
if (specifier.startsWith('/')) {
return path.join(projectRoot, specifier.slice(1))
}
return path.resolve(path.dirname(fromFile), specifier)
}
async function resolveScriptDependency(projectRoot, fromFile, specifier) {
if (isExternalSpecifier(specifier)) return null
const base = resolveBase(projectRoot, fromFile, specifier)
const extension = path.extname(base)
const hasResolvableExtension = RESOLVABLE_EXTENSIONS.includes(
extension.toLowerCase()
)
const candidates = hasResolvableExtension
? [base]
: [
base,
...RESOLVABLE_EXTENSIONS.map(item => base + item),
path.join(base, 'index.js'),
path.join(base, 'index.wxs')
]
for (const candidate of candidates) {
if (await exists(candidate)) return candidate
}
return base
}
async function componentFiles(projectRoot, fromFile, specifier) {
if (isExternalSpecifier(specifier)) return { files: [], missing: [] }
const base = resolveBase(projectRoot, fromFile, specifier)
const required = [base + '.js', base + '.json', base + '.wxml']
const styleCandidates = STYLE_EXTENSIONS.map(extension => base + extension)
const files = []
const missing = []
for (const requiredFile of required) {
if (await exists(requiredFile)) files.push(requiredFile)
else missing.push(requiredFile)
}
const existingStyle = []
for (const candidate of styleCandidates) {
if (await exists(candidate)) existingStyle.push(candidate)
}
if (existingStyle.length) files.push(...existingStyle)
else missing.push(base + '.{sass|scss|wxss|css}')
return { files, missing }
}
function extractScriptSpecifiers(source) {
const specifiers = []
const patterns = [
/(?:import|export)\s+(?:[\s\S]*?\s+from\s+)?['"]([^'"]+)['"]/g,
/require\(\s*['"]([^'"]+)['"]\s*\)/g
]
for (const pattern of patterns) {
for (const match of source.matchAll(pattern)) specifiers.push(match[1])
}
return specifiers
}
function stripScriptComments(source) {
return source
.replace(/\/\*[\s\S]*?\*\//g, '')
.replace(/(^|[^:])\/\/.*$/gm, '$1')
}
function stripWxmlComments(source) {
return source.replace(/<!--[\s\S]*?-->/g, '')
}
function extractStaticImageSpecifiers(source) {
const results = []
for (const match of source.matchAll(
/['"]([^'"]+\.(?:png|jpe?g|gif|svg|webp))['"]/gi
)) {
const value = match[1]
if (
!value.includes('{{') &&
!value.startsWith('http://') &&
!value.startsWith('https://') &&
!value.startsWith('data:')
) {
results.push(value)
}
}
return results
}
function extractWxmlDependencies(source) {
const results = []
for (const match of source.matchAll(
/<(?:wxs|import|include)\b[^>]*\bsrc=['"]([^'"]+)['"]/g
)) {
results.push(match[1])
}
for (const match of source.matchAll(
/<image\b[^>]*\bsrc=['"]([^'"]+)['"]/g
)) {
const value = match[1]
if (!value.includes('{{')) results.push(value)
}
return results
}
function extractStyleDependencies(source) {
const results = []
for (const match of source.matchAll(
/@(?:import|use)\s+['"]([^'"]+)['"]/g
)) {
results.push(match[1])
}
for (const match of source.matchAll(/url\(\s*['"]?([^'")]+)['"]?\s*\)/g)) {
results.push(match[1])
}
return results
}
function shouldResolveAsset(value) {
return (
value &&
!value.includes('{{') &&
!value.startsWith('http://') &&
!value.startsWith('https://') &&
!value.startsWith('data:') &&
!value.startsWith('wxfile:')
)
}
async function resolveAsset(projectRoot, fromFile, specifier) {
if (!shouldResolveAsset(specifier)) return null
const base = resolveBase(projectRoot, fromFile, specifier)
if (await exists(base)) return base
if (path.extname(base).toLowerCase() === '.wxss') {
for (const extension of ['.sass', '.scss']) {
const preprocessorSource = base.slice(0, -5) + extension
if (await exists(preprocessorSource)) return preprocessorSource
}
}
if (!path.extname(base)) {
for (const extension of RESOLVABLE_EXTENSIONS) {
if (await exists(base + extension)) return base + extension
}
}
return base
}
function collectForbiddenRoutes(source, relativeFile) {
const routes = []
for (const match of source.matchAll(
/\$router\.(?:go|redirectTo|replace|reLaunch)\(\s*['"`]([^'"`]+)['"`]/g
)) {
if (FORBIDDEN_ROUTE_PATTERN.test(match[1])) {
routes.push({ file: relativeFile, route: match[1] })
}
}
for (const match of source.matchAll(
/wx\.(?:navigateTo|redirectTo|reLaunch)\(\s*\{[\s\S]{0,300}?url\s*:\s*['"`]([^'"`]+)['"`]/g
)) {
if (FORBIDDEN_ROUTE_PATTERN.test(match[1])) {
routes.push({ file: relativeFile, route: match[1] })
}
}
return routes
}
export async function auditWorkOrderMigration(
projectRoot = defaultProjectRoot
) {
const queue = ENTRY_FILES.map(relativePath =>
path.join(projectRoot, relativePath)
)
const visited = new Set()
const missing = new Map()
const deadRoutes = []
const addMissing = (fromFile, missingPath) => {
const relativeMissing = toPosix(path.relative(projectRoot, missingPath))
const relativeFrom = toPosix(path.relative(projectRoot, fromFile))
missing.set(
`${relativeFrom}:${relativeMissing}`,
`${relativeFrom} -> ${relativeMissing}`
)
}
while (queue.length) {
const currentFile = queue.shift()
const normalized = path.normalize(currentFile)
if (visited.has(normalized)) continue
visited.add(normalized)
if (!(await exists(normalized))) {
addMissing(normalized, normalized)
continue
}
const entry = await stat(normalized)
if (!entry.isFile()) continue
const extension = path.extname(normalized).toLowerCase()
const source = await readFile(normalized, 'utf8')
const relativeFile = toPosix(path.relative(projectRoot, normalized))
if (SCRIPT_EXTENSIONS.includes(extension)) {
const dependencySource = stripScriptComments(source)
deadRoutes.push(...collectForbiddenRoutes(dependencySource, relativeFile))
const dependencies = [
...(source.includes('function(require,module,exports)')
? []
: extractScriptSpecifiers(dependencySource)),
...extractStaticImageSpecifiers(dependencySource)
]
for (const specifier of dependencies) {
if (
isExternalSpecifier(specifier) &&
!IMAGE_EXTENSION_PATTERN.test(specifier)
) {
continue
}
const resolved = await resolveScriptDependency(
projectRoot,
normalized,
specifier
)
if (!resolved) continue
if (await exists(resolved)) queue.push(resolved)
else addMissing(normalized, resolved)
}
} else if (extension === '.json') {
let json
try {
json = JSON.parse(source)
} catch {
addMissing(normalized, normalized + ' (invalid JSON)')
continue
}
for (const componentPath of Object.values(json.usingComponents || {})) {
const result = await componentFiles(
projectRoot,
normalized,
componentPath
)
queue.push(...result.files)
for (const missingFile of result.missing) {
addMissing(normalized, missingFile)
}
}
} else if (extension === '.wxml') {
for (const specifier of extractWxmlDependencies(stripWxmlComments(source))) {
const resolved = await resolveAsset(projectRoot, normalized, specifier)
if (!resolved) continue
if (await exists(resolved)) queue.push(resolved)
else addMissing(normalized, resolved)
}
} else if (STYLE_EXTENSIONS.includes(extension)) {
for (const specifier of extractStyleDependencies(source)) {
const resolved = await resolveAsset(projectRoot, normalized, specifier)
if (!resolved) continue
if (await exists(resolved)) queue.push(resolved)
else addMissing(normalized, resolved)
}
}
}
return {
scannedFiles: visited.size,
missingDependencies: [...missing.values()].sort(),
deadRoutes: deadRoutes.sort((a, b) =>
`${a.file}:${a.route}`.localeCompare(`${b.file}:${b.route}`)
)
}
}
async function collectJavaScriptFiles(rootPath) {
if (!(await exists(rootPath))) return []
const entry = await stat(rootPath)
if (entry.isFile()) {
return SCRIPT_EXTENSIONS.includes(path.extname(rootPath).toLowerCase())
? [rootPath]
: []
}
const files = []
for (const child of await readdir(rootPath, { withFileTypes: true })) {
if (child.name === 'tests') continue
const childPath = path.join(rootPath, child.name)
if (child.isDirectory()) {
files.push(...(await collectJavaScriptFiles(childPath)))
} else if (
child.isFile() &&
SCRIPT_EXTENSIONS.includes(path.extname(child.name).toLowerCase())
) {
files.push(childPath)
}
}
return files
}
export async function auditCommonApiMethods(
projectRoot = defaultProjectRoot
) {
const apiSource = await readFile(path.join(projectRoot, 'api/api.js'), 'utf8')
const availableMethods = new Set(
[...apiSource.matchAll(/^\s+([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*\{/gm)].map(
match => match[1]
)
)
const scanRoots = [
'pages/tab/workspace',
'pages/tabWorkOrder',
'tabWorkOrder',
'tabIndex/components/recordingOrderPopup',
'components/CarBrands',
'components/CustomerInfo',
'components/DateSelect',
'components/Goods',
'components/InventoryInfo',
'components/Qrbox',
'components/RemarkPopup',
'components/SkuGoods',
'components/TechnicianSelectPopup',
'components/areaOperationsModal',
'components/orderPromptPop',
'components/tipsBottom',
'store/ModalToQueueControl.js'
]
const sourceFiles = (
await Promise.all(
scanRoots.map(relativePath =>
collectJavaScriptFiles(path.join(projectRoot, relativePath))
)
)
).flat()
const requiredMethods = new Map()
for (const sourceFile of sourceFiles) {
const source = stripScriptComments(await readFile(sourceFile, 'utf8'))
const relativeFile = toPosix(path.relative(projectRoot, sourceFile))
const defaultImports = [
...source.matchAll(
/import\s+([A-Za-z_$][\w$]*)\s+from\s+['"]~\/api\/api(?:\.js)?['"]/g
)
].map(match => match[1])
for (const localName of defaultImports) {
const usagePattern = new RegExp(
`\\b${localName}\\.([A-Za-z_$][\\w$]*)\\s*\\(`,
'g'
)
for (const usage of source.matchAll(usagePattern)) {
const methodName = usage[1]
const references = requiredMethods.get(methodName) || []
references.push(relativeFile)
requiredMethods.set(methodName, references)
}
}
for (const namedImport of source.matchAll(
/import\s*\{([\s\S]*?)\}\s*from\s*['"]~\/api\/api(?:\.js)?['"]/g
)) {
for (const part of namedImport[1].split(',')) {
const methodName = part.trim().split(/\s+as\s+/)[0]
if (!methodName) continue
const references = requiredMethods.get(methodName) || []
references.push(relativeFile)
requiredMethods.set(methodName, references)
}
}
}
const missingApiMethods = [...requiredMethods.entries()]
.filter(([methodName]) => !availableMethods.has(methodName))
.map(
([methodName, references]) =>
`${methodName} <- ${[...new Set(references)].sort().join(', ')}`
)
.sort()
return {
requiredApiMethods: [...requiredMethods.keys()].sort(),
missingApiMethods
}
}
async function runCli() {
const result = await auditWorkOrderMigration()
const apiResult = await auditCommonApiMethods()
if (
result.missingDependencies.length ||
result.deadRoutes.length ||
apiResult.missingApiMethods.length
) {
console.error(
JSON.stringify(
{
status: 'failed',
...result,
...apiResult
},
null,
2
)
)
process.exitCode = 1
return
}
console.log(
JSON.stringify(
{
status: 'ok',
...result,
...apiResult
},
null,
2
)
)
}
if (path.resolve(process.argv[1] || '') === fileURLToPath(import.meta.url)) {
await runCli()
}