@namzu/sdk 69.2.0 → 69.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/constants/plugin/index.d.ts +8 -0
  3. package/dist/constants/plugin/index.d.ts.map +1 -1
  4. package/dist/constants/plugin/index.js +8 -0
  5. package/dist/constants/plugin/index.js.map +1 -1
  6. package/dist/plugin/common-layout/index.d.ts +5 -0
  7. package/dist/plugin/common-layout/index.d.ts.map +1 -0
  8. package/dist/plugin/common-layout/index.js +3 -0
  9. package/dist/plugin/common-layout/index.js.map +1 -0
  10. package/dist/plugin/common-layout/mcp.d.ts +21 -0
  11. package/dist/plugin/common-layout/mcp.d.ts.map +1 -0
  12. package/dist/plugin/common-layout/mcp.js +305 -0
  13. package/dist/plugin/common-layout/mcp.js.map +1 -0
  14. package/dist/plugin/common-layout/paths.d.ts +27 -0
  15. package/dist/plugin/common-layout/paths.d.ts.map +1 -0
  16. package/dist/plugin/common-layout/paths.js +48 -0
  17. package/dist/plugin/common-layout/paths.js.map +1 -0
  18. package/dist/plugin/common-layout/read.d.ts +25 -0
  19. package/dist/plugin/common-layout/read.d.ts.map +1 -0
  20. package/dist/plugin/common-layout/read.js +1155 -0
  21. package/dist/plugin/common-layout/read.js.map +1 -0
  22. package/dist/plugin/common-layout/types.d.ts +66 -0
  23. package/dist/plugin/common-layout/types.d.ts.map +1 -0
  24. package/dist/plugin/common-layout/types.js +2 -0
  25. package/dist/plugin/common-layout/types.js.map +1 -0
  26. package/dist/plugin/common-layout-names.d.ts +65 -0
  27. package/dist/plugin/common-layout-names.d.ts.map +1 -0
  28. package/dist/plugin/common-layout-names.js +94 -0
  29. package/dist/plugin/common-layout-names.js.map +1 -0
  30. package/dist/plugin/hook-module/capabilities.d.ts +41 -0
  31. package/dist/plugin/hook-module/capabilities.d.ts.map +1 -0
  32. package/dist/plugin/hook-module/capabilities.js +438 -0
  33. package/dist/plugin/hook-module/capabilities.js.map +1 -0
  34. package/dist/plugin/hook-module/consent.d.ts +39 -0
  35. package/dist/plugin/hook-module/consent.d.ts.map +1 -0
  36. package/dist/plugin/hook-module/consent.js +59 -0
  37. package/dist/plugin/hook-module/consent.js.map +1 -0
  38. package/dist/plugin/hook-module/events.d.ts +33 -0
  39. package/dist/plugin/hook-module/events.d.ts.map +1 -0
  40. package/dist/plugin/hook-module/events.js +149 -0
  41. package/dist/plugin/hook-module/events.js.map +1 -0
  42. package/dist/plugin/hook-module/host.d.ts +79 -0
  43. package/dist/plugin/hook-module/host.d.ts.map +1 -0
  44. package/dist/plugin/hook-module/host.js +546 -0
  45. package/dist/plugin/hook-module/host.js.map +1 -0
  46. package/dist/plugin/hook-module/index.d.ts +11 -0
  47. package/dist/plugin/hook-module/index.d.ts.map +1 -0
  48. package/dist/plugin/hook-module/index.js +6 -0
  49. package/dist/plugin/hook-module/index.js.map +1 -0
  50. package/dist/plugin/hook-module/scan.d.ts +99 -0
  51. package/dist/plugin/hook-module/scan.d.ts.map +1 -0
  52. package/dist/plugin/hook-module/scan.js +789 -0
  53. package/dist/plugin/hook-module/scan.js.map +1 -0
  54. package/dist/plugin/hook-module/worker-source.d.ts +31 -0
  55. package/dist/plugin/hook-module/worker-source.d.ts.map +1 -0
  56. package/dist/plugin/hook-module/worker-source.js +498 -0
  57. package/dist/plugin/hook-module/worker-source.js.map +1 -0
  58. package/dist/plugin/index.d.ts +5 -2
  59. package/dist/plugin/index.d.ts.map +1 -1
  60. package/dist/plugin/index.js +4 -1
  61. package/dist/plugin/index.js.map +1 -1
  62. package/dist/plugin/lifecycle.d.ts +57 -0
  63. package/dist/plugin/lifecycle.d.ts.map +1 -1
  64. package/dist/plugin/lifecycle.js +92 -11
  65. package/dist/plugin/lifecycle.js.map +1 -1
  66. package/dist/plugin/loader.d.ts +30 -0
  67. package/dist/plugin/loader.d.ts.map +1 -1
  68. package/dist/plugin/loader.js +76 -19
  69. package/dist/plugin/loader.js.map +1 -1
  70. package/dist/plugin/shell-hook-env.d.ts +7 -0
  71. package/dist/plugin/shell-hook-env.d.ts.map +1 -1
  72. package/dist/plugin/shell-hook-env.js.map +1 -1
  73. package/dist/plugin/shell-hook.d.ts +10 -1
  74. package/dist/plugin/shell-hook.d.ts.map +1 -1
  75. package/dist/plugin/shell-hook.js +81 -70
  76. package/dist/plugin/shell-hook.js.map +1 -1
  77. package/dist/public-runtime.d.ts +3 -2
  78. package/dist/public-runtime.d.ts.map +1 -1
  79. package/dist/public-runtime.js +2 -2
  80. package/dist/public-runtime.js.map +1 -1
  81. package/dist/skills/loader.d.ts +8 -2
  82. package/dist/skills/loader.d.ts.map +1 -1
  83. package/dist/skills/loader.js +22 -11
  84. package/dist/skills/loader.js.map +1 -1
  85. package/dist/skills/registry.d.ts.map +1 -1
  86. package/dist/skills/registry.js +9 -1
  87. package/dist/skills/registry.js.map +1 -1
  88. package/dist/types/plugin/index.d.ts +73 -0
  89. package/dist/types/plugin/index.d.ts.map +1 -1
  90. package/dist/types/plugin/index.js +28 -6
  91. package/dist/types/plugin/index.js.map +1 -1
  92. package/dist/types/skills/index.d.ts +6 -0
  93. package/dist/types/skills/index.d.ts.map +1 -1
  94. package/package.json +2 -1
  95. package/src/constants/plugin/index.ts +9 -0
  96. package/src/plugin/common-layout/index.ts +19 -0
  97. package/src/plugin/common-layout/mcp.ts +362 -0
  98. package/src/plugin/common-layout/paths.ts +70 -0
  99. package/src/plugin/common-layout/read.ts +1282 -0
  100. package/src/plugin/common-layout/types.ts +77 -0
  101. package/src/plugin/common-layout-names.ts +108 -0
  102. package/src/plugin/hook-module/capabilities.ts +500 -0
  103. package/src/plugin/hook-module/consent.ts +96 -0
  104. package/src/plugin/hook-module/events.ts +177 -0
  105. package/src/plugin/hook-module/host.ts +649 -0
  106. package/src/plugin/hook-module/index.ts +52 -0
  107. package/src/plugin/hook-module/scan.ts +1004 -0
  108. package/src/plugin/hook-module/worker-source.ts +500 -0
  109. package/src/plugin/index.ts +13 -1
  110. package/src/plugin/lifecycle.ts +179 -17
  111. package/src/plugin/loader.ts +97 -18
  112. package/src/plugin/shell-hook-env.ts +7 -0
  113. package/src/plugin/shell-hook.ts +91 -70
  114. package/src/public-runtime.ts +35 -0
  115. package/src/skills/loader.ts +26 -9
  116. package/src/skills/registry.ts +9 -1
  117. package/src/types/plugin/index.ts +81 -24
  118. package/src/types/skills/index.ts +7 -0
