@poe-platform/safe-bash 0.1.756 → 0.1.757

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 (113) hide show
  1. package/dist/image-ast/index.browser.js +4 -4
  2. package/dist/image-ast/index.js +4 -4
  3. package/dist/safe-bash/chunks/{chunk-LESPJ3OG.js → chunk-WNWIBBJZ.js} +15 -2
  4. package/dist/safe-bash/command-chunks/{chunk-S4J6MSLY.js → chunk-444OTXM7.js} +3 -3
  5. package/dist/safe-bash/command-chunks/{chunk-6AIOGLZO.js → chunk-CE6Z2ULX.js} +2 -2
  6. package/dist/safe-bash/command-chunks/{chunk-5VSGEE6J.js → chunk-F4IQCXZG.js} +5 -5
  7. package/dist/safe-bash/command-chunks/{chunk-F5MORDSU.js → chunk-FDNCPZQS.js} +32 -1
  8. package/dist/safe-bash/command-chunks/{chunk-SG3ZDZCX.js → chunk-FLMLM7Y4.js} +2 -2
  9. package/dist/safe-bash/command-chunks/{chunk-CT3FB722.js → chunk-J7UMKBRK.js} +1 -1
  10. package/dist/safe-bash/command-chunks/{chunk-QQOAK7JQ.js → chunk-KKJCKPTA.js} +1 -1
  11. package/dist/safe-bash/command-chunks/{chunk-7KS6PX4U.js → chunk-KSIGF4AG.js} +3 -3
  12. package/dist/safe-bash/command-chunks/{chunk-4HQ7WYSI.js → chunk-MED2BOOW.js} +30 -5
  13. package/dist/safe-bash/command-chunks/{chunk-JRNLDPLI.js → chunk-OZSWW23M.js} +1 -1
  14. package/dist/safe-bash/command-chunks/{chunk-DKQ5REXF.js → chunk-QDPRSPHQ.js} +1 -1
  15. package/dist/safe-bash/command-chunks/{chunk-WOPU2VWF.js → chunk-RID3B5RE.js} +1 -1
  16. package/dist/safe-bash/command-chunks/{chunk-DVZCHNB5.js → chunk-S4MLIYSN.js} +7 -7
  17. package/dist/safe-bash/command-chunks/{chunk-REYTQLLB.js → chunk-TT2DMDBY.js} +1 -1
  18. package/dist/safe-bash/command-chunks/{chunk-UGX6MXDD.js → chunk-UIIT4ULR.js} +3 -3
  19. package/dist/safe-bash/command-chunks/{chunk-A6NFLWZI.js → chunk-WKPOGTZY.js} +22 -6
  20. package/dist/safe-bash/command-chunks/{chunk-3DOHQQJR.js → chunk-Y64PA6IA.js} +8 -8
  21. package/dist/safe-bash/command-chunks/{chunk-6Z7OS3TZ.js → chunk-ZP5KDHB4.js} +7 -7
  22. package/dist/safe-bash/commands/pandoc/index.d.ts +1 -1
  23. package/dist/safe-bash/commands/pandoc/index.js +5 -3
  24. package/dist/safe-bash/commands/python/index.browser.js +1 -1
  25. package/dist/safe-bash/commands/python/index.js +6 -0
  26. package/dist/safe-bash/commands/python/jspi.js +11 -2
  27. package/dist/safe-bash/core.browser.js +6 -4
  28. package/dist/safe-bash-command-csvkit/index.js +8 -8
  29. package/dist/safe-bash-command-soffice/index.js +16 -16
  30. package/dist/safe-bash-command-ssconvert/core.js +8 -8
  31. package/dist/safe-bash-command-ssconvert/formats/csv.js +9 -9
  32. package/dist/safe-bash-command-ssconvert/formats/ods.js +8 -8
  33. package/dist/safe-bash-command-ssconvert/formats/spreadsheetml.js +1 -1
  34. package/dist/safe-bash-command-ssconvert/formats/xls.js +9 -8
  35. package/dist/safe-bash-command-ssconvert/formats/xlsx.js +8 -8
  36. package/dist/safe-bash-command-ssconvert/index.js +107 -27
  37. package/dist/safe-bash-contracts/filesystem-descriptor.js +1 -1
  38. package/dist/safe-bash-contracts/filesystem-output.js +1 -1
  39. package/dist/safe-bash-mcp/index.js +4 -4
  40. package/dist/spreadsheet-engine/formulas/ast.d.ts +13 -0
  41. package/dist/spreadsheet-engine/formulas/conventions.js +1 -1
  42. package/dist/spreadsheet-engine/formulas/dependencies.js +2 -2
  43. package/dist/spreadsheet-engine/formulas/evaluator.js +2 -2
  44. package/dist/spreadsheet-engine/formulas/named-expressions.d.ts +2 -2
  45. package/dist/spreadsheet-engine/formulas/named-expressions.js +31 -5
  46. package/dist/spreadsheet-engine/formulas/parser.js +34 -0
  47. package/dist/spreadsheet-engine/formulas/rewriting.js +19 -1
  48. package/dist/spreadsheet-engine/formulas/serialization.js +6 -0
  49. package/dist/spreadsheet-format-xls/biff-write-formulas.js +2 -0
  50. package/dist/xlsx-ast/formula-semantics.js +2 -0
  51. package/package.json +2 -2
  52. package/dist/safe-bash/chunks/browser-ECQX6GMK.js +0 -6766
  53. package/dist/safe-bash/chunks/bz2-4OP3OWW3.js +0 -8
  54. package/dist/safe-bash/chunks/chunk-22XPAAOI.js +0 -173
  55. package/dist/safe-bash/chunks/chunk-44WUNUPV.js +0 -649
  56. package/dist/safe-bash/chunks/chunk-4E3SGG37.js +0 -876
  57. package/dist/safe-bash/chunks/chunk-4QTSSQKP.js +0 -898
  58. package/dist/safe-bash/chunks/chunk-5UVGPVXP.js +0 -410
  59. package/dist/safe-bash/chunks/chunk-64OE6Q6X.js +0 -3487
  60. package/dist/safe-bash/chunks/chunk-6IIFUPN2.js +0 -1526
  61. package/dist/safe-bash/chunks/chunk-BENDLTQD.js +0 -7065
  62. package/dist/safe-bash/chunks/chunk-BMO5LWEX.js +0 -534
  63. package/dist/safe-bash/chunks/chunk-BPMCPTNP.js +0 -1920
  64. package/dist/safe-bash/chunks/chunk-BRJTAWP5.js +0 -2955
  65. package/dist/safe-bash/chunks/chunk-C3GEIN7Q.js +0 -20054
  66. package/dist/safe-bash/chunks/chunk-CBVANNKK.js +0 -174814
  67. package/dist/safe-bash/chunks/chunk-CEWCRI6H.js +0 -2813
  68. package/dist/safe-bash/chunks/chunk-CGL53DQQ.js +0 -37
  69. package/dist/safe-bash/chunks/chunk-CTYJJD4O.js +0 -869
  70. package/dist/safe-bash/chunks/chunk-CWSS4MQA.js +0 -7
  71. package/dist/safe-bash/chunks/chunk-DLIGMTCP.js +0 -3266
  72. package/dist/safe-bash/chunks/chunk-EMAJ7WUW.js +0 -1031
  73. package/dist/safe-bash/chunks/chunk-FDKIZ2IJ.js +0 -1950
  74. package/dist/safe-bash/chunks/chunk-FZWJ2A7V.js +0 -3093
  75. package/dist/safe-bash/chunks/chunk-G2VCIF2J.js +0 -22
  76. package/dist/safe-bash/chunks/chunk-GVKBUQDX.js +0 -2649
  77. package/dist/safe-bash/chunks/chunk-IO2OGW3E.js +0 -28051
  78. package/dist/safe-bash/chunks/chunk-ISCZG7WA.js +0 -2648
  79. package/dist/safe-bash/chunks/chunk-JCN3FXLP.js +0 -38983
  80. package/dist/safe-bash/chunks/chunk-KJHDD4A2.js +0 -759
  81. package/dist/safe-bash/chunks/chunk-LB6HVRXS.js +0 -857
  82. package/dist/safe-bash/chunks/chunk-LLWAJOZH.js +0 -15
  83. package/dist/safe-bash/chunks/chunk-LMUKYZIJ.js +0 -708
  84. package/dist/safe-bash/chunks/chunk-M5SCNKIK.js +0 -2012
  85. package/dist/safe-bash/chunks/chunk-MJPFHANT.js +0 -3350
  86. package/dist/safe-bash/chunks/chunk-MZQW2DOL.js +0 -82
  87. package/dist/safe-bash/chunks/chunk-NB2V7EOY.js +0 -1348
  88. package/dist/safe-bash/chunks/chunk-NJVGOIYN.js +0 -17
  89. package/dist/safe-bash/chunks/chunk-OLNZHDIQ.js +0 -5141
  90. package/dist/safe-bash/chunks/chunk-OSUXMC43.js +0 -2317
  91. package/dist/safe-bash/chunks/chunk-OUUVROTM.js +0 -38
  92. package/dist/safe-bash/chunks/chunk-PA6GYKBQ.js +0 -151
  93. package/dist/safe-bash/chunks/chunk-PEFHZ226.js +0 -6957
  94. package/dist/safe-bash/chunks/chunk-QBB5P5KW.js +0 -4839
  95. package/dist/safe-bash/chunks/chunk-RSAWYAEH.js +0 -973
  96. package/dist/safe-bash/chunks/chunk-UWLYRWT4.js +0 -739
  97. package/dist/safe-bash/chunks/chunk-V463NBQH.js +0 -13
  98. package/dist/safe-bash/chunks/chunk-WPUALYUS.js +0 -843
  99. package/dist/safe-bash/chunks/chunk-XHKFSRGU.js +0 -5747
  100. package/dist/safe-bash/chunks/chunk-XHRCLZ3N.js +0 -13391
  101. package/dist/safe-bash/chunks/chunk-XPF5XHLY.js +0 -15
  102. package/dist/safe-bash/chunks/chunk-ZBFOWARG.js +0 -305
  103. package/dist/safe-bash/chunks/chunk-ZG7GWQ5P.js +0 -1859
  104. package/dist/safe-bash/chunks/model-store-EIY3ZQLZ.js +0 -10
  105. package/dist/safe-bash/chunks/pdf-renderer-CMF3CSVU.js +0 -22
  106. package/dist/safe-bash/chunks/pptx-ZL6L7KP2-O425BFIU.js +0 -30658
  107. package/dist/safe-bash/chunks/src-HHEPGR7U.js +0 -18969
  108. package/dist/safe-bash/chunks/src-MXIKQCIC.js +0 -187
  109. package/dist/safe-bash/chunks/usage-6TGVA2OM.js +0 -35
  110. package/dist/safe-bash/chunks/xz-EGQGQUEI.js +0 -8
  111. package/dist/safe-bash/chunks/xz-K2E2WLM6.js +0 -9
  112. package/dist/safe-bash/chunks/zstd-6JBLP5EF.js +0 -8
  113. package/dist/safe-bash/git_rust-C3QYOAZL.wasm +0 -0
