@nimiplatform/app-tools 0.6.2 → 0.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +106 -10
  2. package/bin/nimi-app.mjs +6 -12
  3. package/lib/app-dependency-combinations.mjs +62 -0
  4. package/lib/app-doctor-update.mjs +18 -16
  5. package/lib/app-info.mjs +25 -2
  6. package/lib/app-lifecycle-guidance.mjs +4 -2
  7. package/lib/app-pack.mjs +5 -2
  8. package/lib/app-project-lifecycle.mjs +208 -50
  9. package/lib/app-safety-profile.mjs +204 -0
  10. package/lib/app-scaffold-capabilities.mjs +8 -0
  11. package/lib/app-scaffold-profiles.mjs +44 -4
  12. package/lib/app-scaffold.mjs +2 -1
  13. package/lib/canonical-capability-ids.generated.mjs +21 -0
  14. package/lib/index.mjs +0 -4
  15. package/package.json +7 -12
  16. package/scripts/dev-shell.mjs +20 -2
  17. package/skills/nimi-app-lifecycle/SKILL.md +7 -3
  18. package/skills/nimi-app-lifecycle/references/acceptance.md +6 -0
  19. package/skills/nimi-app-lifecycle/references/adapt.md +46 -1
  20. package/skills/nimi-app-lifecycle/references/audit.md +55 -0
  21. package/skills/nimi-app-lifecycle/references/platform-gaps.md +15 -0
  22. package/skills/nimi-app-lifecycle/references/release.md +3 -1
  23. package/skills/nimi-app-lifecycle/references/safety-declaration.md +37 -0
  24. package/skills/nimi-app-lifecycle/references/upgrade-platform.md +2 -2
  25. package/templates/app-source/src/studio-modules/studio-voice/parameters.ts +8 -10
  26. package/templates/default-starter/AGENTS.md +4 -2
  27. package/templates/default-starter/README.md +1 -1
  28. package/lib/simulator-conformance-ast.mjs +0 -498
  29. package/lib/simulator-conformance-css.mjs +0 -116
  30. package/lib/simulator-conformance-graph.mjs +0 -757
  31. package/lib/simulator-conformance.d.mts +0 -14
  32. package/lib/simulator-conformance.mjs +0 -203
  33. package/lib/simulator-css-profile.d.mts +0 -27
  34. package/lib/simulator-css-profile.mjs +0 -531
  35. package/lib/simulator-kit-export-resolution.mjs +0 -70
  36. package/lib/simulator-manifest.mjs +0 -334