@@ -0,0 +1,789 @@
1
+ import { lstatSync, readFileSync, realpathSync } from 'node:fs';
2
+ import * as nodeModule from 'node:module';
3
+ import { isAbsolute, join, posix, relative, resolve } from 'node:path';
4
+ import * as acorn from 'acorn';
5
+ import { COMMON_HOOKS_FILE, COMMON_MODULE_TYPES_SPECIFIER } from '../common-layout-names.js';
6
+ import { resolvePattern } from './events.js';
7
+ /** The most one scanned file, and the hooks file, may hold. */
8
+ export const MAX_MODULE_FILE_BYTES = 1024 * 1024;
9
+ /** The most all the files of one module may hold together. */
10
+ export const MAX_MODULE_TOTAL_BYTES = 8 * 1024 * 1024;
11
+ /** The most files one module may be made of. */
12
+ export const MAX_MODULE_FILES = 64;
13
+ /** The calls on `$` Namzu answers, by noun. Every other call throws where it is made. */
14
+ export const SUPPORTED_CAPABILITY_CALLS = {
15
+ fs: ['read', 'exists', 'stat', 'list'],
16
+ store: ['get', 'set', 'delete', 'keys'],
17
+ process: ['run'],
18
+ env: ['get'],
19
+ ui: ['log'],
20
+ http: ['fetch'],
21
+ };
22
+ /** The properties of `$.plugin` a module may read. */
23
+ export const PLUGIN_PROPERTIES = ['root', 'name'];
24
+ /** `stripTypeScriptTypes` where this Node has it, quiet about its experimental status. */
25
+ function typeStripper() {
26
+ const stripper = nodeModule.stripTypeScriptTypes;
27
+ if (typeof stripper !== 'function')
28
+ return undefined;
29
+ return (code, options) => {
30
+ const original = process.emitWarning;
31
+ process.emitWarning = ((warning, ...rest) => {
32
+ const text = typeof warning === 'string' ? warning : String(warning?.message ?? '');
33
+ if (/type stripping|stripTypeScriptTypes/i.test(text))
34
+ return;
35
+ return original.call(process, warning, ...rest);
36
+ });
37
+ try {
38
+ return stripper(code, options);
39
+ }
40
+ finally {
41
+ process.emitWarning = original;
42
+ }
43
+ };
44
+ }
45
+ /** The path inside `root`, or `undefined` when it leaves it. */
46
+ function within(root, path) {
47
+ const rel = relative(root, path);
48
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
49
+ }
50
+ /**
51
+ * A plugin's file as text: a regular file inside the plugin, not a link, no
52
+ * larger than `cap`. A problem says why it was not read.
53
+ */
54
+ export function readPluginFile(root, rel, cap = MAX_MODULE_FILE_BYTES) {
55
+ const path = resolve(root, rel);
56
+ let realRoot;
57
+ try {
58
+ realRoot = realpathSync(root);
59
+ }
60
+ catch {
61
+ return { problem: 'the plugin folder cannot be read' };
62
+ }
63
+ if (!within(resolve(root), path))
64
+ return { problem: 'is outside the plugin folder' };
65
+ let info;
66
+ try {
67
+ info = lstatSync(path);
68
+ }
69
+ catch {
70
+ return { problem: 'no such file' };
71
+ }
72
+ if (info.isSymbolicLink())
73
+ return { problem: 'is a link, and links are not followed' };
74
+ if (!info.isFile())
75
+ return { problem: 'is not a regular file' };
76
+ if (info.size > cap)
77
+ return { problem: `is larger than ${cap / 1024} KiB` };
78
+ let real;
79
+ try {
80
+ real = realpathSync(path);
81
+ }
82
+ catch {
83
+ return { problem: 'no such file' };
84
+ }
85
+ if (!within(realRoot, real))
86
+ return { problem: 'leaves the plugin folder through a link' };
87
+ try {
88
+ return { text: readFileSync(real, 'utf8'), real };
89
+ }
90
+ catch {
91
+ return { problem: 'cannot be read' };
92
+ }
93
+ }
94
+ /**
95
+ * Read the hooks file of the common layout for the module it names: `modules`
96
+ * holds one path, relative to the folder the hooks file is in. The file is read
97
+ * as the hook entries are: no link, valid JSON, one mebibyte at most.
98
+ */
99
+ export function locateHookModule(root) {
100
+ const hooksFile = COMMON_HOOKS_FILE;
101
+ const read = readPluginFile(root, hooksFile);
102
+ if ('problem' in read) {
103
+ // A missing file is not a module; any other problem is the hook entries' to say.
104
+ return { kind: 'none' };
105
+ }
106
+ let parsed;
107
+ try {
108
+ parsed = JSON.parse(read.text);
109
+ }
110
+ catch {
111
+ return { kind: 'none' };
112
+ }
113
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
114
+ return { kind: 'none' };
115
+ const modules = parsed.modules;
116
+ if (modules === undefined)
117
+ return { kind: 'none' };
118
+ if (!Array.isArray(modules)) {
119
+ return {
120
+ kind: 'refused',
121
+ hooksFile,
122
+ message: `${hooksFile}: "modules" must be a list of one path.`,
123
+ };
124
+ }
125
+ if (modules.length === 0)
126
+ return { kind: 'none' };
127
+ if (modules.length > 1) {
128
+ return {
129
+ kind: 'refused',
130
+ hooksFile,
131
+ message: `${hooksFile}: \`modules\` names one hooks module per plugin; a second entry is refused.`,
132
+ };
133
+ }
134
+ const specifier = modules[0];
135
+ if (typeof specifier !== 'string' || specifier.trim() === '') {
136
+ return { kind: 'refused', hooksFile, message: `${hooksFile}: \`modules\` must name a file.` };
137
+ }
138
+ if (isAbsolute(specifier) || /^[A-Za-z]:/.test(specifier) || specifier.startsWith('\\')) {
139
+ return {
140
+ kind: 'refused',
141
+ hooksFile,
142
+ message: `${hooksFile}: "${specifier}" is an absolute path; a module is named relative to the hooks file.`,
143
+ };
144
+ }
145
+ const entry = posix.normalize(posix.join(posix.dirname(hooksFile), specifier.replaceAll('\\', '/')));
146
+ if (entry === '..' || entry.startsWith('../') || posix.isAbsolute(entry)) {
147
+ return {
148
+ kind: 'refused',
149
+ hooksFile,
150
+ message: `${hooksFile}: "${specifier}" leaves the plugin folder.`,
151
+ };
152
+ }
153
+ return { kind: 'found', hooksFile, specifier, entry };
154
+ }
155
+ const SCRIPT_EXTENSIONS = ['.js', '.mjs', '.cjs'];
156
+ const TYPED_EXTENSIONS = ['.ts', '.mts', '.cts'];
157
+ function extensionOf(path) {
158
+ const index = path.lastIndexOf('.');
159
+ return index < 0 ? '' : path.slice(index).toLowerCase();
160
+ }
161
+ /** Names a script uses to climb from an object to the constructors behind it. */
162
+ const REACHING_NAMES = new Set([
163
+ 'constructor',
164
+ '__proto__',
165
+ '__defineGetter__',
166
+ '__defineSetter__',
167
+ '__lookupGetter__',
168
+ '__lookupSetter__',
169
+ 'getPrototypeOf',
170
+ 'setPrototypeOf',
171
+ ]);
172
+ function walk(node, enter, parents = []) {
173
+ enter(node, parents);
174
+ parents.push(node);
175
+ for (const key of Object.keys(node)) {
176
+ if (key === 'type' || key === 'start' || key === 'end' || key === 'loc')
177
+ continue;
178
+ const value = node[key];
179
+ if (Array.isArray(value)) {
180
+ for (const child of value) {
181
+ if (child !== null && typeof child === 'object' && typeof child.type === 'string') {
182
+ walk(child, enter, parents);
183
+ }
184
+ }
185
+ }
186
+ else if (value !== null && typeof value === 'object' && typeof value.type === 'string') {
187
+ walk(value, enter, parents);
188
+ }
189
+ }
190
+ parents.pop();
191
+ }
192
+ function isFunctionNode(node) {
193
+ return (node !== undefined &&
194
+ (node.type === 'FunctionDeclaration' ||
195
+ node.type === 'FunctionExpression' ||
196
+ node.type === 'ArrowFunctionExpression'));
197
+ }
198
+ function stringValue(node) {
199
+ if (node === undefined)
200
+ return undefined;
201
+ if (node.type === 'Literal' && typeof node.value === 'string')
202
+ return node.value;
203
+ if (node.type === 'TemplateLiteral' && node.expressions.length === 0) {
204
+ return node.quasis[0]?.value?.cooked ?? undefined;
205
+ }
206
+ return undefined;
207
+ }
208
+ function patternNames(node, into) {
209
+ if (node === null || node === undefined)
210
+ return;
211
+ switch (node.type) {
212
+ case 'Identifier':
213
+ into.push(node.name);
214
+ return;
215
+ case 'ObjectPattern':
216
+ for (const property of node.properties) {
217
+ patternNames(property.type === 'RestElement' ? property.argument : property.value, into);
218
+ }
219
+ return;
220
+ case 'ArrayPattern':
221
+ for (const element of node.elements)
222
+ patternNames(element, into);
223
+ return;
224
+ case 'AssignmentPattern':
225
+ patternNames(node.left, into);
226
+ return;
227
+ case 'RestElement':
228
+ patternNames(node.argument, into);
229
+ return;
230
+ }
231
+ }
232
+ /** Blank a stretch of source, keeping its line breaks so line numbers stay true. */
233
+ function blank(text) {
234
+ return text.replace(/[^\n]/g, ' ');
235
+ }
236
+ function refuse(state, file, node, message) {
237
+ const line = typeof node === 'number' ? node : (node.loc?.start.line ?? 1);
238
+ // The refusal carries its file and line already; a message that opens with the file says it twice.
239
+ const bare = message.startsWith(`${file}: `) ? message.slice(file.length + 2) : message;
240
+ state.refusals.push({ file, line, message: bare });
241
+ }
242
+ function resolveImport(state, fromRel, specifier) {
243
+ const base = posix.normalize(posix.join(posix.dirname(fromRel), specifier));
244
+ if (base.startsWith('../') || base === '..' || posix.isAbsolute(base))
245
+ return undefined;
246
+ const candidates = [base];
247
+ if (/\.m?js$/.test(base))
248
+ candidates.push(base.replace(/\.(m?)js$/, '.$1ts'));
249
+ for (const extension of ['.ts', '.js', '.mjs'])
250
+ candidates.push(`${base}${extension}`);
251
+ for (const candidate of candidates) {
252
+ let info;
253
+ try {
254
+ info = lstatSync(join(state.root, candidate));
255
+ }
256
+ catch {
257
+ info = undefined;
258
+ }
259
+ if (info !== undefined && (info.isFile() || info.isSymbolicLink()))
260
+ return candidate;
261
+ }
262
+ return undefined;
263
+ }
264
+ /** Which top-level bindings of a file are functions, by name. */
265
+ function topLevelFunctions(ast) {
266
+ const found = new Map();
267
+ for (const statement of ast.body) {
268
+ const declaration = statement.type === 'ExportNamedDeclaration'
269
+ ? statement.declaration
270
+ : statement;
271
+ if (declaration === null || declaration === undefined)
272
+ continue;
273
+ if (declaration.type === 'FunctionDeclaration' && declaration.id !== null) {
274
+ found.set(declaration.id.name, declaration);
275
+ }
276
+ else if (declaration.type === 'VariableDeclaration') {
277
+ for (const declarator of declaration.declarations) {
278
+ if (declarator.id.type === 'Identifier' && isFunctionNode(declarator.init)) {
279
+ found.set(declarator.id.name, declarator.init);
280
+ }
281
+ }
282
+ }
283
+ }
284
+ return found;
285
+ }
286
+ /** The function the entry exports as `register`, or as its default. */
287
+ function findRegister(ast, functions) {
288
+ for (const statement of ast.body) {
289
+ if (statement.type === 'ExportNamedDeclaration') {
290
+ const declaration = statement.declaration;
291
+ if (declaration?.type === 'FunctionDeclaration' && declaration.id?.name === 'register') {
292
+ return declaration;
293
+ }
294
+ if (declaration?.type === 'VariableDeclaration') {
295
+ for (const declarator of declaration.declarations) {
296
+ if (declarator.id.type === 'Identifier' && declarator.id.name === 'register') {
297
+ return isFunctionNode(declarator.init) ? declarator.init : undefined;
298
+ }
299
+ }
300
+ }
301
+ for (const specifier of (statement.specifiers ?? [])) {
302
+ if (specifier.exported.name === 'register' && statement.source === null) {
303
+ return functions.get(specifier.local.name);
304
+ }
305
+ }
306
+ }
307
+ else if (statement.type === 'ExportDefaultDeclaration') {
308
+ const declaration = statement.declaration;
309
+ if (isFunctionNode(declaration))
310
+ return declaration;
311
+ if (declaration.type === 'Identifier')
312
+ return functions.get(declaration.name);
313
+ }
314
+ }
315
+ return undefined;
316
+ }
317
+ function capabilityUse(state, rel, node, parents) {
318
+ const parent = parents[parents.length - 1];
319
+ const grand = parents[parents.length - 2];
320
+ const great = parents[parents.length - 3];
321
+ const spelled = '$ is always spelled $.noun.event(...) at the call site';
322
+ if (parent?.type !== 'MemberExpression' ||
323
+ parent.object !== node ||
324
+ parent.computed === true ||
325
+ parent.property.type !== 'Identifier') {
326
+ refuse(state, rel, node, spelled);
327
+ return;
328
+ }
329
+ const noun = parent.property.name;
330
+ if (grand?.type !== 'MemberExpression' ||
331
+ grand.object !== parent ||
332
+ grand.computed === true ||
333
+ grand.property.type !== 'Identifier') {
334
+ refuse(state, rel, node, spelled);
335
+ return;
336
+ }
337
+ const member = grand.property.name;
338
+ const called = great?.type === 'CallExpression' && great.callee === grand;
339
+ if (noun === 'plugin' && !called && PLUGIN_PROPERTIES.includes(member))
340
+ return;
341
+ if (!called) {
342
+ refuse(state, rel, node, spelled);
343
+ return;
344
+ }
345
+ const supported = SUPPORTED_CAPABILITY_CALLS[noun]?.includes(member) === true;
346
+ state.calls.push({
347
+ call: `$.${noun}.${member}`,
348
+ file: rel,
349
+ line: node.loc?.start.line ?? 1,
350
+ supported,
351
+ });
352
+ state.callStarts.push({ file: rel, start: node.start });
353
+ if (noun === 'env' && member === 'get' && supported) {
354
+ const name = stringValue(great.arguments[0]);
355
+ if (name === undefined) {
356
+ refuse(state, rel, node, '$.env.get takes a string literal: the variables a module reads are listed before it loads');
357
+ }
358
+ else
359
+ state.envNames.add(name);
360
+ }
361
+ }
362
+ /**
363
+ * Read one file: parse it, refuse what is refused, and note what it hooks and
364
+ * calls. The entry file also has its `register` function read for `on` calls.
365
+ */
366
+ function analyseFile(state, rel, isEntry, queue) {
367
+ const extension = extensionOf(rel);
368
+ if (extension === '.tsx' || extension === '.jsx') {
369
+ refuse(state, rel, 1, `${rel}: JSX is not supported in a hooks module.`);
370
+ return;
371
+ }
372
+ if (!SCRIPT_EXTENSIONS.includes(extension) && !TYPED_EXTENSIONS.includes(extension)) {
373
+ refuse(state, rel, 1, `${rel}: only .js, .mjs, .cjs, .ts, .mts and .cts files are loaded as a hooks module.`);
374
+ return;
375
+ }
376
+ const read = readPluginFile(state.root, rel);
377
+ if ('problem' in read) {
378
+ refuse(state, rel, 1, `${rel}: ${read.problem}.`);
379
+ return;
380
+ }
381
+ state.total += read.text.length;
382
+ if (state.total > MAX_MODULE_TOTAL_BYTES) {
383
+ refuse(state, rel, 1, `${rel}: the module's files together are past ${MAX_MODULE_TOTAL_BYTES / 1024 / 1024} MiB.`);
384
+ return;
385
+ }
386
+ let code = read.text;
387
+ if (TYPED_EXTENSIONS.includes(extension)) {
388
+ const strip = typeStripper();
389
+ if (strip === undefined) {
390
+ refuse(state, rel, 1, `${rel}: a TypeScript module needs Node 22.13 or later; write it as .js or run a newer Node.`);
391
+ return;
392
+ }
393
+ try {
394
+ code = strip(code, { mode: 'strip' });
395
+ }
396
+ catch (error) {
397
+ const message = error instanceof Error ? error.message.split('\n')[0] : String(error);
398
+ refuse(state, rel, 1, `${rel} does not parse as TypeScript: ${message}`);
399
+ return;
400
+ }
401
+ }
402
+ let ast;
403
+ try {
404
+ ast = acorn.parse(code, {
405
+ ecmaVersion: 'latest',
406
+ sourceType: 'module',
407
+ locations: true,
408
+ allowHashBang: true,
409
+ });
410
+ }
411
+ catch (error) {
412
+ const problem = error;
413
+ const text = (problem.message ?? String(error)).replace(/\s*\(\d+:\d+\)$/, '');
414
+ refuse(state, rel, problem.loc?.line ?? 1, `${rel} does not parse: ${text} (line ${problem.loc?.line ?? 1}, column ${(problem.loc?.column ?? 0) + 1})`);
415
+ return;
416
+ }
417
+ const imports = [];
418
+ const importedNames = new Map();
419
+ for (const statement of ast.body) {
420
+ const isImport = statement.type === 'ImportDeclaration';
421
+ const isReexport = (statement.type === 'ExportNamedDeclaration' || statement.type === 'ExportAllDeclaration') &&
422
+ statement.source !== null &&
423
+ statement.source !== undefined;
424
+ if (!isImport && !isReexport)
425
+ continue;
426
+ const specifier = String(statement.source.value);
427
+ if (specifier.startsWith('./') || specifier.startsWith('../')) {
428
+ imports.push({ specifier, line: statement.loc?.start.line ?? 1 });
429
+ if (isImport) {
430
+ for (const item of statement.specifiers) {
431
+ importedNames.set(item.local.name, item.type === 'ImportNamespaceSpecifier' ? 'namespace' : 'function-ok');
432
+ }
433
+ }
434
+ }
435
+ else if (specifier === COMMON_MODULE_TYPES_SPECIFIER) {
436
+ refuse(state, rel, statement, `${rel}: cannot import "${specifier}" as a value (from ${rel}): it holds types only, and only import type is read.`);
437
+ }
438
+ else {
439
+ refuse(state, rel, statement, `${rel}: cannot import "${specifier}" (from ${rel}): a hooks module imports its own files by relative path and "${COMMON_MODULE_TYPES_SPECIFIER}", nothing else`);
440
+ }
441
+ }
442
+ const functions = topLevelFunctions(ast);
443
+ const register = isEntry ? findRegister(ast, functions) : undefined;
444
+ if (isEntry && register === undefined) {
445
+ refuse(state, rel, 1, `${rel}: the module does not export a function named register (export function register(on) { ... }).`);
446
+ }
447
+ let onName;
448
+ if (register !== undefined) {
449
+ const first = register.params[0];
450
+ if (first !== undefined) {
451
+ if (first.type === 'Identifier')
452
+ onName = first.name;
453
+ else
454
+ refuse(state, rel, register, `${rel}: register takes on as a plain first parameter.`);
455
+ }
456
+ }
457
+ const inRegister = (node) => register !== undefined && node.start >= register.start && node.end <= register.end;
458
+ const patterns = new Map();
459
+ walk(ast, (node, parents) => {
460
+ const parent = parents[parents.length - 1];
461
+ if (node.type === 'ImportExpression') {
462
+ refuse(state, rel, node, `${rel}: a dynamic import(); a hooks module imports its own files with an import declaration, as in import { name } from "./file.js"`);
463
+ return;
464
+ }
465
+ if (node.type === 'MetaProperty' && node.meta.name === 'import') {
466
+ refuse(state, rel, node, `${rel}: import.meta is not available in a hooks module.`);
467
+ return;
468
+ }
469
+ if ((node.type === 'AwaitExpression' ||
470
+ (node.type === 'ForOfStatement' && node.await === true)) &&
471
+ !parents.some(isFunctionNode)) {
472
+ refuse(state, rel, node, `${rel}: a top-level await in a file the entry imports; the environment links the entry alone as an async module`);
473
+ return;
474
+ }
475
+ if (node.type === 'MemberExpression') {
476
+ const property = node.property;
477
+ const written = !node.computed && property.type === 'Identifier'
478
+ ? property.name
479
+ : node.computed && property.type === 'Literal' && typeof property.value === 'string'
480
+ ? property.value
481
+ : undefined;
482
+ if (written !== undefined && REACHING_NAMES.has(written)) {
483
+ refuse(state, rel, node, `${rel}: .${written} is how a script reaches the functions behind the objects it is given; a hooks module does not use it`);
484
+ }
485
+ }
486
+ if (node.type !== 'Identifier') {
487
+ if (node.type === 'CallExpression' &&
488
+ onName !== undefined &&
489
+ node.callee.type === 'Identifier' &&
490
+ node.callee.name === onName &&
491
+ inRegister(node)) {
492
+ registration(state, rel, node, parents, functions, importedNames, patterns);
493
+ }
494
+ return;
495
+ }
496
+ // An identifier that is not a use: a property key or name, a parameter.
497
+ if (parent?.type === 'MemberExpression' && parent.property === node && !parent.computed)
498
+ return;
499
+ if (parent?.type === 'Property' &&
500
+ parent.key === node &&
501
+ !parent.computed &&
502
+ !parent.shorthand) {
503
+ return;
504
+ }
505
+ if (node.name === '$') {
506
+ const declared = parents.some((ancestor) => {
507
+ if (!isFunctionNode(ancestor))
508
+ return false;
509
+ return ancestor.params.some((param) => {
510
+ const names = [];
511
+ patternNames(param, names);
512
+ return names.includes('$') && param.start <= node.start && node.end <= param.end;
513
+ });
514
+ });
515
+ if (declared)
516
+ return;
517
+ if (parent?.type === 'VariableDeclarator' && parent.id === node) {
518
+ refuse(state, rel, node, `${rel}: $ is declared again in this file; it is the capability object and is spelled $.noun.event(...)`);
519
+ return;
520
+ }
521
+ capabilityUse(state, rel, node, parents);
522
+ return;
523
+ }
524
+ if (onName !== undefined && node.name === onName && inRegister(node)) {
525
+ const isParam = parent === register && (register?.params).includes(node);
526
+ const isCallee = parent?.type === 'CallExpression' && parent.callee === node;
527
+ if (!isParam && !isCallee) {
528
+ refuse(state, rel, node, `${rel}: on is always on("<event>", hook): it is not passed, bound or assigned`);
529
+ }
530
+ }
531
+ });
532
+ state.analyses.set(rel, { rel, ast, code, imports });
533
+ for (const item of imports) {
534
+ const target = resolveImport(state, rel, item.specifier);
535
+ if (target === undefined) {
536
+ refuse(state, rel, item.line, `${rel}: cannot import "${item.specifier}" (from ${rel}): no such file in the plugin`);
537
+ }
538
+ else if (!state.analyses.has(target) && !queue.includes(target)) {
539
+ if (state.analyses.size + queue.length >= MAX_MODULE_FILES) {
540
+ refuse(state, rel, item.line, `${rel}: the module is made of more than ${MAX_MODULE_FILES} files.`);
541
+ }
542
+ else
543
+ queue.push(target);
544
+ }
545
+ }
546
+ }
547
+ function registration(state, rel, call, parents, functions, importedNames, patterns) {
548
+ const args = call.arguments;
549
+ if (args.length < 2 || args.length > 3) {
550
+ refuse(state, rel, call, `${rel}: on() takes (pattern, hook) or (pattern, matcher, hook)`);
551
+ return;
552
+ }
553
+ const pattern = stringValue(args[0]);
554
+ if (pattern === undefined) {
555
+ refuse(state, rel, call, `${rel}: the event name passed to on() is not a string literal`);
556
+ return;
557
+ }
558
+ const resolved = resolvePattern(pattern);
559
+ if (!resolved.ok) {
560
+ refuse(state, rel, call, `${rel}: ${resolved.message}`);
561
+ return;
562
+ }
563
+ const hook = args[args.length - 1];
564
+ let isFunction = isFunctionNode(hook);
565
+ if (!isFunction && hook.type === 'Identifier') {
566
+ if (importedNames.get(hook.name) === 'namespace') {
567
+ refuse(state, rel, hook, `${rel}: "${hook.name}" is a namespace import, not a function`);
568
+ return;
569
+ }
570
+ isFunction = functions.has(hook.name) || importedNames.has(hook.name);
571
+ }
572
+ if (!isFunction) {
573
+ refuse(state, rel, hook, `${rel}: the hook passed to on("${pattern}") is not a function declared at the top of this file (a function declaration, or a const bound to a function), nor imported from one of the module's own files`);
574
+ return;
575
+ }
576
+ const body = isFunctionNode(hook)
577
+ ? hook
578
+ : hook.type === 'Identifier'
579
+ ? functions.get(hook.name)
580
+ : undefined;
581
+ if (body !== undefined) {
582
+ state.hookBodies.push({
583
+ file: rel,
584
+ start: body.start,
585
+ end: body.end,
586
+ runs: resolved.runs.length > 0,
587
+ });
588
+ }
589
+ const matcher = args.length === 3;
590
+ if (!matcher) {
591
+ const earlier = patterns.get(pattern);
592
+ if (earlier !== undefined) {
593
+ refuse(state, rel, call, `${rel}: on("${pattern}") is registered twice without a matcher; the first is at ${earlier.file}:${earlier.line}`);
594
+ return;
595
+ }
596
+ }
597
+ const parent = parents[parents.length - 1];
598
+ const catches = parent?.type === 'MemberExpression' &&
599
+ parent.object === call &&
600
+ parent.property.type === 'Identifier' &&
601
+ parent.property.name === 'catch';
602
+ const scanned = {
603
+ pattern,
604
+ file: rel,
605
+ line: call.loc?.start.line ?? 1,
606
+ matcher,
607
+ catches,
608
+ runs: resolved.runs,
609
+ ...(resolved.notUsed !== undefined ? { notUsed: resolved.notUsed } : {}),
610
+ };
611
+ if (!matcher)
612
+ patterns.set(pattern, scanned);
613
+ state.hooks.push(scanned);
614
+ }
615
+ /**
616
+ * Rewrite one file to run as a script: imports become reads of the importing
617
+ * file's neighbours, exports become assignments, and nothing else changes, so a
618
+ * line number in an error is the line in the author's file.
619
+ */
620
+ function rewrite(code, ast, resolved) {
621
+ const edits = [];
622
+ const prelude = [];
623
+ const tail = [];
624
+ let counter = 0;
625
+ const target = (specifier) => JSON.stringify(resolved.get(specifier) ?? specifier);
626
+ for (const statement of ast.body) {
627
+ const span = () => ({
628
+ start: statement.start,
629
+ end: statement.end,
630
+ text: blank(code.slice(statement.start, statement.end)),
631
+ });
632
+ switch (statement.type) {
633
+ case 'ImportDeclaration': {
634
+ const specifier = String(statement.source.value);
635
+ const variable = `__m${counter++}`;
636
+ prelude.push(`const ${variable} = __import(${target(specifier)});`);
637
+ for (const item of statement.specifiers) {
638
+ if (item.type === 'ImportDefaultSpecifier') {
639
+ prelude.push(`const ${item.local.name} = ${variable}.default;`);
640
+ }
641
+ else if (item.type === 'ImportNamespaceSpecifier') {
642
+ prelude.push(`const ${item.local.name} = ${variable};`);
643
+ }
644
+ else {
645
+ prelude.push(`const ${item.local.name} = ${variable}[${JSON.stringify(item.imported.name ?? item.imported.value)}];`);
646
+ }
647
+ }
648
+ edits.push(span());
649
+ break;
650
+ }
651
+ case 'ExportNamedDeclaration': {
652
+ if (statement.source !== null && statement.source !== undefined) {
653
+ const variable = `__m${counter++}`;
654
+ prelude.push(`const ${variable} = __import(${target(String(statement.source.value))});`);
655
+ for (const item of statement.specifiers) {
656
+ const exported = item.exported.name ?? item.exported.value;
657
+ const local = item.local.name ?? item.local.value;
658
+ tail.push(`__exports[${JSON.stringify(exported)}] = ${variable}[${JSON.stringify(local)}];`);
659
+ }
660
+ edits.push(span());
661
+ }
662
+ else if (statement.declaration !== null && statement.declaration !== undefined) {
663
+ const declaration = statement.declaration;
664
+ edits.push({
665
+ start: statement.start,
666
+ end: declaration.start,
667
+ text: blank(code.slice(statement.start, declaration.start)),
668
+ });
669
+ const names = [];
670
+ if (declaration.type === 'VariableDeclaration') {
671
+ for (const declarator of declaration.declarations) {
672
+ patternNames(declarator.id, names);
673
+ }
674
+ }
675
+ else if (declaration.id)
676
+ names.push(declaration.id.name);
677
+ for (const name of names)
678
+ tail.push(`__exports[${JSON.stringify(name)}] = ${name};`);
679
+ }
680
+ else {
681
+ for (const item of statement.specifiers) {
682
+ tail.push(`__exports[${JSON.stringify(item.exported.name ?? item.exported.value)}] = ${item.local.name};`);
683
+ }
684
+ edits.push(span());
685
+ }
686
+ break;
687
+ }
688
+ case 'ExportAllDeclaration': {
689
+ const variable = `__m${counter++}`;
690
+ prelude.push(`const ${variable} = __import(${target(String(statement.source.value))});`);
691
+ if (statement.exported) {
692
+ tail.push(`__exports[${JSON.stringify(statement.exported.name ?? statement.exported.value)}] = ${variable};`);
693
+ }
694
+ else {
695
+ tail.push(`for (const __k of Object.keys(${variable})) { if (__k !== "default") __exports[__k] = ${variable}[__k]; }`);
696
+ }
697
+ edits.push(span());
698
+ break;
699
+ }
700
+ case 'ExportDefaultDeclaration': {
701
+ const declaration = statement.declaration;
702
+ const named = (declaration.type === 'FunctionDeclaration' || declaration.type === 'ClassDeclaration') &&
703
+ declaration.id !== null &&
704
+ declaration.id !== undefined;
705
+ if (named) {
706
+ edits.push({
707
+ start: statement.start,
708
+ end: declaration.start,
709
+ text: blank(code.slice(statement.start, declaration.start)),
710
+ });
711
+ tail.push(`__exports.default = ${declaration.id.name};`);
712
+ }
713
+ else {
714
+ edits.push({
715
+ start: statement.start,
716
+ end: declaration.start,
717
+ text: '__exports.default = ',
718
+ });
719
+ edits.push({ start: statement.end, end: statement.end, text: ';' });
720
+ }
721
+ break;
722
+ }
723
+ }
724
+ }
725
+ let out = code;
726
+ for (const edit of [...edits].sort((a, b) => b.start - a.start || b.end - a.end)) {
727
+ out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
728
+ }
729
+ return `${prelude.join(' ')}${out}\n${tail.join('\n')}`;
730
+ }
731
+ /**
732
+ * Read a plugin's hooks module before anything runs it: the files it is made
733
+ * of, what it hooks, what it calls on `$`, and whatever the module is refused
734
+ * for. Nothing here runs the module.
735
+ */
736
+ export function scanHookModule(root, entry) {
737
+ const state = {
738
+ root: resolve(root),
739
+ refusals: [],
740
+ hooks: [],
741
+ calls: [],
742
+ callStarts: [],
743
+ hookBodies: [],
744
+ envNames: new Set(),
745
+ analyses: new Map(),
746
+ rewritten: new Map(),
747
+ total: 0,
748
+ };
749
+ const queue = [entry];
750
+ const entryRel = entry;
751
+ while (queue.length > 0) {
752
+ const next = queue.shift();
753
+ if (state.analyses.has(next))
754
+ continue;
755
+ analyseFile(state, next, next === entryRel, queue);
756
+ }
757
+ let program;
758
+ if (state.refusals.length === 0) {
759
+ const files = {};
760
+ for (const [rel, analysis] of state.analyses) {
761
+ const resolved = new Map();
762
+ for (const item of analysis.imports) {
763
+ const target = resolveImport(state, rel, item.specifier);
764
+ if (target !== undefined)
765
+ resolved.set(item.specifier, target);
766
+ }
767
+ files[rel] = rewrite(analysis.code, analysis.ast, resolved);
768
+ }
769
+ program = { entry: entryRel, files };
770
+ }
771
+ const calls = state.calls.map((call, index) => {
772
+ const at = state.callStarts[index];
773
+ if (at === undefined)
774
+ return call;
775
+ const inside = state.hookBodies.filter((body) => body.file === at.file && body.start <= at.start && at.start < body.end);
776
+ const neverRuns = inside.length > 0 && inside.every((body) => !body.runs);
777
+ return neverRuns ? { ...call, neverRuns } : call;
778
+ });
779
+ return {
780
+ entry: entryRel,
781
+ files: [...state.analyses.keys()],
782
+ hooks: state.hooks,
783
+ calls,
784
+ envNames: [...state.envNames].sort(),
785
+ refusals: state.refusals,
786
+ ...(program !== undefined ? { program } : {}),
787
+ };
788
+ }
789
+ //# sourceMappingURL=scan.js.map