rapydscript-ns 0.8.1 → 0.8.3

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 (58) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/CONTRIBUTORS +3 -2
  3. package/PYTHON_DIFFERENCES_REPORT.md +291 -0
  4. package/PYTHON_FEATURE_COVERAGE.md +200 -0
  5. package/README.md +480 -79
  6. package/TODO.md +6 -318
  7. package/hack_demo.pyj +112 -0
  8. package/language-service/index.js +4474 -0
  9. package/language-service/language-service.d.ts +40 -0
  10. package/package.json +9 -10
  11. package/src/ast.pyj +30 -6
  12. package/src/baselib-builtins.pyj +181 -11
  13. package/src/baselib-containers.pyj +154 -5
  14. package/src/baselib-errors.pyj +3 -0
  15. package/src/baselib-internal.pyj +40 -1
  16. package/src/baselib-str.pyj +42 -1
  17. package/src/lib/collections.pyj +1 -1
  18. package/src/lib/numpy.pyj +10 -10
  19. package/src/monaco-language-service/analyzer.js +132 -22
  20. package/src/monaco-language-service/builtins.js +22 -2
  21. package/src/monaco-language-service/completions.js +224 -3
  22. package/src/monaco-language-service/diagnostics.js +55 -5
  23. package/src/monaco-language-service/index.js +26 -5
  24. package/src/monaco-language-service/scope.js +3 -0
  25. package/src/output/classes.pyj +20 -3
  26. package/src/output/codegen.pyj +38 -3
  27. package/src/output/functions.pyj +35 -25
  28. package/src/output/loops.pyj +64 -11
  29. package/src/output/modules.pyj +1 -4
  30. package/src/output/operators.pyj +67 -1
  31. package/src/output/statements.pyj +7 -3
  32. package/src/output/stream.pyj +6 -13
  33. package/src/parse.pyj +94 -14
  34. package/src/tokenizer.pyj +1 -0
  35. package/test/baselib.pyj +4 -4
  36. package/test/classes.pyj +56 -17
  37. package/test/collections.pyj +5 -5
  38. package/test/python_compat.pyj +326 -0
  39. package/test/python_features.pyj +1271 -0
  40. package/test/slice.pyj +105 -0
  41. package/test/str.pyj +25 -0
  42. package/test/unit/fixtures/fibonacci_expected.js +1 -1
  43. package/test/unit/index.js +119 -7
  44. package/test/unit/language-service-builtins.js +70 -0
  45. package/test/unit/language-service-bundle.js +83 -0
  46. package/test/unit/language-service-completions.js +289 -0
  47. package/test/unit/language-service-index.js +350 -0
  48. package/test/unit/language-service-scope.js +255 -0
  49. package/test/unit/language-service.js +158 -1
  50. package/test/unit/run-language-service.js +2 -0
  51. package/test/unit/web-repl.js +134 -0
  52. package/tools/build-language-service.js +2 -2
  53. package/tools/compiler.js +0 -24
  54. package/tools/export.js +3 -37
  55. package/tools/lint.js +1 -1
  56. package/tools/self.js +1 -9
  57. package/web-repl/rapydscript.js +6 -40
  58. package/web-repl/language-service.js +0 -4084
package/TODO.md CHANGED
@@ -1,327 +1,15 @@
1
1
 
2
2
  ### libraries
3
- - allow var etc as property name
4
- - revert numpy variance method to be var
5
3
 
6
- - omit_function_metadata breaks imports - it needs to be changed to only affect imported modules, maybe?
4
+ - fix error from vuln report
5
+ - https://socket.dev/npm/package/rapydscript-ns/alerts/0.8.1?tab=dependencies
6
+ - https://snyk.io/test/github/ficocelliguy/rapydscript-ns
7
7
 
8
- - variables just say (variable) on hover, not their type?
8
+ - omit_function_metadata breaks imports - it needs to be changed to only affect imported modules, maybe?
9
9
 
10
10
  - vscode plugin based on language service
11
11
 
