@loozo/angular-launch 0.0.6 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +715 -255
- package/builders/application.js +32 -3
- package/builders/channel-forwarding.d.ts +15 -0
- package/builders/channel-forwarding.js +61 -0
- package/builders/options.d.ts +6 -2
- package/builders/options.js +16 -5
- package/builders/serve.js +198 -140
- package/channel.d.ts +3 -1
- package/channel.js +3 -2
- package/client.d.ts +14 -24
- package/generation/index.d.ts +2 -123
- package/generation/index.js +3 -685
- package/generation/redirects.d.ts +14 -0
- package/generation/redirects.js +43 -0
- package/generation/run.d.ts +168 -0
- package/generation/run.js +659 -0
- package/index.d.ts +2 -0
- package/index.js +1 -0
- package/launch-queries.d.ts +16 -0
- package/launch-queries.js +3 -0
- package/navigation.d.ts +3 -3
- package/navigation.js +1 -1
- package/node/index.d.ts +3 -0
- package/node/index.js +6 -3
- package/node/upgrade-listener-slot.d.ts +1 -0
- package/node/upgrade-listener-slot.js +4 -0
- package/outcomes.d.ts +23 -7
- package/outcomes.js +58 -12
- package/package.json +15 -11
- package/redirect-translation.d.ts +53 -0
- package/redirect-translation.js +141 -0
- package/{generated.js → remote-client.js} +27 -21
- package/route-types.d.ts +130 -0
- package/route-types.js +1 -0
- package/route.d.ts +45 -0
- package/route.js +113 -0
- package/schemas/application.json +19 -3
- package/schemas/serve.json +3 -3
- package/server/application.d.ts +107 -0
- package/server/application.js +108 -0
- package/server/backend.d.ts +25 -13
- package/server/backend.js +39 -24
- package/server/channel-messages.d.ts +1 -1
- package/server/channel-messages.js +1 -1
- package/server/channel-socket.d.ts +1 -1
- package/server/definitions.d.ts +146 -298
- package/server/definitions.js +29 -117
- package/server/dispatch.d.ts +67 -63
- package/server/dispatch.js +121 -61
- package/server/event-stream.d.ts +2 -2
- package/server/event-stream.js +1 -1
- package/server/generated.d.ts +2 -1
- package/server/generated.js +2 -1
- package/server/index.d.ts +3 -2
- package/server/index.js +2 -1
- package/server/outcomes.d.ts +26 -13
- package/server/outcomes.js +43 -16
- package/server/read-cookies.d.ts +19 -0
- package/server/read-cookies.js +39 -0
- package/server/response-effects.d.ts +2 -2
- package/server/stages.d.ts +62 -0
- package/server/stages.js +51 -0
- package/server/upgrade.d.ts +11 -12
- package/server/upgrade.js +13 -14
- package/source-text.d.ts +1 -0
- package/source-text.js +56 -0
- package/stream.d.ts +6 -3
- package/stream.js +8 -6
- package/tanstack-query/README.md +15 -15
- package/tanstack-query/create-queries.d.ts +2 -0
- package/tanstack-query/{generated.js → create-queries.js} +8 -9
- package/tanstack-query/hydration-window.d.ts +11 -0
- package/tanstack-query/hydration-window.js +9 -0
- package/tanstack-query/hydration.d.ts +4 -14
- package/tanstack-query/hydration.js +9 -12
- package/tanstack-query/index.d.ts +1 -1
- package/tanstack-query/queries.d.ts +42 -27
- package/testing/call-procedure.d.ts +154 -0
- package/testing/call-procedure.js +97 -0
- package/testing/index.d.ts +2 -0
- package/testing/index.js +1 -0
- package/generation/context-file.d.ts +0 -2
- package/generation/context-file.js +0 -3
- package/tanstack-query/generated.d.ts +0 -5
- /package/{generated.d.ts → remote-client.d.ts} +0 -0
|
@@ -0,0 +1,659 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import { frameworkFailures } from "../client.js";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { readFile, realpath } from "node:fs/promises";
|
|
5
|
+
import { dirname, resolve, relative, sep } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { discoverLaunchRoutes, emitLaunchRoutes, createValidationProgram, validateRoutes, planOutputs, publish, walk, auditPath, launchMarkers, fail, properties, specifier, CompilerState, AnchorState, validateLocales, } from "@loozo/angular-router/_generation";
|
|
8
|
+
import { emitRedirects } from "./redirects.js";
|
|
9
|
+
function directCall(node, label) {
|
|
10
|
+
if (!ts.isCallExpression(node) || node.typeArguments?.length) {
|
|
11
|
+
fail(node, `${label} requires a direct nongeneric factory call`);
|
|
12
|
+
}
|
|
13
|
+
return node;
|
|
14
|
+
}
|
|
15
|
+
const builderShape = ".remote() requires an arrow function destructuring query, mutation, stream and/or channel, returning a parenthesized object of namespaces";
|
|
16
|
+
const builders = ["query", "mutation", "stream", "channel"];
|
|
17
|
+
// `({ query, mutation }) => ({ ... })`: the builder names it binds and its namespaces.
|
|
18
|
+
function builderCallback(node) {
|
|
19
|
+
if (!ts.isArrowFunction(node) ||
|
|
20
|
+
node.modifiers?.length ||
|
|
21
|
+
node.typeParameters?.length ||
|
|
22
|
+
node.type ||
|
|
23
|
+
node.parameters.length !== 1) {
|
|
24
|
+
fail(node, builderShape);
|
|
25
|
+
}
|
|
26
|
+
const [parameter] = node.parameters;
|
|
27
|
+
if (!ts.isObjectBindingPattern(parameter.name) ||
|
|
28
|
+
parameter.type ||
|
|
29
|
+
parameter.initializer ||
|
|
30
|
+
parameter.dotDotDotToken) {
|
|
31
|
+
fail(parameter, builderShape);
|
|
32
|
+
}
|
|
33
|
+
const bound = new Set();
|
|
34
|
+
for (const element of parameter.name.elements) {
|
|
35
|
+
if (element.propertyName ||
|
|
36
|
+
element.initializer ||
|
|
37
|
+
element.dotDotDotToken ||
|
|
38
|
+
!ts.isIdentifier(element.name) ||
|
|
39
|
+
!builders.includes(element.name.text) ||
|
|
40
|
+
bound.has(element.name.text)) {
|
|
41
|
+
fail(element, ".remote()'s callback may only destructure query, mutation, stream and channel, without renaming");
|
|
42
|
+
}
|
|
43
|
+
bound.add(element.name.text);
|
|
44
|
+
}
|
|
45
|
+
if (!ts.isParenthesizedExpression(node.body)) {
|
|
46
|
+
fail(node.body, builderShape);
|
|
47
|
+
}
|
|
48
|
+
return { bound, namespaces: properties(node.body.expression, "RPC namespaces") };
|
|
49
|
+
}
|
|
50
|
+
function onlyKeys(fields, allowed, node) {
|
|
51
|
+
for (const key of fields.keys()) {
|
|
52
|
+
if (!allowed.includes(key)) {
|
|
53
|
+
fail(node, `Unsupported Launch option: ${key}`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function errorMetadata(node) {
|
|
58
|
+
const result = [];
|
|
59
|
+
if (!node) {
|
|
60
|
+
return result;
|
|
61
|
+
}
|
|
62
|
+
for (const [code, value] of properties(node, "Declared RPC errors")) {
|
|
63
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(code) ||
|
|
64
|
+
code === "__proto__" ||
|
|
65
|
+
Object.hasOwn(frameworkFailures, code)) {
|
|
66
|
+
fail(value, `Invalid or reserved declared RPC error code: ${code}`);
|
|
67
|
+
}
|
|
68
|
+
const fields = properties(value, "Declared RPC error");
|
|
69
|
+
onlyKeys(fields, ["status", "message", "data"], value);
|
|
70
|
+
const status = fields.get("status");
|
|
71
|
+
const message = fields.get("message");
|
|
72
|
+
if (!status ||
|
|
73
|
+
!ts.isNumericLiteral(status) ||
|
|
74
|
+
!Number.isInteger(Number(status.text)) ||
|
|
75
|
+
Number(status.text) < 400 ||
|
|
76
|
+
Number(status.text) > 599 ||
|
|
77
|
+
!message ||
|
|
78
|
+
!ts.isStringLiteral(message) ||
|
|
79
|
+
message.text.length === 0 ||
|
|
80
|
+
!fields.has("data")) {
|
|
81
|
+
fail(value, "Declared errors require literal integer status 400–599, nonempty message and data schema");
|
|
82
|
+
}
|
|
83
|
+
result.push({ code, status: Number(status.text), message: message.text });
|
|
84
|
+
}
|
|
85
|
+
return result;
|
|
86
|
+
}
|
|
87
|
+
function hasNonConcreteSchemaBranch(type) {
|
|
88
|
+
if (type.isUnion()) {
|
|
89
|
+
return type.types.some(hasNonConcreteSchemaBranch);
|
|
90
|
+
}
|
|
91
|
+
return ((type.flags &
|
|
92
|
+
(ts.TypeFlags.Undefined | ts.TypeFlags.Null | ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !==
|
|
93
|
+
0);
|
|
94
|
+
}
|
|
95
|
+
function add(desired, path, text) {
|
|
96
|
+
if (desired.has(path)) {
|
|
97
|
+
throw new Error(`Duplicate desired output path: ${path}`);
|
|
98
|
+
}
|
|
99
|
+
desired.set(path, text);
|
|
100
|
+
}
|
|
101
|
+
function located(node) {
|
|
102
|
+
const source = node.getSourceFile();
|
|
103
|
+
return { file: source.fileName, start: node.getStart(source), end: node.getEnd() };
|
|
104
|
+
}
|
|
105
|
+
// The same node in another program's copy of its file.
|
|
106
|
+
function nodeAt(program, at) {
|
|
107
|
+
const source = program.getSourceFile(at.file);
|
|
108
|
+
let found;
|
|
109
|
+
function visit(node) {
|
|
110
|
+
if (found || node.getStart(source) > at.start || node.getEnd() < at.end) {
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
if (node.getStart(source) === at.start && node.getEnd() === at.end && ts.isExpression(node)) {
|
|
114
|
+
found = node;
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
ts.forEachChild(node, visit);
|
|
118
|
+
}
|
|
119
|
+
visit(source);
|
|
120
|
+
return found;
|
|
121
|
+
}
|
|
122
|
+
function label(workspace, file) {
|
|
123
|
+
return relative(workspace, file).split(sep).join("/");
|
|
124
|
+
}
|
|
125
|
+
// Reads every route's Launch steps: the procedure metadata its copy carries, and the nodes
|
|
126
|
+
// the validation program checks once it exists.
|
|
127
|
+
async function analyze(sources, launchEntry) {
|
|
128
|
+
const analysis = { data: new Map(), schemas: [] };
|
|
129
|
+
const namespaces = new Map();
|
|
130
|
+
for (const declaration of sources.declarations) {
|
|
131
|
+
if (!declaration.extension) {
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if ((await realpath(declaration.extension.entry)) !== launchEntry) {
|
|
135
|
+
fail(declaration.root, "Route uses a route extension that isn't Launch's defineRoute");
|
|
136
|
+
}
|
|
137
|
+
for (const step of declaration.steps) {
|
|
138
|
+
if (step.name !== "remote") {
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
const own = {};
|
|
142
|
+
const { bound, namespaces: declared } = builderCallback(step.args[0]);
|
|
143
|
+
for (const [namespace, value] of declared) {
|
|
144
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(namespace)) {
|
|
145
|
+
fail(value, "RPC namespaces must be identifier names");
|
|
146
|
+
}
|
|
147
|
+
if (namespace === "__proto__") {
|
|
148
|
+
fail(value, "RPC namespace '__proto__' is reserved");
|
|
149
|
+
}
|
|
150
|
+
const previous = namespaces.get(namespace);
|
|
151
|
+
if (previous) {
|
|
152
|
+
fail(value, `Duplicate RPC namespace: ${namespace}; also declared in ${previous.file}`);
|
|
153
|
+
}
|
|
154
|
+
namespaces.set(namespace, declaration);
|
|
155
|
+
const methods = [];
|
|
156
|
+
for (const [name, entry] of properties(value, "RPC procedures")) {
|
|
157
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
|
|
158
|
+
fail(entry, "RPC methods must be identifier names");
|
|
159
|
+
}
|
|
160
|
+
if (name === "__proto__") {
|
|
161
|
+
fail(entry, "RPC procedure '__proto__' is reserved");
|
|
162
|
+
}
|
|
163
|
+
const procedure = directCall(entry, "query/mutation/stream/channel");
|
|
164
|
+
// The callback's own binding: its body is an object literal, so nothing can shadow it.
|
|
165
|
+
if (!ts.isIdentifier(procedure.expression) || !bound.has(procedure.expression.text)) {
|
|
166
|
+
fail(procedure, "Procedure must directly call the callback's query, mutation, stream or channel");
|
|
167
|
+
}
|
|
168
|
+
const kind = procedure.expression.text;
|
|
169
|
+
if (procedure.arguments.length !== 1) {
|
|
170
|
+
fail(procedure, `${kind} requires one inline options object`);
|
|
171
|
+
}
|
|
172
|
+
const fields = properties(procedure.arguments[0], "Procedure options");
|
|
173
|
+
if (kind === "channel") {
|
|
174
|
+
onlyKeys(fields, ["handler", "input", "message", "use", "errors"], procedure);
|
|
175
|
+
if (!fields.has("message")) {
|
|
176
|
+
fail(procedure, "channel requires message");
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
onlyKeys(fields, ["handler", "input", "use", "errors"], procedure);
|
|
181
|
+
}
|
|
182
|
+
if (!fields.has("handler")) {
|
|
183
|
+
fail(procedure, `${kind} requires handler`);
|
|
184
|
+
}
|
|
185
|
+
const input = fields.get("input");
|
|
186
|
+
const message = fields.get("message");
|
|
187
|
+
const errors = fields.get("errors");
|
|
188
|
+
if (input) {
|
|
189
|
+
analysis.schemas.push({
|
|
190
|
+
node: located(input),
|
|
191
|
+
message: "Explicit query input must have a concrete Standard Schema type (also required for mutations)",
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
if (message) {
|
|
195
|
+
analysis.schemas.push({
|
|
196
|
+
node: located(message),
|
|
197
|
+
message: "A channel's message must have a concrete Standard Schema type",
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
if (errors) {
|
|
201
|
+
for (const error of properties(errors, "Declared RPC errors").values()) {
|
|
202
|
+
const data = properties(error, "Declared RPC error").get("data");
|
|
203
|
+
if (data) {
|
|
204
|
+
analysis.schemas.push({
|
|
205
|
+
node: located(data),
|
|
206
|
+
message: "Declared error data must have a concrete Standard Schema type",
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
methods.push({ name, input: input !== undefined, kind, errors: errorMetadata(errors) });
|
|
212
|
+
}
|
|
213
|
+
own[namespace] = { methods };
|
|
214
|
+
}
|
|
215
|
+
analysis.data.set(declaration, { remote: own });
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return analysis;
|
|
219
|
+
}
|
|
220
|
+
// server.generated.ts: every authored route with a server step, bound into the application.
|
|
221
|
+
function emitServer(sources, desired, workspace, appId, translateSegments) {
|
|
222
|
+
const payloads = [];
|
|
223
|
+
const file = resolve(sources.output, "server.generated.ts");
|
|
224
|
+
const lines = [launchMarkers["server.generated.ts"]];
|
|
225
|
+
// First, so the host has a source-text $localize before any destination copy evaluates.
|
|
226
|
+
if (translateSegments) {
|
|
227
|
+
lines.push(`import '@loozo/angular-launch/_source-text';`);
|
|
228
|
+
}
|
|
229
|
+
lines.push(`import type { HandleOptions } from '@loozo/angular-launch/server';`, `import { bindApplication, createRequestScope as scopeFor, handleChannelUpgrade, handleRpc, provideLaunchServer } from '@loozo/angular-launch/_server';`);
|
|
230
|
+
const routes = [];
|
|
231
|
+
// By code unit, so the order doesn't depend on the machine's locale.
|
|
232
|
+
const declarations = [...sources.declarations].sort((a, b) => {
|
|
233
|
+
if (a.id < b.id) {
|
|
234
|
+
return -1;
|
|
235
|
+
}
|
|
236
|
+
return Number(a.id > b.id);
|
|
237
|
+
});
|
|
238
|
+
for (const declaration of declarations) {
|
|
239
|
+
if (!declaration.steps.some((step) => step.serverOnly)) {
|
|
240
|
+
continue;
|
|
241
|
+
}
|
|
242
|
+
const local = `route${routes.length}`;
|
|
243
|
+
payloads.push({ from: file, target: declaration.file, local });
|
|
244
|
+
lines.push(`import ${local} from ${JSON.stringify(specifier(file, declaration.file))};`);
|
|
245
|
+
routes.push(`[${local}, ${JSON.stringify(label(workspace, declaration.file))}]`);
|
|
246
|
+
}
|
|
247
|
+
const binding = translateSegments ? ", { translateSegments: true }" : "";
|
|
248
|
+
lines.push(`const application = bindApplication(${JSON.stringify(appId)}, [${routes.join(", ")}]${binding});`, `export const createRequestScope = (request: Request) => scopeFor(application, request);`, `export const handleRequest = (request: Request, options: HandleOptions) => handleRpc(application, request, options);`, `export const handleUpgrade = (request: Request, options: HandleOptions) => handleChannelUpgrade(application, request, options);`, `export const provideServer = () => provideLaunchServer(application);`, "");
|
|
249
|
+
add(desired, file, lines.join("\n"));
|
|
250
|
+
return payloads;
|
|
251
|
+
}
|
|
252
|
+
function unalias(checker, symbol) {
|
|
253
|
+
if (symbol && symbol.flags & ts.SymbolFlags.Alias) {
|
|
254
|
+
return checker.getAliasedSymbol(symbol);
|
|
255
|
+
}
|
|
256
|
+
return symbol;
|
|
257
|
+
}
|
|
258
|
+
async function validatePayloadImports(validation, payloads) {
|
|
259
|
+
const { program, host } = validation;
|
|
260
|
+
const checker = program.getTypeChecker();
|
|
261
|
+
for (const payload of payloads) {
|
|
262
|
+
const source = program.getSourceFile(payload.from);
|
|
263
|
+
const statement = source.statements.find((node) => ts.isImportDeclaration(node) && node.importClause?.name?.text === payload.local);
|
|
264
|
+
const name = statement.moduleSpecifier;
|
|
265
|
+
const resolved = ts.resolveModuleName(name.text, source.fileName, program.getCompilerOptions(), host, undefined, undefined, program.getModeForUsageLocation(source, name)).resolvedModule;
|
|
266
|
+
if (!resolved ||
|
|
267
|
+
(await realpath(resolved.resolvedFileName)) !== (await realpath(payload.target))) {
|
|
268
|
+
fail(statement, `Generated payload import must resolve to its discovered declaration: ${payload.target}`);
|
|
269
|
+
}
|
|
270
|
+
const target = program.getSourceFile(payload.target);
|
|
271
|
+
const module = checker.getSymbolAtLocation(target);
|
|
272
|
+
const expected = unalias(checker, checker.getExportsOfModule(module).find((symbol) => symbol.name === "default"));
|
|
273
|
+
const actual = unalias(checker, checker.getSymbolAtLocation(statement.importClause.name));
|
|
274
|
+
if (!expected?.declarations?.length ||
|
|
275
|
+
actual !== expected ||
|
|
276
|
+
expected.declarations.some((node) => node.getSourceFile() !== target)) {
|
|
277
|
+
fail(statement, "Generated payload import does not bind the discovered default declaration");
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
// What only the validation program's checker can tell: schema concreteness.
|
|
282
|
+
function checkLaunchTypes(validation, analysis) {
|
|
283
|
+
const { program } = validation;
|
|
284
|
+
const checker = program.getTypeChecker();
|
|
285
|
+
for (const { node, message } of analysis.schemas) {
|
|
286
|
+
const expression = nodeAt(program, node);
|
|
287
|
+
if (hasNonConcreteSchemaBranch(checker.getTypeAtLocation(expression))) {
|
|
288
|
+
fail(expression, message);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
function moduleReferences(source) {
|
|
293
|
+
const references = [];
|
|
294
|
+
function visit(node) {
|
|
295
|
+
let specifier;
|
|
296
|
+
if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
|
|
297
|
+
specifier = node.moduleSpecifier;
|
|
298
|
+
}
|
|
299
|
+
else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
|
|
300
|
+
specifier = node.arguments[0];
|
|
301
|
+
}
|
|
302
|
+
else if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument)) {
|
|
303
|
+
specifier = node.argument.literal;
|
|
304
|
+
}
|
|
305
|
+
else if (ts.isImportEqualsDeclaration(node) &&
|
|
306
|
+
ts.isExternalModuleReference(node.moduleReference)) {
|
|
307
|
+
specifier = node.moduleReference.expression;
|
|
308
|
+
}
|
|
309
|
+
if (specifier && ts.isStringLiteralLike(specifier)) {
|
|
310
|
+
references.push(specifier);
|
|
311
|
+
}
|
|
312
|
+
ts.forEachChild(node, visit);
|
|
313
|
+
}
|
|
314
|
+
visit(source);
|
|
315
|
+
return references;
|
|
316
|
+
}
|
|
317
|
+
const translationProvider = "provideRedirectTranslation";
|
|
318
|
+
// Whether `specifier` is a value import declaration that names the translation provider.
|
|
319
|
+
function importsProvider(specifier) {
|
|
320
|
+
const statement = specifier.parent;
|
|
321
|
+
if (!ts.isImportDeclaration(statement) || statement.importClause?.isTypeOnly) {
|
|
322
|
+
return false;
|
|
323
|
+
}
|
|
324
|
+
const bindings = statement.importClause?.namedBindings;
|
|
325
|
+
if (!bindings || !ts.isNamedImports(bindings)) {
|
|
326
|
+
return false;
|
|
327
|
+
}
|
|
328
|
+
return bindings.elements.some((element) => !element.isTypeOnly && (element.propertyName ?? element.name).text === translationProvider);
|
|
329
|
+
}
|
|
330
|
+
// Check generation's own domain before publication: generated outputs, discovered
|
|
331
|
+
// route/Launch declarations and application TypeScript files that directly import
|
|
332
|
+
// a generated output (import/export-from, import(), import types, import =). Other
|
|
333
|
+
// application files and dependencies are left to the application's own build. With
|
|
334
|
+
// `redirects`, some application file must import its provider: the check proves the import,
|
|
335
|
+
// not that both applications install it.
|
|
336
|
+
function checkGeneratedDomain(sources, validation, generated, redirects) {
|
|
337
|
+
const { program, host } = validation;
|
|
338
|
+
const options = program.getCompilerOptions();
|
|
339
|
+
const selected = new Set(generated.keys());
|
|
340
|
+
for (const declaration of sources.declarations) {
|
|
341
|
+
selected.add(declaration.file);
|
|
342
|
+
}
|
|
343
|
+
const cache = ts.createModuleResolutionCache(program.getCurrentDirectory(), (file) => host.getCanonicalFileName(file), options);
|
|
344
|
+
let provided = false;
|
|
345
|
+
for (const source of program.getSourceFiles()) {
|
|
346
|
+
const file = resolve(source.fileName);
|
|
347
|
+
if (selected.has(file) ||
|
|
348
|
+
source.fileName.includes("/node_modules/") ||
|
|
349
|
+
program.isSourceFileFromExternalLibrary(source) ||
|
|
350
|
+
program.isSourceFileDefaultLibrary(source)) {
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
for (const specifier of moduleReferences(source)) {
|
|
354
|
+
const resolved = ts.resolveModuleName(specifier.text, source.fileName, options, host, cache, undefined, program.getModeForUsageLocation(source, specifier)).resolvedModule;
|
|
355
|
+
if (!resolved) {
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
const target = resolve(resolved.resolvedFileName);
|
|
359
|
+
if (generated.has(target)) {
|
|
360
|
+
selected.add(file);
|
|
361
|
+
if (target === redirects && importsProvider(specifier)) {
|
|
362
|
+
provided = true;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
if (redirects !== undefined && !provided) {
|
|
368
|
+
throw new Error(`translateSegments needs ${translationProvider}() from ${label(dirname(sources.configFile), redirects)} in your application config's providers, so RPC redirects reach the page's language`);
|
|
369
|
+
}
|
|
370
|
+
const declarationEmit = options.declaration || options.composite;
|
|
371
|
+
const diagnostics = [...program.getOptionsDiagnostics()];
|
|
372
|
+
for (const file of selected) {
|
|
373
|
+
const source = program.getSourceFile(file);
|
|
374
|
+
diagnostics.push(...program.getSyntacticDiagnostics(source), ...program.getSemanticDiagnostics(source));
|
|
375
|
+
if (declarationEmit && !source.isDeclarationFile) {
|
|
376
|
+
diagnostics.push(...program.getDeclarationDiagnostics(source));
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
// Global diagnostics can surface while checking the selected files.
|
|
380
|
+
diagnostics.push(...program.getGlobalDiagnostics());
|
|
381
|
+
const unique = ts.sortAndDeduplicateDiagnostics(diagnostics);
|
|
382
|
+
if (unique.length > 0) {
|
|
383
|
+
throw new Error(ts.formatDiagnosticsWithColorAndContext(unique, {
|
|
384
|
+
getCanonicalFileName: (name) => name,
|
|
385
|
+
getCurrentDirectory: () => dirname(sources.configFile),
|
|
386
|
+
getNewLine: () => "\n",
|
|
387
|
+
}));
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Generation for the builders: {@link generate}, resolving to each non-source locale's text for
|
|
392
|
+
* every route word when `translateSegments` is on, and undefined otherwise.
|
|
393
|
+
*/
|
|
394
|
+
export async function runGeneration(workspace, options, stopped, compiler) {
|
|
395
|
+
// The built package root (dist/ in the workspace, the tarball root when installed).
|
|
396
|
+
const root = fileURLToPath(new URL("../", import.meta.url));
|
|
397
|
+
const manifest = JSON.parse(await readFile(resolve(root, "package.json"), "utf8"));
|
|
398
|
+
const launchEntry = await realpath(resolve(root, manifest.exports["."].types));
|
|
399
|
+
const application = await realpath(workspace);
|
|
400
|
+
function requireInside(file) {
|
|
401
|
+
const suffix = relative(application, file);
|
|
402
|
+
if (suffix === ".." || suffix.startsWith(`..${sep}`) || resolve(application, suffix) !== file) {
|
|
403
|
+
throw new Error(`Launch source/output escapes application workspace: ${file}`);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
const config = resolve(application, options.tsconfig);
|
|
407
|
+
requireInside(config);
|
|
408
|
+
requireInside(resolve(application, options.outDirectory));
|
|
409
|
+
for (const directory of options.scanDirectories) {
|
|
410
|
+
requireInside(resolve(dirname(config), directory));
|
|
411
|
+
}
|
|
412
|
+
const sources = await discoverLaunchRoutes(application, options, compiler?.discovery);
|
|
413
|
+
for (const file of sources.parsed.fileNames) {
|
|
414
|
+
requireInside(file);
|
|
415
|
+
}
|
|
416
|
+
// TS 6 defaults strict checking on, but each explicit false overrides it.
|
|
417
|
+
// Match its getStrictOptionValue rule without relying on an untyped internal API.
|
|
418
|
+
for (const flag of [
|
|
419
|
+
"noImplicitAny",
|
|
420
|
+
"strictNullChecks",
|
|
421
|
+
"strictFunctionTypes",
|
|
422
|
+
"strictBindCallApply",
|
|
423
|
+
"strictPropertyInitialization",
|
|
424
|
+
"strictBuiltinIteratorReturn",
|
|
425
|
+
"noImplicitThis",
|
|
426
|
+
"useUnknownInCatchVariables",
|
|
427
|
+
]) {
|
|
428
|
+
const enabled = sources.parsed.options[flag] ?? sources.parsed.options.strict ?? true;
|
|
429
|
+
if (!enabled) {
|
|
430
|
+
throw new Error(`Launch generation requires effective strict TypeScript checking: ${flag} is disabled`);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
if (sources.parsed.options.noCheck) {
|
|
434
|
+
throw new Error("Launch generation requires effective strict TypeScript checking: noCheck must be false");
|
|
435
|
+
}
|
|
436
|
+
const translateSegments = options.translateSegments === true;
|
|
437
|
+
let words;
|
|
438
|
+
if (translateSegments) {
|
|
439
|
+
if (!options.localization) {
|
|
440
|
+
throw new Error("translateSegments needs the build's localization");
|
|
441
|
+
}
|
|
442
|
+
words = await validateLocales(sources, options.localization);
|
|
443
|
+
}
|
|
444
|
+
const analysis = await analyze(sources, launchEntry);
|
|
445
|
+
const tanstackQuery = options.tanstackQuery === true;
|
|
446
|
+
const copies = {
|
|
447
|
+
data: analysis.data,
|
|
448
|
+
types: [
|
|
449
|
+
{ name: "Remote", type: "RemoteOf", from: "@loozo/angular-launch" },
|
|
450
|
+
{ name: "Context", type: "ContextOf", from: "@loozo/angular-launch" },
|
|
451
|
+
...(tanstackQuery
|
|
452
|
+
? [{ name: "Queries", type: "QueriesOf", from: "@loozo/angular-launch/tanstack-query" }]
|
|
453
|
+
: []),
|
|
454
|
+
],
|
|
455
|
+
members: [
|
|
456
|
+
{ member: "remote", type: "Remote" },
|
|
457
|
+
...(tanstackQuery ? [{ member: "queries", type: "Queries" }] : []),
|
|
458
|
+
],
|
|
459
|
+
};
|
|
460
|
+
const desired = emitLaunchRoutes(sources, copies, { translateSegments });
|
|
461
|
+
const redirects = resolve(sources.output, "redirects.generated.ts");
|
|
462
|
+
if (translateSegments) {
|
|
463
|
+
add(desired, redirects, emitRedirects(sources));
|
|
464
|
+
}
|
|
465
|
+
const appManifest = JSON.parse(await readFile(resolve(application, "package.json"), "utf8"));
|
|
466
|
+
if (typeof appManifest.name !== "string" || appManifest.name.length === 0) {
|
|
467
|
+
throw new Error("Launch application package.json requires a name for generated app identity");
|
|
468
|
+
}
|
|
469
|
+
// Stable across route edits: the application is its package, tsconfig and output.
|
|
470
|
+
const appId = createHash("sha256")
|
|
471
|
+
.update("launch-app-v2\0")
|
|
472
|
+
.update(appManifest.name)
|
|
473
|
+
.update("\0")
|
|
474
|
+
.update(label(application, sources.configFile))
|
|
475
|
+
.update("\0")
|
|
476
|
+
.update(label(application, sources.output))
|
|
477
|
+
.digest("hex");
|
|
478
|
+
const payloads = emitServer(sources, desired, application, appId, translateSegments);
|
|
479
|
+
await auditPath(sources.output);
|
|
480
|
+
const outputInventory = await walk(sources.output);
|
|
481
|
+
// context.generated.d.ts is a retired output. The router's retired marker for it is what
|
|
482
|
+
// finds a marked leftover in the output directory and deletes it; listing it here keeps its
|
|
483
|
+
// location in the plan's set of owned outputs. redirects.generated.ts is listed so turning
|
|
484
|
+
// translateSegments off removes it as stale.
|
|
485
|
+
const globals = [
|
|
486
|
+
"routes.generated.ts",
|
|
487
|
+
"server.generated.ts",
|
|
488
|
+
"redirects.generated.ts",
|
|
489
|
+
"context.generated.d.ts",
|
|
490
|
+
].map((name) => resolve(sources.output, name));
|
|
491
|
+
const plan = await planOutputs(desired, [...sources.encountered, ...outputInventory], globals, "router-and-launch");
|
|
492
|
+
const validation = createValidationProgram(sources, desired, plan.stale, compiler?.overlay);
|
|
493
|
+
await validateRoutes(sources, desired, validation, compiler?.routerAnchor);
|
|
494
|
+
await validatePayloadImports(validation, payloads);
|
|
495
|
+
checkLaunchTypes(validation, analysis);
|
|
496
|
+
checkGeneratedDomain(sources, validation, desired, translateSegments ? redirects : undefined);
|
|
497
|
+
publish(plan, options.check === true, stopped, new Map(), new Set());
|
|
498
|
+
return words;
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* Generates the router's and Launch's files for an application, or checks them.
|
|
502
|
+
*
|
|
503
|
+
* @remarks
|
|
504
|
+
* Node-only. Generation reads your sources without running them. It writes the router's
|
|
505
|
+
* files, with each route copy carrying its route's `.remote()` metadata and the `Remote`,
|
|
506
|
+
* `Context` and, with `tanstackQuery`, `Queries` types, and `server.generated.ts` in the
|
|
507
|
+
* output directory, which binds every route with a server step. With `translateSegments`,
|
|
508
|
+
* every locale's translated route tree is validated first, static segments become `$localize`
|
|
509
|
+
* messages, `server.generated.ts` first imports Launch's source-text `$localize` for the
|
|
510
|
+
* unlocalized host, and `redirects.generated.ts` holds the word table an application file must
|
|
511
|
+
* import `provideRedirectTranslation()` from. It deletes a marked
|
|
512
|
+
* `rpc.generated.ts` or `context.generated.d.ts` an earlier version wrote. Run it before
|
|
513
|
+
* the Angular build.
|
|
514
|
+
*
|
|
515
|
+
* Everything is validated, including a type check of the generated files with
|
|
516
|
+
* `skipLibCheck: false`, before anything is written, so a failed run changes nothing.
|
|
517
|
+
* Files are then written one at a time without rollback; a write error partway through
|
|
518
|
+
* can leave some files updated, which the next successful run repairs. Generation only
|
|
519
|
+
* replaces or removes files carrying its ownership marker, and removes stale ones.
|
|
520
|
+
*
|
|
521
|
+
* @example
|
|
522
|
+
* ```js
|
|
523
|
+
* import { generate } from "@loozo/angular-launch/generation";
|
|
524
|
+
*
|
|
525
|
+
* await generate(import.meta.dirname, {
|
|
526
|
+
* tsconfig: "tsconfig.app.json",
|
|
527
|
+
* scanDirectories: ["src/routes"],
|
|
528
|
+
* outDirectory: "generated",
|
|
529
|
+
* check: process.argv.includes("--check"),
|
|
530
|
+
* });
|
|
531
|
+
* ```
|
|
532
|
+
*
|
|
533
|
+
* @param workspace - The absolute path of the application directory, which contains
|
|
534
|
+
* its `package.json`. The tsconfig, scanned directory, sources and output directory
|
|
535
|
+
* must all be inside it.
|
|
536
|
+
* @param options - The generation options.
|
|
537
|
+
* @param stopped - Called once just before writing; returning `true` skips writing and
|
|
538
|
+
* resolves. Defaults to never stopping.
|
|
539
|
+
* @returns A promise that resolves when generation finishes.
|
|
540
|
+
* @throws Rejects when a path escapes the workspace, the tsconfig disables strict
|
|
541
|
+
* checking or enables `noCheck`, the application's `package.json` has no `name`, the
|
|
542
|
+
* sources or generated files fail validation, a file to replace lacks the ownership
|
|
543
|
+
* marker, or, with `check`, a generated file is out of date; with `translateSegments`, also
|
|
544
|
+
* when `localization` is missing, the build lacks the `@angular/localize/init` polyfill, a
|
|
545
|
+
* locale's catalog fails the router's checks, or no application file imports
|
|
546
|
+
* `provideRedirectTranslation`.
|
|
547
|
+
*/
|
|
548
|
+
export async function generate(workspace, options, stopped = () => false) {
|
|
549
|
+
await runGeneration(workspace, options, stopped);
|
|
550
|
+
}
|
|
551
|
+
/**
|
|
552
|
+
* Creates a generation session that reuses compiler work between sequential calls.
|
|
553
|
+
*
|
|
554
|
+
* @remarks
|
|
555
|
+
* Node-only. For long-running tools that regenerate repeatedly, such as after file
|
|
556
|
+
* changes. A session doesn't watch files; you decide when to call `generate`. Edits
|
|
557
|
+
* inside the application are picked up by the next call. Create a new session after
|
|
558
|
+
* moving the application directory or changing dependencies. Don't run two sessions or
|
|
559
|
+
* generators against the same output at once.
|
|
560
|
+
*
|
|
561
|
+
* @example
|
|
562
|
+
* ```js
|
|
563
|
+
* const session = createGenerationSession(workspace, {
|
|
564
|
+
* tsconfig: "tsconfig.app.json",
|
|
565
|
+
* scanDirectories: ["src/routes"],
|
|
566
|
+
* outDirectory: "generated",
|
|
567
|
+
* });
|
|
568
|
+
*
|
|
569
|
+
* try {
|
|
570
|
+
* await session.generate();
|
|
571
|
+
* await session.generate({ check: true });
|
|
572
|
+
* } finally {
|
|
573
|
+
* await session.dispose();
|
|
574
|
+
* }
|
|
575
|
+
* ```
|
|
576
|
+
*
|
|
577
|
+
* @param workspace - The absolute path of the application directory, as for
|
|
578
|
+
* {@link generate}.
|
|
579
|
+
* @param options - The generation options, fixed for the session's lifetime; `check` is
|
|
580
|
+
* passed per call instead.
|
|
581
|
+
* @returns The session. Dispose it when done.
|
|
582
|
+
*/
|
|
583
|
+
export function createGenerationSession(workspace, options) {
|
|
584
|
+
const session = createBuilderSession(workspace, options);
|
|
585
|
+
return {
|
|
586
|
+
async generate(options, stopped) {
|
|
587
|
+
await session.generate(options, stopped);
|
|
588
|
+
},
|
|
589
|
+
dispose: () => session.dispose(),
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
/** {@link createGenerationSession} for the builders, whose calls resolve to the locale words. */
|
|
593
|
+
export function createBuilderSession(workspace, { tsconfig, scanDirectories, outDirectory, tanstackQuery, translateSegments, localization, }) {
|
|
594
|
+
const application = resolve(workspace);
|
|
595
|
+
const fixed = {
|
|
596
|
+
tsconfig,
|
|
597
|
+
scanDirectories: [...scanDirectories],
|
|
598
|
+
outDirectory,
|
|
599
|
+
tanstackQuery,
|
|
600
|
+
translateSegments,
|
|
601
|
+
localization,
|
|
602
|
+
};
|
|
603
|
+
const compiler = {
|
|
604
|
+
discovery: new CompilerState(),
|
|
605
|
+
overlay: new CompilerState(),
|
|
606
|
+
routerAnchor: new AnchorState(),
|
|
607
|
+
};
|
|
608
|
+
let closed = false;
|
|
609
|
+
let active;
|
|
610
|
+
function clear() {
|
|
611
|
+
for (const slot of Object.values(compiler)) {
|
|
612
|
+
slot.clear();
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
const session = {
|
|
616
|
+
async generate({ check = false } = {}, stopped = () => false) {
|
|
617
|
+
if (closed) {
|
|
618
|
+
throw new Error("Generation session is disposed");
|
|
619
|
+
}
|
|
620
|
+
if (active) {
|
|
621
|
+
throw new Error("Generation session requires sequential calls");
|
|
622
|
+
}
|
|
623
|
+
let interrupted = false;
|
|
624
|
+
function isStopped() {
|
|
625
|
+
if (closed) {
|
|
626
|
+
interrupted = true;
|
|
627
|
+
return true;
|
|
628
|
+
}
|
|
629
|
+
const requested = stopped();
|
|
630
|
+
if (closed || requested) {
|
|
631
|
+
interrupted = true;
|
|
632
|
+
return true;
|
|
633
|
+
}
|
|
634
|
+
return false;
|
|
635
|
+
}
|
|
636
|
+
const work = runGeneration(application, { ...fixed, check }, isStopped, compiler);
|
|
637
|
+
active = work;
|
|
638
|
+
try {
|
|
639
|
+
return await work;
|
|
640
|
+
}
|
|
641
|
+
catch (error) {
|
|
642
|
+
clear();
|
|
643
|
+
throw error;
|
|
644
|
+
}
|
|
645
|
+
finally {
|
|
646
|
+
active = undefined;
|
|
647
|
+
if (closed || interrupted) {
|
|
648
|
+
clear();
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
},
|
|
652
|
+
async dispose() {
|
|
653
|
+
closed = true;
|
|
654
|
+
await active?.catch(() => undefined);
|
|
655
|
+
clear();
|
|
656
|
+
},
|
|
657
|
+
};
|
|
658
|
+
return session;
|
|
659
|
+
}
|
package/index.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
export { defineRoute } from "./route.js";
|
|
2
|
+
export type { ChainContext, ChainNamespaces, ContextOf, ContextStep, LaunchInput, LaunchSpec, LaunchStep, RemoteOf, RemoteStep, UseStep, } from "./route-types.js";
|
|
1
3
|
export { RpcError, frameworkFailures } from "./client.js";
|
|
2
4
|
export type { CallOptions, ChannelCallOptions, MutationCallOptions, StreamCallOptions, Client, ClientProcedure, ClientRpcError, FrameworkCode, } from "./client.js";
|
|
3
5
|
export type { Channel } from "./channel.js";
|
package/index.js
CHANGED