@blazetrails/trails-tsc 0.0.0-stage → 0.1.0-alpha0.2
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/LICENSE +21 -0
- package/bin/trails-tsc-views.js +4 -0
- package/dist/build-autoload.d.ts +6 -0
- package/dist/build-autoload.js +432 -0
- package/dist/build-autoload.js.map +1 -0
- package/dist/build-templates.d.ts +3 -0
- package/dist/build-templates.js +86 -0
- package/dist/build-templates.js.map +1 -0
- package/dist/build-views.d.ts +15 -0
- package/dist/build-views.js +1080 -0
- package/dist/build-views.js.map +1 -0
- package/dist/build.d.ts +15 -0
- package/dist/build.js +63 -0
- package/dist/build.js.map +1 -0
- package/dist/cli.d.ts +4 -0
- package/dist/cli.js +128 -0
- package/dist/cli.js.map +1 -0
- package/dist/host.d.ts +11 -0
- package/dist/host.js +89 -0
- package/dist/host.js.map +1 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +13 -0
- package/dist/index.js.map +1 -0
- package/dist/lsp-plugin.d.ts +22 -0
- package/dist/lsp-plugin.js +119 -0
- package/dist/lsp-plugin.js.map +1 -0
- package/dist/plugin.d.ts +14 -0
- package/dist/plugin.js +2 -0
- package/dist/plugin.js.map +1 -0
- package/dist/plugins/tse-diagnose.d.ts +7 -0
- package/dist/plugins/tse-diagnose.js +58 -0
- package/dist/plugins/tse-diagnose.js.map +1 -0
- package/dist/plugins/tse.d.ts +39 -0
- package/dist/plugins/tse.js +612 -0
- package/dist/plugins/tse.js.map +1 -0
- package/dist/program.d.ts +14 -0
- package/dist/program.js +44 -0
- package/dist/program.js.map +1 -0
- package/dist/remap.d.ts +6 -0
- package/dist/remap.js +59 -0
- package/dist/remap.js.map +1 -0
- package/dist/watch-views.d.ts +15 -0
- package/dist/watch-views.js +93 -0
- package/dist/watch-views.js.map +1 -0
- package/package.json +51 -3
- package/README.md +0 -3
|
@@ -0,0 +1,1080 @@
|
|
|
1
|
+
import * as fs from "node:fs/promises";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import ts from "typescript-5";
|
|
4
|
+
import { Encoding, getPath, rbFLoad } from "@blazetrails/ruby-compat";
|
|
5
|
+
import { TopLevel, camelize, chomp, dasherize, pluralize, underscore, } from "@blazetrails/activesupport";
|
|
6
|
+
import { decodeLineMappings, generateSourceMap, parse, } from "@blazetrails/tse-compiler";
|
|
7
|
+
import { tseHandlerScope, tseLookupTransformer, virtualizeHandler, virtualizeTseWithDeltas, parseLocalsSignature, localsParamType, } from "./plugins/tse.js";
|
|
8
|
+
export async function buildViews(opts = {}) {
|
|
9
|
+
const cwd = opts.cwd ?? process.cwd();
|
|
10
|
+
const viewsDir = path.resolve(cwd, opts.viewsDir ?? "app/views");
|
|
11
|
+
const outDir = path.resolve(cwd, opts.outDir ?? ".trails");
|
|
12
|
+
const appViews = `${path.sep}app${path.sep}views${path.sep}`;
|
|
13
|
+
const viewsRoot = `${viewsDir}${path.sep}`;
|
|
14
|
+
const appViewsAt = viewsRoot.lastIndexOf(appViews);
|
|
15
|
+
const besideTemplates = opts.inPlace && appViewsAt === -1;
|
|
16
|
+
const outViews = besideTemplates
|
|
17
|
+
? viewsDir
|
|
18
|
+
: opts.inPlace
|
|
19
|
+
? path.join(viewsRoot.slice(0, appViewsAt), ".trails/views", viewsRoot.slice(appViewsAt + appViews.length))
|
|
20
|
+
: path.join(outDir, "views");
|
|
21
|
+
const { PathParser, Template, TseHandler, UnboundTemplate, WrongEncodingError } = await import("@blazetrails/actionview");
|
|
22
|
+
for (const ext of ["ts", "js"]) {
|
|
23
|
+
const application = path.join(cwd, `config/application.${ext}`);
|
|
24
|
+
if (await exists(application)) {
|
|
25
|
+
await import(getPath().pathToFileURL(application).href);
|
|
26
|
+
break;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const application = TopLevel.Trails?.application;
|
|
30
|
+
if (application && !application.initialized())
|
|
31
|
+
await application.initializeBang();
|
|
32
|
+
if (application && (await application.reloadRoutesUnlessLoaded()) === false) {
|
|
33
|
+
for (const ext of ["ts", "js"]) {
|
|
34
|
+
const routes = path.join(cwd, `config/routes.${ext}`);
|
|
35
|
+
if (await exists(routes)) {
|
|
36
|
+
await rbFLoad(routes);
|
|
37
|
+
break;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const pathParser = new PathParser();
|
|
42
|
+
const { files, skipped } = await walkTemplates(viewsDir, Template.templateHandlerExtensions());
|
|
43
|
+
if (!besideTemplates)
|
|
44
|
+
await clearOutViews(cwd, outDir, outViews);
|
|
45
|
+
const registryMap = new Map();
|
|
46
|
+
const appDir = path.dirname(viewsDir);
|
|
47
|
+
const helpers = await allHelpersFromPath(path.join(appDir, "helpers"));
|
|
48
|
+
const controllers = await allControllers(path.join(appDir, "controllers"));
|
|
49
|
+
const mailers = await allMailers(path.join(appDir, "mailers"));
|
|
50
|
+
const views = [];
|
|
51
|
+
const handled = [];
|
|
52
|
+
for (const rel of files) {
|
|
53
|
+
const source = await fs.readFile(path.join(viewsDir, rel), "utf8");
|
|
54
|
+
const outBase = path.join(outViews, rel);
|
|
55
|
+
const parsed = pathParser.parse(rel);
|
|
56
|
+
const template = new UnboundTemplate(source, path.join(viewsDir, rel), {
|
|
57
|
+
details: parsed.details,
|
|
58
|
+
virtualPath: parsed.path.virtual,
|
|
59
|
+
}).bindLocals([]);
|
|
60
|
+
await fs.mkdir(path.dirname(outBase), { recursive: true });
|
|
61
|
+
if (!(template.handler instanceof TseHandler)) {
|
|
62
|
+
const code = template.handler.call(template, source);
|
|
63
|
+
if (/\p{Surrogate}/u.test(code))
|
|
64
|
+
throw new WrongEncodingError(code, Encoding.defaultInternal);
|
|
65
|
+
const shim = { rel, src: source, outBase };
|
|
66
|
+
handled.push(shim);
|
|
67
|
+
await writeHandlerShim(shim, code, viewsDir);
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
const src = template.handler.stripTrailingNewlines ? chomp(source) : source;
|
|
71
|
+
const ast = parse(src);
|
|
72
|
+
views.push({
|
|
73
|
+
rel,
|
|
74
|
+
src,
|
|
75
|
+
outBase,
|
|
76
|
+
handlerScope: tseHandlerScope({
|
|
77
|
+
handler: template.handler,
|
|
78
|
+
format: template.format,
|
|
79
|
+
get type() {
|
|
80
|
+
return template.type;
|
|
81
|
+
},
|
|
82
|
+
get shortIdentifier() {
|
|
83
|
+
return template.shortIdentifier;
|
|
84
|
+
},
|
|
85
|
+
}),
|
|
86
|
+
strictLocals: ast.localsSignature !== null,
|
|
87
|
+
resolved: false,
|
|
88
|
+
...(await templateScope(appDir, rel, path.dirname(outBase), helpers, controllers, mailers)),
|
|
89
|
+
});
|
|
90
|
+
await writeShim(views[views.length - 1], viewsDir);
|
|
91
|
+
const registryKey = partialRegistryKey(rel);
|
|
92
|
+
if (registryKey !== null && ast.localsSignature !== null) {
|
|
93
|
+
const locals = parseLocalsSignature(ast.localsSignature);
|
|
94
|
+
const existing = registryMap.get(registryKey) ?? [];
|
|
95
|
+
registryMap.set(registryKey, [...existing, localsParamType(ast, locals)]);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const shimPaths = [...views, ...handled].map((v) => v.outBase + ".ts");
|
|
99
|
+
if (shimPaths.length > 0) {
|
|
100
|
+
const host = cachingHost();
|
|
101
|
+
const helperFiles = helpers.map((file) => path.join(appDir, "helpers", file));
|
|
102
|
+
const roots = [
|
|
103
|
+
...shimPaths,
|
|
104
|
+
...controllers.map((c) => c.file),
|
|
105
|
+
...mailers.classes.map((m) => m.file),
|
|
106
|
+
...helperFiles,
|
|
107
|
+
];
|
|
108
|
+
let program = ts.createProgram(roots, EMIT_OPTIONS, host);
|
|
109
|
+
for (let pass = 0; pass <= views.length && bindCheckedTypes(views, controllers, helperFiles, program); pass++) {
|
|
110
|
+
for (const view of views)
|
|
111
|
+
await writeShim(view, viewsDir);
|
|
112
|
+
program = ts.createProgram(roots, EMIT_OPTIONS, host, program);
|
|
113
|
+
}
|
|
114
|
+
emitViews(program, host, outViews);
|
|
115
|
+
for (const view of [...views, ...handled])
|
|
116
|
+
await chainSourceMap(view, viewsDir);
|
|
117
|
+
}
|
|
118
|
+
const registryEntries = Array.from(registryMap, ([key, types]) => ({
|
|
119
|
+
key,
|
|
120
|
+
localsType: types.length === 1 ? types[0] : types.map((t) => `(${t})`).join(" & "),
|
|
121
|
+
}));
|
|
122
|
+
if (opts.inPlace) {
|
|
123
|
+
for (const view of [...views, ...handled]) {
|
|
124
|
+
for (const ext of [".ts", ".ts.map", ".d.ts", ".d.ts.map"]) {
|
|
125
|
+
await fs.rm(view.outBase + ext, { force: true });
|
|
126
|
+
}
|
|
127
|
+
if (besideTemplates)
|
|
128
|
+
continue;
|
|
129
|
+
for (const ext of [".js", ".js.map"]) {
|
|
130
|
+
await fs.rm(path.join(viewsDir, view.rel) + ext, { force: true });
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return { count: files.length, files, skipped };
|
|
134
|
+
}
|
|
135
|
+
await fs.mkdir(outDir, { recursive: true });
|
|
136
|
+
await fs.writeFile(path.join(outDir, "template-registry-augmentation.d.ts"), emitRegistryAugmentation(registryEntries));
|
|
137
|
+
await fs.writeFile(path.join(outDir, "routes-augmentation.d.ts"), emitRoutesAugmentation(TopLevel.Trails?.application?.routes().namedRoutes.helperNames() ?? []));
|
|
138
|
+
return { count: files.length, files, skipped };
|
|
139
|
+
}
|
|
140
|
+
async function clearOutViews(cwd, outDir, outViews) {
|
|
141
|
+
const lexicalRel = path.relative(cwd, outViews);
|
|
142
|
+
if (lexicalRel === "" || lexicalRel.startsWith("..") || path.isAbsolute(lexicalRel)) {
|
|
143
|
+
throw new Error(`refusing to build into ${JSON.stringify(outViews)} — outDir must resolve under cwd ${JSON.stringify(cwd)}`);
|
|
144
|
+
}
|
|
145
|
+
const realCwd = await fs.realpath(cwd);
|
|
146
|
+
const realOutAncestor = await fs.realpath(await deepestExisting(outViews));
|
|
147
|
+
const realRel = path.relative(realCwd, realOutAncestor);
|
|
148
|
+
if (realRel !== "" && (realRel.startsWith("..") || path.isAbsolute(realRel))) {
|
|
149
|
+
throw new Error(`refusing to build into ${JSON.stringify(outViews)} — resolved path ${JSON.stringify(realOutAncestor)} is outside cwd ${JSON.stringify(realCwd)} (symlink escape)`);
|
|
150
|
+
}
|
|
151
|
+
await fs.rm(outViews, { recursive: true, force: true });
|
|
152
|
+
await fs.rm(path.join(outDir, "views-manifest.ts"), { force: true });
|
|
153
|
+
await fs.mkdir(outViews, { recursive: true });
|
|
154
|
+
}
|
|
155
|
+
async function exists(p) {
|
|
156
|
+
return (await fs.stat(p).catch(() => null)) !== null;
|
|
157
|
+
}
|
|
158
|
+
async function deepestExisting(p) {
|
|
159
|
+
let cur = path.resolve(p);
|
|
160
|
+
while (!(await exists(cur))) {
|
|
161
|
+
const parent = path.dirname(cur);
|
|
162
|
+
if (parent === cur)
|
|
163
|
+
return cur;
|
|
164
|
+
cur = parent;
|
|
165
|
+
}
|
|
166
|
+
return cur;
|
|
167
|
+
}
|
|
168
|
+
async function walkTemplates(dir, extensions) {
|
|
169
|
+
if (!(await exists(dir)))
|
|
170
|
+
return { files: [], skipped: [] };
|
|
171
|
+
const files = [];
|
|
172
|
+
const skipped = [];
|
|
173
|
+
const entries = await fs.readdir(dir, { recursive: true, withFileTypes: true });
|
|
174
|
+
for (const e of entries) {
|
|
175
|
+
if (!e.isFile())
|
|
176
|
+
continue;
|
|
177
|
+
const parent = e.parentPath ??
|
|
178
|
+
e.path ??
|
|
179
|
+
dir;
|
|
180
|
+
const rel = path.relative(dir, path.join(parent, e.name)).split(path.sep).join("/");
|
|
181
|
+
const dot = e.name.lastIndexOf(".");
|
|
182
|
+
if (dot !== -1 && extensions.includes(e.name.slice(dot + 1)))
|
|
183
|
+
files.push(rel);
|
|
184
|
+
else if (!e.name.startsWith(".") && !/\.(?:js|ts)(?:\.map)?$/u.test(e.name))
|
|
185
|
+
skipped.push(rel);
|
|
186
|
+
}
|
|
187
|
+
return { files: files.sort(), skipped: skipped.sort() };
|
|
188
|
+
}
|
|
189
|
+
async function allHelpersFromPath(helpersDir) {
|
|
190
|
+
if (!(await exists(helpersDir)))
|
|
191
|
+
return [];
|
|
192
|
+
const names = (await fs.readdir(helpersDir, { recursive: true, encoding: "utf8" }))
|
|
193
|
+
.map((file) => file.split(path.sep).join("/"))
|
|
194
|
+
.filter((file) => /[-_]helper\.ts$/u.test(file));
|
|
195
|
+
return names.sort();
|
|
196
|
+
}
|
|
197
|
+
async function allMailers(mailersDir) {
|
|
198
|
+
const mailers = { classes: [], paths: [], layouts: [] };
|
|
199
|
+
if (!(await exists(mailersDir)))
|
|
200
|
+
return mailers;
|
|
201
|
+
const classes = new Map();
|
|
202
|
+
const framework = new Set();
|
|
203
|
+
for (const file of await fs.readdir(mailersDir, { recursive: true, encoding: "utf8" })) {
|
|
204
|
+
if (!file.endsWith(".ts"))
|
|
205
|
+
continue;
|
|
206
|
+
const source = ts.createSourceFile(file, await fs.readFile(path.join(mailersDir, file), "utf8"), ts.ScriptTarget.Latest);
|
|
207
|
+
for (const statement of source.statements) {
|
|
208
|
+
if (ts.isImportDeclaration(statement) &&
|
|
209
|
+
ts.isStringLiteral(statement.moduleSpecifier) &&
|
|
210
|
+
statement.moduleSpecifier.text === "@blazetrails/actionmailer") {
|
|
211
|
+
const bindings = statement.importClause?.namedBindings;
|
|
212
|
+
if (bindings && ts.isNamedImports(bindings)) {
|
|
213
|
+
for (const e of bindings.elements) {
|
|
214
|
+
if ((e.propertyName ?? e.name).text === "Base")
|
|
215
|
+
framework.add(e.name.text);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
else if (bindings)
|
|
219
|
+
framework.add(`${bindings.name.text}.Base`);
|
|
220
|
+
}
|
|
221
|
+
if (!ts.isClassDeclaration(statement) || statement.name === undefined)
|
|
222
|
+
continue;
|
|
223
|
+
const superclass = statement.heritageClauses?.find((h) => h.token === ts.SyntaxKind.ExtendsKeyword)?.types[0]?.expression;
|
|
224
|
+
if (superclass === undefined)
|
|
225
|
+
continue;
|
|
226
|
+
const layouts = [];
|
|
227
|
+
const visit = (node) => {
|
|
228
|
+
if (ts.isCallExpression(node) &&
|
|
229
|
+
ts.isPropertyAccessExpression(node.expression) &&
|
|
230
|
+
node.expression.name.text === "layout" &&
|
|
231
|
+
node.arguments[0] !== undefined &&
|
|
232
|
+
ts.isStringLiteral(node.arguments[0])) {
|
|
233
|
+
layouts.push(node.arguments[0].text.replace(/^layouts\//u, ""));
|
|
234
|
+
}
|
|
235
|
+
ts.forEachChild(node, visit);
|
|
236
|
+
};
|
|
237
|
+
ts.forEachChild(statement, visit);
|
|
238
|
+
const dir = path.posix.dirname(file.split(path.sep).join("/"));
|
|
239
|
+
classes.set(statement.name.text, {
|
|
240
|
+
file: path.join(mailersDir, file),
|
|
241
|
+
dir,
|
|
242
|
+
superclass: superclass.getText(source),
|
|
243
|
+
layouts,
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
const isMailer = (name, seen = new Set()) => {
|
|
248
|
+
if (framework.has(name))
|
|
249
|
+
return true;
|
|
250
|
+
const klass = classes.get(name);
|
|
251
|
+
if (klass === undefined || seen.has(name))
|
|
252
|
+
return false;
|
|
253
|
+
seen.add(name);
|
|
254
|
+
return isMailer(klass.superclass, seen);
|
|
255
|
+
};
|
|
256
|
+
for (const [name, { file, dir, superclass, layouts }] of classes) {
|
|
257
|
+
if (!isMailer(superclass))
|
|
258
|
+
continue;
|
|
259
|
+
const mailerPath = dasherize(underscore(name));
|
|
260
|
+
const controllerPath = dir === "." ? mailerPath : `${dir}/${mailerPath}`;
|
|
261
|
+
mailers.classes.push({ file, name, path: controllerPath });
|
|
262
|
+
mailers.paths.push(controllerPath);
|
|
263
|
+
mailers.layouts.push(controllerPath);
|
|
264
|
+
mailers.layouts.push(...layouts);
|
|
265
|
+
}
|
|
266
|
+
return mailers;
|
|
267
|
+
}
|
|
268
|
+
function isMailerView(rel, layout, mailers) {
|
|
269
|
+
if (layout !== undefined)
|
|
270
|
+
return mailers.layouts.includes(layout);
|
|
271
|
+
return mailers.paths.includes(path.posix.dirname(rel));
|
|
272
|
+
}
|
|
273
|
+
async function allControllers(controllersDir) {
|
|
274
|
+
if (!(await exists(controllersDir)))
|
|
275
|
+
return [];
|
|
276
|
+
const files = (await fs.readdir(controllersDir, { recursive: true, encoding: "utf8" }))
|
|
277
|
+
.map((file) => file.split(path.sep).join("/"))
|
|
278
|
+
.filter((file) => file.endsWith("-controller.ts"))
|
|
279
|
+
.sort();
|
|
280
|
+
return await Promise.all(files.map(async (file) => {
|
|
281
|
+
const controllerPath = underscore(file.slice(0, -"-controller.ts".length));
|
|
282
|
+
const absolute = path.join(controllersDir, file);
|
|
283
|
+
return {
|
|
284
|
+
file: absolute,
|
|
285
|
+
name: `${constantName(controllerPath)}Controller`,
|
|
286
|
+
path: controllerPath,
|
|
287
|
+
helpers: helperModules(absolute, await fs.readFile(absolute, "utf8")),
|
|
288
|
+
};
|
|
289
|
+
}));
|
|
290
|
+
}
|
|
291
|
+
function helperModules(file, text) {
|
|
292
|
+
const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest);
|
|
293
|
+
const imports = new Map();
|
|
294
|
+
for (const statement of source.statements) {
|
|
295
|
+
if (!ts.isImportDeclaration(statement) ||
|
|
296
|
+
!ts.isStringLiteral(statement.moduleSpecifier) ||
|
|
297
|
+
!statement.moduleSpecifier.text.startsWith(".")) {
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
const bindings = statement.importClause?.namedBindings;
|
|
301
|
+
if (!bindings || !ts.isNamedImports(bindings))
|
|
302
|
+
continue;
|
|
303
|
+
const target = path.resolve(path.dirname(file), statement.moduleSpecifier.text);
|
|
304
|
+
for (const e of bindings.elements) {
|
|
305
|
+
imports.set(e.name.text, [target, (e.propertyName ?? e.name).text]);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
const helpers = [];
|
|
309
|
+
const visit = (node) => {
|
|
310
|
+
if (ts.isCallExpression(node) &&
|
|
311
|
+
ts.isPropertyAccessExpression(node.expression) &&
|
|
312
|
+
node.expression.expression.kind === ts.SyntaxKind.ThisKeyword &&
|
|
313
|
+
node.expression.name.text === "helper") {
|
|
314
|
+
for (const arg of node.arguments) {
|
|
315
|
+
const imported = ts.isIdentifier(arg) ? imports.get(arg.text) : undefined;
|
|
316
|
+
if (imported)
|
|
317
|
+
helpers.push(imported);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
ts.forEachChild(node, visit);
|
|
321
|
+
};
|
|
322
|
+
ts.forEachChild(source, visit);
|
|
323
|
+
return helpers;
|
|
324
|
+
}
|
|
325
|
+
function importPath(fromDir, file) {
|
|
326
|
+
const rel = path.relative(fromDir, file).split(path.sep).join("/").replace(/\.ts$/u, ".js");
|
|
327
|
+
return JSON.stringify(rel.startsWith(".") ? rel : `./${rel}`);
|
|
328
|
+
}
|
|
329
|
+
function constantName(path_) {
|
|
330
|
+
return camelize(underscore(path_)).split("::").at(-1);
|
|
331
|
+
}
|
|
332
|
+
async function writeShim(shim, viewsDir) {
|
|
333
|
+
const shimDir = path.dirname(shim.outBase);
|
|
334
|
+
const locals = [...shim.locals].map(([name, types]) => `${name}: ${[...types].join(" | ")}`);
|
|
335
|
+
const scope = {
|
|
336
|
+
view: relocateImports(shim.view.join(" & "), shimDir),
|
|
337
|
+
locals: relocateImports(locals.length === 0 ? "{}" : `{ ${locals.join("; ")} }`, shimDir),
|
|
338
|
+
resolved: shim.resolved,
|
|
339
|
+
...shim.handlerScope,
|
|
340
|
+
};
|
|
341
|
+
const { ts: code, mappings } = virtualizeTseWithDeltas(shim.src, scope);
|
|
342
|
+
const base = path.basename(shim.rel);
|
|
343
|
+
await fs.writeFile(shim.outBase + ".ts", code + `//# sourceMappingURL=${base}.ts.map\n`);
|
|
344
|
+
const sourceFileName = path
|
|
345
|
+
.relative(shimDir, path.join(viewsDir, shim.rel))
|
|
346
|
+
.split(path.sep)
|
|
347
|
+
.join("/");
|
|
348
|
+
const map = generateSourceMap(`${base}.ts`, sourceFileName, shim.src, mappings);
|
|
349
|
+
await fs.writeFile(shim.outBase + ".ts.map", JSON.stringify(map));
|
|
350
|
+
}
|
|
351
|
+
async function writeHandlerShim(shim, code, viewsDir) {
|
|
352
|
+
const { ts: text, mappings } = virtualizeHandler(code, shim.src);
|
|
353
|
+
const base = path.basename(shim.rel);
|
|
354
|
+
await fs.writeFile(shim.outBase + ".ts", text + `//# sourceMappingURL=${base}.ts.map\n`);
|
|
355
|
+
const sourceFileName = path
|
|
356
|
+
.relative(path.dirname(shim.outBase), path.join(viewsDir, shim.rel))
|
|
357
|
+
.split(path.sep)
|
|
358
|
+
.join("/");
|
|
359
|
+
const map = generateSourceMap(`${base}.ts`, sourceFileName, shim.src, mappings);
|
|
360
|
+
await fs.writeFile(shim.outBase + ".ts.map", JSON.stringify(map));
|
|
361
|
+
}
|
|
362
|
+
export function chainLineMappings(jsMappings, tsMappings) {
|
|
363
|
+
const byLine = new Map();
|
|
364
|
+
for (const m of tsMappings) {
|
|
365
|
+
byLine.set(m.genLine, [...(byLine.get(m.genLine) ?? []), m]);
|
|
366
|
+
}
|
|
367
|
+
const mappings = [];
|
|
368
|
+
for (const m of jsMappings) {
|
|
369
|
+
const line = byLine.get(m.srcLine);
|
|
370
|
+
if (line === undefined)
|
|
371
|
+
continue;
|
|
372
|
+
const t = line.filter((c) => (c.genCol ?? 0) <= (m.srcCol ?? 0)).at(-1) ?? line[0];
|
|
373
|
+
const srcCol = (t.srcCol ?? 0) + Math.max(0, (m.srcCol ?? 0) - (t.genCol ?? 0));
|
|
374
|
+
mappings.push({ genLine: m.genLine, genCol: m.genCol, srcLine: t.srcLine, srcCol });
|
|
375
|
+
}
|
|
376
|
+
return mappings;
|
|
377
|
+
}
|
|
378
|
+
async function chainSourceMap(shim, viewsDir) {
|
|
379
|
+
const jsMap = JSON.parse(await fs.readFile(shim.outBase + ".js.map", "utf8"));
|
|
380
|
+
const tsMap = JSON.parse(await fs.readFile(shim.outBase + ".ts.map", "utf8"));
|
|
381
|
+
const mappings = chainLineMappings(decodeLineMappings(jsMap.mappings), decodeLineMappings(tsMap.mappings));
|
|
382
|
+
const shimDir = path.dirname(shim.outBase);
|
|
383
|
+
const sourceFileName = path
|
|
384
|
+
.relative(shimDir, path.join(viewsDir, shim.rel))
|
|
385
|
+
.split(path.sep)
|
|
386
|
+
.join("/");
|
|
387
|
+
const base = path.basename(shim.rel);
|
|
388
|
+
const map = generateSourceMap(`${base}.js`, sourceFileName, shim.src, mappings);
|
|
389
|
+
await fs.writeFile(shim.outBase + ".js.map", JSON.stringify(map));
|
|
390
|
+
const js = await fs.readFile(shim.outBase + ".js", "utf8");
|
|
391
|
+
await fs.writeFile(shim.outBase + ".js", `${js.replace(/^\/\/# sourceMappingURL=.*\n?/gmu, "")}//# sourceMappingURL=${base}.js.map\n`);
|
|
392
|
+
}
|
|
393
|
+
function relocateImports(typeText, shimDir) {
|
|
394
|
+
return typeText.replace(/import\("([^"]+)"\)/gu, (whole, target) => path.isAbsolute(target)
|
|
395
|
+
? `import(${importPath(shimDir, target.replace(/(\.ts)?$/u, ".ts"))})`
|
|
396
|
+
: whole);
|
|
397
|
+
}
|
|
398
|
+
const EMIT_OPTIONS = {
|
|
399
|
+
declaration: true,
|
|
400
|
+
declarationMap: true,
|
|
401
|
+
sourceMap: true,
|
|
402
|
+
skipLibCheck: true,
|
|
403
|
+
strict: true,
|
|
404
|
+
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
|
405
|
+
module: ts.ModuleKind.ESNext,
|
|
406
|
+
target: ts.ScriptTarget.ESNext,
|
|
407
|
+
};
|
|
408
|
+
function cachingHost() {
|
|
409
|
+
const host = ts.createCompilerHost(EMIT_OPTIONS, true);
|
|
410
|
+
const getSourceFile = host.getSourceFile.bind(host);
|
|
411
|
+
const parsed = new Map();
|
|
412
|
+
host.getSourceFile = (fileName, ...rest) => {
|
|
413
|
+
if (fileName.endsWith(".tse.ts"))
|
|
414
|
+
return getSourceFile(fileName, ...rest);
|
|
415
|
+
if (!parsed.has(fileName))
|
|
416
|
+
parsed.set(fileName, getSourceFile(fileName, ...rest));
|
|
417
|
+
return parsed.get(fileName);
|
|
418
|
+
};
|
|
419
|
+
return host;
|
|
420
|
+
}
|
|
421
|
+
function bindCheckedTypes(views, controllers, helperFiles, program) {
|
|
422
|
+
const checker = program.getTypeChecker();
|
|
423
|
+
const typeText = (type) => checker.typeToString(type, undefined, ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.UseFullyQualifiedType);
|
|
424
|
+
const baseText = (type) => typeText(checker.getBaseTypeOfLiteralType(type));
|
|
425
|
+
const before = views.map(scopeSignature);
|
|
426
|
+
const partials = new Map();
|
|
427
|
+
const renders = new Map();
|
|
428
|
+
const unresolved = new Set();
|
|
429
|
+
let unknownTarget = false;
|
|
430
|
+
let unknownTemplate = false;
|
|
431
|
+
for (const view of views) {
|
|
432
|
+
view.view = [...view.base.view];
|
|
433
|
+
view.locals = new Map([...view.base.locals].map(([k, v]) => [k, new Set(v)]));
|
|
434
|
+
view.resolved = true;
|
|
435
|
+
const key = partialRegistryKey(view.rel);
|
|
436
|
+
if (key !== null && !view.strictLocals)
|
|
437
|
+
partials.set(key, view);
|
|
438
|
+
}
|
|
439
|
+
const modelPartial = (type) => {
|
|
440
|
+
const symbol = type.getSymbol();
|
|
441
|
+
const file = symbol?.declarations?.[0]?.getSourceFile().fileName;
|
|
442
|
+
if (symbol === undefined || file === undefined)
|
|
443
|
+
return undefined;
|
|
444
|
+
return [...partials.values()].find((p) => p.model?.klass === symbol.name && path.resolve(p.model.file) === path.resolve(file));
|
|
445
|
+
};
|
|
446
|
+
const objectTypes = (type) => {
|
|
447
|
+
const nonNull = checker.getNonNullableType(type);
|
|
448
|
+
if (nonNull.isUnion())
|
|
449
|
+
return nonNull.types.flatMap(objectTypes);
|
|
450
|
+
if (checker.isArrayType(nonNull)) {
|
|
451
|
+
return checker.getTypeArguments(nonNull).flatMap(objectTypes);
|
|
452
|
+
}
|
|
453
|
+
return [nonNull];
|
|
454
|
+
};
|
|
455
|
+
const renderedBy = new Map();
|
|
456
|
+
const sources = [
|
|
457
|
+
...views.map((v) => ({
|
|
458
|
+
file: v.outBase + ".ts",
|
|
459
|
+
prefix: path.posix.dirname(v.rel),
|
|
460
|
+
inController: false,
|
|
461
|
+
})),
|
|
462
|
+
...controllers.map((c) => ({
|
|
463
|
+
file: c.file,
|
|
464
|
+
prefix: dasherize(c.path),
|
|
465
|
+
inController: true,
|
|
466
|
+
controller: c,
|
|
467
|
+
})),
|
|
468
|
+
...helperFiles.map((file) => ({ file, inController: false })),
|
|
469
|
+
];
|
|
470
|
+
for (const { file, prefix, inController, controller } of sources) {
|
|
471
|
+
const sf = program.getSourceFile(file);
|
|
472
|
+
if (sf === undefined)
|
|
473
|
+
continue;
|
|
474
|
+
const named = (key, name) => name.includes("/") || prefix === undefined
|
|
475
|
+
? key === name || (prefix === undefined && key?.endsWith(`/${name}`) === true)
|
|
476
|
+
: key === `${prefix}/${name}`;
|
|
477
|
+
const visit = (node) => {
|
|
478
|
+
const site = ts.isCallExpression(node) ? renderSite(node, inController) : undefined;
|
|
479
|
+
const targets = [];
|
|
480
|
+
const bound = new Map();
|
|
481
|
+
let untyped = false;
|
|
482
|
+
if (site === "unknown")
|
|
483
|
+
unknownTarget = true;
|
|
484
|
+
else if (site !== undefined && "assigns" in site) {
|
|
485
|
+
if (controller !== undefined) {
|
|
486
|
+
for (const v of views.filter((v) => named(v.rel.replace(/\.[^/]*$/u, ""), site.assigns))) {
|
|
487
|
+
renderedBy.set(v, (renderedBy.get(v) ?? new Set()).add(controller));
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
else if (site !== undefined && "template" in site) {
|
|
492
|
+
const { template } = site;
|
|
493
|
+
if (template === undefined)
|
|
494
|
+
unknownTemplate = true;
|
|
495
|
+
else
|
|
496
|
+
targets.push(...views.filter((v) => named(v.rel.replace(/\.[^/]*$/u, ""), template)));
|
|
497
|
+
untyped = site.untyped === true;
|
|
498
|
+
}
|
|
499
|
+
else if (site !== undefined && "object" in site) {
|
|
500
|
+
for (const type of objectTypes(checker.getTypeAtLocation(site.object))) {
|
|
501
|
+
const reached = modelPartial(type);
|
|
502
|
+
if (reached === undefined)
|
|
503
|
+
unknownTarget = true;
|
|
504
|
+
else
|
|
505
|
+
targets.push(reached);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
else if (site !== undefined) {
|
|
509
|
+
targets.push(...[...partials].flatMap(([key, p]) => (named(key, site.name) ? [p] : [])));
|
|
510
|
+
const { options } = site;
|
|
511
|
+
const as = options && option(options, "as");
|
|
512
|
+
const variable = as ? (ts.isStringLiteral(as) ? as.text : undefined) : localVariable(site);
|
|
513
|
+
const object = options && option(options, "object");
|
|
514
|
+
const collection = options && option(options, "collection");
|
|
515
|
+
const each = collection &&
|
|
516
|
+
checker.getIndexTypeOfType(checker.getNonNullableType(checker.getTypeAtLocation(collection)), ts.IndexKind.Number);
|
|
517
|
+
if (options && (variable === undefined || (collection && each === undefined))) {
|
|
518
|
+
untyped = true;
|
|
519
|
+
}
|
|
520
|
+
else if (collection) {
|
|
521
|
+
bound.set(variable, baseText(each));
|
|
522
|
+
bound.set(`${variable}_counter`, "number");
|
|
523
|
+
bound.set(`${variable}_iteration`, 'import("@blazetrails/actionview").PartialIteration');
|
|
524
|
+
}
|
|
525
|
+
else if (object)
|
|
526
|
+
bound.set(variable, baseText(checker.getTypeAtLocation(object)));
|
|
527
|
+
}
|
|
528
|
+
const locals = site === undefined || site === "unknown" || "assigns" in site ? undefined : site.locals;
|
|
529
|
+
for (const target of targets) {
|
|
530
|
+
if (controller !== undefined) {
|
|
531
|
+
renderedBy.set(target, (renderedBy.get(target) ?? new Set()).add(controller));
|
|
532
|
+
}
|
|
533
|
+
if (target.strictLocals)
|
|
534
|
+
continue;
|
|
535
|
+
if (untyped)
|
|
536
|
+
unresolved.add(target);
|
|
537
|
+
const seen = renders.get(target) ?? { calls: 0, keys: new Map() };
|
|
538
|
+
renders.set(target, seen);
|
|
539
|
+
const hash = locals && checker.getTypeAtLocation(locals);
|
|
540
|
+
if (hash && hash.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown))
|
|
541
|
+
unresolved.add(target);
|
|
542
|
+
for (const each of hash === undefined
|
|
543
|
+
? [undefined]
|
|
544
|
+
: hash.isUnion()
|
|
545
|
+
? hash.types
|
|
546
|
+
: [hash]) {
|
|
547
|
+
seen.calls++;
|
|
548
|
+
const passed = new Map([...bound].map(([name, type]) => [name, { type, optional: false }]));
|
|
549
|
+
for (const prop of each ? checker.getPropertiesOfType(each) : []) {
|
|
550
|
+
const type = checker.getTypeOfSymbolAtLocation(prop, locals);
|
|
551
|
+
passed.set(prop.name, {
|
|
552
|
+
type: typeText(checker.getBaseTypeOfLiteralType(type)),
|
|
553
|
+
optional: (prop.flags & ts.SymbolFlags.Optional) !== 0,
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
for (const [name, { type, optional }] of passed) {
|
|
557
|
+
target.locals.set(name, (target.locals.get(name) ?? new Set()).add(type));
|
|
558
|
+
if (!optional)
|
|
559
|
+
seen.keys.set(name, (seen.keys.get(name) ?? 0) + 1);
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
ts.forEachChild(node, visit);
|
|
564
|
+
};
|
|
565
|
+
visit(sf);
|
|
566
|
+
}
|
|
567
|
+
const members = new Map();
|
|
568
|
+
const layouts = new Map();
|
|
569
|
+
const existing = new Set(views.flatMap((v) => (v.layout === undefined ? [] : [v.layout])));
|
|
570
|
+
for (const controller of new Set([
|
|
571
|
+
...controllers,
|
|
572
|
+
...views.flatMap((v) => (v.controller ? [v.controller] : [])),
|
|
573
|
+
])) {
|
|
574
|
+
const klass = controllerClass(program, controller);
|
|
575
|
+
if (!klass)
|
|
576
|
+
continue;
|
|
577
|
+
members.set(controller, controllerMembers(checker, klass, typeText));
|
|
578
|
+
layouts.set(controller, layoutsOf(checker, controllers, existing, klass));
|
|
579
|
+
}
|
|
580
|
+
for (const view of views) {
|
|
581
|
+
const rendering = view.layout === undefined
|
|
582
|
+
? [
|
|
583
|
+
...new Set([
|
|
584
|
+
...(view.controller ? [view.controller] : []),
|
|
585
|
+
...(renderedBy.get(view) ?? []),
|
|
586
|
+
]),
|
|
587
|
+
]
|
|
588
|
+
: controllers.filter((c) => {
|
|
589
|
+
const rendered = layouts.get(c);
|
|
590
|
+
return rendered === "every" || rendered?.has(view.layout);
|
|
591
|
+
});
|
|
592
|
+
const merged = new Map();
|
|
593
|
+
for (const controller of rendering ?? []) {
|
|
594
|
+
for (const [name, type] of members.get(controller) ?? []) {
|
|
595
|
+
merged.set(name, (merged.get(name) ?? new Set()).add(type));
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
const fields = [...merged].map(([name, types]) => {
|
|
599
|
+
const everywhere = (rendering ?? []).every((c) => members.get(c)?.has(name));
|
|
600
|
+
return `${JSON.stringify(name)}: ${[...types, ...(everywhere ? [] : ["undefined"])].join(" | ")}`;
|
|
601
|
+
});
|
|
602
|
+
if (fields.length > 0)
|
|
603
|
+
view.view.push(`{ ${fields.join("; ")} }`);
|
|
604
|
+
}
|
|
605
|
+
for (const [target, { calls, keys }] of renders) {
|
|
606
|
+
for (const [name, count] of keys)
|
|
607
|
+
if (count < calls)
|
|
608
|
+
target.locals.get(name).add("undefined");
|
|
609
|
+
}
|
|
610
|
+
for (const view of views) {
|
|
611
|
+
const partial = partialRegistryKey(view.rel) !== null;
|
|
612
|
+
if (unresolved.has(view) || (partial ? unknownTarget : unknownTemplate))
|
|
613
|
+
view.resolved = false;
|
|
614
|
+
}
|
|
615
|
+
return views.some((view, i) => scopeSignature(view) !== before[i]);
|
|
616
|
+
}
|
|
617
|
+
function scopeSignature(view) {
|
|
618
|
+
return JSON.stringify([view.view, [...view.locals].map(([k, v]) => [k, [...v]]), view.resolved]);
|
|
619
|
+
}
|
|
620
|
+
function controllerClass(program, { file, name }) {
|
|
621
|
+
return program
|
|
622
|
+
.getSourceFile(file)
|
|
623
|
+
?.statements.find((s) => ts.isClassDeclaration(s) && s.name?.text === name);
|
|
624
|
+
}
|
|
625
|
+
function controllerMembers(checker, klass, typeText) {
|
|
626
|
+
const instance = checker.getDeclaredTypeOfSymbol(checker.getSymbolAtLocation(klass.name));
|
|
627
|
+
const members = new Map();
|
|
628
|
+
for (const prop of checker.getPropertiesOfType(instance)) {
|
|
629
|
+
const declarations = prop.declarations ?? [];
|
|
630
|
+
if (declarations.every((d) => d.getSourceFile().isDeclarationFile))
|
|
631
|
+
continue;
|
|
632
|
+
const type = checker.getTypeOfSymbolAtLocation(prop, klass);
|
|
633
|
+
if (type.getCallSignatures().length > 0)
|
|
634
|
+
continue;
|
|
635
|
+
members.set(prop.name, typeText(type));
|
|
636
|
+
}
|
|
637
|
+
for (const { name, args } of classMacros(checker, klass)) {
|
|
638
|
+
for (const arg of args.flatMap(stringLiterals)) {
|
|
639
|
+
const member = name === "helperMethod" && instance.getProperty(arg);
|
|
640
|
+
if (member)
|
|
641
|
+
members.set(arg, typeText(checker.getTypeOfSymbolAtLocation(member, klass)));
|
|
642
|
+
if (name === "addFlashTypes")
|
|
643
|
+
members.set(arg, "unknown");
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
return members;
|
|
647
|
+
}
|
|
648
|
+
function stringLiterals(arg) {
|
|
649
|
+
if (ts.isStringLiteral(arg))
|
|
650
|
+
return [arg.text];
|
|
651
|
+
return ts.isArrayLiteralExpression(arg) ? arg.elements.flatMap(stringLiterals) : [];
|
|
652
|
+
}
|
|
653
|
+
function superclassOf(checker, klass) {
|
|
654
|
+
const superclass = klass.heritageClauses?.find((h) => h.token === ts.SyntaxKind.ExtendsKeyword)
|
|
655
|
+
?.types[0];
|
|
656
|
+
const parent = superclass && sourceDeclaration(checker, superclass.expression);
|
|
657
|
+
return parent && ts.isClassDeclaration(parent) ? parent : undefined;
|
|
658
|
+
}
|
|
659
|
+
function layoutsOf(checker, controllers, existing, klass) {
|
|
660
|
+
const layouts = new Set();
|
|
661
|
+
const add = (type) => {
|
|
662
|
+
if (type.isStringLiteral() && !type.value.startsWith(":")) {
|
|
663
|
+
layouts.add(type.value.replace(/^layouts\//u, ""));
|
|
664
|
+
}
|
|
665
|
+
else if (checker.typeToString(type) !== "false") {
|
|
666
|
+
return false;
|
|
667
|
+
}
|
|
668
|
+
return true;
|
|
669
|
+
};
|
|
670
|
+
const implied = (from) => {
|
|
671
|
+
for (let current = from; current; current = superclassOf(checker, current)) {
|
|
672
|
+
const file = current.getSourceFile().fileName;
|
|
673
|
+
const owner = controllers.find((c) => c.file === file && c.name === current.name?.text);
|
|
674
|
+
const name = owner && dasherize(owner.path);
|
|
675
|
+
if (name !== undefined && existing.has(name))
|
|
676
|
+
return void layouts.add(name);
|
|
677
|
+
}
|
|
678
|
+
};
|
|
679
|
+
const declared = classMacros(checker, klass).filter((m) => m.name === "layout");
|
|
680
|
+
const nearest = declared.filter((m) => m.depth === declared[0].depth).at(-1);
|
|
681
|
+
const [value, conditions] = nearest?.args ?? [];
|
|
682
|
+
if (value === undefined || value.kind === ts.SyntaxKind.NullKeyword)
|
|
683
|
+
implied(klass);
|
|
684
|
+
else if (!add(checker.getTypeAtLocation(value)))
|
|
685
|
+
return "every";
|
|
686
|
+
else if (conditions !== undefined)
|
|
687
|
+
implied(klass);
|
|
688
|
+
let every = false;
|
|
689
|
+
const perRender = (options) => {
|
|
690
|
+
let found = [];
|
|
691
|
+
let wide = false;
|
|
692
|
+
const read = (source) => {
|
|
693
|
+
const type = checker.getTypeAtLocation(source);
|
|
694
|
+
const layouts = [];
|
|
695
|
+
let definite = true;
|
|
696
|
+
for (const part of type.isUnion() ? type.types : [type]) {
|
|
697
|
+
const property = part.getProperty("layout");
|
|
698
|
+
const anything = part.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown);
|
|
699
|
+
if (anything || (!property && part.getStringIndexType()))
|
|
700
|
+
wide = true;
|
|
701
|
+
if (property)
|
|
702
|
+
layouts.push(checker.getTypeOfSymbolAtLocation(property, source));
|
|
703
|
+
if (!property || property.flags & ts.SymbolFlags.Optional)
|
|
704
|
+
definite = false;
|
|
705
|
+
}
|
|
706
|
+
found = definite ? layouts : [...found, ...layouts];
|
|
707
|
+
if (definite)
|
|
708
|
+
wide = false;
|
|
709
|
+
};
|
|
710
|
+
const literal = ts.isObjectLiteralExpression(options) ? options : undefined;
|
|
711
|
+
if (!literal)
|
|
712
|
+
read(options);
|
|
713
|
+
for (const p of literal?.properties ?? []) {
|
|
714
|
+
if (ts.isSpreadAssignment(p))
|
|
715
|
+
read(p.expression);
|
|
716
|
+
else if (propertyName(p) === "layout") {
|
|
717
|
+
found = [checker.getTypeAtLocation(option(literal, "layout"))];
|
|
718
|
+
wide = false;
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
if (wide)
|
|
722
|
+
every = true;
|
|
723
|
+
for (const each of found.flatMap((type) => (type.isUnion() ? type.types : [type]))) {
|
|
724
|
+
if (each.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined))
|
|
725
|
+
continue;
|
|
726
|
+
if (checker.typeToString(each) === "true")
|
|
727
|
+
implied(klass);
|
|
728
|
+
else if (!add(each))
|
|
729
|
+
every = true;
|
|
730
|
+
}
|
|
731
|
+
};
|
|
732
|
+
const visit = (node) => {
|
|
733
|
+
const callee = ts.isCallExpression(node) ? node.expression : undefined;
|
|
734
|
+
if (callee &&
|
|
735
|
+
ts.isPropertyAccessExpression(callee) &&
|
|
736
|
+
callee.expression.kind === ts.SyntaxKind.ThisKeyword &&
|
|
737
|
+
callee.name.text === "render") {
|
|
738
|
+
node.arguments.slice(0, 2).forEach(perRender);
|
|
739
|
+
}
|
|
740
|
+
ts.forEachChild(node, visit);
|
|
741
|
+
};
|
|
742
|
+
for (let current = klass; current;) {
|
|
743
|
+
visit(current);
|
|
744
|
+
current = superclassOf(checker, current);
|
|
745
|
+
}
|
|
746
|
+
return every ? "every" : layouts;
|
|
747
|
+
}
|
|
748
|
+
const CLASS_MACROS = ["helperMethod", "layout", "addFlashTypes"];
|
|
749
|
+
function classMacros(checker, klass) {
|
|
750
|
+
const macros = [];
|
|
751
|
+
const scanned = new Set();
|
|
752
|
+
let depth = 0;
|
|
753
|
+
const macro = (node, isSelf) => {
|
|
754
|
+
if (ts.isFunctionLike(node))
|
|
755
|
+
return;
|
|
756
|
+
if (ts.isCallExpression(node)) {
|
|
757
|
+
const callee = node.expression;
|
|
758
|
+
const [receiver, name] = ts.isPropertyAccessExpression(callee)
|
|
759
|
+
? [callee.expression, callee.name.text]
|
|
760
|
+
: [undefined, ts.isIdentifier(callee) ? callee.text : ""];
|
|
761
|
+
const viaCall = name === "call" && receiver !== undefined && ts.isIdentifier(receiver);
|
|
762
|
+
const self = viaCall ? node.arguments[0] : receiver;
|
|
763
|
+
const args = viaCall ? node.arguments.slice(1) : node.arguments;
|
|
764
|
+
const macroName = viaCall ? receiver.text : name;
|
|
765
|
+
if (CLASS_MACROS.includes(macroName) && isSelf(self)) {
|
|
766
|
+
macros.push({ name: macroName, args, depth });
|
|
767
|
+
}
|
|
768
|
+
else if (name === "include" && isSelf(node.arguments[0])) {
|
|
769
|
+
for (const arg of node.arguments.slice(1)) {
|
|
770
|
+
const included = sourceDeclaration(checker, arg);
|
|
771
|
+
if (included)
|
|
772
|
+
scanModule(included);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
ts.forEachChild(node, (child) => macro(child, isSelf));
|
|
777
|
+
};
|
|
778
|
+
const resolvesTo = (declaration, thisIsSelf) => (receiver) => receiver !== undefined &&
|
|
779
|
+
((thisIsSelf && receiver.kind === ts.SyntaxKind.ThisKeyword) ||
|
|
780
|
+
sourceDeclaration(checker, receiver) === declaration);
|
|
781
|
+
const isIncludedHook = (name) => (ts.isIdentifier(name) && name.text === "included") ||
|
|
782
|
+
(ts.isComputedPropertyName(name) &&
|
|
783
|
+
ts.isIdentifier(name.expression) &&
|
|
784
|
+
name.expression.text === "included");
|
|
785
|
+
const scanModule = (declaration) => {
|
|
786
|
+
if (scanned.has(declaration))
|
|
787
|
+
return;
|
|
788
|
+
scanned.add(declaration);
|
|
789
|
+
const findHook = (node) => {
|
|
790
|
+
if ((ts.isMethodDeclaration(node) || ts.isPropertyAssignment(node)) &&
|
|
791
|
+
isIncludedHook(node.name)) {
|
|
792
|
+
const hook = ts.isPropertyAssignment(node) ? node.initializer : node;
|
|
793
|
+
const base = (ts.isMethodDeclaration(hook) ||
|
|
794
|
+
ts.isArrowFunction(hook) ||
|
|
795
|
+
ts.isFunctionExpression(hook)) &&
|
|
796
|
+
hook.parameters[0];
|
|
797
|
+
if (base && hook.body)
|
|
798
|
+
macro(hook.body, resolvesTo(base, false));
|
|
799
|
+
return;
|
|
800
|
+
}
|
|
801
|
+
if (ts.isFunctionLike(node))
|
|
802
|
+
return;
|
|
803
|
+
ts.forEachChild(node, findHook);
|
|
804
|
+
};
|
|
805
|
+
findHook(declaration);
|
|
806
|
+
};
|
|
807
|
+
const scanClass = (declaration) => {
|
|
808
|
+
if (scanned.has(declaration))
|
|
809
|
+
return;
|
|
810
|
+
scanned.add(declaration);
|
|
811
|
+
const inClass = resolvesTo(declaration, true);
|
|
812
|
+
for (const member of declaration.members) {
|
|
813
|
+
if (ts.isClassStaticBlockDeclaration(member)) {
|
|
814
|
+
macro(member.body, inClass);
|
|
815
|
+
}
|
|
816
|
+
else if (ts.isPropertyDeclaration(member) &&
|
|
817
|
+
member.initializer &&
|
|
818
|
+
ts.getCombinedModifierFlags(member) & ts.ModifierFlags.Static) {
|
|
819
|
+
macro(member.initializer, inClass);
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
const atTopLevel = resolvesTo(declaration, false);
|
|
823
|
+
for (const statement of declaration.getSourceFile().statements) {
|
|
824
|
+
if (ts.isExpressionStatement(statement))
|
|
825
|
+
macro(statement, atTopLevel);
|
|
826
|
+
}
|
|
827
|
+
const parent = superclassOf(checker, declaration);
|
|
828
|
+
depth++;
|
|
829
|
+
if (parent)
|
|
830
|
+
scanClass(parent);
|
|
831
|
+
};
|
|
832
|
+
scanClass(klass);
|
|
833
|
+
return macros;
|
|
834
|
+
}
|
|
835
|
+
function sourceDeclaration(checker, expr) {
|
|
836
|
+
let symbol = checker.getSymbolAtLocation(expr);
|
|
837
|
+
if (symbol && symbol.flags & ts.SymbolFlags.Alias)
|
|
838
|
+
symbol = checker.getAliasedSymbol(symbol);
|
|
839
|
+
const declaration = symbol?.valueDeclaration ?? symbol?.declarations?.[0];
|
|
840
|
+
return declaration && !declaration.getSourceFile().isDeclarationFile ? declaration : undefined;
|
|
841
|
+
}
|
|
842
|
+
function renderSite(call, inController) {
|
|
843
|
+
const callee = call.expression;
|
|
844
|
+
const isRender = ts.isIdentifier(callee)
|
|
845
|
+
? callee.text === "render"
|
|
846
|
+
: ts.isPropertyAccessExpression(callee) &&
|
|
847
|
+
callee.expression.kind === ts.SyntaxKind.ThisKeyword &&
|
|
848
|
+
callee.name.text === "render";
|
|
849
|
+
if (!isRender)
|
|
850
|
+
return turboStreamRenderSite(call);
|
|
851
|
+
const [first, second] = call.arguments;
|
|
852
|
+
if (!first)
|
|
853
|
+
return undefined;
|
|
854
|
+
if (ts.isStringLiteral(first)) {
|
|
855
|
+
if (!inController)
|
|
856
|
+
return { name: first.text, locals: second };
|
|
857
|
+
if (second === undefined || !passesLocals(second))
|
|
858
|
+
return { assigns: first.text };
|
|
859
|
+
const typeable = ts.isObjectLiteralExpression(second) &&
|
|
860
|
+
!second.properties.map(propertyName).includes(undefined);
|
|
861
|
+
return {
|
|
862
|
+
template: first.text,
|
|
863
|
+
locals: typeable ? option(second, "locals") : undefined,
|
|
864
|
+
untyped: !typeable,
|
|
865
|
+
};
|
|
866
|
+
}
|
|
867
|
+
if (!ts.isObjectLiteralExpression(first))
|
|
868
|
+
return { object: first, locals: second };
|
|
869
|
+
const keys = first.properties.map(propertyName);
|
|
870
|
+
if (keys.includes(undefined))
|
|
871
|
+
return "unknown";
|
|
872
|
+
const block = !inController && second !== undefined && isFunction(second);
|
|
873
|
+
const partialKey = block ? "layout" : "partial";
|
|
874
|
+
if (!keys.includes(partialKey)) {
|
|
875
|
+
const template = option(first, "template");
|
|
876
|
+
const action = template ? undefined : option(first, "action");
|
|
877
|
+
if (!keys.includes("locals")) {
|
|
878
|
+
const named = template ?? action;
|
|
879
|
+
if (!inController || named === undefined || !ts.isStringLiteral(named))
|
|
880
|
+
return undefined;
|
|
881
|
+
return { assigns: action ? dasherize(underscore(named.text)) : named.text };
|
|
882
|
+
}
|
|
883
|
+
const named = template ?? action;
|
|
884
|
+
return {
|
|
885
|
+
template: named
|
|
886
|
+
? ts.isStringLiteral(named)
|
|
887
|
+
? action
|
|
888
|
+
? dasherize(underscore(named.text))
|
|
889
|
+
: named.text
|
|
890
|
+
: undefined
|
|
891
|
+
: inController
|
|
892
|
+
? actionName(call)
|
|
893
|
+
: undefined,
|
|
894
|
+
locals: option(first, "locals"),
|
|
895
|
+
};
|
|
896
|
+
}
|
|
897
|
+
const partial = option(first, partialKey);
|
|
898
|
+
if (partial && ts.isStringLiteral(partial)) {
|
|
899
|
+
const implicitLocals = keys.some((k) => k === "collection" || k === "object" || k === "as");
|
|
900
|
+
return {
|
|
901
|
+
name: partial.text,
|
|
902
|
+
locals: option(first, "locals"),
|
|
903
|
+
options: implicitLocals ? first : undefined,
|
|
904
|
+
};
|
|
905
|
+
}
|
|
906
|
+
return "unknown";
|
|
907
|
+
}
|
|
908
|
+
function turboStreamRenderSite(call) {
|
|
909
|
+
const callee = call.expression;
|
|
910
|
+
if (!ts.isPropertyAccessExpression(callee) ||
|
|
911
|
+
!((ts.isIdentifier(callee.expression) && callee.expression.text === "turboStream") ||
|
|
912
|
+
/^broadcast\w*To$/u.test(callee.name.text))) {
|
|
913
|
+
return undefined;
|
|
914
|
+
}
|
|
915
|
+
const options = call.arguments.find((arg) => ts.isObjectLiteralExpression(arg) && arg.properties.map(propertyName).includes("partial"));
|
|
916
|
+
const partial = options && option(options, "partial");
|
|
917
|
+
if (!partial || !ts.isStringLiteral(partial))
|
|
918
|
+
return undefined;
|
|
919
|
+
return { name: partial.text, locals: option(options, "locals") };
|
|
920
|
+
}
|
|
921
|
+
function actionName(call) {
|
|
922
|
+
const method = ts.findAncestor(call.parent, (node) => ts.isFunctionLike(node) && !ts.isArrowFunction(node));
|
|
923
|
+
const hidden = ts.ModifierFlags.Private | ts.ModifierFlags.Protected | ts.ModifierFlags.Static;
|
|
924
|
+
return method &&
|
|
925
|
+
ts.isMethodDeclaration(method) &&
|
|
926
|
+
ts.isClassDeclaration(method.parent) &&
|
|
927
|
+
ts.isIdentifier(method.name) &&
|
|
928
|
+
!(ts.getCombinedModifierFlags(method) & hidden)
|
|
929
|
+
? dasherize(underscore(method.name.text))
|
|
930
|
+
: undefined;
|
|
931
|
+
}
|
|
932
|
+
function localVariable({ name }) {
|
|
933
|
+
const base = name.endsWith("/") ? "" : path.posix.basename(name);
|
|
934
|
+
return /^_?(.*?)(?:\.\w+)*$/u.exec(base)?.[1] || undefined;
|
|
935
|
+
}
|
|
936
|
+
function propertyName(p) {
|
|
937
|
+
return (ts.isPropertyAssignment(p) || ts.isShorthandPropertyAssignment(p)) &&
|
|
938
|
+
(ts.isIdentifier(p.name) || ts.isStringLiteral(p.name))
|
|
939
|
+
? p.name.text
|
|
940
|
+
: undefined;
|
|
941
|
+
}
|
|
942
|
+
function option(hash, key) {
|
|
943
|
+
const property = hash.properties.find((p) => propertyName(p) === key);
|
|
944
|
+
return property && ts.isPropertyAssignment(property)
|
|
945
|
+
? property.initializer
|
|
946
|
+
: property && ts.isShorthandPropertyAssignment(property)
|
|
947
|
+
? property.name
|
|
948
|
+
: undefined;
|
|
949
|
+
}
|
|
950
|
+
function passesLocals(options) {
|
|
951
|
+
if (!ts.isObjectLiteralExpression(options))
|
|
952
|
+
return true;
|
|
953
|
+
const keys = options.properties.map(propertyName);
|
|
954
|
+
return keys.includes(undefined) || keys.includes("locals");
|
|
955
|
+
}
|
|
956
|
+
function isFunction(node) {
|
|
957
|
+
return ts.isArrowFunction(node) || ts.isFunctionExpression(node);
|
|
958
|
+
}
|
|
959
|
+
async function templateScope(appDir, rel, shimDir, helpers, controllers, mailers) {
|
|
960
|
+
const view = ['import("@blazetrails/actionview").Base'];
|
|
961
|
+
for (const file of helpers) {
|
|
962
|
+
const name = constantName(file.replace(/[-_]helper\.ts$/u, ""));
|
|
963
|
+
view.push(`(typeof import(${importPath(shimDir, path.join(appDir, "helpers", file))}))["${name}Helper"]`);
|
|
964
|
+
}
|
|
965
|
+
view.push(`{ ${(TopLevel.Trails?.application?.routes().namedRoutes.helperNames() ?? []).map((name) => `${name}(...args: unknown[]): string;`).join(" ")} }`, 'Record<"alert" | "notice", unknown>');
|
|
966
|
+
const prefix = path.posix.dirname(rel);
|
|
967
|
+
const layout = /^layouts\/((?:[^/]+\/)*[^_/][^/.]*)\./u.exec(rel)?.[1];
|
|
968
|
+
const ownController = layout === undefined ? controllers.find((c) => dasherize(c.path) === prefix) : undefined;
|
|
969
|
+
const controller = ownController ??
|
|
970
|
+
(layout === undefined ? mailers.classes.find((m) => m.path === prefix) : undefined);
|
|
971
|
+
const helpersFrom = ownController ??
|
|
972
|
+
(isMailerView(rel, layout, mailers)
|
|
973
|
+
? controller
|
|
974
|
+
: controllers.find((c) => c.path === "application"));
|
|
975
|
+
if (helpersFrom !== undefined) {
|
|
976
|
+
view.push(`((typeof import(${importPath(shimDir, helpersFrom.file)}))[${JSON.stringify(helpersFrom.name)}] extends { _helpers: infer H } ? H : unknown)`);
|
|
977
|
+
}
|
|
978
|
+
const helperSources = new Set([helpersFrom, controllers.find((c) => c.path === "application")]);
|
|
979
|
+
for (const source of helperSources) {
|
|
980
|
+
for (const [file, name] of source?.helpers ?? []) {
|
|
981
|
+
view.push(`(typeof import(${importPath(shimDir, file)}))[${JSON.stringify(name)}]`);
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
const delegatesFrom = controller ?? helpersFrom;
|
|
985
|
+
if (delegatesFrom !== undefined) {
|
|
986
|
+
const instance = `InstanceType<(typeof import(${importPath(shimDir, delegatesFrom.file)}))[${JSON.stringify(delegatesFrom.name)}]>`;
|
|
987
|
+
view.push(`Pick<${instance}, Extract<import("@blazetrails/actionview").ControllerDelegate | "request", keyof ${instance}>>`);
|
|
988
|
+
}
|
|
989
|
+
const locals = new Map();
|
|
990
|
+
let modelClass;
|
|
991
|
+
const partial = /^_([a-z_]\w*)/u.exec(path.posix.basename(rel));
|
|
992
|
+
const element = partial?.[1];
|
|
993
|
+
if (element !== undefined && path.posix.basename(prefix) === pluralize(element)) {
|
|
994
|
+
const namespace = prefix.split("/").slice(0, -1);
|
|
995
|
+
const model = path.join(appDir, "models", ...namespace.map(dasherize), `${dasherize(element)}.ts`);
|
|
996
|
+
if (await exists(model)) {
|
|
997
|
+
const klass = constantName([...namespace, element].join("/"));
|
|
998
|
+
locals.set(element, new Set([`import(${JSON.stringify(model)}).${klass}`]));
|
|
999
|
+
modelClass = { file: model, klass };
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
return {
|
|
1003
|
+
view,
|
|
1004
|
+
locals,
|
|
1005
|
+
model: modelClass,
|
|
1006
|
+
base: { view: [...view], locals: new Map(locals) },
|
|
1007
|
+
controller,
|
|
1008
|
+
layout,
|
|
1009
|
+
};
|
|
1010
|
+
}
|
|
1011
|
+
function partialRegistryKey(rel) {
|
|
1012
|
+
const parts = rel.replace(/\.tse$/u, "").split("/");
|
|
1013
|
+
const filename = parts[parts.length - 1];
|
|
1014
|
+
if (!filename.startsWith("_"))
|
|
1015
|
+
return null;
|
|
1016
|
+
const nameWithoutUnderscore = filename.slice(1).replace(/\.[^.]+$/u, "");
|
|
1017
|
+
return [...parts.slice(0, -1), nameWithoutUnderscore].join("/");
|
|
1018
|
+
}
|
|
1019
|
+
function emitRegistryAugmentation(entries) {
|
|
1020
|
+
const lines = [
|
|
1021
|
+
"// AUTO-GENERATED by `trails-tsc-views build` — do not edit.",
|
|
1022
|
+
"// Regenerate by running `trails-tsc-views build`.",
|
|
1023
|
+
"",
|
|
1024
|
+
"export {};",
|
|
1025
|
+
"",
|
|
1026
|
+
'declare module "@blazetrails/actionview" {',
|
|
1027
|
+
" interface TemplateRegistry {",
|
|
1028
|
+
];
|
|
1029
|
+
for (const { key, localsType } of entries) {
|
|
1030
|
+
lines.push(` ${JSON.stringify(key)}: ${localsType};`);
|
|
1031
|
+
}
|
|
1032
|
+
lines.push(" }", "}", "");
|
|
1033
|
+
return lines.join("\n");
|
|
1034
|
+
}
|
|
1035
|
+
function emitRoutesAugmentation(helperNames) {
|
|
1036
|
+
const members = helperNames.map((name) => `${name}(...args: unknown[]): string;`);
|
|
1037
|
+
const body = (indent) => members.map((m) => `${indent}${m}`);
|
|
1038
|
+
return [
|
|
1039
|
+
"// AUTO-GENERATED by `trails-tsc-views build` — do not edit.",
|
|
1040
|
+
"// Regenerate by running `trails-tsc-views build`.",
|
|
1041
|
+
"",
|
|
1042
|
+
"export {};",
|
|
1043
|
+
"",
|
|
1044
|
+
'declare module "@blazetrails/actionpack" {',
|
|
1045
|
+
" namespace ActionController {",
|
|
1046
|
+
" interface Base {",
|
|
1047
|
+
...body(" "),
|
|
1048
|
+
" }",
|
|
1049
|
+
" interface API {",
|
|
1050
|
+
...body(" "),
|
|
1051
|
+
" }",
|
|
1052
|
+
" }",
|
|
1053
|
+
"}",
|
|
1054
|
+
"",
|
|
1055
|
+
'declare module "@blazetrails/actionpack/testing" {',
|
|
1056
|
+
" interface IntegrationTest<App> {",
|
|
1057
|
+
...body(" "),
|
|
1058
|
+
" }",
|
|
1059
|
+
"}",
|
|
1060
|
+
"",
|
|
1061
|
+
'declare module "@blazetrails/actionpack/system-testing" {',
|
|
1062
|
+
" interface SystemTestCase {",
|
|
1063
|
+
...body(" "),
|
|
1064
|
+
" }",
|
|
1065
|
+
"}",
|
|
1066
|
+
"",
|
|
1067
|
+
].join("\n");
|
|
1068
|
+
}
|
|
1069
|
+
function emitViews(program, host, outViews) {
|
|
1070
|
+
const emitResult = program.emit(undefined, (fileName, ...rest) => {
|
|
1071
|
+
if (path.resolve(fileName).startsWith(outViews + path.sep))
|
|
1072
|
+
host.writeFile(fileName, ...rest);
|
|
1073
|
+
}, undefined, undefined, { before: [tseLookupTransformer] });
|
|
1074
|
+
if (emitResult.emitSkipped) {
|
|
1075
|
+
const diagnostics = [...ts.getPreEmitDiagnostics(program), ...emitResult.diagnostics];
|
|
1076
|
+
const formatted = ts.formatDiagnostics(ts.sortAndDeduplicateDiagnostics(diagnostics), host);
|
|
1077
|
+
throw new Error(`view emit failed:\n${formatted}`);
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
//# sourceMappingURL=build-views.js.map
|