@@ -1,757 +0,0 @@
1
- import { readFileSync, realpathSync, statSync } from 'node:fs';
2
- import path from 'node:path';
3
- import ts from 'typescript';
4
- import { SimulatorConformanceError } from './simulator-manifest.mjs';
5
-
6
- const SOURCE_EXTENSIONS = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs', '.css'];
7
- const STATIC_ASSET_EXTENSIONS = new Set(['.json', '.png']);
8
-
9
- export function isSimulatorStaticAssetPath(filePath) {
10
- return STATIC_ASSET_EXTENSIONS.has(path.extname(filePath).toLowerCase());
11
- }
12
- const FORBIDDEN_IMPORT_PATTERNS = [
13
- ['SIM_IMPORT_RUNTIME_PRIVATE', /(?:^|\/)runtime\/internal(?:\/|$)/],
14
- ['SIM_IMPORT_DESKTOP_PRIVATE', /(?:^|\/)apps\/desktop(?:\/|$)/],
15
- ['SIM_IMPORT_TAURI', /^@tauri-apps\//],
16
- ['SIM_IMPORT_ELECTRON', /^electron(?:\/|$)/],
17
- ['SIM_FACTORY_HOST_DISCRIMINATOR', /^@nimiplatform\/kit\/core\/shell-mode$/],
18
- ['SIM_IMPORT_NODE_BUILTIN', /^(?:node:|fs(?:\/|$)|net(?:\/|$)|tls(?:\/|$)|child_process$|worker_threads$)/],
19
- ];
20
- const FORBIDDEN_CALLS = new Map([
21
- ['createBrowserHistory', 'SIM_FACTORY_BROWSER_HISTORY'],
22
- ['createBrowserRouter', 'SIM_FACTORY_BROWSER_HISTORY'],
23
- ['createHashRouter', 'SIM_FACTORY_BROWSER_HISTORY'],
24
- ['createRoot', 'SIM_RENDERER_SELF_MOUNT'],
25
- ]);
26
- const FACTORY_FORBIDDEN_BINDINGS = new Set([
27
- 'environment',
28
- 'hostKind',
29
- 'isSimulator',
30
- 'providerIdentity',
31
- 'rawEpoch',
32
- 'rawInstanceId',
33
- 'rawModuleId',
34
- 'shellMode',
35
- ]);
36
- const MODULE_MUTATING_METHODS = new Set([
37
- 'add',
38
- 'clear',
39
- 'copyWithin',
40
- 'delete',
41
- 'fill',
42
- 'pop',
43
- 'push',
44
- 'reverse',
45
- 'set',
46
- 'shift',
47
- 'sort',
48
- 'splice',
49
- 'unshift',
50
- ]);
51
- const MODULE_RESOURCE_FACTORY_PATTERN = /^(?:build|configure|create|make|open)[A-Za-z0-9_$]*(?:Cache|Channel|Client|History|I18n|Instance|Loader|Pool|QueryClient|Registry|Router|Session|Store|Transport)$/u;
52
- const MODULE_SCOPE_IMMUTABLE_CONSTRUCTORS = new Set(['Intl.DateTimeFormat']);
53
- const IMPORT_META_GLOB_METHODS = new Set(['glob', 'globEager']);
54
- const ADAPTER_FORBIDDEN_RUNTIME_IMPORTS = [
55
- /^react$/u,
56
- /^react\//u,
57
- /^react-dom$/u,
58
- /^react-dom\//u,
59
- ];
60
- const ADAPTER_DOM_METHODS = new Set([
61
- 'append',
62
- 'appendChild',
63
- 'before',
64
- 'insertAdjacentElement',
65
- 'insertAdjacentHTML',
66
- 'insertAdjacentText',
67
- 'insertBefore',
68
- 'prepend',
69
- 'querySelector',
70
- 'querySelectorAll',
71
- 'remove',
72
- 'removeAttribute',
73
- 'removeChild',
74
- 'replaceChild',
75
- 'replaceChildren',
76
- 'setAttribute',
77
- 'toggleAttribute',
78
- ]);
79
- const ADAPTER_DOM_MUTABLE_PROPERTIES = new Set([
80
- 'className',
81
- 'innerHTML',
82
- 'inert',
83
- 'outerHTML',
84
- 'textContent',
85
- ]);
86
-
87
- function fail(code, message, fieldPath = '') {
88
- throw new SimulatorConformanceError(code, message, fieldPath);
89
- }
90
-
91
- export function canonicalRelative(rootDir, absolutePath) {
92
- return path.relative(rootDir, absolutePath).split(path.sep).join('/');
93
- }
94
-
95
- export function assertContainedFile(rootDir, relativePath, fieldPath) {
96
- const absoluteRoot = realpathSync(rootDir);
97
- const absolutePath = path.resolve(absoluteRoot, ...relativePath.split('/'));
98
- if (!absolutePath.startsWith(`${absoluteRoot}${path.sep}`)) {
99
- fail('SIM_SOURCE_PATH_ESCAPE', 'path escapes source root', fieldPath);
100
- }
101
- let stat;
102
- try {
103
- stat = statSync(absolutePath);
104
- } catch {
105
- fail('SIM_SOURCE_FILE_MISSING', `source file ${JSON.stringify(relativePath)} does not exist`, fieldPath);
106
- }
107
- if (!stat.isFile()) {
108
- fail('SIM_SOURCE_FILE_KIND', 'source path must resolve to a regular file', fieldPath);
109
- }
110
- const real = realpathSync(absolutePath);
111
- if (!real.startsWith(`${absoluteRoot}${path.sep}`)) {
112
- fail('SIM_SOURCE_PATH_ESCAPE', 'source file realpath escapes source root', fieldPath);
113
- }
114
- return real;
115
- }
116
-
117
- function sourceKind(filePath) {
118
- if (/\.[cm]?tsx?$/.test(filePath)) return ts.ScriptKind.TSX;
119
- if (/\.jsx$/.test(filePath)) return ts.ScriptKind.JSX;
120
- return ts.ScriptKind.JS;
121
- }
122
-
123
- function parseSourceFile(filePath) {
124
- const text = readFileSync(filePath, 'utf8');
125
- return parseSourceText(text, filePath);
126
- }
127
-
128
- function parseSourceText(text, filePath) {
129
- const source = ts.createSourceFile(filePath, text, ts.ScriptTarget.Latest, true, sourceKind(filePath));
130
- const diagnostics = source.parseDiagnostics || [];
131
- if (diagnostics.length > 0) {
132
- fail(
133
- 'SIM_SOURCE_PARSE',
134
- diagnostics.map((entry) => ts.flattenDiagnosticMessageText(entry.messageText, '\n')).join('; '),
135
- filePath,
136
- );
137
- }
138
- return source;
139
- }
140
-
141
- function tryFile(candidate) {
142
- try {
143
- return statSync(candidate).isFile() ? realpathSync(candidate) : null;
144
- } catch {
145
- return null;
146
- }
147
- }
148
-
149
- export function resolveRelativeImport(rootDir, importerPath, specifier) {
150
- const candidate = path.resolve(path.dirname(importerPath), specifier);
151
- const attempts = [candidate];
152
- const extension = path.extname(candidate);
153
- if (!extension) {
154
- attempts.push(...SOURCE_EXTENSIONS.map((sourceExtension) => `${candidate}${sourceExtension}`));
155
- attempts.push(...SOURCE_EXTENSIONS.map((sourceExtension) => path.join(candidate, `index${sourceExtension}`)));
156
- } else {
157
- const sourceExtensions = extension === '.js' || extension === '.jsx'
158
- ? ['.ts', '.tsx']
159
- : extension === '.mjs'
160
- ? ['.mts']
161
- : extension === '.cjs'
162
- ? ['.cts']
163
- : [];
164
- const stem = candidate.slice(0, -extension.length);
165
- attempts.push(...sourceExtensions.map((sourceExtension) => `${stem}${sourceExtension}`));
166
- }
167
- const resolved = attempts.map(tryFile).find(Boolean);
168
- if (!resolved) {
169
- fail('SIM_IMPORT_UNRESOLVED', `cannot resolve relative import ${JSON.stringify(specifier)}`, canonicalRelative(rootDir, importerPath));
170
- }
171
- const rootReal = realpathSync(rootDir);
172
- if (!resolved.startsWith(`${rootReal}${path.sep}`)) {
173
- fail('SIM_IMPORT_ESCAPE', `relative import ${JSON.stringify(specifier)} escapes source root`, canonicalRelative(rootDir, importerPath));
174
- }
175
- return resolved;
176
- }
177
-
178
- function isImportMetaProperty(node, propertyNames) {
179
- if (!ts.isPropertyAccessExpression(node) && !ts.isElementAccessExpression(node)) return false;
180
- if (!ts.isMetaProperty(node.expression)
181
- || node.expression.keywordToken !== ts.SyntaxKind.ImportKeyword
182
- || node.expression.name.text !== 'meta') return false;
183
- const propertyName = ts.isPropertyAccessExpression(node)
184
- ? node.name.text
185
- : node.argumentExpression && (ts.isStringLiteral(node.argumentExpression)
186
- || ts.isNoSubstitutionTemplateLiteral(node.argumentExpression))
187
- ? node.argumentExpression.text
188
- : '';
189
- return propertyNames.has(propertyName);
190
- }
191
-
192
- function isTypeOnlyImportDeclaration(node) {
193
- const clause = node.importClause;
194
- if (!clause) return false;
195
- if (clause.isTypeOnly) return true;
196
- if (clause.name || !clause.namedBindings || ts.isNamespaceImport(clause.namedBindings)) return false;
197
- return clause.namedBindings.elements.length > 0
198
- && clause.namedBindings.elements.every((element) => element.isTypeOnly);
199
- }
200
-
201
- function importSpecifiers(source, relativePath) {
202
- const values = [];
203
- const visit = (node) => {
204
- if (ts.isImportEqualsDeclaration(node)) {
205
- fail('SIM_IMPORT_EQUALS', 'TypeScript import-equals/require loading is forbidden', relativePath);
206
- }
207
- if (ts.isImportDeclaration(node)
208
- && node.moduleSpecifier
209
- && ts.isStringLiteral(node.moduleSpecifier)
210
- && !isTypeOnlyImportDeclaration(node)) {
211
- values.push(node.moduleSpecifier.text);
212
- } else if (ts.isExportDeclaration(node)
213
- && node.moduleSpecifier
214
- && ts.isStringLiteral(node.moduleSpecifier)
215
- && !node.isTypeOnly) {
216
- values.push(node.moduleSpecifier.text);
217
- } else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
218
- if (node.arguments.length !== 1
219
- || (!ts.isStringLiteral(node.arguments[0]) && !ts.isNoSubstitutionTemplateLiteral(node.arguments[0]))) {
220
- fail('SIM_IMPORT_DYNAMIC_NON_LITERAL', 'dynamic import targets must be one exact string literal', relativePath);
221
- }
222
- values.push(node.arguments[0].text);
223
- } else if (ts.isCallExpression(node)
224
- && (isImportMetaProperty(node.expression, IMPORT_META_GLOB_METHODS)
225
- || (ts.isPropertyAccessExpression(node.expression)
226
- && isImportMetaProperty(node.expression.expression, IMPORT_META_GLOB_METHODS)))) {
227
- fail('SIM_IMPORT_META_GLOB', 'import.meta glob module discovery is forbidden', relativePath);
228
- } else if (ts.isCallExpression(node)
229
- && ((ts.isIdentifier(node.expression) && node.expression.text === 'require')
230
- || (ts.isPropertyAccessExpression(node.expression)
231
- && ((ts.isIdentifier(node.expression.expression) && node.expression.expression.text === 'require')
232
- || node.expression.name.text === 'require')))) {
233
- fail('SIM_IMPORT_REQUIRE', 'CommonJS require loading is forbidden', relativePath);
234
- }
235
- ts.forEachChild(node, visit);
236
- };
237
- visit(source);
238
- return values;
239
- }
240
-
241
- export function assertImportAllowed(specifier, importer) {
242
- for (const [code, pattern] of FORBIDDEN_IMPORT_PATTERNS) {
243
- if (pattern.test(specifier)) {
244
- fail(code, `forbidden import ${JSON.stringify(specifier)}`, importer);
245
- }
246
- }
247
- if (specifier.startsWith('/') || specifier.includes('\\') || /^[A-Za-z][A-Za-z0-9+.-]*:/.test(specifier)) {
248
- fail('SIM_IMPORT_ABSOLUTE_OR_REMOTE', `absolute and remote import ${JSON.stringify(specifier)} is forbidden`, importer);
249
- }
250
- if (specifier.startsWith('#')) {
251
- fail('SIM_IMPORT_APP_CONDITION', `App-owned import condition ${JSON.stringify(specifier)} is forbidden`, importer);
252
- }
253
- }
254
-
255
- function exportedNames(source) {
256
- const names = new Set();
257
- for (const statement of source.statements) {
258
- const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) || [] : [];
259
- const isExported = modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword);
260
- if (isExported) {
261
- if ((ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) && statement.name) {
262
- names.add(statement.name.text);
263
- }
264
- if (ts.isVariableStatement(statement)) {
265
- for (const declaration of statement.declarationList.declarations) {
266
- if (ts.isIdentifier(declaration.name)) names.add(declaration.name.text);
267
- }
268
- }
269
- }
270
- if (ts.isExportDeclaration(statement) && statement.exportClause && ts.isNamedExports(statement.exportClause)) {
271
- for (const element of statement.exportClause.elements) names.add(element.name.text);
272
- }
273
- if (ts.isExportAssignment(statement)) names.add('default');
274
- }
275
- return names;
276
- }
277
-
278
- function unwrapTsExpression(node) {
279
- let current = node;
280
- while (current
281
- && (ts.isAsExpression(current)
282
- || ts.isSatisfiesExpression(current)
283
- || ts.isParenthesizedExpression(current)
284
- || ts.isTypeAssertionExpression(current))) {
285
- current = current.expression;
286
- }
287
- return current;
288
- }
289
-
290
- function bindingIdentifiers(name, result = new Set()) {
291
- if (ts.isIdentifier(name)) {
292
- result.add(name.text);
293
- return result;
294
- }
295
- for (const element of name.elements || []) {
296
- if (ts.isBindingElement(element)) bindingIdentifiers(element.name, result);
297
- }
298
- return result;
299
- }
300
-
301
- function expressionRootIdentifier(node) {
302
- let current = unwrapTsExpression(node);
303
- while (current && (ts.isPropertyAccessExpression(current) || ts.isElementAccessExpression(current))) {
304
- current = unwrapTsExpression(current.expression);
305
- }
306
- return current && ts.isIdentifier(current) ? current.text : null;
307
- }
308
-
309
- function assignmentOperator(kind) {
310
- return kind >= ts.SyntaxKind.FirstAssignment && kind <= ts.SyntaxKind.LastAssignment;
311
- }
312
-
313
- function callName(node) {
314
- const expression = unwrapTsExpression(node.expression);
315
- if (ts.isIdentifier(expression)) return expression.text;
316
- if (ts.isPropertyAccessExpression(expression)) return expression.name.text;
317
- return '';
318
- }
319
-
320
- function hasModifier(node, kind) {
321
- return (ts.canHaveModifiers(node) ? ts.getModifiers(node) || [] : [])
322
- .some((modifier) => modifier.kind === kind);
323
- }
324
-
325
- function functionLikeInitializer(node) {
326
- const initializer = unwrapTsExpression(node);
327
- return initializer && (ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer))
328
- ? initializer
329
- : null;
330
- }
331
-
332
- function assertNoModuleEvaluationResources(node, source, relativePath) {
333
- const visit = (current) => {
334
- const expression = unwrapTsExpression(current);
335
- if (!expression) return;
336
- if (isFunctionLikeNode(expression)) return;
337
- if (ts.isCallExpression(expression) && functionLikeInitializer(expression.expression)) {
338
- fail('SIM_MODULE_SCOPE_IIFE', 'module-evaluation IIFEs are forbidden in the canonical local closure', relativePath);
339
- }
340
- if (ts.isCallExpression(expression) && MODULE_RESOURCE_FACTORY_PATTERN.test(callName(expression))) {
341
- fail(
342
- 'SIM_MODULE_SCOPE_RESOURCE',
343
- `module-scope resource factory ${JSON.stringify(callName(expression))} must run per renderer instance`,
344
- relativePath,
345
- );
346
- }
347
- if (ts.isNewExpression(expression)) {
348
- const constructorName = expression.expression.getText(source);
349
- if (!MODULE_SCOPE_IMMUTABLE_CONSTRUCTORS.has(constructorName)) {
350
- fail(
351
- 'SIM_MODULE_SCOPE_RESOURCE',
352
- `module-scope constructed resource ${JSON.stringify(constructorName)} must be created per renderer instance`,
353
- relativePath,
354
- );
355
- }
356
- }
357
- ts.forEachChild(expression, (child) => visit(child));
358
- };
359
- visit(node);
360
- }
361
-
362
- function isFunctionLikeNode(node) {
363
- return ts.isFunctionDeclaration(node)
364
- || ts.isFunctionExpression(node)
365
- || ts.isArrowFunction(node)
366
- || ts.isMethodDeclaration(node)
367
- || ts.isGetAccessorDeclaration(node)
368
- || ts.isSetAccessorDeclaration(node)
369
- || ts.isConstructorDeclaration(node);
370
- }
371
-
372
- function mutatedParameterIndexes(functionNode) {
373
- const parameters = new Map();
374
- for (const [index, parameter] of functionNode.parameters.entries()) {
375
- if (ts.isIdentifier(parameter.name)) parameters.set(parameter.name.text, index);
376
- }
377
- const mutated = new Set();
378
- const recordRoot = (expression) => {
379
- const index = parameters.get(expressionRootIdentifier(expression));
380
- if (index !== undefined) mutated.add(index);
381
- };
382
- const visit = (node) => {
383
- if (node !== functionNode && isFunctionLikeNode(node)) return;
384
- if (ts.isBinaryExpression(node) && assignmentOperator(node.operatorToken.kind)) recordRoot(node.left);
385
- if ((ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node))
386
- && [ts.SyntaxKind.PlusPlusToken, ts.SyntaxKind.MinusMinusToken].includes(node.operator)) {
387
- recordRoot(node.operand);
388
- }
389
- if (ts.isDeleteExpression(node)) recordRoot(node.expression);
390
- if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {
391
- if (MODULE_MUTATING_METHODS.has(node.expression.name.text)) recordRoot(node.expression.expression);
392
- if (ts.isIdentifier(node.expression.expression)
393
- && ['Object', 'Reflect'].includes(node.expression.expression.text)
394
- && ['assign', 'defineProperties', 'defineProperty', 'set'].includes(node.expression.name.text)
395
- && node.arguments.length > 0) {
396
- recordRoot(node.arguments[0]);
397
- }
398
- }
399
- ts.forEachChild(node, visit);
400
- };
401
- visit(functionNode.body);
402
- return mutated;
403
- }
404
-
405
- function assertNoThisMutation(node, relativePath) {
406
- const rootedAtThis = (expression) => {
407
- let current = unwrapTsExpression(expression);
408
- while (current && (ts.isPropertyAccessExpression(current) || ts.isElementAccessExpression(current))) {
409
- current = unwrapTsExpression(current.expression);
410
- }
411
- return current?.kind === ts.SyntaxKind.ThisKeyword;
412
- };
413
- const visit = (current) => {
414
- if (ts.isBinaryExpression(current)
415
- && assignmentOperator(current.operatorToken.kind)
416
- && rootedAtThis(current.left)) {
417
- fail('SIM_MODULE_SCOPE_MUTATION', 'module-scope object mutates shared state through this', relativePath);
418
- }
419
- if ((ts.isPrefixUnaryExpression(current) || ts.isPostfixUnaryExpression(current))
420
- && [ts.SyntaxKind.PlusPlusToken, ts.SyntaxKind.MinusMinusToken].includes(current.operator)
421
- && rootedAtThis(current.operand)) {
422
- fail('SIM_MODULE_SCOPE_MUTATION', 'module-scope object mutates shared state through this', relativePath);
423
- }
424
- if (ts.isDeleteExpression(current) && rootedAtThis(current.expression)) {
425
- fail('SIM_MODULE_SCOPE_MUTATION', 'module-scope object mutates shared state through this', relativePath);
426
- }
427
- if (ts.isCallExpression(current)
428
- && ts.isPropertyAccessExpression(current.expression)
429
- && MODULE_MUTATING_METHODS.has(current.expression.name.text)
430
- && rootedAtThis(current.expression.expression)) {
431
- fail('SIM_MODULE_SCOPE_MUTATION', 'module-scope object mutates shared state through this', relativePath);
432
- }
433
- ts.forEachChild(current, visit);
434
- };
435
- visit(node);
436
- }
437
-
438
- function moduleObjectLiteral(node) {
439
- const expression = unwrapTsExpression(node);
440
- if (ts.isObjectLiteralExpression(expression)) return expression;
441
- if (ts.isCallExpression(expression)
442
- && staticMemberName(expression.expression) === 'Object.freeze'
443
- && expression.arguments.length === 1) {
444
- const argument = unwrapTsExpression(expression.arguments[0]);
445
- return ts.isObjectLiteralExpression(argument) ? argument : null;
446
- }
447
- return null;
448
- }
449
-
450
- function staticMemberName(node) {
451
- const expression = unwrapTsExpression(node);
452
- if (ts.isIdentifier(expression)) return expression.text;
453
- if (ts.isPropertyAccessExpression(expression)) {
454
- const owner = staticMemberName(expression.expression);
455
- return owner ? `${owner}.${expression.name.text}` : '';
456
- }
457
- return '';
458
- }
459
-
460
- function assertModuleScopeResources(source, relativePath) {
461
- const moduleBindings = new Set();
462
- const mutatingHelpers = new Map();
463
- for (const statement of source.statements) {
464
- if (ts.isImportDeclaration(statement) && statement.importClause) {
465
- if (statement.importClause.name) moduleBindings.add(statement.importClause.name.text);
466
- const bindings = statement.importClause.namedBindings;
467
- if (bindings && ts.isNamespaceImport(bindings)) moduleBindings.add(bindings.name.text);
468
- if (bindings && ts.isNamedImports(bindings)) {
469
- for (const element of bindings.elements) moduleBindings.add(element.name.text);
470
- }
471
- continue;
472
- }
473
- if (ts.isFunctionDeclaration(statement) && statement.name && statement.body) {
474
- const indexes = mutatedParameterIndexes(statement);
475
- if (indexes.size > 0) mutatingHelpers.set(statement.name.text, indexes);
476
- continue;
477
- }
478
- if (ts.isClassDeclaration(statement)) {
479
- for (const member of statement.members) {
480
- if (ts.isClassStaticBlockDeclaration(member)
481
- || (ts.isPropertyDeclaration(member) && hasModifier(member, ts.SyntaxKind.StaticKeyword))) {
482
- fail('SIM_MODULE_SCOPE_RESOURCE', 'class static state is forbidden in the canonical local closure', relativePath);
483
- }
484
- }
485
- continue;
486
- }
487
- if (ts.isExpressionStatement(statement)) {
488
- assertNoModuleEvaluationResources(statement.expression, source, relativePath);
489
- continue;
490
- }
491
- if (!ts.isVariableStatement(statement)) continue;
492
- if ((statement.declarationList.flags & ts.NodeFlags.Const) === 0) {
493
- fail('SIM_MODULE_SCOPE_MUTABLE', 'canonical local closure cannot declare module-scope let/var state', relativePath);
494
- }
495
- for (const declaration of statement.declarationList.declarations) {
496
- bindingIdentifiers(declaration.name, moduleBindings);
497
- const initializer = unwrapTsExpression(declaration.initializer);
498
- if (!initializer) continue;
499
- const functionInitializer = functionLikeInitializer(initializer);
500
- if (functionInitializer && ts.isIdentifier(declaration.name)) {
501
- const indexes = mutatedParameterIndexes(functionInitializer);
502
- if (indexes.size > 0) mutatingHelpers.set(declaration.name.text, indexes);
503
- }
504
- assertNoModuleEvaluationResources(initializer, source, relativePath);
505
- const sharedObject = moduleObjectLiteral(initializer);
506
- if (sharedObject) assertNoThisMutation(sharedObject, relativePath);
507
- if (ts.isClassExpression(initializer)) {
508
- for (const member of initializer.members) {
509
- if (ts.isClassStaticBlockDeclaration(member)
510
- || (ts.isPropertyDeclaration(member) && hasModifier(member, ts.SyntaxKind.StaticKeyword))) {
511
- fail('SIM_MODULE_SCOPE_RESOURCE', 'class static state is forbidden in the canonical local closure', relativePath);
512
- }
513
- }
514
- }
515
- }
516
- }
517
-
518
- const visit = (node) => {
519
- if (ts.isBinaryExpression(node)
520
- && assignmentOperator(node.operatorToken.kind)
521
- && moduleBindings.has(expressionRootIdentifier(node.left))) {
522
- fail('SIM_MODULE_SCOPE_MUTATION', 'canonical local closure mutates a module-scope binding', relativePath);
523
- }
524
- if ((ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node))
525
- && [ts.SyntaxKind.PlusPlusToken, ts.SyntaxKind.MinusMinusToken].includes(node.operator)
526
- && moduleBindings.has(expressionRootIdentifier(node.operand))) {
527
- fail('SIM_MODULE_SCOPE_MUTATION', 'canonical local closure mutates a module-scope binding', relativePath);
528
- }
529
- if (ts.isDeleteExpression(node) && moduleBindings.has(expressionRootIdentifier(node.expression))) {
530
- fail('SIM_MODULE_SCOPE_MUTATION', 'canonical local closure deletes from a module-scope binding', relativePath);
531
- }
532
- if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {
533
- const root = expressionRootIdentifier(node.expression.expression);
534
- if (root && moduleBindings.has(root) && MODULE_MUTATING_METHODS.has(node.expression.name.text)) {
535
- fail(
536
- 'SIM_MODULE_SCOPE_MUTATION',
537
- `canonical local closure calls mutating method ${JSON.stringify(node.expression.name.text)} on module binding ${JSON.stringify(root)}`,
538
- relativePath,
539
- );
540
- }
541
- if (ts.isIdentifier(node.expression.expression)
542
- && ['Object', 'Reflect'].includes(node.expression.expression.text)
543
- && ['assign', 'defineProperties', 'defineProperty', 'set'].includes(node.expression.name.text)
544
- && node.arguments.length > 0
545
- && moduleBindings.has(expressionRootIdentifier(node.arguments[0]))) {
546
- fail('SIM_MODULE_SCOPE_MUTATION', 'canonical local closure mutates a module-scope binding through Object/Reflect', relativePath);
547
- }
548
- }
549
- if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
550
- const indexes = mutatingHelpers.get(node.expression.text);
551
- if (indexes && [...indexes].some((index) => moduleBindings.has(expressionRootIdentifier(node.arguments[index])))) {
552
- fail(
553
- 'SIM_MODULE_SCOPE_MUTATION',
554
- `helper ${JSON.stringify(node.expression.text)} mutates a module-scope binding through a parameter`,
555
- relativePath,
556
- );
557
- }
558
- }
559
- ts.forEachChild(node, visit);
560
- };
561
- visit(source);
562
- }
563
-
564
- function assertAstRestrictions(source, relativePath) {
565
- const visit = (node) => {
566
- if (ts.isPropertyAccessExpression(node)) {
567
- if (FACTORY_FORBIDDEN_BINDINGS.has(node.name.text)) {
568
- fail('SIM_FACTORY_HOST_DISCRIMINATOR', `host discriminator ${JSON.stringify(node.name.text)} is forbidden`, relativePath);
569
- }
570
- }
571
- if (ts.isElementAccessExpression(node)
572
- && node.argumentExpression
573
- && ts.isStringLiteral(node.argumentExpression)
574
- && FACTORY_FORBIDDEN_BINDINGS.has(node.argumentExpression.text)) {
575
- fail(
576
- 'SIM_FACTORY_HOST_DISCRIMINATOR',
577
- `host discriminator ${JSON.stringify(node.argumentExpression.text)} is forbidden`,
578
- relativePath,
579
- );
580
- }
581
- if (ts.isCallExpression(node)) {
582
- const name = ts.isIdentifier(node.expression)
583
- ? node.expression.text
584
- : ts.isPropertyAccessExpression(node.expression)
585
- ? node.expression.name.text
586
- : '';
587
- const code = FORBIDDEN_CALLS.get(name);
588
- if (code) fail(code, `forbidden call ${JSON.stringify(name)}`, relativePath);
589
- if (name === 'eval' || name === 'Function') {
590
- fail('SIM_DYNAMIC_CODE', 'dynamic code evaluation is forbidden in the canonical local closure', relativePath);
591
- }
592
- }
593
- if (ts.isNewExpression(node)
594
- && ts.isIdentifier(node.expression)
595
- && node.expression.text === 'Function') {
596
- fail('SIM_DYNAMIC_CODE', 'dynamic code evaluation is forbidden in the canonical local closure', relativePath);
597
- }
598
- ts.forEachChild(node, visit);
599
- };
600
- visit(source);
601
- }
602
-
603
- function assertAdapterRestrictions(source, relativePath, specifiers) {
604
- for (const specifier of specifiers) {
605
- if (ADAPTER_FORBIDDEN_RUNTIME_IMPORTS.some((pattern) => pattern.test(specifier))) {
606
- fail('SIM_ADAPTER_UI_IMPORT', `Adapter closure cannot import UI runtime ${JSON.stringify(specifier)}`, relativePath);
607
- }
608
- }
609
- const visit = (node) => {
610
- if (ts.isTypeNode(node)) return;
611
- if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node)) {
612
- fail('SIM_ADAPTER_UI', 'Adapter closure cannot create renderer UI', relativePath);
613
- }
614
- if (ts.isIdentifier(node)
615
- && ['document', 'window'].includes(node.text)
616
- && !(ts.isPropertyAccessExpression(node.parent) && node.parent.name === node)) {
617
- fail('SIM_ADAPTER_DOM', `Adapter closure cannot access ${node.text}`, relativePath);
618
- }
619
- if (ts.isCallExpression(node)) {
620
- const name = callName(node);
621
- if (ADAPTER_DOM_METHODS.has(name)) {
622
- fail('SIM_ADAPTER_DOM', `Adapter closure cannot call DOM method ${JSON.stringify(name)}`, relativePath);
623
- }
624
- if (MODULE_RESOURCE_FACTORY_PATTERN.test(name)) {
625
- fail(
626
- 'SIM_ADAPTER_RESOURCE_FACTORY',
627
- `Adapter closure cannot reconstruct renderer resource ${JSON.stringify(name)}`,
628
- relativePath,
629
- );
630
- }
631
- }
632
- if (ts.isBinaryExpression(node) && assignmentOperator(node.operatorToken.kind)) {
633
- const target = node.left.getText(source);
634
- const terminal = ts.isPropertyAccessExpression(node.left) ? node.left.name.text : '';
635
- if (ADAPTER_DOM_MUTABLE_PROPERTIES.has(terminal)
636
- || /\.(?:classList|dataset|style)(?:\.|\[)/u.test(target)) {
637
- fail('SIM_ADAPTER_DOM', 'Adapter closure cannot mutate DOM state', relativePath);
638
- }
639
- }
640
- ts.forEachChild(node, visit);
641
- };
642
- visit(source);
643
- }
644
-
645
- export function buildModuleGraph(rootDir, entryPaths) {
646
- const queue = entryPaths.map((entry) => assertContainedFile(rootDir, entry.path, entry.fieldPath));
647
- const nodes = new Map();
648
- const packages = new Set();
649
- while (queue.length > 0) {
650
- const absolutePath = queue.shift();
651
- if (nodes.has(absolutePath)) continue;
652
- if (absolutePath.endsWith('.css')) {
653
- nodes.set(absolutePath, { type: 'css', imports: [] });
654
- continue;
655
- }
656
- const relativePath = canonicalRelative(rootDir, absolutePath);
657
- if (isSimulatorStaticAssetPath(absolutePath)) {
658
- if (path.extname(absolutePath).toLowerCase() === '.json') {
659
- try {
660
- JSON.parse(readFileSync(absolutePath, 'utf8'));
661
- } catch {
662
- fail('SIM_IMPORT_JSON_INVALID', 'imported JSON data module is not valid JSON', relativePath);
663
- }
664
- }
665
- nodes.set(absolutePath, { type: 'asset', imports: [] });
666
- continue;
667
- }
668
- if (!SOURCE_EXTENSIONS.includes(path.extname(absolutePath).toLowerCase())) {
669
- fail('SIM_IMPORT_ASSET_TYPE', 'imported static asset type is not admitted', relativePath);
670
- }
671
- const source = parseSourceFile(absolutePath);
672
- const localImports = [];
673
- const specifiers = importSpecifiers(source, relativePath);
674
- for (const specifier of specifiers) {
675
- if (specifier.startsWith('.')) {
676
- const resolved = resolveRelativeImport(rootDir, absolutePath, specifier);
677
- localImports.push(resolved);
678
- queue.push(resolved);
679
- } else {
680
- packages.add(specifier);
681
- }
682
- }
683
- nodes.set(absolutePath, {
684
- type: 'module',
685
- imports: localImports,
686
- specifiers,
687
- source,
688
- exports: exportedNames(source),
689
- });
690
- }
691
- return { nodes, packages: [...packages].sort() };
692
- }
693
-
694
- export function assertRestrictedClosure(rootDir, graph, entries) {
695
- const queue = entries.map((entry) => ({ path: entry.path, rootOwner: entry.owner }));
696
- const seen = new Set();
697
- const packages = new Set();
698
- while (queue.length > 0) {
699
- const { path: current, rootOwner } = queue.shift();
700
- const seenKey = `${rootOwner}:${current}`;
701
- if (seen.has(seenKey)) continue;
702
- seen.add(seenKey);
703
- const node = graph.nodes.get(current);
704
- if (!node) continue;
705
- const relativePath = canonicalRelative(rootDir, current);
706
- if (node.type === 'asset') continue;
707
- if (node.type === 'css') {
708
- fail('SIM_CSS_OUTSIDE_CANONICAL_STYLE', 'restricted module closure cannot import CSS outside the canonical style identity', relativePath);
709
- }
710
- for (const specifier of node.specifiers) {
711
- assertImportAllowed(specifier, relativePath);
712
- if (/\.css(?:$|[?#])/u.test(specifier)) {
713
- fail('SIM_CSS_OUTSIDE_CANONICAL_STYLE', 'restricted module closure cannot import CSS outside the canonical style identity', relativePath);
714
- }
715
- if (!specifier.startsWith('.')) packages.add(specifier);
716
- }
717
- assertModuleScopeResources(node.source, relativePath);
718
- assertAstRestrictions(node.source, relativePath);
719
- if (rootOwner === 'app_adapter') assertAdapterRestrictions(node.source, relativePath, node.specifiers);
720
- queue.push(...node.imports.map((entry) => ({
721
- path: entry,
722
- rootOwner,
723
- })));
724
- }
725
- return [...packages].sort();
726
- }
727
-
728
- export function validateSimulatorSelectedDependencyModule(code, canonicalPath) {
729
- const source = parseSourceText(code, canonicalPath);
730
- const specifiers = importSpecifiers(source, canonicalPath);
731
- for (const specifier of specifiers) {
732
- assertImportAllowed(specifier, canonicalPath);
733
- if (/\.css(?:$|[?#])/u.test(specifier)) {
734
- fail(
735
- 'SIM_SELECTED_DEPENDENCY_RESOURCE',
736
- 'selected dependency runtime closure cannot import CSS outside the canonical style identity',
737
- canonicalPath,
738
- );
739
- }
740
- }
741
- assertModuleScopeResources(source, canonicalPath);
742
- assertAstRestrictions(source, canonicalPath);
743
- return Object.freeze({ specifiers: Object.freeze([...specifiers]) });
744
- }
745
-
746
- export function reachable(graph, entry, target) {
747
- const queue = [entry];
748
- const seen = new Set();
749
- while (queue.length > 0) {
750
- const current = queue.shift();
751
- if (current === target) return true;
752
- if (seen.has(current)) continue;
753
- seen.add(current);
754
- queue.push(...(graph.nodes.get(current)?.imports || []));
755
- }
756
- return false;
757
- }