@@ -1,534 +0,0 @@
1
- import {
2
- init_platform
3
- } from "./chunk-ZG7GWQ5P.js";
4
-
5
- // packages/safe-bash/src/commands/python/invocation.ts
6
- init_platform();
7
- var PythonInvocationError = class extends Error {
8
- constructor(message) {
9
- super(message);
10
- this.name = "PythonInvocationError";
11
- }
12
- };
13
- function parsePythonInvocation(args, env) {
14
- const startupArgs = [];
15
- let informational = false;
16
- scan: for (let index = 0; index < args.length; index++) {
17
- const option = args[index];
18
- if (option === "--" || option === "-" || !option.startsWith("-")) break;
19
- if (option === "--help") {
20
- informational = true;
21
- break;
22
- }
23
- if (option === "--version") {
24
- informational = true;
25
- continue;
26
- }
27
- if (option.startsWith("--")) throw new PythonInvocationError("unsupported option " + option);
28
- for (let offset = 1; offset < option.length; offset++) {
29
- const flag = option[offset];
30
- if (flag === "h" || flag === "?") {
31
- informational = true;
32
- break scan;
33
- }
34
- if (flag === "V") {
35
- informational = true;
36
- continue;
37
- }
38
- if ("cmWX".includes(flag)) {
39
- const operand = option.slice(offset + 1) || args[++index];
40
- if (operand === void 0) throw new PythonInvocationError("argument expected for -" + flag);
41
- if (flag === "c" || flag === "m") break scan;
42
- if (flag === "X") {
43
- const separator = operand.indexOf("=");
44
- const name = separator < 0 ? operand : operand.slice(0, separator);
45
- const value = separator < 0 ? void 0 : operand.slice(separator + 1);
46
- let decimal = value ?? "";
47
- while (decimal.length && " \n\r\v\f".includes(decimal[0])) decimal = decimal.slice(1);
48
- if (decimal[0] === "+" || decimal[0] === "-") decimal = decimal.slice(1);
49
- const digits = decimal.length > 0 && [...decimal].every((character) => character >= "0" && character <= "9");
50
- const supported = name === "utf8" && (value === void 0 || value === "0" || value === "1") || (name === "dev" || name === "warn_default_encoding") && value === void 0 || name === "int_max_str_digits" && digits && Number.isSafeInteger(Number(value)) && Number(value) <= 2147483647 && (Number(value) === 0 || Number(value) >= 640);
51
- if (!supported) throw new PythonInvocationError("unsupported -X option " + operand);
52
- startupArgs.push("-X", operand);
53
- }
54
- break;
55
- }
56
- if (!"BEPOusISbdvqR".includes(flag)) throw new PythonInvocationError("unsupported option -" + flag);
57
- startupArgs.push("-" + flag);
58
- }
59
- }
60
- if (!informational && !startupArgs.includes("-E") && !startupArgs.includes("-I")) {
61
- if (env.PYTHONINSPECT) throw new PythonInvocationError("PYTHONINSPECT requires an interactive terminal, which the shell does not expose");
62
- if (env.PYTHONHOME) throw new PythonInvocationError("PYTHONHOME cannot replace the configured Pyodide runtime");
63
- }
64
- const runtimeEnv = { ...env };
65
- delete runtimeEnv.PYTHONPATH;
66
- delete runtimeEnv.PYTHONHOME;
67
- delete runtimeEnv.PYTHONWARNINGS;
68
- runtimeEnv.PYTHONINSPECT = "";
69
- startupArgs.push("-c", "");
70
- return { startupArgs, env: runtimeEnv };
71
- }
72
-
73
- // packages/safe-bash/src/commands/python/diagnostics.ts
74
- init_platform();
75
- var messages = {
76
- "executor-unavailable": "Python executor is unavailable; configure exactly one supported executor or interpreter worker.",
77
- "transport-unavailable": "Python worker transport or shared-memory operations are unavailable.",
78
- "runtime-abi": "Python runtime version or native ABI is unsupported.",
79
- "runtime-assets": "Python runtime or package assets could not be loaded.",
80
- "isolation-unavailable": "Python host isolation or resource enforcement is unavailable.",
81
- deadline: "Python execution exceeded its host deadline.",
82
- "filesystem-open": "Python filesystem handle access is unavailable; the backend must support retained open.",
83
- "filesystem-read": "Python filesystem reads are unavailable for this backend.",
84
- "filesystem-write": "Python filesystem writes are unavailable for this backend.",
85
- "filesystem-directory": "Python retained directory operations are unavailable for this backend.",
86
- "filesystem-operation": "The requested Python filesystem operation is unavailable for this backend.",
87
- capacity: "Python worker capacity exhausted.",
88
- cleanup: "Python resource cleanup failed; retirement could not be confirmed.",
89
- startup: "Python startup failed; consult the host diagnostic callback.",
90
- runtime: "Python runtime failed; consult the host diagnostic callback."
91
- };
92
- var PythonFailure = class extends Error {
93
- constructor(category, options) {
94
- super(messages[category], options);
95
- this.category = category;
96
- this.name = "PythonFailure";
97
- }
98
- category;
99
- };
100
- function isPythonFailureCategory(value) {
101
- return typeof value === "string" && Object.hasOwn(messages, value);
102
- }
103
- function reportPythonFailure(category, cause, observer) {
104
- const failure = new PythonFailure(category);
105
- try {
106
- void Promise.resolve(observer?.({ failure, cause })).catch(() => {
107
- });
108
- } catch {
109
- }
110
- return failure;
111
- }
112
- function inspectPythonCapabilities(options = {}) {
113
- const failures = /* @__PURE__ */ new Set();
114
- if (typeof options.createWorker === "function" === (typeof options.createExecutor === "function") || options.createWorker !== void 0 && typeof options.createWorker !== "function" || options.createExecutor !== void 0 && typeof options.createExecutor !== "function") failures.add("executor-unavailable");
115
- if (typeof options.createExecutor !== "function" && (typeof SharedArrayBuffer !== "function" || typeof Atomics !== "object" || typeof Atomics.store !== "function" || typeof Atomics.notify !== "function")) failures.add("transport-unavailable");
116
- if (options.runtimeVersion !== void 0 && options.runtimeVersion !== "314.0.6") failures.add("runtime-abi");
117
- for (const requirement of options.requiredFileSystem ?? []) {
118
- if (!["open", "read", "write", "directory"].includes(requirement)) throw new TypeError("Unknown Python filesystem requirement");
119
- const category = requirement === "open" ? "filesystem-open" : requirement === "read" ? "filesystem-read" : requirement === "write" ? "filesystem-write" : "filesystem-directory";
120
- try {
121
- const fs = options.fs;
122
- if (requirement === "directory") {
123
- failures.add(category);
124
- } else if (!fs || typeof fs.open !== "function" || fs.capabilities.open === false) failures.add("filesystem-open");
125
- else if (requirement === "write" && (fs.capabilities.readOnly === true || fs.capabilities.write === false)) failures.add(category);
126
- else if (requirement === "read" && fs.capabilities.read === false) failures.add(category);
127
- } catch {
128
- failures.add(category);
129
- }
130
- }
131
- return Object.freeze({
132
- configurationValid: failures.size === 0,
133
- failures: Object.freeze([...failures].map((category) => new PythonFailure(category)))
134
- });
135
- }
136
-
137
- // packages/safe-bash/src/commands/python/execution.ts
138
- init_platform();
139
- var pythonExecution = `
140
- import sys, os, json, runpy, traceback, types, warnings, textwrap, io, struct, linecache
141
- _safe_invocation = json.loads(_safe_invocation_json)
142
- os.environ.clear()
143
- os.environ.update(_safe_invocation['env'])
144
- _safe_args = list(_safe_invocation['args'])
145
- sys.orig_argv = [_safe_invocation.get('command', 'python')] + _safe_args
146
- _safe_exit = 0
147
-
148
- class _SafeOptionError(ValueError):
149
- pass
150
-
151
- def _safe_system_exit(_error):
152
- if isinstance(_error.code, int):
153
- _status = int.__index__(_error.code)
154
- _long_bound = 1 << (8 * struct.calcsize('@l') - 1)
155
- status = (_status & 255) if -_long_bound <= _status < _long_bound else 255
156
- else:
157
- status = 0 if _error.code is None else 1
158
- if _error.code is not None and not isinstance(_error.code, int):
159
- print(_error.code, file=sys.stderr)
160
- return status
161
-
162
- def _safe_launch():
163
- args = list(_safe_args)
164
- unbuffered = False
165
- ignore_env = bool(sys.flags.ignore_environment)
166
- safe_path = bool(sys.flags.safe_path)
167
- native_warning_options = list(sys.warnoptions)
168
- # Pyodide adds a bootstrap cwd entry even when CPython safe-path mode is set.
169
- # Each execution mode below supplies its own entry after explicit PYTHONPATH.
170
- sys.path[:] = [entry for entry in sys.path if entry != '']
171
- warning_options = []
172
- version_count = 0
173
- options_terminated = False
174
- while args and args[0].startswith('-') and args[0] != '-':
175
- option = args.pop(0)
176
- if option == '--':
177
- options_terminated = True
178
- break
179
- if option in ('--help', '-h', '-?'):
180
- print('usage: python [-uBEPOsSIbdvqR] [-W filter] [-X option] [-c code | -m module | file | -] [args ...]')
181
- print('Dedicated Pyodide interpreter; stdin is noninteractive.')
182
- print('-u: unbuffered binary output; -B: disable bytecode writes; -E: ignore PYTHON* settings')
183
- print('-P: omit automatic unsafe sys.path entry; -W: Python warning filter')
184
- print('-O/-OO, -S/-s/-I, -b/-bb, -d/-v/-q/-R: CPython startup flags')
185
- print('-X: utf8, dev, warn_default_encoding, int_max_str_digits; interactive flags are unsupported.')
186
- return
187
- if option == '--version':
188
- version_count += 1
189
- continue
190
- if option.startswith('--'):
191
- raise _SafeOptionError('unsupported option ' + option)
192
- index = 1
193
- while index < len(option):
194
- flag = option[index]
195
- if flag in ('h', '?'):
196
- args = ['--help']
197
- break
198
- if flag == 'V':
199
- version_count += 1
200
- index += 1
201
- continue
202
- if flag in ('c', 'm', 'W', 'X'):
203
- operand = option[index + 1:] if index + 1 < len(option) else args.pop(0) if args else None
204
- if operand is None:
205
- raise _SafeOptionError('argument expected for -' + flag)
206
- if flag in ('W', 'X'):
207
- if flag == 'W': warning_options.append(operand)
208
- break
209
- args = ['-' + flag, operand] + args
210
- break
211
- elif flag in ('O', 'S', 's', 'I', 'b', 'd', 'v', 'q', 'R'):
212
- pass # Applied by CPython startup configuration before bootstrap.
213
- elif flag == 'u':
214
- unbuffered = True
215
- elif flag == 'B':
216
- sys.dont_write_bytecode = True
217
- elif flag == 'E':
218
- ignore_env = True
219
- elif flag == 'P':
220
- safe_path = True
221
- else:
222
- raise _SafeOptionError('unsupported option -' + flag)
223
- index += 1
224
- if args and args[0] in ('-c', '-m'):
225
- break
226
- if version_count:
227
- print('Python ' + (sys.version if version_count > 1 else sys.version.split()[0]))
228
- return
229
- if not ignore_env:
230
- unbuffered = unbuffered or bool(os.environ.get('PYTHONUNBUFFERED'))
231
- sys.dont_write_bytecode = sys.dont_write_bytecode or bool(os.environ.get('PYTHONDONTWRITEBYTECODE'))
232
- safe_path = safe_path or bool(os.environ.get('PYTHONSAFEPATH'))
233
- path = os.environ.get('PYTHONPATH')
234
- if path:
235
- sys.path[0:0] = [os.path.abspath(entry) for entry in path.split(os.pathsep)]
236
- if os.environ.get('PYTHONWARNINGS'):
237
- warning_options[0:0] = os.environ['PYTHONWARNINGS'].split(',')
238
- encoding = os.environ.get('PYTHONIOENCODING')
239
- if encoding:
240
- name, separator, errors = encoding.partition(':')
241
- for stream in (sys.stdin, sys.stdout):
242
- stream.reconfigure(encoding=name or None, errors=(errors or 'strict'))
243
- sys.stderr.reconfigure(encoding=name or None, errors='backslashreplace')
244
- # CPython's -b/-bb filter follows environment and command-line -W filters.
245
- byte_warning = ('error' if sys.flags.bytes_warning > 1 else 'default') + '::BytesWarning'
246
- native_before = [value for value in native_warning_options if not (sys.flags.bytes_warning and value == byte_warning)]
247
- warning_options = native_before + warning_options + ([byte_warning] if sys.flags.bytes_warning else [])
248
- warnings._processoptions(warning_options)
249
- sys.warnoptions[:] = warning_options
250
- if unbuffered:
251
- for name in ('stdout', 'stderr'):
252
- stream = getattr(sys, name)
253
- stream.flush()
254
- encoding, errors = stream.encoding, stream.errors
255
- binary = stream.detach()
256
- raw = binary.detach() if hasattr(binary, 'detach') else binary
257
- replacement = io.TextIOWrapper(raw, encoding=encoding, errors=errors, write_through=True)
258
- setattr(sys, name, replacement)
259
- setattr(sys, '__' + name + '__', replacement)
260
- main = types.ModuleType('__main__')
261
- main.__dict__.update(__package__=None, __spec__=None, __loader__=__import__('importlib.machinery', fromlist=['BuiltinImporter']).BuiltinImporter, __builtins__=__builtins__)
262
- sys.modules['__main__'] = main
263
- if not options_terminated and args and args[0] == '-c':
264
- sys.argv = ['-c'] + args[2:]
265
- if not safe_path: sys.path.insert(0, '')
266
- source = textwrap.dedent(args[1])
267
- code = compile(source, '<string>', 'exec')
268
- # CPython 3.14 retains -c source for both top-level and nested tracebacks.
269
- linecache._register_code(code, source, '<string>')
270
- exec(code, main.__dict__)
271
- elif not options_terminated and args and args[0] == '-m':
272
- sys.argv = args[1:]
273
- if not safe_path: sys.path.insert(0, os.getcwd())
274
- runpy._run_module_as_main(args[1], alter_argv=True)
275
- elif not args or args[0] == '-':
276
- sys.argv = (['-'] + args[1:]) if args else ['']
277
- if not safe_path: sys.path.insert(0, '')
278
- main.__file__ = '<stdin>'
279
- exec(compile(sys.stdin.buffer.read(), '<stdin>', 'exec'), main.__dict__)
280
- else:
281
- sys.argv = args
282
- # CPython makes __file__ absolute without collapsing ./ or ../ components.
283
- path = args[0] if os.path.isabs(args[0]) else os.path.join(os.getcwd(), args[0])
284
- importer = __import__('pkgutil').get_importer(path)
285
- if importer is not None:
286
- sys.path.insert(0, path)
287
- runpy._run_module_as_main('__main__', alter_argv=False)
288
- else:
289
- if not safe_path: sys.path.insert(0, os.path.dirname(os.path.realpath(path)))
290
- try:
291
- with open(path, 'rb') as source:
292
- code = source.read()
293
- except OSError as error:
294
- print("python: can't open file " + repr(path) + ': [Errno ' + str(error.errno) + '] ' + error.strerror, file=sys.stderr)
295
- return 2
296
- main.__file__ = path
297
- main.__loader__ = __import__('importlib.machinery', fromlist=['SourceFileLoader']).SourceFileLoader('__main__', path)
298
- exec(compile(code, path, 'exec'), main.__dict__)
299
- return 0
300
-
301
- try:
302
- _safe_exit = _safe_launch() or 0
303
- except SystemExit as _error:
304
- _safe_exit = _safe_system_exit(_error)
305
- except _SafeOptionError as _error:
306
- print('python: ' + str(_error), file=sys.stderr)
307
- _safe_exit = 2
308
- except BaseException as _error:
309
- # Hide bridge frames while preserving actual Python frames and chained errors.
310
- _trace = _error.__traceback__
311
- while _trace is not None and _trace.tb_frame.f_code.co_filename == '<exec>':
312
- _trace = _trace.tb_next
313
- _error.__traceback__ = _trace
314
- sys.last_exc = _error
315
- _safe_exit = 130 if isinstance(_error, KeyboardInterrupt) else 1
316
- try:
317
- sys.excepthook(type(_error), _error, _trace)
318
- except SystemExit as _hook_error:
319
- _safe_exit = _safe_system_exit(_hook_error)
320
- except BaseException as _hook_error:
321
- print('Error in sys.excepthook:', file=sys.stderr)
322
- traceback.print_exception(type(_hook_error), _hook_error, _hook_error.__traceback__.tb_next)
323
- print('\\nOriginal exception was:', file=sys.stderr)
324
- sys.__excepthook__(type(_error), _error, _trace)
325
- finally:
326
- for _stream in (sys.stdout, sys.stderr):
327
- if _stream is not None and not getattr(_stream, 'closed', False):
328
- try:
329
- _stream.flush()
330
- except BaseException:
331
- _safe_exit = 120
332
- _safe_exit
333
- `;
334
-
335
- // packages/safe-bash/src/commands/python/runtime-scripts.ts
336
- init_platform();
337
- var pythonRuntimeRelocation = `
338
- import sys, zipimport, importlib.machinery
339
-
340
- def _rebase_runtime_path(value):
341
- return _safe_runtime_mount + value if isinstance(value, str) and (value == '/lib' or value.startswith('/lib/')) else value
342
-
343
- def _rebase_runtime_loader(loader):
344
- if isinstance(loader, zipimport.zipimporter):
345
- archive = _rebase_runtime_path(loader.archive)
346
- if archive != loader.archive:
347
- return zipimport.zipimporter(archive + '/' + loader.prefix)
348
- elif isinstance(loader, (importlib.machinery.SourceFileLoader, importlib.machinery.SourcelessFileLoader, importlib.machinery.ExtensionFileLoader)):
349
- path = _rebase_runtime_path(loader.path)
350
- if path != loader.path:
351
- return type(loader)(loader.name, path)
352
- return loader
353
- sys.path[:] = [_rebase_runtime_path(value) for value in sys.path]
354
- for _module in list(sys.modules.values()):
355
- if _module is None:
356
- continue
357
- for _attribute in ('__file__', '__cached__'):
358
- if hasattr(_module, _attribute):
359
- setattr(_module, _attribute, _rebase_runtime_path(getattr(_module, _attribute)))
360
- if hasattr(_module, '__path__'):
361
- _module.__path__ = [_rebase_runtime_path(value) for value in _module.__path__]
362
- if hasattr(_module, '__loader__'):
363
- _module.__loader__ = _rebase_runtime_loader(_module.__loader__)
364
- _spec = getattr(_module, '__spec__', None)
365
- if _spec is not None:
366
- _spec.origin = _rebase_runtime_path(_spec.origin)
367
- _spec.loader = _rebase_runtime_loader(_spec.loader)
368
- if _spec.submodule_search_locations is not None:
369
- _spec.submodule_search_locations = [_rebase_runtime_path(value) for value in _spec.submodule_search_locations]
370
- sys.path_importer_cache.clear()
371
- `;
372
- var pythonImportMetadata = `
373
- import importlib._bootstrap_external, types, json
374
- _safe_import_stat_callback = _safe_import_stat
375
- _safe_original_import_stat = importlib._bootstrap_external._path_stat
376
- def _safe_import_path_stat(path):
377
- if path == _safe_runtime_mount or path.startswith(_safe_runtime_mount + '/'):
378
- return _safe_original_import_stat(path)
379
- value = json.loads(_safe_import_stat_callback(path))
380
- if 'errno' in value:
381
- raise OSError(value['errno'], 'filesystem import metadata unavailable', path)
382
- return types.SimpleNamespace(st_mode=value['mode'], st_size=value['size'], st_mtime=value['mtimeMs'] / 1000)
383
- importlib._bootstrap_external._path_stat = _safe_import_path_stat
384
- `;
385
- var pythonDirectoryEntries = `
386
- import os, json, errno
387
- _safe_directory_callback = _safe_directory_entries
388
- def _safe_listdir(path='.'):
389
- if isinstance(path, int):
390
- raise OSError(errno.ENOTSUP, 'retained directory descriptors are unsupported')
391
- original = os.fspath(path) if path is not None else '.'
392
- value = json.loads(_safe_directory_callback(os.fsdecode(original)))
393
- if 'errno' in value:
394
- raise OSError(value['errno'], 'directory enumeration failed', path)
395
- return [os.fsencode(name) for name in value['entries']] if isinstance(original, bytes) else value['entries']
396
- os.listdir = _safe_listdir
397
- # The frozen importer holds the posix module separately from os.
398
- importlib._bootstrap_external._os.listdir = _safe_listdir
399
- `;
400
- var pythonStatProjection = `
401
- import os, json, errno
402
- _safe_stat_callback = _safe_stat_projection
403
- _safe_stat_type = os.stat_result
404
- _safe_fspath = os.fspath
405
- _safe_fsdecode = os.fsdecode
406
-
407
- def _safe_stat(path, *, dir_fd=None, follow_symlinks=True):
408
- if dir_fd is not None:
409
- raise OSError(errno.ENOTSUP, 'dir_fd metadata is unsupported')
410
- if isinstance(path, int):
411
- if not follow_symlinks:
412
- raise ValueError('stat: cannot use fd and follow_symlinks together')
413
- else:
414
- path = _safe_fsdecode(_safe_fspath(path))
415
- value = json.loads(_safe_stat_callback(path, follow_symlinks))
416
- if 'errno' in value:
417
- raise OSError(value['errno'], 'filesystem metadata unavailable', path)
418
- keys = ('mode','ino','dev','nlink','uid','gid','size')
419
- if any(key not in value for key in keys):
420
- raise OSError(errno.EOVERFLOW, 'canonical identity or required stat metadata unavailable', path)
421
- times = [value[key] / 1000 for key in ('atimeMs','mtimeMs','ctimeMs')]
422
- extras = dict(zip(('st_atime','st_mtime','st_ctime'), times))
423
- for name, milliseconds in zip(('atime','mtime','ctime'), (value['atimeMs'],value['mtimeMs'],value['ctimeMs'])):
424
- seconds = int(milliseconds // 1000)
425
- extras['st_' + name + '_ns'] = seconds * 1000000000 + round((milliseconds - seconds * 1000) * 1000000)
426
- for key in ('blocks','blksize','rdev'):
427
- if key in value:
428
- extras['st_' + key] = value[key]
429
- return _safe_stat_type(tuple(value[key] for key in keys) + tuple(int(time // 1) for time in times), extras)
430
-
431
- def _safe_lstat(path, *, dir_fd=None):
432
- return _safe_stat(path, dir_fd=dir_fd, follow_symlinks=False)
433
-
434
- def _safe_fstat(fd):
435
- if not isinstance(fd, int):
436
- raise TypeError('file descriptor must be an integer')
437
- return _safe_stat(fd)
438
- os.stat = _safe_stat
439
- os.lstat = _safe_lstat
440
- os.fstat = _safe_fstat
441
- import stat as _safe_stat_module
442
- class _SafeDirEntry:
443
- def __init__(self, root, name):
444
- self.name = name
445
- self.path = os.path.join(root, name)
446
- self._cache = {}
447
- def __fspath__(self):
448
- return self.path
449
- def stat(self, *, follow_symlinks=True):
450
- if follow_symlinks not in self._cache:
451
- self._cache[follow_symlinks] = os.stat(self.path, follow_symlinks=follow_symlinks)
452
- return self._cache[follow_symlinks]
453
- def inode(self):
454
- return self.stat(follow_symlinks=False).st_ino
455
- def is_dir(self, *, follow_symlinks=True):
456
- try:
457
- return _safe_stat_module.S_ISDIR(self.stat(follow_symlinks=follow_symlinks).st_mode)
458
- except FileNotFoundError:
459
- return False
460
- def is_file(self, *, follow_symlinks=True):
461
- try:
462
- return _safe_stat_module.S_ISREG(self.stat(follow_symlinks=follow_symlinks).st_mode)
463
- except FileNotFoundError:
464
- return False
465
- def is_symlink(self):
466
- try:
467
- return _safe_stat_module.S_ISLNK(self.stat(follow_symlinks=False).st_mode)
468
- except FileNotFoundError:
469
- return False
470
- class _SafeScandir:
471
- def __init__(self, path):
472
- self._entries = iter([_SafeDirEntry(path, name) for name in os.listdir(path)])
473
- def __iter__(self):
474
- return self
475
- def __next__(self):
476
- return next(self._entries)
477
- def close(self):
478
- self._entries = iter(())
479
- def __enter__(self):
480
- return self
481
- def __exit__(self, *args):
482
- self.close()
483
- def _safe_scandir(path='.'):
484
- if isinstance(path, int):
485
- raise OSError(errno.ENOTSUP, 'retained directory descriptors are unsupported')
486
- return _SafeScandir(os.fspath(path) if path is not None else '.')
487
- os.scandir = _safe_scandir
488
-
489
- `;
490
- var pythonHardLinks = `
491
- import os, json, errno
492
- _safe_link_callback = _safe_hard_link
493
- def _safe_link(src, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True):
494
- if src_dir_fd is not None or dst_dir_fd is not None:
495
- raise OSError(errno.ENOTSUP, 'dir_fd hard links are unsupported')
496
- source = os.fsdecode(os.fspath(src))
497
- destination = os.fsdecode(os.fspath(dst))
498
- value = json.loads(_safe_link_callback(source, destination, bool(follow_symlinks)))
499
- if 'errno' in value:
500
- raise OSError(value['errno'], 'hard link creation failed', src, None, dst)
501
- os.link = _safe_link
502
- os.supports_follow_symlinks.add(_safe_link)
503
- `;
504
- var pythonTreeCleanup = `
505
- import shutil, os, json
506
- _safe_tree_callback = _safe_tree_cleanup
507
- _safe_original_rmtree_impl = shutil._rmtree_impl
508
- def _safe_rmtree_impl(path, dir_fd, onexc):
509
- if dir_fd is not None:
510
- return _safe_original_rmtree_impl(path, dir_fd, onexc)
511
- value = json.loads(_safe_tree_callback(os.fsdecode(path)))
512
- if not value['supported']:
513
- return _safe_original_rmtree_impl(path, dir_fd, onexc)
514
- if 'errno' in value:
515
- onexc(os.rmdir, path, OSError(value['errno'], 'directory cleanup failed', path))
516
- shutil._rmtree_impl = _safe_rmtree_impl
517
- `;
518
-
519
- export {
520
- PythonInvocationError,
521
- parsePythonInvocation,
522
- PythonFailure,
523
- isPythonFailureCategory,
524
- reportPythonFailure,
525
- inspectPythonCapabilities,
526
- pythonExecution,
527
- pythonRuntimeRelocation,
528
- pythonImportMetadata,
529
- pythonDirectoryEntries,
530
- pythonStatProjection,
531
- pythonHardLinks,
532
- pythonTreeCleanup
533
- };
534
- //# sourceMappingURL=chunk-BMO5LWEX.js.map