12
- - export language service to npm module
13
- - update url links
14
- - make npm module
15
-
16
-
17
-
18
- I would like you to add support for [ Python's extended subscript syntax where commas inside [] implicitly form a tuple ] to rapydscript. It should have the same syntax as the Python implementation, and be transpiled into equivalent javascript. Please ensure with unit tests that it transpiles and the output JS runs correctly, and that the language service correctly handles it in parsed code. Please make sure it works in the web-repl too. Please also update the README to mention this support.
19
-
20
-
21
-
22
-
23
- # 1. Placeholder body (like pass)
24
- def todo():
25
- ...
26
-
27
- class MyProtocol:
28
- def method(self) -> int: ...
29
-
30
-
31
- # 3. Sentinel / default marker
32
- _MISSING = ...
33
-
34
- def greet(name=...):
35
- if name is ...:
36
- name = "World"
37
- print(f"Hello, {name}!")
38
-
39
- greet() # Hello, World!
40
- greet("Alice") # Hello, Alice!
41
-
42
-
43
- # 4. NumPy-style slice shorthand (all leading dimensions)
44
- import numpy as np
45
- arr = np.zeros((2, 3, 4))
46
- print(arr[..., 0] ) # shape (2, 3) — first element of last axis
47
- print(arr[1, ...]) # shape (3, 4) — entire second "sheet"
48
-
49
- # 5. Identity check
50
- print(... is ...) # True (singleton)
51
- print(... is Ellipsis) # True
52
- print(type(...).__name__) # ellipsis
53
-
54
-
55
-
56
-
57
-
58
-
59
-
60
- Python Feature Gap Report: RapydScript-NS
61
-
62
- Summary
63
-
64
- RapydScript-NS covers the vast majority of Python 2/3 core syntax well. The gaps fall into four categories: modern Python syntax, OOP/protocol features, standard library modules, and semantic
65
- differences.
66
-
67
- ---
68
- 1. Modern Python Syntax (Not Supported)
69
-
70
- ┌───────────────────────────────────────────────┬────────────────┬──────────────────────────────────────────────────────────────┐
71
- │ Feature │ Python Version │ Notes │
72
- ├───────────────────────────────────────────────┼────────────────┼──────────────────────────────────────────────────────────────┤
73
- │ match/case (structural pattern matching) │ 3.10+ │ -tested │
74
- ├───────────────────────────────────────────────┼────────────────┼──────────────────────────────────────────────────────────────┤
75
- │ Walrus operator := │ 3.8+ │ -tested │
76
- ├───────────────────────────────────────────────┼────────────────┼──────────────────────────────────────────────────────────────┤
77
- │ lambda keyword │ all │ -tested │
78
- ├───────────────────────────────────────────────┼────────────────┼──────────────────────────────────────────────────────────────┤
79
- │ Variable type annotations x: int = 1 │ 3.6+ │ needs testing │
80
- ├───────────────────────────────────────────────┼────────────────┼──────────────────────────────────────────────────────────────┤
81
- │ Positional-only parameters (def f(a, /, b):) │ 3.8+ │ -tested │
82
- ├───────────────────────────────────────────────┼────────────────┼──────────────────────────────────────────────────────────────┤
83
- │ Keyword-only parameters (def f(a, *, b):) │ 3.0+ │ -tested │
84
- ├───────────────────────────────────────────────┼────────────────┼──────────────────────────────────────────────────────────────┤
85
- │ Starred assignment a, *b, c = [1,2,3,4,5] │ 3.0+ │ -tested │
86
- ├───────────────────────────────────────────────┼────────────────┼──────────────────────────────────────────────────────────────┤
87
- │ Dict merge literal {**d1, **d2} │ 3.5+ │ -tested │
88
- ├───────────────────────────────────────────────┼────────────────┼──────────────────────────────────────────────────────────────┤
89
- │ Parenthesized with (multi-context) │ 3.10+ │ - doesn't make sense in a web context │
90
- ├───────────────────────────────────────────────┼────────────────┼──────────────────────────────────────────────────────────────┤
91
- │ Exception chaining raise X from Y │ 3.0+ │ Plain raise only │
92
- ├───────────────────────────────────────────────┼────────────────┼──────────────────────────────────────────────────────────────┤
93
- │ except* (exception groups) │ 3.11+ │ No support │
94
- ├───────────────────────────────────────────────┼────────────────┼──────────────────────────────────────────────────────────────┤
95
- │ Nested comprehensions (for a in b for c in d) │ all │ -tested │
96
- ├───────────────────────────────────────────────┼────────────────┼──────────────────────────────────────────────────────────────┤
97
- │ Complex number literals 3+4j │ all │ No j suffix │
98
- ├───────────────────────────────────────────────┼────────────────┼──────────────────────────────────────────────────────────────┤
99
- │ Ellipsis literal ... as expression │ all │ Only valid as slice (a[...]) │
100
- ├───────────────────────────────────────────────┼────────────────┼──────────────────────────────────────────────────────────────┤
101
- │ b'...' bytes literals │ all │ No b prefix; encoding module exists but no native bytes type │
102
- └───────────────────────────────────────────────┴────────────────┴──────────────────────────────────────────────────────────────┘
103
-
104
- ---
105
- 2. OOP and Dunder Protocol Gaps
106
-
107
- Not Supported at All
108
-
109
- ┌─────────────────────────────────────────┬─────────────────────────────────────────────────────────────────┐
110
- │ Feature │ Notes │
111
- ├─────────────────────────────────────────┼─────────────────────────────────────────────────────────────────┤
112
- │ super() │ -tested │
113
- ├─────────────────────────────────────────┼─────────────────────────────────────────────────────────────────┤
114
- │ __new__ │ No alternative constructor support │
115
- ├─────────────────────────────────────────┼─────────────────────────────────────────────────────────────────┤
116
- │ __del__ │ No destructor/finalizer │
117
- ├─────────────────────────────────────────┼─────────────────────────────────────────────────────────────────┤
118
- │ __hash__ │ Explicitly noted as not implemented; set/dict uses === identity │
119
- ├─────────────────────────────────────────┼─────────────────────────────────────────────────────────────────┤
120
- │ __bool__ │ Empty [] and {} are truthy in JS (differs from Python) │
121
- ├─────────────────────────────────────────┼─────────────────────────────────────────────────────────────────┤
122
- │ __call__ │ Objects cannot be made callable via dunder │
123
- ├─────────────────────────────────────────┼─────────────────────────────────────────────────────────────────┤
124
- │ __getattr__ / __setattr__ / __delattr__ │ No attribute access interception │
125
- ├─────────────────────────────────────────┼─────────────────────────────────────────────────────────────────┤
126
- │ __getattribute__ │ No attribute lookup overriding │
127
- ├─────────────────────────────────────────┼─────────────────────────────────────────────────────────────────┤
128
- │ __format__ │ No custom format() behavior │
129
- ├─────────────────────────────────────────┼─────────────────────────────────────────────────────────────────┤
130
- │ __slots__ │ No slot declarations │
131
- ├─────────────────────────────────────────┼─────────────────────────────────────────────────────────────────┤
132
- │ __class_getitem__ │ No MyClass[T] generic syntax support │
133
- ├─────────────────────────────────────────┼─────────────────────────────────────────────────────────────────┤
134
- │ __init_subclass__ │ No subclass hooks │
135
- ├─────────────────────────────────────────┼─────────────────────────────────────────────────────────────────┤
136
- │ classmethod decorator │ Not tested/documented (may partially work via @staticmethod) │
137
- └─────────────────────────────────────────┴─────────────────────────────────────────────────────────────────┘
138
-
139
- Arithmetic/Comparison Operator Overloading
140
-
141
- All of these dunder methods are not dispatched — operators always use JS native semantics:
142
-
143
- __add__, __radd__, __sub__, __mul__, __truediv__, __floordiv__, __mod__, __pow__, __lt__, __le__, __gt__, __ge__, __ne__, __neg__, __pos__, __abs__, __invert__, __lshift__, __rshift__, __and__,
144
- __or__, __xor__
145
-
146
- (Only __eq__, __contains__, __iter__, __len__, __enter__, __exit__, __repr__, __str__ are dispatched)
147
-
148
- Nested Classes
149
-
150
- Noted in test file (test/classes.pyj) as "not yet fully implemented."
151
-
152
- Abstract Base Classes (ABCs)
153
-
154
- No abc module, no @abstractmethod, no Protocol support.
155
-
156
- ---
157
- 3. Built-in Functions Missing
158
-
159
- ┌──────────────────────────┬────────────────────────────────────────────────┐
160
- │ Function │ Notes │
161
- ├──────────────────────────┼────────────────────────────────────────────────┤
162
- │ super() │ tested │
163
- ├──────────────────────────┼────────────────────────────────────────────────┤
164
- │ issubclass() │ Not implemented │
165
- ├──────────────────────────┼────────────────────────────────────────────────┤
166
- │ hash() │ Not implemented │
167
- ├──────────────────────────┼────────────────────────────────────────────────┤
168
- │ format(value, spec) │ Not listed; str.format() works │
169
- ├──────────────────────────┼────────────────────────────────────────────────┤
170
- │ vars() │ Not listed │
171
- ├──────────────────────────┼────────────────────────────────────────────────┤
172
- │ locals() │ Not listed │
173
- ├──────────────────────────┼────────────────────────────────────────────────┤
174
- │ globals() │ Not listed │
175
- ├──────────────────────────┼────────────────────────────────────────────────┤
176
- │ exec() │ Not listed (JS eval works directly via v'...') │
177
- ├──────────────────────────┼────────────────────────────────────────────────┤
178
- │ eval() │ Not listed │
179
- ├──────────────────────────┼────────────────────────────────────────────────┤
180
- │ compile() │ N/A │
181
- ├──────────────────────────┼────────────────────────────────────────────────┤
182
- │ __import__() │ Not supported │
183
- ├──────────────────────────┼────────────────────────────────────────────────┤
184
- │ input() │ Not built in │
185
- ├──────────────────────────┼────────────────────────────────────────────────┤
186
- │ open() │ Not built in │
187
- ├──────────────────────────┼────────────────────────────────────────────────┤
188
- │ bytes() / bytearray() │ Not built in │
189
- ├──────────────────────────┼────────────────────────────────────────────────┤
190
- │ memoryview() │ N/A (browser context) │
191
- ├──────────────────────────┼────────────────────────────────────────────────┤
192
- │ zip(..., strict=True) │ strict kwarg not supported │
193
- ├──────────────────────────┼────────────────────────────────────────────────┤
194
- │ enumerate(x, start=N) │ start parameter may not be supported │
195
- ├──────────────────────────┼────────────────────────────────────────────────┤
196
- │ all() / any() │ tested │
197
- ├──────────────────────────┼────────────────────────────────────────────────┤
198
- │ next(iter, default?) │ Not listed │
199
- ├──────────────────────────┼────────────────────────────────────────────────┤
200
- │ iter(callable, sentinel) │ Two-arg form likely not supported │
201
- ├──────────────────────────┼────────────────────────────────────────────────┤
202
- │ round(x, ndigits?) │ Not listed │
203
- ├──────────────────────────┼────────────────────────────────────────────────┤
204
- │ slice() │ Not listed as builtin object │
205
- ├──────────────────────────┼────────────────────────────────────────────────┤
206
- │ frozenset() │ Not listed │
207
- ├──────────────────────────┼────────────────────────────────────────────────┤
208
- │ complex() │ Not listed │
209
- ├──────────────────────────┼────────────────────────────────────────────────┤
210
- │ object() │ Not listed │
211
- └──────────────────────────┴────────────────────────────────────────────────┘
212
-
213
- ---
214
- 4. Standard Library Modules Missing
215
-
216
- These are Python stdlib modules with no equivalent in src/lib/:
217
-
218
- ┌─────────────┬─────────────────────────────────────────────────────────────────────────────────┐
219
- │ Module │ What's Missing │
220
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
221
- │ collections │ tested │
222
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
223
- │ functools │ tested │
224
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
225
- │ itertools │ tested │
226
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
227
- │ typing │ List, Dict, Optional, Union, Tuple, Generic, TypeVar, etc. │
228
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
229
- │ dataclasses │ @dataclass, field(), asdict(), astuple() │
230
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
231
- │ contextlib │ contextmanager, suppress, ExitStack, asynccontextmanager │
232
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
233
- │ copy │ copy(), deepcopy() │
234
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
235
- │ string │ Character constants, Template, Formatter │
236
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
237
- │ json │ dumps, loads (JS JSON works directly, but no Python wrapper) │
238
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
239
- │ datetime │ date, time, datetime, timedelta │
240
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
241
- │ inspect │ signature, getmembers, isfunction, etc. │
242
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
243
- │ asyncio │ Event loop, gather, sleep, Queue, Task wrappers │
244
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
245
- │ enum │ Enum, IntEnum, Flag │
246
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
247
- │ abc │ ABC, abstractmethod │
248
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
249
- │ io │ StringIO, BytesIO │
250
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
251
- │ struct │ Binary packing/unpacking │
252
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
253
- │ hashlib │ MD5, SHA-256, etc. │
254
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
255
- │ hmac │ Keyed hashing │
256
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
257
- │ base64 │ (partial — encodings module exists) │
258
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
259
- │ urllib │ URL parsing/encoding (no urllib.parse) │
260
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
261
- │ html │ escape, unescape │
262
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
263
- │ csv │ CSV parsing │
264
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
265
- │ textwrap │ wrap, fill, dedent, indent │
266
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
267
- │ pprint │ Pretty-printing │
268
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
269
- │ logging │ Logging framework │
270
- ├─────────────┼─────────────────────────────────────────────────────────────────────────────────┤
271
- │ unittest │ Test framework (custom runner used instead) │
272
- └─────────────┴─────────────────────────────────────────────────────────────────────────────────┘
273
-
274
- ---
275
- 5. Semantic Differences (Traps)
276
-
277
- These features exist but behave differently from Python:
278
-
279
- ┌─────────────────────────┬────────────────────────────────────────────┬─────────────────────────────────────────────────────────────────────────────────┐
280
- │ Feature │ Python Behavior │ RapydScript Behavior │
281
- ├─────────────────────────┼────────────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────────┤
282
- │ Truthiness of [] │ False │ True (JS semantics) │
283
- ├─────────────────────────┼────────────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────────┤
284
- │ Truthiness of {} │ False │ True (JS semantics) │
285
- ├─────────────────────────┼────────────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────────┤
286
- │ is / is not │ Object identity │ Strict equality === / !== │
287
- ├─────────────────────────┼────────────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────────┤
288
- │ // on floats │ math.floor(a/b) │ Correct for integers; JS Math.floor used │
289
- ├─────────────────────────┼────────────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────────┤
290
- │ % on negative numbers │ Python modulo (always positive) │ JS remainder (can be negative) │
291
- ├─────────────────────────┼────────────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────────┤
292
- │ int / float distinction │ Separate types │ Both are JS number │
293
- ├─────────────────────────┼────────────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────────┤
294
- │ String * repetition │ 'a' * 3 == 'aaa' │ Requires pythonize module or JS-side workaround │
295
- ├─────────────────────────┼────────────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────────┤
296
- │ sort() / pop() │ Standard list methods │ Renamed to pysort() / pypop() │
297
- ├─────────────────────────┼────────────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────────┤
298
- │ Method binding │ Unbound by default, self passed explicitly │ Same — but differs if you store methods in variables without bound_methods flag │
299
- ├─────────────────────────┼────────────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────────┤
300
- │ dict key ordering │ Insertion order (3.7+) │ Depends on JS engine (V8: insertion order) │
301
- ├─────────────────────────┼────────────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────────┤
302
- │ global scoping │ Full cross-scope declaration │ Partial — interactions with nonlocal can be confusing │
303
- ├─────────────────────────┼────────────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────────┤
304
- │ Exception .message │ Not standard (Python uses .args[0]) │ .message is standard (JS style) │
305
- ├─────────────────────────┼────────────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────────┤
306
- │ re module │ Full PCRE features │ No lookbehind, limited unicode, no (?(1)...) │
307
- └─────────────────────────┴────────────────────────────────────────────┴─────────────────────────────────────────────────────────────────────────────────┘
308
-
309
- ---
310
- Priority Gaps (Most Impactful)
311
-
312
- If prioritizing what to implement next, these have the highest user impact:
313
-
314
- 1. super() — required for idiomatic OOP code - done
315
- 2. Operator overloading (__add__, __lt__, etc.) — blocks numerical/scientific code - done
316
- 3. __bool__ / truthiness fix — silent Python compatibility trap
317
- 4. lambda keyword — commonly expected - done
318
- 5. all() / any() — extremely common builtins - done
319
- 6. functools.reduce / partial — core functional programming tools - done
320
- 7. collections.defaultdict / Counter — frequently used - done
321
- 8. Nested comprehensions — common Python pattern - done
322
- 9. Walrus operator := — increasingly common in modern Python - done
323
- 10. classmethod decorator — standard OOP pattern - done
324
-
12
+ - examples of using js libraries in rapydscript in readme
325
13
 
326
14
 
327
-
15
+ I would like you to add support for [ [List Concatenation (+) Without overload_operators]() ] to rapydscript. It should have the same syntax as the Python implementation, and be transpiled into equivalent javascript. Please ensure with unit tests that it transpiles and the output JS runs correctly, and that the language service correctly handles it in parsed code. Please make sure it works in the web-repl too. Please also update the README if it has any outdated info about this, and the PYTHON_FEATURE_COVERAGE report.
package/hack_demo.pyj ADDED
@@ -0,0 +1,112 @@
1
+ # Over-engineered RapydScript hacking script — Python features on parade
2
+
3
+ class HackAction:
4
+ """Enum-like action namespace."""
5
+ WEAKEN = 'weaken'
6
+ GROW = 'grow'
7
+ HACK = 'hack'
8
+
9
+ @staticmethod
10
+ def all():
11
+ return [HackAction.WEAKEN, HackAction.GROW, HackAction.HACK]
12
+
13
+
14
+ class ServerConfig:
15
+ """Data-class-style target config with property + fluent builder."""
16
+
17
+ def __init__(self, name, money_factor=1.0, sec_buffer=0.0):
18
+ self._name = name
19
+ self.money_factor = money_factor
20
+ self.sec_buffer = sec_buffer
21
+ self._tags = {'auto', 'hack'} # set literal
22
+
23
+ @property
24
+ def name(self):
25
+ return self._name
26
+
27
+ def __repr__(self):
28
+ return "ServerConfig(name={}, tags={})".format(
29
+ repr(self._name), sorted(list(self._tags))
30
+ )
31
+
32
+ def add_tags(self, *tags): # *args + fluent return
33
+ for t in tags:
34
+ self._tags.add(t)
35
+ return self
36
+
37
+
38
+ def decide_action(ns, target, money_thresh, sec_thresh):
39
+ """next() + generator expression to pick highest-priority action."""
40
+ checks = [
41
+ (ns.getServerSecurityLevel(target) > sec_thresh, HackAction.WEAKEN),
42
+ (ns.getServerMoneyAvailable(target) < money_thresh, HackAction.GROW),
43
+ ]
44
+ return next((action for cond, action in checks if cond), HackAction.HACK)
45
+
46
+
47
+ async def breach(ns, target, exploits):
48
+ """Apply available exploits via (exe, fn) tuple list, nuke, return summary."""
49
+ # list of (exe filename, bound ns method) tuples
50
+ exe_methods = [
51
+ ('BruteSSH.exe', ns.brutessh),
52
+ ('FTPCrack.exe', ns.ftpcrack),
53
+ ('relaySMTP.exe', ns.relaysmtp),
54
+ ]
55
+ applied = [fn for exe, fn in exe_methods if ns.fileExists(exe, "home")]
56
+ missing = [exe for exe, fn in exe_methods if not ns.fileExists(exe, "home")]
57
+
58
+ if missing:
59
+ ns.tprint("Missing: {}".format(', '.join(missing)))
60
+
61
+ for fn in applied:
62
+ fn(target)
63
+ ns.nuke(target)
64
+
65
+ return {'applied': len(applied), 'total': len(exploits),
66
+ 'rooted': ns.hasRootAccess(target)}
67
+
68
+
69
+ async def main(ns):
70
+ config = ServerConfig("n00dles").add_tags('target', 'beginner') # fluent
71
+ ns.tprint(repr(config)) # __repr__
72
+
73
+ target = config.name # @property
74
+ money_thresh = ns.getServerMaxMoney(target) * config.money_factor
75
+ sec_thresh = ns.getServerMinSecurityLevel(target) + config.sec_buffer
76
+
77
+ def by_name_len(p): # named key fn (required for
78
+ return len(p[0]) # anonymous fns in call args)
79
+ exploits = sorted([
80
+ ('brutessh', 'BruteSSH.exe'),
81
+ ('ftpcrack', 'FTPCrack.exe'),
82
+ ('relaysmtp', 'relaySMTP.exe'),
83
+ ], key=by_name_len)
84
+
85
+ result = await breach(ns, target, exploits)
86
+ ns.tprint("Breach: {applied}/{total} applied, rooted={rooted}".format(**result))
87
+ assert result['rooted'], "Root access denied on {}!".format(target)
88
+
89
+ dispatch = { # dict literal
90
+ 'weaken': ns.weaken,
91
+ 'grow': ns.grow,
92
+ 'hack': ns.hack,
93
+ }
94
+ stats = {a: 0 for a in HackAction.all()} # dict comprehension
95
+
96
+ cycle = 0
97
+ while True:
98
+ cycle += 1
99
+ action = decide_action(ns, target, money_thresh, sec_thresh)
100
+ stats[action] += 1
101
+
102
+ if cycle % 10 is 0: # periodic summary
103
+ counts = [stats[a] for a in HackAction.all()]
104
+ summary = ', '.join(["{}: {}".format(a, v)
105
+ for a, v in zip(HackAction.all(), counts)])
106
+ ns.tprint("Cycle {} | {} any={} all={}".format(
107
+ cycle, summary,
108
+ any([v > 0 for v in counts]), # any()
109
+ all([v > 0 for v in counts]) # all()
110
+ ))
111
+
112
+ await dispatch[action](target)