neutralino-python 0.1.0__py3-none-any.whl

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 (521) hide show
  1. neutralino/__init__.py +88 -0
  2. neutralino/_catalog.py +297 -0
  3. neutralino/_data/LICENSE.neutralino-js-client +21 -0
  4. neutralino/_data/LICENSE.neutralinojs +1066 -0
  5. neutralino/_data/docs/cli.md +315 -0
  6. neutralino/_data/docs/custom-components.md +107 -0
  7. neutralino/_data/docs/custom-frontends.md +80 -0
  8. neutralino/_data/docs/desktop-helpers.md +296 -0
  9. neutralino/_data/docs/guide.md +131 -0
  10. neutralino/_data/docs/llms-full.txt +3921 -0
  11. neutralino/_data/docs/llms.txt +43 -0
  12. neutralino/_data/docs/manifests/components.json +20128 -0
  13. neutralino/_data/docs/manifests/examples.json +52 -0
  14. neutralino/_data/docs/manifests/native.json +3024 -0
  15. neutralino/_data/docs/manifests/schema.json +43 -0
  16. neutralino/_data/docs/manual-checklist.md +189 -0
  17. neutralino/_data/docs/packaging.md +252 -0
  18. neutralino/_data/docs/performance.md +15 -0
  19. neutralino/_data/docs/platforms.md +15 -0
  20. neutralino/_data/docs/reference/components.md +1685 -0
  21. neutralino/_data/docs/reference/native.md +148 -0
  22. neutralino/_data/docs/security.md +60 -0
  23. neutralino/_data/docs/ui.md +249 -0
  24. neutralino/_data/docs/updates.md +366 -0
  25. neutralino/_data/examples/README.md +6 -0
  26. neutralino/_data/examples/crud/README.md +36 -0
  27. neutralino/_data/examples/crud/app.py +243 -0
  28. neutralino/_data/examples/dashboard/README.md +36 -0
  29. neutralino/_data/examples/dashboard/app.py +367 -0
  30. neutralino/_data/examples/editor/README.md +35 -0
  31. neutralino/_data/examples/editor/app.py +190 -0
  32. neutralino/_data/examples/file-manager/README.md +40 -0
  33. neutralino/_data/examples/file-manager/app.py +120 -0
  34. neutralino/_data/examples/file-manager/frontend/index.html +20 -0
  35. neutralino/_data/examples/file-manager/frontend/main.js +55 -0
  36. neutralino/_data/examples/file-manager/frontend/neutralino.js +1 -0
  37. neutralino/_data/examples/file-manager/frontend/python-bridge.d.ts +207 -0
  38. neutralino/_data/examples/file-manager/frontend/python-bridge.mjs +854 -0
  39. neutralino/_data/examples/file-manager/frontend/style.css +4 -0
  40. neutralino/_data/examples/hybrid/README.md +48 -0
  41. neutralino/_data/examples/hybrid/app.py +80 -0
  42. neutralino/_data/examples/hybrid/components/counter.mjs +37 -0
  43. neutralino/_data/examples/hybrid/components/widget.mjs +23 -0
  44. neutralino/_data/examples/hybrid/styles.css +21 -0
  45. neutralino/_data/examples/hybrid/widget/package.json +20 -0
  46. neutralino/_data/examples/hybrid/widget/src/Widget.jsx +25 -0
  47. neutralino/_data/examples/hybrid/widget/vite.config.mjs +19 -0
  48. neutralino/_data/examples/monitor/README.md +36 -0
  49. neutralino/_data/examples/monitor/app.py +375 -0
  50. neutralino/_data/examples/react/README.md +90 -0
  51. neutralino/_data/examples/react/app.py +68 -0
  52. neutralino/_data/examples/react/frontend/.gitignore +5 -0
  53. neutralino/_data/examples/react/frontend/index.html +17 -0
  54. neutralino/_data/examples/react/frontend/package-lock.json +1232 -0
  55. neutralino/_data/examples/react/frontend/package.json +25 -0
  56. neutralino/_data/examples/react/frontend/scripts/prepare-bridge.mjs +49 -0
  57. neutralino/_data/examples/react/frontend/src/App.tsx +157 -0
  58. neutralino/_data/examples/react/frontend/src/backend.ts +21 -0
  59. neutralino/_data/examples/react/frontend/src/calls.test.ts +206 -0
  60. neutralino/_data/examples/react/frontend/src/calls.ts +306 -0
  61. neutralino/_data/examples/react/frontend/src/globals.d.ts +14 -0
  62. neutralino/_data/examples/react/frontend/src/hooks.ts +45 -0
  63. neutralino/_data/examples/react/frontend/src/main.tsx +13 -0
  64. neutralino/_data/examples/react/frontend/src/styles.css +11 -0
  65. neutralino/_data/examples/react/frontend/tsconfig.json +18 -0
  66. neutralino/_data/examples/react/frontend/vite.config.ts +9 -0
  67. neutralino/_data/examples/settings/README.md +38 -0
  68. neutralino/_data/examples/settings/app.py +440 -0
  69. neutralino/_data/examples/updater/.gitignore +2 -0
  70. neutralino/_data/examples/updater/README.md +82 -0
  71. neutralino/_data/examples/updater/app.py +160 -0
  72. neutralino/_data/examples/updater/app.toml +21 -0
  73. neutralino/_data/examples/updater/demo.py +107 -0
  74. neutralino/_data/examples/updater/requirements.txt +2 -0
  75. neutralino/_data/examples/updater/sources/github-private.toml +21 -0
  76. neutralino/_data/examples/updater/sources/github-public.toml +21 -0
  77. neutralino/_data/examples/vanilla/README.md +35 -0
  78. neutralino/_data/examples/vanilla/app.py +46 -0
  79. neutralino/_data/examples/vanilla/frontend/index.html +17 -0
  80. neutralino/_data/examples/vanilla/frontend/main.js +29 -0
  81. neutralino/_data/examples/vanilla/frontend/neutralino.js +1 -0
  82. neutralino/_data/examples/vanilla/frontend/python-bridge.d.ts +207 -0
  83. neutralino/_data/examples/vanilla/frontend/python-bridge.mjs +854 -0
  84. neutralino/_data/examples/vanilla/frontend/style.css +4 -0
  85. neutralino/_data/explorer/app.py +1328 -0
  86. neutralino/_data/explorer/catalogue.json +48179 -0
  87. neutralino/_data/explorer/explorer_previews.py +247 -0
  88. neutralino/_data/explorer/sources/native/always_on_top.py +55 -0
  89. neutralino/_data/explorer/sources/native/binary.py +125 -0
  90. neutralino/_data/explorer/sources/native/borderless.py +99 -0
  91. neutralino/_data/explorer/sources/native/broadcast.py +90 -0
  92. neutralino/_data/explorer/sources/native/config.py +78 -0
  93. neutralino/_data/explorer/sources/native/controls.py +140 -0
  94. neutralino/_data/explorer/sources/native/directory.py +163 -0
  95. neutralino/_data/explorer/sources/native/displays.py +75 -0
  96. neutralino/_data/explorer/sources/native/env.py +98 -0
  97. neutralino/_data/explorer/sources/native/events.py +124 -0
  98. neutralino/_data/explorer/sources/native/exec_command.py +79 -0
  99. neutralino/_data/explorer/sources/native/folder.py +70 -0
  100. neutralino/_data/explorer/sources/native/icon_badge.py +101 -0
  101. neutralino/_data/explorer/sources/native/image.py +119 -0
  102. neutralino/_data/explorer/sources/native/lifecycle.py +99 -0
  103. neutralino/_data/explorer/sources/native/locale.py +70 -0
  104. neutralino/_data/explorer/sources/native/main_menu.py +103 -0
  105. neutralino/_data/explorer/sources/native/message_box.py +101 -0
  106. neutralino/_data/explorer/sources/native/mouse.py +70 -0
  107. neutralino/_data/explorer/sources/native/multi_window.py +134 -0
  108. neutralino/_data/explorer/sources/native/notification.py +74 -0
  109. neutralino/_data/explorer/sources/native/open_external.py +81 -0
  110. neutralino/_data/explorer/sources/native/open_file.py +102 -0
  111. neutralino/_data/explorer/sources/native/paths.py +77 -0
  112. neutralino/_data/explorer/sources/native/print_snapshot.py +84 -0
  113. neutralino/_data/explorer/sources/native/read_write.py +192 -0
  114. neutralino/_data/explorer/sources/native/resources.py +110 -0
  115. neutralino/_data/explorer/sources/native/save_file.py +101 -0
  116. neutralino/_data/explorer/sources/native/server_mount.py +106 -0
  117. neutralino/_data/explorer/sources/native/sound.py +84 -0
  118. neutralino/_data/explorer/sources/native/spawn_process.py +128 -0
  119. neutralino/_data/explorer/sources/native/states.py +122 -0
  120. neutralino/_data/explorer/sources/native/stats_permissions.py +147 -0
  121. neutralino/_data/explorer/sources/native/storage.py +108 -0
  122. neutralino/_data/explorer/sources/native/system_info.py +115 -0
  123. neutralino/_data/explorer/sources/native/text.py +133 -0
  124. neutralino/_data/explorer/sources/native/trash.py +98 -0
  125. neutralino/_data/explorer/sources/native/tray.py +109 -0
  126. neutralino/_data/explorer/sources/native/watcher.py +167 -0
  127. neutralino/_data/explorer/sources/patterns/content_blocks.py +119 -0
  128. neutralino/_data/explorer/sources/patterns/dynamic_dashboard.py +121 -0
  129. neutralino/_data/explorer/sources/patterns/dynamic_form.py +120 -0
  130. neutralino/_data/explorer/sources/patterns/dynamic_table.py +109 -0
  131. neutralino/_data/explorer/sources/patterns/error_reporting.mjs +24 -0
  132. neutralino/_data/explorer/sources/patterns/error_reporting.py +124 -0
  133. neutralino/_data/explorer/sources/patterns/errors_timeouts.py +108 -0
  134. neutralino/_data/explorer/sources/patterns/feature_flags.py +99 -0
  135. neutralino/_data/explorer/sources/patterns/file_drop.py +126 -0
  136. neutralino/_data/explorer/sources/patterns/http_from_python.py +152 -0
  137. neutralino/_data/explorer/sources/patterns/keyboard_shortcuts.py +153 -0
  138. neutralino/_data/explorer/sources/patterns/live_config_reload.py +160 -0
  139. neutralino/_data/explorer/sources/patterns/logging.py +184 -0
  140. neutralino/_data/explorer/sources/patterns/long_tasks.py +121 -0
  141. neutralino/_data/explorer/sources/patterns/multi_window_sync.py +68 -0
  142. neutralino/_data/explorer/sources/patterns/navigation_from_backend.py +109 -0
  143. neutralino/_data/explorer/sources/patterns/onboarding.py +123 -0
  144. neutralino/_data/explorer/sources/patterns/optimistic_updates.py +89 -0
  145. neutralino/_data/explorer/sources/patterns/persistence.py +114 -0
  146. neutralino/_data/explorer/sources/patterns/python_calls_page.mjs +10 -0
  147. neutralino/_data/explorer/sources/patterns/python_calls_page.py +64 -0
  148. neutralino/_data/explorer/sources/patterns/python_push.py +84 -0
  149. neutralino/_data/explorer/sources/patterns/recurring_events.py +114 -0
  150. neutralino/_data/explorer/sources/patterns/roles_permissions.py +104 -0
  151. neutralino/_data/explorer/sources/patterns/scheduled_jobs.py +194 -0
  152. neutralino/_data/explorer/sources/patterns/settings_page.py +165 -0
  153. neutralino/_data/explorer/sources/patterns/sqlite.py +181 -0
  154. neutralino/_data/explorer/sources/patterns/streaming.py +102 -0
  155. neutralino/_data/explorer/sources/patterns/texts_i18n.py +81 -0
  156. neutralino/_data/explorer/sources/patterns/theme_from_backend.py +86 -0
  157. neutralino/_data/explorer/sources/patterns/updater.py +232 -0
  158. neutralino/_data/explorer/sources/workspace/calendar/app.py +547 -0
  159. neutralino/_data/explorer/sources/workspace/customers/app.py +467 -0
  160. neutralino/_data/explorer/sources/workspace/dashboard/README.md +36 -0
  161. neutralino/_data/explorer/sources/workspace/dashboard/app.py +367 -0
  162. neutralino/_data/explorer/sources/workspace/documents/app.py +511 -0
  163. neutralino/_data/explorer/sources/workspace/inbox/app.py +439 -0
  164. neutralino/_data/explorer/sources/workspace/orders/app.py +491 -0
  165. neutralino/_data/explorer/sources/workspace/reports/app.py +386 -0
  166. neutralino/_data/explorer/sources/workspace/settings/README.md +38 -0
  167. neutralino/_data/explorer/sources/workspace/settings/app.py +440 -0
  168. neutralino/_data/explorer/sources/workspace/system/README.md +36 -0
  169. neutralino/_data/explorer/sources/workspace/system/app.py +375 -0
  170. neutralino/_data/explorer/sources/workspace/tasks/app.py +462 -0
  171. neutralino/_data/renderer/LICENSES/@babel__runtime@7.29.17/LICENSE +22 -0
  172. neutralino/_data/renderer/LICENSES/@codemirror__autocomplete@6.20.4/LICENSE +21 -0
  173. neutralino/_data/renderer/LICENSES/@codemirror__commands@6.11.2/LICENSE +21 -0
  174. neutralino/_data/renderer/LICENSES/@codemirror__lang-css@6.3.1/LICENSE +21 -0
  175. neutralino/_data/renderer/LICENSES/@codemirror__lang-html@6.4.12/LICENSE +21 -0
  176. neutralino/_data/renderer/LICENSES/@codemirror__lang-javascript@6.2.5/LICENSE +21 -0
  177. neutralino/_data/renderer/LICENSES/@codemirror__lang-json@6.0.2/LICENSE +21 -0
  178. neutralino/_data/renderer/LICENSES/@codemirror__lang-markdown@6.5.3/LICENSE +21 -0
  179. neutralino/_data/renderer/LICENSES/@codemirror__lang-python@6.2.1/LICENSE +21 -0
  180. neutralino/_data/renderer/LICENSES/@codemirror__lang-sql@6.10.0/LICENSE +21 -0
  181. neutralino/_data/renderer/LICENSES/@codemirror__lang-yaml@6.1.3/LICENSE +21 -0
  182. neutralino/_data/renderer/LICENSES/@codemirror__language@6.13.1/LICENSE +21 -0
  183. neutralino/_data/renderer/LICENSES/@codemirror__search@6.7.3/LICENSE +21 -0
  184. neutralino/_data/renderer/LICENSES/@codemirror__state@6.7.6/LICENSE +21 -0
  185. neutralino/_data/renderer/LICENSES/@codemirror__view@6.44.2/LICENSE +21 -0
  186. neutralino/_data/renderer/LICENSES/@dnd-kit__accessibility@3.1.1/LICENSE +21 -0
  187. neutralino/_data/renderer/LICENSES/@dnd-kit__core@6.3.1/LICENSE +21 -0
  188. neutralino/_data/renderer/LICENSES/@dnd-kit__sortable@10.0.0/LICENSE +21 -0
  189. neutralino/_data/renderer/LICENSES/@dnd-kit__utilities@3.2.2/LICENSE +21 -0
  190. neutralino/_data/renderer/LICENSES/@emoji-mart__data@1.2.1/LICENSE +21 -0
  191. neutralino/_data/renderer/LICENSES/@floating-ui__core@1.8.0/LICENSE +20 -0
  192. neutralino/_data/renderer/LICENSES/@floating-ui__dom@1.8.0/LICENSE +20 -0
  193. neutralino/_data/renderer/LICENSES/@floating-ui__react-dom@2.1.9/LICENSE +20 -0
  194. neutralino/_data/renderer/LICENSES/@floating-ui__react@0.27.20/LICENSE +20 -0
  195. neutralino/_data/renderer/LICENSES/@floating-ui__utils@0.2.12/LICENSE +20 -0
  196. neutralino/_data/renderer/LICENSES/@lezer__common@1.5.7/LICENSE +21 -0
  197. neutralino/_data/renderer/LICENSES/@lezer__css@1.3.9/LICENSE +21 -0
  198. neutralino/_data/renderer/LICENSES/@lezer__highlight@1.2.5/LICENSE +21 -0
  199. neutralino/_data/renderer/LICENSES/@lezer__html@1.3.13/LICENSE +21 -0
  200. neutralino/_data/renderer/LICENSES/@lezer__javascript@1.5.7/LICENSE +21 -0
  201. neutralino/_data/renderer/LICENSES/@lezer__json@1.0.3/LICENSE +21 -0
  202. neutralino/_data/renderer/LICENSES/@lezer__lr@1.4.13/LICENSE +21 -0
  203. neutralino/_data/renderer/LICENSES/@lezer__markdown@1.8.3/LICENSE +21 -0
  204. neutralino/_data/renderer/LICENSES/@lezer__python@1.1.21/LICENSE +21 -0
  205. neutralino/_data/renderer/LICENSES/@lezer__yaml@1.0.4/LICENSE +21 -0
  206. neutralino/_data/renderer/LICENSES/@mantine__carousel@9.8.3/LICENSE +21 -0
  207. neutralino/_data/renderer/LICENSES/@mantine__charts@9.8.3/LICENSE +21 -0
  208. neutralino/_data/renderer/LICENSES/@mantine__code-highlight@9.8.3/LICENSE +21 -0
  209. neutralino/_data/renderer/LICENSES/@mantine__core@9.8.3/LICENSE +21 -0
  210. neutralino/_data/renderer/LICENSES/@mantine__dates@9.8.3/LICENSE +21 -0
  211. neutralino/_data/renderer/LICENSES/@mantine__dropzone@9.8.3/LICENSE +21 -0
  212. neutralino/_data/renderer/LICENSES/@mantine__emoji@9.8.3/LICENSE +21 -0
  213. neutralino/_data/renderer/LICENSES/@mantine__hooks@9.8.3/LICENSE +21 -0
  214. neutralino/_data/renderer/LICENSES/@mantine__lightbox@9.8.3/LICENSE +21 -0
  215. neutralino/_data/renderer/LICENSES/@mantine__notifications@9.8.3/LICENSE +21 -0
  216. neutralino/_data/renderer/LICENSES/@mantine__nprogress@9.8.3/LICENSE +21 -0
  217. neutralino/_data/renderer/LICENSES/@mantine__schedule@9.8.3/LICENSE +21 -0
  218. neutralino/_data/renderer/LICENSES/@mantine__spotlight@9.8.3/LICENSE +21 -0
  219. neutralino/_data/renderer/LICENSES/@mantine__store@9.8.3/LICENSE +21 -0
  220. neutralino/_data/renderer/LICENSES/@mantine__tiptap@9.8.3/LICENSE +21 -0
  221. neutralino/_data/renderer/LICENSES/@marijn__find-cluster-break@1.0.4/LICENSE +21 -0
  222. neutralino/_data/renderer/LICENSES/@reduxjs__toolkit@2.16.0/LICENSE +21 -0
  223. neutralino/_data/renderer/LICENSES/@tabler__icons-react@3.55.0/LICENSE +21 -0
  224. neutralino/_data/renderer/LICENSES/@tanstack__react-virtual@3.14.32/LICENSE +21 -0
  225. neutralino/_data/renderer/LICENSES/@tanstack__virtual-core@3.19.17/LICENSE +21 -0
  226. neutralino/_data/renderer/LICENSES/@tiptap__core@3.35.1/LICENSE.md +21 -0
  227. neutralino/_data/renderer/LICENSES/@tiptap__extension-blockquote@3.35.1/LICENSE.md +21 -0
  228. neutralino/_data/renderer/LICENSES/@tiptap__extension-bold@3.35.1/LICENSE.md +21 -0
  229. neutralino/_data/renderer/LICENSES/@tiptap__extension-code-block@3.35.1/LICENSE.md +21 -0
  230. neutralino/_data/renderer/LICENSES/@tiptap__extension-code@3.35.1/LICENSE.md +21 -0
  231. neutralino/_data/renderer/LICENSES/@tiptap__extension-document@3.35.1/LICENSE.md +21 -0
  232. neutralino/_data/renderer/LICENSES/@tiptap__extension-hard-break@3.35.1/LICENSE.md +21 -0
  233. neutralino/_data/renderer/LICENSES/@tiptap__extension-heading@3.35.1/LICENSE.md +21 -0
  234. neutralino/_data/renderer/LICENSES/@tiptap__extension-horizontal-rule@3.35.1/LICENSE.md +21 -0
  235. neutralino/_data/renderer/LICENSES/@tiptap__extension-italic@3.35.1/LICENSE.md +21 -0
  236. neutralino/_data/renderer/LICENSES/@tiptap__extension-link@3.35.1/LICENSE.md +21 -0
  237. neutralino/_data/renderer/LICENSES/@tiptap__extension-list@3.35.1/LICENSE.md +21 -0
  238. neutralino/_data/renderer/LICENSES/@tiptap__extension-paragraph@3.35.1/LICENSE.md +21 -0
  239. neutralino/_data/renderer/LICENSES/@tiptap__extension-strike@3.35.1/LICENSE.md +21 -0
  240. neutralino/_data/renderer/LICENSES/@tiptap__extension-text@3.35.1/LICENSE.md +21 -0
  241. neutralino/_data/renderer/LICENSES/@tiptap__extension-underline@3.35.1/LICENSE.md +21 -0
  242. neutralino/_data/renderer/LICENSES/@tiptap__extensions@3.35.1/LICENSE.md +21 -0
  243. neutralino/_data/renderer/LICENSES/@tiptap__react@3.35.1/LICENSE.md +21 -0
  244. neutralino/_data/renderer/LICENSES/@tiptap__starter-kit@3.35.1/LICENSE.md +21 -0
  245. neutralino/_data/renderer/LICENSES/attr-accept@4.0.1/LICENSE +22 -0
  246. neutralino/_data/renderer/LICENSES/clsx@2.1.1/license +9 -0
  247. neutralino/_data/renderer/LICENSES/crelt@1.0.7/LICENSE +19 -0
  248. neutralino/_data/renderer/LICENSES/d3-array@3.2.5/LICENSE +13 -0
  249. neutralino/_data/renderer/LICENSES/d3-color@3.1.1/LICENSE +13 -0
  250. neutralino/_data/renderer/LICENSES/d3-format@3.1.3/LICENSE +13 -0
  251. neutralino/_data/renderer/LICENSES/d3-interpolate@3.0.2/LICENSE +13 -0
  252. neutralino/_data/renderer/LICENSES/d3-path@3.1.1/LICENSE +13 -0
  253. neutralino/_data/renderer/LICENSES/d3-scale@4.0.3/LICENSE +13 -0
  254. neutralino/_data/renderer/LICENSES/d3-shape@3.2.1/LICENSE +13 -0
  255. neutralino/_data/renderer/LICENSES/d3-time-format@4.1.1/LICENSE +13 -0
  256. neutralino/_data/renderer/LICENSES/d3-time@3.1.1/LICENSE +13 -0
  257. neutralino/_data/renderer/LICENSES/dayjs@1.11.23/LICENSE +21 -0
  258. neutralino/_data/renderer/LICENSES/decimal.js-light@2.5.1/LICENCE.md +23 -0
  259. neutralino/_data/renderer/LICENSES/diff@9.0.0/LICENSE +29 -0
  260. neutralino/_data/renderer/LICENSES/dompurify@3.5.1/LICENSE +202 -0
  261. neutralino/_data/renderer/LICENSES/dompurify@3.5.1/LICENSE-MPL +373 -0
  262. neutralino/_data/renderer/LICENSES/embla-carousel-react@8.6.0/MIT-embla-carousel.txt +21 -0
  263. neutralino/_data/renderer/LICENSES/embla-carousel-reactive-utils@8.6.0/MIT-embla-carousel.txt +21 -0
  264. neutralino/_data/renderer/LICENSES/embla-carousel@8.6.0/MIT-embla-carousel.txt +21 -0
  265. neutralino/_data/renderer/LICENSES/es-toolkit@1.53.2/LICENSE +21 -0
  266. neutralino/_data/renderer/LICENSES/es-toolkit@1.53.2/NOTICE +39 -0
  267. neutralino/_data/renderer/LICENSES/eventemitter3@5.0.4/LICENSE +21 -0
  268. neutralino/_data/renderer/LICENSES/fast-equals@5.4.7/LICENSE +21 -0
  269. neutralino/_data/renderer/LICENSES/file-selector@5.0.3/LICENSE +21 -0
  270. neutralino/_data/renderer/LICENSES/get-nonce@1.0.1/LICENSE +21 -0
  271. neutralino/_data/renderer/LICENSES/immer@11.2.14/LICENSE +21 -0
  272. neutralino/_data/renderer/LICENSES/linkifyjs@4.4.0/LICENSE +19 -0
  273. neutralino/_data/renderer/LICENSES/marked@18.4.0/LICENSE +44 -0
  274. neutralino/_data/renderer/LICENSES/neutralino.js@6.11.0/LICENSE +21 -0
  275. neutralino/_data/renderer/LICENSES/orderedmap@2.1.1/LICENSE +19 -0
  276. neutralino/_data/renderer/LICENSES/packages.json +1838 -0
  277. neutralino/_data/renderer/LICENSES/prosemirror-commands@1.7.2/LICENSE +19 -0
  278. neutralino/_data/renderer/LICENSES/prosemirror-dropcursor@1.8.4/LICENSE +19 -0
  279. neutralino/_data/renderer/LICENSES/prosemirror-gapcursor@1.4.1/LICENSE +19 -0
  280. neutralino/_data/renderer/LICENSES/prosemirror-history@1.5.2/LICENSE +19 -0
  281. neutralino/_data/renderer/LICENSES/prosemirror-keymap@1.2.3/LICENSE +19 -0
  282. neutralino/_data/renderer/LICENSES/prosemirror-model@1.25.13/LICENSE +19 -0
  283. neutralino/_data/renderer/LICENSES/prosemirror-schema-list@1.6.1/LICENSE +19 -0
  284. neutralino/_data/renderer/LICENSES/prosemirror-state@1.4.4/LICENSE +19 -0
  285. neutralino/_data/renderer/LICENSES/prosemirror-transform@1.12.7/LICENSE +19 -0
  286. neutralino/_data/renderer/LICENSES/prosemirror-view@1.44.0/LICENSE +19 -0
  287. neutralino/_data/renderer/LICENSES/react-dom@19.3.1/LICENSE +21 -0
  288. neutralino/_data/renderer/LICENSES/react-dropzone@20.1.4/LICENSE +22 -0
  289. neutralino/_data/renderer/LICENSES/react-is@19.3.1/LICENSE +21 -0
  290. neutralino/_data/renderer/LICENSES/react-number-format@5.4.5/LICENSE +21 -0
  291. neutralino/_data/renderer/LICENSES/react-redux@9.3.1/LICENSE.md +21 -0
  292. neutralino/_data/renderer/LICENSES/react-remove-scroll-bar@2.3.8/MIT-react-remove-scroll-bar.txt +21 -0
  293. neutralino/_data/renderer/LICENSES/react-remove-scroll@2.7.2/LICENSE +21 -0
  294. neutralino/_data/renderer/LICENSES/react-style-singleton@2.2.3/LICENSE +21 -0
  295. neutralino/_data/renderer/LICENSES/react-transition-group@4.4.5/LICENSE +30 -0
  296. neutralino/_data/renderer/LICENSES/react@19.3.1/LICENSE +21 -0
  297. neutralino/_data/renderer/LICENSES/recharts@3.11.3/LICENSE +22 -0
  298. neutralino/_data/renderer/LICENSES/redux-thunk@3.1.0/LICENSE.md +21 -0
  299. neutralino/_data/renderer/LICENSES/redux@5.0.1/LICENSE.md +21 -0
  300. neutralino/_data/renderer/LICENSES/reselect@5.2.0/LICENSE +21 -0
  301. neutralino/_data/renderer/LICENSES/rolldown@1.3.4/LICENSE +25 -0
  302. neutralino/_data/renderer/LICENSES/rope-sequence@1.3.4/LICENSE +19 -0
  303. neutralino/_data/renderer/LICENSES/rrule@2.8.1/LICENCE +65 -0
  304. neutralino/_data/renderer/LICENSES/scheduler@0.28.0/LICENSE +21 -0
  305. neutralino/_data/renderer/LICENSES/style-mod@4.1.5/LICENSE +19 -0
  306. neutralino/_data/renderer/LICENSES/tiny-invariant@1.3.3/LICENSE +21 -0
  307. neutralino/_data/renderer/LICENSES/tslib@2.9.1/LICENSE.txt +12 -0
  308. neutralino/_data/renderer/LICENSES/use-callback-ref@1.3.3/LICENSE +21 -0
  309. neutralino/_data/renderer/LICENSES/use-sidecar@1.1.3/LICENSE +21 -0
  310. neutralino/_data/renderer/LICENSES/use-sync-external-store@1.7.0/LICENSE +21 -0
  311. neutralino/_data/renderer/LICENSES/victory-vendor@38.1.1/LICENSE.txt +150 -0
  312. neutralino/_data/renderer/LICENSES/vite@8.4.1/LICENSE.md +2320 -0
  313. neutralino/_data/renderer/LICENSES/w3c-keyname@2.2.8/LICENSE +19 -0
  314. neutralino/_data/renderer/assets/IconGripVertical-BlJrWVuo.js +1 -0
  315. neutralino/_data/renderer/assets/carousel-D1j1SkWR.css +1 -0
  316. neutralino/_data/renderer/assets/carousel-DniHwTLK.js +1 -0
  317. neutralino/_data/renderer/assets/chunk-CCkLOSkX.css +1 -0
  318. neutralino/_data/renderer/assets/chunk-Du0h7lB-.js +9 -0
  319. neutralino/_data/renderer/assets/codehighlight-CCe_blv1.js +10 -0
  320. neutralino/_data/renderer/assets/codehighlight-THJMNDh8.css +1 -0
  321. neutralino/_data/renderer/assets/codemirror-CinrNxVJ.js +2 -0
  322. neutralino/_data/renderer/assets/css-CMUk25uq.js +1 -0
  323. neutralino/_data/renderer/assets/dist-70Le0T2N.js +1 -0
  324. neutralino/_data/renderer/assets/dist-BCHbQlae.js +11 -0
  325. neutralino/_data/renderer/assets/dist-BXts23GT.js +1 -0
  326. neutralino/_data/renderer/assets/dist-D2RX2UgP.js +23 -0
  327. neutralino/_data/renderer/assets/dist-DikJK2lp.js +1 -0
  328. neutralino/_data/renderer/assets/dist-acbbRM1z.js +1 -0
  329. neutralino/_data/renderer/assets/dnd-DaaaVala.js +5 -0
  330. neutralino/_data/renderer/assets/dropzone-CeqF5SZx.js +1 -0
  331. neutralino/_data/renderer/assets/dropzone-aPCBPjDN.css +1 -0
  332. neutralino/_data/renderer/assets/embla-carousel-react.esm-CbyYjwMN.js +1 -0
  333. neutralino/_data/renderer/assets/emoji-BfRPfoVw.js +1 -0
  334. neutralino/_data/renderer/assets/emoji-DV8OzU1E.css +1 -0
  335. neutralino/_data/renderer/assets/esm-C5ZYjSBQ.js +82 -0
  336. neutralino/_data/renderer/assets/highlight-CB6hGb5A.js +3 -0
  337. neutralino/_data/renderer/assets/highlight-Dlb5DJwL.css +1 -0
  338. neutralino/_data/renderer/assets/html-Dad3kwIa.js +1 -0
  339. neutralino/_data/renderer/assets/icon-chunk-X3Kr0nh-.js +1 -0
  340. neutralino/_data/renderer/assets/index-CU0HB-J7.js +69 -0
  341. neutralino/_data/renderer/assets/index-TWpF4Lef.css +1 -0
  342. neutralino/_data/renderer/assets/javascript-BQb8vpw3.js +1 -0
  343. neutralino/_data/renderer/assets/json-BCFmxlML.js +1 -0
  344. neutralino/_data/renderer/assets/lightbox-BHtgbsUV.js +1 -0
  345. neutralino/_data/renderer/assets/lightbox-BzKDpkAD.css +1 -0
  346. neutralino/_data/renderer/assets/markdown-DSuAylvy.js +5 -0
  347. neutralino/_data/renderer/assets/markdown-DjaNWMgH.js +77 -0
  348. neutralino/_data/renderer/assets/python-pdbIAveZ.js +9 -0
  349. neutralino/_data/renderer/assets/richtext-DIAsHMuK.css +1 -0
  350. neutralino/_data/renderer/assets/richtext-Z6fG9G2_.js +137 -0
  351. neutralino/_data/renderer/assets/spotlight-Ccstaz1-.css +1 -0
  352. neutralino/_data/renderer/assets/spotlight-knlyJw_A.js +1 -0
  353. neutralino/_data/renderer/assets/sql-DLoQFEde.js +2 -0
  354. neutralino/_data/renderer/assets/with-selector-BOM9_OlN.js +1 -0
  355. neutralino/_data/renderer/assets/yaml-BJNzokSe.js +1 -0
  356. neutralino/_data/renderer/index.html +22 -0
  357. neutralino/_data/renderer/manifest.json +202 -0
  358. neutralino/_data/renderer/neutralino.js +1 -0
  359. neutralino/_data/renderer/shared/mantine-core.mjs +5 -0
  360. neutralino/_data/renderer/shared/mantine-hooks.mjs +5 -0
  361. neutralino/_data/renderer/shared/react-dom-client.mjs +5 -0
  362. neutralino/_data/renderer/shared/react-dom.mjs +6 -0
  363. neutralino/_data/renderer/shared/react-jsx-runtime.mjs +5 -0
  364. neutralino/_data/renderer/shared/react.mjs +6 -0
  365. neutralino/_data/skills/README.md +6 -0
  366. neutralino/_data/skills/neutralino-app-patterns/SKILL.md +101 -0
  367. neutralino/_data/skills/neutralino-app-patterns/references/dashboards-and-background-work.md +55 -0
  368. neutralino/_data/skills/neutralino-app-patterns/references/storage-and-settings.md +57 -0
  369. neutralino/_data/skills/neutralino-app-patterns/references/tables-and-crud.md +81 -0
  370. neutralino/_data/skills/neutralino-frontend/SKILL.md +121 -0
  371. neutralino/_data/skills/neutralino-frontend/references/bridge.md +63 -0
  372. neutralino/_data/skills/neutralino-frontend/references/custom-components.md +84 -0
  373. neutralino/_data/skills/neutralino-frontend/references/frameworks.md +61 -0
  374. neutralino/_data/skills/neutralino-maintenance/SKILL.md +85 -0
  375. neutralino/_data/skills/neutralino-maintenance/references/platforms-and-gates.md +35 -0
  376. neutralino/_data/skills/neutralino-maintenance/references/records.md +38 -0
  377. neutralino/_data/skills/neutralino-maintenance/references/review-process.md +36 -0
  378. neutralino/_data/skills/neutralino-native/SKILL.md +107 -0
  379. neutralino/_data/skills/neutralino-native/references/api-conventions.md +72 -0
  380. neutralino/_data/skills/neutralino-native/references/desktop-helpers.md +53 -0
  381. neutralino/_data/skills/neutralino-native/references/permissions-windows.md +53 -0
  382. neutralino/_data/skills/neutralino-packaging/SKILL.md +99 -0
  383. neutralino/_data/skills/neutralino-packaging/references/build-layout.md +51 -0
  384. neutralino/_data/skills/neutralino-packaging/references/managed-install.md +59 -0
  385. neutralino/_data/skills/neutralino-packaging/references/templates-and-config.md +63 -0
  386. neutralino/_data/skills/neutralino-python/SKILL.md +109 -0
  387. neutralino/_data/skills/neutralino-python/references/architecture.md +53 -0
  388. neutralino/_data/skills/neutralino-python/references/cli.md +60 -0
  389. neutralino/_data/skills/neutralino-python/references/platforms-security.md +44 -0
  390. neutralino/_data/skills/neutralino-rpc/SKILL.md +114 -0
  391. neutralino/_data/skills/neutralino-rpc/references/errors-and-limits.md +44 -0
  392. neutralino/_data/skills/neutralino-rpc/references/expose-and-context.md +74 -0
  393. neutralino/_data/skills/neutralino-rpc/references/streams-and-cancellation.md +53 -0
  394. neutralino/_data/skills/neutralino-ui/SKILL.md +115 -0
  395. neutralino/_data/skills/neutralino-ui/references/components-and-tree.md +74 -0
  396. neutralino/_data/skills/neutralino-ui/references/state-forms-events.md +85 -0
  397. neutralino/_data/skills/neutralino-ui/references/themes-profiles-assets.md +105 -0
  398. neutralino/_data/skills/neutralino-updates/SKILL.md +94 -0
  399. neutralino/_data/skills/neutralino-updates/references/config-and-api.md +80 -0
  400. neutralino/_data/skills/neutralino-updates/references/releases-and-install.md +77 -0
  401. neutralino/_data/skills/neutralino-updates/references/security-rollback.md +48 -0
  402. neutralino/_data/ui/contracts.json +32927 -0
  403. neutralino/_data/ui/emoji.json +1 -0
  404. neutralino/_data/upstream-lock.json +97 -0
  405. neutralino/_managed.py +1099 -0
  406. neutralino/_paths.py +220 -0
  407. neutralino/_platform.py +150 -0
  408. neutralino/_scaffold.py +344 -0
  409. neutralino/api/_base.py +99 -0
  410. neutralino/api/_custom.py +1350 -0
  411. neutralino/api/_dec.py +21 -0
  412. neutralino/api/_enc.py +80 -0
  413. neutralino/api/app.py +119 -0
  414. neutralino/api/clipboard.py +101 -0
  415. neutralino/api/computer.py +261 -0
  416. neutralino/api/custom.py +36 -0
  417. neutralino/api/debug.py +41 -0
  418. neutralino/api/extensions.py +57 -0
  419. neutralino/api/filesystem.py +633 -0
  420. neutralino/api/net.py +22 -0
  421. neutralino/api/os.py +508 -0
  422. neutralino/api/resources.py +124 -0
  423. neutralino/api/server.py +66 -0
  424. neutralino/api/storage.py +98 -0
  425. neutralino/api/types.py +342 -0
  426. neutralino/api/updater.py +22 -0
  427. neutralino/api/window.py +397 -0
  428. neutralino/application.py +1260 -0
  429. neutralino/bundle.py +187 -0
  430. neutralino/cli.py +629 -0
  431. neutralino/client.py +496 -0
  432. neutralino/config.py +671 -0
  433. neutralino/devtools.py +1973 -0
  434. neutralino/errors.py +142 -0
  435. neutralino/events.py +579 -0
  436. neutralino/execution.py +293 -0
  437. neutralino/extension.py +134 -0
  438. neutralino/frontend/python-bridge.d.ts +207 -0
  439. neutralino/frontend/python-bridge.mjs +854 -0
  440. neutralino/protocol.py +456 -0
  441. neutralino/py.typed +0 -0
  442. neutralino/rpc.py +1625 -0
  443. neutralino/runtime.py +591 -0
  444. neutralino/supervisor.py +866 -0
  445. neutralino/sync_client.py +376 -0
  446. neutralino/templates/default/app.py +32 -0
  447. neutralino/templates/default/frontend/app.js +28 -0
  448. neutralino/templates/default/frontend/index.html +26 -0
  449. neutralino/templates/default/frontend/neutralino.js +1 -0
  450. neutralino/templates/default/frontend/styles.css +8 -0
  451. neutralino/templates/default/gitignore.txt +3 -0
  452. neutralino/templates/default/neutralino.config.json +25 -0
  453. neutralino/templates/hybrid/README.md +17 -0
  454. neutralino/templates/hybrid/app.py +49 -0
  455. neutralino/templates/hybrid/components/counter.mjs +37 -0
  456. neutralino/templates/hybrid/styles.css +21 -0
  457. neutralino/templates/python-ui/README.md +15 -0
  458. neutralino/templates/python-ui/app.py +44 -0
  459. neutralino/templates/python-ui/gitignore.txt +3 -0
  460. neutralino/templates/python-ui/requirements.txt +4 -0
  461. neutralino/templates/react/README.md +28 -0
  462. neutralino/templates/react/app.py +52 -0
  463. neutralino/templates/react/components/widget.mjs +23 -0
  464. neutralino/templates/react/widget/package.json +20 -0
  465. neutralino/templates/react/widget/src/Widget.jsx +25 -0
  466. neutralino/templates/react/widget/vite.config.mjs +19 -0
  467. neutralino/transport.py +661 -0
  468. neutralino/types.py +93 -0
  469. neutralino/ui/__init__.py +139 -0
  470. neutralino/ui/_app.py +1529 -0
  471. neutralino/ui/_assets.py +407 -0
  472. neutralino/ui/_bases.py +1210 -0
  473. neutralino/ui/_behaviours.py +1066 -0
  474. neutralino/ui/_charts.py +732 -0
  475. neutralino/ui/_component.py +882 -0
  476. neutralino/ui/_dates.py +168 -0
  477. neutralino/ui/_desktop.py +879 -0
  478. neutralino/ui/_events.py +192 -0
  479. neutralino/ui/_filters.py +427 -0
  480. neutralino/ui/_forms.py +282 -0
  481. neutralino/ui/_protocol.py +201 -0
  482. neutralino/ui/_schedule.py +543 -0
  483. neutralino/ui/_security.py +106 -0
  484. neutralino/ui/_session.py +969 -0
  485. neutralino/ui/_state.py +199 -0
  486. neutralino/ui/_tables.py +256 -0
  487. neutralino/ui/_theme.py +154 -0
  488. neutralino/ui/blocks/__init__.py +19 -0
  489. neutralino/ui/blocks/_data.py +2239 -0
  490. neutralino/ui/blocks/_interactive.py +622 -0
  491. neutralino/ui/blocks/_layout.py +2967 -0
  492. neutralino/ui/components/__init__.py +81 -0
  493. neutralino/ui/components/_dates.py +879 -0
  494. neutralino/ui/components/_editors.py +217 -0
  495. neutralino/ui/components/_extensions.py +790 -0
  496. neutralino/ui/components/_extras.py +303 -0
  497. neutralino/ui/components/_generated.py +30565 -0
  498. neutralino/ui/components/_types.py +17 -0
  499. neutralino/ui/schema.py +824 -0
  500. neutralino/ui/validators.py +362 -0
  501. neutralino/updates/__init__.py +96 -0
  502. neutralino/updates/_http.py +320 -0
  503. neutralino/updates/_layout.py +762 -0
  504. neutralino/updates/archive.py +216 -0
  505. neutralino/updates/config.py +256 -0
  506. neutralino/updates/errors.py +97 -0
  507. neutralino/updates/install.sh.in +201 -0
  508. neutralino/updates/launcher.py +18 -0
  509. neutralino/updates/manager.py +808 -0
  510. neutralino/updates/manifest.py +196 -0
  511. neutralino/updates/release.py +314 -0
  512. neutralino/updates/semver.py +84 -0
  513. neutralino/updates/sources.py +392 -0
  514. neutralino/windows.py +316 -0
  515. neutralino_python-0.1.0.dist-info/METADATA +121 -0
  516. neutralino_python-0.1.0.dist-info/RECORD +521 -0
  517. neutralino_python-0.1.0.dist-info/WHEEL +4 -0
  518. neutralino_python-0.1.0.dist-info/entry_points.txt +3 -0
  519. neutralino_python-0.1.0.dist-info/licenses/LICENSE +21 -0
  520. neutralino_python-0.1.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +16 -0
  521. neutralino_python-0.1.0.dist-info/licenses/src/neutralino/_data/renderer/LICENSES/packages.json +1838 -0
neutralino/devtools.py ADDED
@@ -0,0 +1,1973 @@
1
+ """Developer tooling behind the ``neutralino`` CLI: scaffold, frontend export,
2
+ doctor, staged build and watch-and-restart. Nothing here runs on import or on
3
+ the runtime call path."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import ast
8
+ import base64
9
+ import contextlib
10
+ import ctypes.util
11
+ import difflib
12
+ import fnmatch
13
+ import hashlib
14
+ import hmac
15
+ import html
16
+ import json
17
+ import logging
18
+ import os
19
+ import platform
20
+ import re
21
+ import shutil
22
+ import signal
23
+ import socket
24
+ import stat
25
+ import subprocess
26
+ import sys
27
+ import tempfile
28
+ import threading
29
+ import time
30
+ from collections.abc import Callable, Generator, Iterable, Mapping, Sequence
31
+ from dataclasses import dataclass, field
32
+ from importlib import resources as importlib_resources
33
+ from pathlib import Path, PurePosixPath, PureWindowsPath
34
+ from typing import Any, cast
35
+
36
+ from . import config as config_mod
37
+ from ._platform import DEV_RELOAD_READY_ENV, is_windows, platform_key, user_cache_dir
38
+ from ._scaffold import AppConfig as _AppToml
39
+ from ._scaffold import exclude_match
40
+ from .bundle import read_bundle_config
41
+ from .errors import RuntimeIntegrityError, UnsupportedError, ValidationError
42
+ from .runtime import (
43
+ CLIENT_VERSION,
44
+ CORE_VERSION,
45
+ LOCK,
46
+ binary_spec,
47
+ resolve_binary,
48
+ sha256_file,
49
+ verify_binary,
50
+ )
51
+
52
+ __all__ = [
53
+ "BuildResult",
54
+ "Watcher",
55
+ "build",
56
+ "doctor",
57
+ "export_frontend",
58
+ "scaffold",
59
+ ]
60
+
61
+ _PKG = importlib_resources.files("neutralino")
62
+
63
+ log = logging.getLogger("neutralino.devtools")
64
+
65
+
66
+ def _template_root() -> Path:
67
+ return Path(str(_PKG.joinpath("templates/default")))
68
+
69
+
70
+ def _companion_files() -> dict[str, str]:
71
+ return {
72
+ "python-bridge.mjs": _PKG.joinpath("frontend/python-bridge.mjs").read_text(
73
+ encoding="utf-8"
74
+ ),
75
+ "python-bridge.d.ts": _PKG.joinpath("frontend/python-bridge.d.ts").read_text(
76
+ encoding="utf-8"
77
+ ),
78
+ }
79
+
80
+
81
+ # ---------------------------------------------------------------- path safety
82
+ # One policy for every file the tools write (scaffold, frontend export) or
83
+ # ship (build): links are never followed when writing, sources must be
84
+ # regular files inside the project, and paths given on the command line stay
85
+ # inside the project.
86
+ #
87
+ # Limits (TOCTOU): the checks use os.lstat and then act on the path, so a
88
+ # process that can rename entries inside the project at the same moment can
89
+ # still race them. Writes are temp + rename in the checked directory and
90
+ # sources are opened with O_NOFOLLOW (where the OS has it) and compared with
91
+ # the checked inode, which narrows that window but does not close it; the
92
+ # project is assumed to be owned by the user running the tool. The goal is
93
+ # that a stray or planted link can never make a scaffold overwrite, or a
94
+ # build ship, something outside the project by accident.
95
+
96
+ _REPARSE_POINT = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
97
+ _O_NOFOLLOW: int = getattr(os, "O_NOFOLLOW", 0)
98
+ _O_NONBLOCK: int = getattr(os, "O_NONBLOCK", 0) # a FIFO swapped in never blocks open()
99
+ _O_BINARY: int = getattr(os, "O_BINARY", 0)
100
+ _CONTROL = re.compile(r"[\x00-\x1f\x7f]")
101
+
102
+
103
+ def _is_link(st: os.stat_result, path: Path) -> bool:
104
+ """True for a symlink, an NTFS junction or any other reparse point, judged
105
+ from an ``os.lstat`` result (the link itself is never followed)."""
106
+ if stat.S_ISLNK(st.st_mode):
107
+ return True
108
+ if getattr(st, "st_file_attributes", 0) & _REPARSE_POINT:
109
+ return True
110
+ is_junction: Callable[[], bool] | None = getattr(path, "is_junction", None) # 3.12+
111
+ return bool(is_junction is not None and is_junction())
112
+
113
+
114
+ def _lstat(path: Path) -> os.stat_result | None:
115
+ try:
116
+ return os.lstat(path)
117
+ except FileNotFoundError:
118
+ return None
119
+
120
+
121
+ def _relative_inside(option: str, value: str) -> PurePosixPath:
122
+ """``value`` (a command-line path, ``option`` names the flag) as a plain
123
+ relative path below the project: not absolute, no drive, no ``..``, no
124
+ control characters. Any other character a file name may hold is fine:
125
+ the path is never part of shell or batch code."""
126
+ if not value or _CONTROL.search(value):
127
+ raise ValidationError(f"{option} {value!r}: empty or contains control characters")
128
+ if PureWindowsPath(value).anchor or PurePosixPath(value).is_absolute():
129
+ raise ValidationError(f"{option} {value!r} must be a path relative to the project")
130
+ parts = PureWindowsPath(value).parts if is_windows() else PurePosixPath(value).parts
131
+ if ".." in parts:
132
+ raise ValidationError(f"{option} {value!r} must stay inside the project (no '..')")
133
+ rel = PurePosixPath(*[p for p in parts if p != "."]) if parts else PurePosixPath()
134
+ if not rel.parts:
135
+ raise ValidationError(f"{option} {value!r} must name a path below the project")
136
+ return rel
137
+
138
+
139
+ def _check_parents(root: Path, rel: PurePosixPath) -> None:
140
+ """Refuse a link (symlink/junction) or a non-directory among the existing
141
+ parents of ``rel`` below ``root`` (``root`` itself is the user's choice)."""
142
+ here = root
143
+ for part in rel.parts[:-1]:
144
+ here = here / part
145
+ st = _lstat(here)
146
+ if st is None:
147
+ return
148
+ if _is_link(st, here):
149
+ raise ValidationError(f"refusing to write below {here}: it is a symlink or junction")
150
+ if not stat.S_ISDIR(st.st_mode):
151
+ raise ValidationError(f"refusing to write below {here}: it is not a directory")
152
+
153
+
154
+ def _check_target(root: Path, rel: PurePosixPath) -> os.stat_result | None:
155
+ """The lstat of the file to write (None if absent) after refusing links
156
+ (dangling or not, whatever ``--force`` says) and non-regular files."""
157
+ _check_parents(root, rel)
158
+ target = root.joinpath(*rel.parts)
159
+ st = _lstat(target)
160
+ if st is not None and _is_link(st, target):
161
+ raise ValidationError(
162
+ f"refusing to write {rel}: it is a symlink or junction (never followed, even with "
163
+ "--force); remove it first"
164
+ )
165
+ if st is not None and not stat.S_ISREG(st.st_mode):
166
+ raise ValidationError(f"refusing to write {rel}: it exists and is not a regular file")
167
+ return st
168
+
169
+
170
+ def _read_regular(path: Path) -> bytes:
171
+ fd = os.open(path, os.O_RDONLY | _O_NOFOLLOW | _O_NONBLOCK | _O_BINARY)
172
+ with os.fdopen(fd, "rb") as f:
173
+ if not stat.S_ISREG(os.fstat(f.fileno()).st_mode):
174
+ raise ValidationError(f"{path} is not a regular file")
175
+ return f.read()
176
+
177
+
178
+ def _safe_write(root: Path, rel: PurePosixPath, data: bytes, *, replace: bool) -> None:
179
+ """Write ``root/rel`` atomically without following links.
180
+
181
+ The data goes to an exclusive temp file in the target's directory, which
182
+ then replaces the target (``replace``) or is hard-linked to its name, which
183
+ fails if anything (a file, a dangling link) appeared there meanwhile.
184
+ """
185
+ _check_parents(root, rel)
186
+ here = root
187
+ for part in rel.parts[:-1]: # create missing parents one level at a time
188
+ here = here / part
189
+ with contextlib.suppress(FileExistsError):
190
+ here.mkdir()
191
+ st = _check_target(root, rel) # parents again, now that they exist
192
+ target = root.joinpath(*rel.parts)
193
+ mode = stat.S_IMODE(st.st_mode) if st is not None else 0o644
194
+ fd, tmp_name = tempfile.mkstemp(dir=target.parent, prefix=f".{target.name}.", suffix=".tmp")
195
+ tmp = Path(tmp_name)
196
+ try:
197
+ with os.fdopen(fd, "wb") as f:
198
+ f.write(data)
199
+ tmp.chmod(mode)
200
+ if replace:
201
+ tmp.replace(target)
202
+ else:
203
+ _create_exclusive(tmp, target, data, mode)
204
+ finally:
205
+ with contextlib.suppress(FileNotFoundError):
206
+ tmp.unlink()
207
+
208
+
209
+ def _create_exclusive(tmp: Path, target: Path, data: bytes, mode: int) -> None:
210
+ try:
211
+ os.link(tmp, target) # tmp is our own regular file
212
+ return
213
+ except FileExistsError:
214
+ raise ValidationError(f"{target} appeared while writing; left untouched") from None
215
+ except OSError: # no hard links on this filesystem: exclusive no-follow create
216
+ pass
217
+ try:
218
+ fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL | _O_NOFOLLOW | _O_BINARY, mode)
219
+ except FileExistsError:
220
+ raise ValidationError(f"{target} appeared while writing; left untouched") from None
221
+ with os.fdopen(fd, "wb") as f:
222
+ f.write(data)
223
+
224
+
225
+ # ------------------------------------------------------------------- scaffold
226
+ @dataclass
227
+ class WriteReport:
228
+ created: list[str] = field(default_factory=list[str])
229
+ unchanged: list[str] = field(default_factory=list[str])
230
+ conflicts: dict[str, str] = field(default_factory=dict[str, str]) # path -> unified diff
231
+ overwritten: list[str] = field(default_factory=list[str])
232
+
233
+
234
+ def _write_files(dest: Path, files: dict[str, str | bytes], force: bool) -> WriteReport:
235
+ """Write files without clobbering: existing different files are reported
236
+ as conflicts (with a diff) unless ``force``.
237
+
238
+ Every target is checked before anything is written: a symlink or junction
239
+ (dangling or not), a symlinked parent folder or a non-regular file is
240
+ refused even with ``force``. Each write is atomic (see ``_safe_write``)."""
241
+ report = WriteReport()
242
+ existing = {rel: _check_target(dest, PurePosixPath(rel)) for rel in sorted(files)}
243
+ for rel, content in sorted(files.items()):
244
+ target = dest / rel
245
+ data = content.encode() if isinstance(content, str) else content
246
+ if existing[rel] is not None:
247
+ old = _read_regular(target)
248
+ if old == data:
249
+ report.unchanged.append(rel)
250
+ continue
251
+ if not force:
252
+ diff = "".join(
253
+ difflib.unified_diff(
254
+ old.decode("utf-8", "replace").splitlines(keepends=True),
255
+ data.decode("utf-8", "replace").splitlines(keepends=True),
256
+ f"{rel} (existing)",
257
+ f"{rel} (template)",
258
+ )
259
+ )
260
+ report.conflicts[rel] = diff
261
+ continue
262
+ report.overwritten.append(rel)
263
+ else:
264
+ report.created.append(rel)
265
+ _safe_write(dest, PurePosixPath(rel), data, replace=existing[rel] is not None)
266
+ return report
267
+
268
+
269
+ def slugify(name: str) -> str:
270
+ slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")
271
+ return slug or "app"
272
+
273
+
274
+ def scaffold(dest: Path, *, name: str | None = None, force: bool = False) -> WriteReport:
275
+ """Create a minimal app (backend, frontend, config) in ``dest``."""
276
+ dest = dest.resolve()
277
+ title = name or dest.name.replace("-", " ").replace("_", " ").title() or "App"
278
+ if len(title) > 200 or any(ord(c) < 32 or ord(c) == 127 for c in title):
279
+ raise ValidationError("--name must be at most 200 characters without control characters")
280
+ slug = slugify(name or dest.name)
281
+ app_id = "org.example." + (re.sub(r"[^a-z0-9]", "", slug) or "app")
282
+ plain = {"__APP_ID__": app_id, "__SLUG__": slug} # [a-z0-9.-] only
283
+ root = _template_root()
284
+ files: dict[str, str | bytes] = {}
285
+ for path in sorted(root.rglob("*")):
286
+ if path.is_dir() or "__pycache__" in path.parts:
287
+ continue
288
+ rel = path.relative_to(root).as_posix()
289
+ if rel == "gitignore.txt":
290
+ rel = ".gitignore"
291
+ if (
292
+ path.suffix in (".py", ".json", ".html", ".js", ".css", ".txt")
293
+ and rel != "frontend/neutralino.js"
294
+ ):
295
+ text = path.read_text(encoding="utf-8")
296
+ for k, v in plain.items():
297
+ text = text.replace(k, v)
298
+ # The free-form name is escaped for the file it lands in.
299
+ quoted = _escape_for(path.suffix, title)
300
+ text = text.replace("__TITLE__", quoted).replace("__NAME__", quoted)
301
+ files[rel] = text
302
+ else:
303
+ files[rel] = path.read_bytes()
304
+ for fname, text in _companion_files().items():
305
+ files[f"frontend/{fname}"] = text
306
+ dest.mkdir(parents=True, exist_ok=True)
307
+ return _write_files(dest, files, force)
308
+
309
+
310
+ def _escape_for(suffix: str, text: str) -> str:
311
+ """``text`` safe inside a string literal / text node of a ``suffix`` file."""
312
+ if suffix in (".py", ".json", ".js"):
313
+ return json.dumps(text, ensure_ascii=False)[1:-1] # also valid Python/JS escapes
314
+ if suffix == ".html":
315
+ return html.escape(text, quote=True)
316
+ return text
317
+
318
+
319
+ def export_frontend(
320
+ dest: Path, *, include_client: bool = False, force: bool = False
321
+ ) -> WriteReport:
322
+ """Copy python-bridge.mjs/.d.ts (and optionally the pinned neutralino.js).
323
+
324
+ The declarations are also written as ``python-bridge.d.mts``: TypeScript
325
+ looks for that name beside an ``import "./python-bridge.mjs"``."""
326
+ files: dict[str, str | bytes] = dict(_companion_files())
327
+ files["python-bridge.d.mts"] = files["python-bridge.d.ts"]
328
+ if include_client:
329
+ files["neutralino.js"] = (_template_root() / "frontend" / "neutralino.js").read_bytes()
330
+ dest.mkdir(parents=True, exist_ok=True)
331
+ return _write_files(dest, files, force)
332
+
333
+
334
+ # --------------------------------------------------------------------- doctor
335
+ def _check(ok: bool | None, name: str, detail: str, fix: str = "") -> dict[str, Any]:
336
+ status = "ok" if ok else ("warn" if ok is None else "fail")
337
+ return {"check": name, "status": status, "detail": detail, "fix": fix}
338
+
339
+
340
+ def _linux_webview() -> dict[str, Any]:
341
+ for lib in ("webkit2gtk-4.1", "webkit2gtk-4.0"):
342
+ if ctypes.util.find_library(lib):
343
+ return _check(True, "webview", f"lib{lib} found")
344
+ return _check(
345
+ False,
346
+ "webview",
347
+ "WebKitGTK not found",
348
+ "Debian/Ubuntu: sudo apt install libwebkit2gtk-4.1-0; Fedora: sudo dnf install "
349
+ "webkit2gtk4.1",
350
+ )
351
+
352
+
353
+ def doctor(*, config_path: Path | None = None, smoke: bool = False) -> dict[str, Any]:
354
+ """Inspect the environment. Never modifies the host. No secrets in output."""
355
+ checks: list[dict[str, Any]] = []
356
+ checks.append(
357
+ _check(
358
+ sys.version_info >= (3, 11),
359
+ "python",
360
+ f"{platform.python_implementation()} {platform.python_version()} ({sys.executable})",
361
+ "Python 3.11+ is required",
362
+ )
363
+ )
364
+ key = platform_key()
365
+ try:
366
+ member, expected = binary_spec(CORE_VERSION)
367
+ checks.append(_check(True, "platform", f"{key} -> {member}"))
368
+ except Exception as e:
369
+ checks.append(_check(False, "platform", str(e)))
370
+ expected = ""
371
+ runtime_path = None
372
+ try:
373
+ info = resolve_binary()
374
+ runtime_path = info.path
375
+ pinned = info.sha256 == expected
376
+ checks.append(
377
+ _check(
378
+ True if pinned else None,
379
+ "runtime",
380
+ f"{info.path} ({info.source}, sha256 "
381
+ f"{'matches the lock' if pinned else 'NOT the pinned build'})",
382
+ )
383
+ )
384
+ except UnsupportedError as e: # no official binary for this platform
385
+ checks.append(_check(False, "runtime", str(e)))
386
+ except RuntimeIntegrityError as e:
387
+ checks.append(_check(False, "runtime", str(e), "neutralino runtime install"))
388
+ if sys.platform.startswith("linux"):
389
+ checks.append(_linux_webview())
390
+ wl, x = os.environ.get("WAYLAND_DISPLAY"), os.environ.get("DISPLAY")
391
+ checks.append(
392
+ _check(
393
+ bool(wl or x),
394
+ "display",
395
+ f"WAYLAND_DISPLAY={wl or '-'} DISPLAY={x or '-'}",
396
+ "run inside a desktop session or under xvfb-run",
397
+ )
398
+ )
399
+ found = ctypes.util.find_library("ayatana-appindicator3")
400
+ checks.append(
401
+ _check(
402
+ True if found else None,
403
+ "libayatana-appindicator3",
404
+ "found" if found else "not found (tray icon)",
405
+ "install libayatana-appindicator3-1",
406
+ )
407
+ )
408
+ # Upstream shows dialogs and notifications through portable-file-dialogs,
409
+ # which runs one of these desktop helpers (pfd: check_program).
410
+ helpers = [h for h in ("zenity", "kdialog", "qarma", "matedialog") if shutil.which(h)]
411
+ checks.append(
412
+ _check(
413
+ True if helpers else None,
414
+ "dialog-helper",
415
+ f"found {', '.join(helpers)}"
416
+ if helpers
417
+ else "none of zenity/kdialog/qarma/matedialog (dialogs and notifications)",
418
+ "install zenity (GNOME and most desktops) or kdialog (KDE)",
419
+ )
420
+ )
421
+ elif sys.platform == "win32":
422
+ checks.append(_check(None, "webview", "WebView2 runtime is required (Windows 11 ships it)"))
423
+ elif sys.platform == "darwin":
424
+ checks.append(_check(True, "webview", "WKWebView (system)"))
425
+ checks.append(_ui_assets_check())
426
+ import importlib.util
427
+
428
+ has_ensurepip = importlib.util.find_spec("ensurepip") is not None
429
+ checks.append(
430
+ _check(
431
+ True if has_ensurepip else None,
432
+ "venv",
433
+ "venv + ensurepip available (managed installs)"
434
+ if has_ensurepip
435
+ else "ensurepip missing: managed installs (neutralino build --mode managed) cannot "
436
+ "create their virtual environment with this interpreter",
437
+ "Debian/Ubuntu: sudo apt install python3-venv, or put a user-level CPython of the "
438
+ "target version that has ensurepip (uv, pyenv) on PATH as pythonX.Y "
439
+ "(see packaging.md, managed builds)",
440
+ )
441
+ )
442
+ for tool in ("node", "npm"):
443
+ found = shutil.which(tool)
444
+ checks.append(
445
+ _check(
446
+ True if found else None,
447
+ tool,
448
+ found or "not installed (only needed for bundling/React builds)",
449
+ )
450
+ )
451
+ cache = user_cache_dir()
452
+ checks.append(_check(True, "cache", str(cache)))
453
+ if config_path is not None:
454
+ try:
455
+ cfg = config_mod.load_config(config_path)
456
+ built = config_mod.build_instance_config(
457
+ cfg, extension_id="org.doctor.check", resources_mount="/app/"
458
+ )
459
+ blocked = config_mod.check_permissions(built, built["defaultMode"])
460
+ checks.append(
461
+ _check(
462
+ not blocked,
463
+ "config",
464
+ f"{config_path} valid" if not blocked else f"allow/block list blocks {blocked}",
465
+ "allow extensions.getStats and app.broadcast",
466
+ )
467
+ )
468
+ except (OSError, ValidationError) as e:
469
+ checks.append(_check(False, "config", str(e)))
470
+ if smoke and runtime_path is not None:
471
+ checks.append(_smoke(runtime_path))
472
+ failed = [f"{c['check']}: {c['detail']}" for c in checks if c["status"] == "fail"]
473
+ result: dict[str, Any] = {
474
+ "sdk": {"version": _sdk_version(), "core": CORE_VERSION, "client": CLIENT_VERSION},
475
+ "platform": key,
476
+ "ok": not failed,
477
+ "checks": checks,
478
+ }
479
+ if failed:
480
+ result["error"] = "; ".join(failed)
481
+ return result
482
+
483
+
484
+ def _renderer_problems(base: Path) -> tuple[dict[str, Any], list[str]]:
485
+ """The renderer manifest in ``base`` and the files that are missing,
486
+ unsafe or do not match their SHA-256 (RuntimeIntegrityError without a manifest)."""
487
+ from .ui._assets import renderer_manifest
488
+
489
+ mf = renderer_manifest(base)
490
+ files = cast("dict[str, Any]", mf.get("files") or {})
491
+ bad: list[str] = []
492
+ for rel, digest in sorted(files.items()):
493
+ parts = PurePosixPath(rel).parts
494
+ path = base.joinpath(*parts)
495
+ if (
496
+ PurePosixPath(rel).is_absolute()
497
+ or ".." in parts
498
+ or not path.is_file()
499
+ or path.is_symlink()
500
+ or sha256_file(path) != digest
501
+ ):
502
+ bad.append(rel)
503
+ if not files:
504
+ bad.append("manifest.json (lists no files)")
505
+ return mf, bad
506
+
507
+
508
+ def _ui_assets_check() -> dict[str, Any]:
509
+ """The packaged UI renderer: every file listed in its manifest present
510
+ and matching its SHA-256 (what ``ui.Application`` verifies when staging)."""
511
+ from .ui._assets import renderer_dir
512
+
513
+ base = renderer_dir()
514
+ try:
515
+ mf, bad = _renderer_problems(base)
516
+ except (RuntimeIntegrityError, OSError, ValueError) as e:
517
+ return _check(False, "ui-renderer", str(e), "reinstall neutralino-python")
518
+ n = len(cast("dict[str, Any]", mf.get("files") or {}))
519
+ if bad:
520
+ detail = f"{len(bad)} of {n} renderer files missing or modified: " + ", ".join(bad[:5])
521
+ return _check(False, "ui-renderer", detail, "reinstall neutralino-python")
522
+ return _check(
523
+ True,
524
+ "ui-renderer",
525
+ f"{n} files match manifest.json (build {mf.get('build', '?')}, "
526
+ f"protocol {mf.get('protocol', '?')}) in {base}",
527
+ )
528
+
529
+
530
+ def _sdk_version() -> str:
531
+ from . import __version__
532
+
533
+ return __version__
534
+
535
+
536
+ def _smoke(runtime: Path) -> dict[str, Any]:
537
+ """Start the runtime with a hidden window and make one call.
538
+
539
+ Window mode binds 127.0.0.1 only (cloud mode would bind 0.0.0.0, and
540
+ browser mode would open the user's browser)."""
541
+ import asyncio
542
+
543
+ from .application import AsyncApplication
544
+
545
+ async def go() -> str:
546
+ async with AsyncApplication(
547
+ mode="window",
548
+ runtime=runtime,
549
+ window_options={"hidden": True},
550
+ native_allow_list=["computer.getArch"],
551
+ ) as app:
552
+ return await app.computer.get_arch()
553
+
554
+ try:
555
+ t0 = time.monotonic()
556
+ arch = asyncio.run(go())
557
+ return _check(
558
+ True,
559
+ "smoke",
560
+ f"runtime answered ({arch}) in {time.monotonic() - t0:.2f}s (hidden window, 127.0.0.1)",
561
+ )
562
+ except Exception as e:
563
+ return _check(False, "smoke", f"{type(e).__name__}: {e}")
564
+
565
+
566
+ def port_available(port: int) -> bool:
567
+ with socket.socket() as s:
568
+ try:
569
+ s.bind(("127.0.0.1", port))
570
+ return True
571
+ except OSError:
572
+ return False
573
+
574
+
575
+ # ---------------------------------------------------------------------- build
576
+ def _built_at() -> str:
577
+ """Build time; ``SOURCE_DATE_EPOCH`` (reproducible builds) wins, in UTC."""
578
+ epoch = os.environ.get("SOURCE_DATE_EPOCH", "")
579
+ if epoch.isdigit():
580
+ return time.strftime("%Y-%m-%dT%H:%M:%S+0000", time.gmtime(int(epoch)))
581
+ return time.strftime("%Y-%m-%dT%H:%M:%S%z")
582
+
583
+
584
+ @dataclass
585
+ class BuildResult:
586
+ out: Path
587
+ files: int
588
+ manifest: dict[str, Any]
589
+
590
+
591
+ # The launchers are fixed text (identical in every build): they only start
592
+ # boot.py, which reads the entry, the runtime binary and the bundle flag from
593
+ # manifest.json. No file name is ever interpolated into shell or batch code.
594
+ _LAUNCHER_SH = """#!/bin/sh
595
+ # Launcher generated by neutralino-python. Requires Python 3.11+ on PATH (or
596
+ # $PYTHON). Fixed text: boot.py reads the entry from manifest.json.
597
+ HERE=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) || exit 1
598
+ export PYTHONPATH="$HERE/vendor${PYTHONPATH:+:$PYTHONPATH}"
599
+ exec "${PYTHON:-python3}" -I "$HERE/boot.py" "$@"
600
+ """
601
+
602
+ _LAUNCHER_BAT = """@echo off
603
+ rem Launcher generated by neutralino-python. Requires Python 3.11+ (py launcher).
604
+ rem Fixed text: boot.py reads the entry from manifest.json.
605
+ setlocal DisableDelayedExpansion
606
+ py -3 -I "%~dp0boot.py" %*
607
+ """
608
+
609
+ _BOOT_PY = '''"""Bootstrap generated by neutralino-python (fixed text, same in every build).
610
+
611
+ Runs the entry recorded in manifest.json like ``python <entry>`` from app/:
612
+ vendor/ and the entry's folder first on sys.path, the pinned runtime (and, for
613
+ a bundled build, app/resources.neu) in the environment. Started with
614
+ ``python -I``, so neither PYTHON* variables nor the current folder change what
615
+ is imported.
616
+ """
617
+
618
+ import json
619
+ import os
620
+ import runpy
621
+ import sys
622
+
623
+
624
+ def _fail(message):
625
+ sys.stderr.write("neutralino build: " + message + "\\n")
626
+ raise SystemExit(2)
627
+
628
+
629
+ def main():
630
+ here = os.path.dirname(os.path.abspath(__file__))
631
+ try:
632
+ with open(os.path.join(here, "manifest.json"), encoding="utf-8") as f:
633
+ manifest = json.load(f)
634
+ entry = manifest["entry"]
635
+ binary = manifest["runtime"]["binary"]
636
+ except (OSError, ValueError, KeyError, TypeError) as e:
637
+ _fail("unreadable manifest.json: %s" % (e,))
638
+ parts = entry.split("/") if isinstance(entry, str) else []
639
+ app = os.path.join(here, "app")
640
+ path = os.path.join(app, *parts) if parts else app
641
+ if (
642
+ not parts
643
+ or any(p in ("", ".", "..") for p in parts)
644
+ or any(ord(c) < 32 or ord(c) == 127 for c in entry)
645
+ or not os.path.realpath(path).startswith(os.path.realpath(app) + os.sep)
646
+ or not os.path.isfile(path)
647
+ ):
648
+ _fail("manifest.json names an invalid entry %r (a file below app/ is required)" % (entry,))
649
+ if not isinstance(binary, str) or binary in ("", ".", ".."):
650
+ _fail("manifest.json names an invalid runtime binary %r" % (binary,))
651
+ if os.path.basename(binary) != binary:
652
+ _fail("manifest.json names an invalid runtime binary %r" % (binary,))
653
+ os.environ["NEUTRALINO_RUNTIME"] = os.path.join(here, "runtime", binary)
654
+ if manifest.get("bundle") == "resources.neu":
655
+ os.environ["NEUTRALINO_RESOURCES"] = os.path.join(app, "resources.neu")
656
+ os.chdir(app)
657
+ rel = os.path.join(*parts)
658
+ sys.path[:0] = [os.path.join(here, "vendor"), os.path.dirname(os.path.abspath(rel))]
659
+ sys.argv = [rel] + sys.argv[1:]
660
+ runpy.run_path(rel, run_name="__main__")
661
+
662
+
663
+ if __name__ == "__main__":
664
+ main()
665
+ '''
666
+
667
+ # Always vendored (distribution -> import names).
668
+ _SDK_DISTRIBUTIONS = {"neutralino-python": ["neutralino"], "websockets": ["websockets"]}
669
+ _SDK_MODULES = frozenset({"neutralino", "websockets"})
670
+
671
+
672
+ def _license_files(dist_name: str) -> dict[str, str]:
673
+ """Licence/notice files of an installed distribution (wheel or source tree)."""
674
+ from importlib import metadata
675
+
676
+ found: dict[str, str] = {}
677
+ try:
678
+ dist = metadata.distribution(dist_name)
679
+ except metadata.PackageNotFoundError:
680
+ return found
681
+ for f in dist.files or ():
682
+ parts = Path(str(f)).parts
683
+ name = parts[-1]
684
+ # Only the distribution's own metadata (``*.dist-info/``, PEP 639
685
+ # ``licenses/``): package data can hold other projects' licence files
686
+ # (the renderer's third-party notices are named LICENSE*, too).
687
+ if not any(p.endswith(".dist-info") for p in parts[:-1]):
688
+ continue
689
+ if name.upper().startswith(("LICENSE", "LICENCE", "COPYING", "THIRD_PARTY_NOTICES")):
690
+ try:
691
+ found.setdefault(name, f.read_text(encoding="utf-8") or "")
692
+ except (OSError, UnicodeDecodeError):
693
+ continue
694
+ if dist_name == "neutralino-python":
695
+ repo = Path(str(_PKG)).parent.parent # editable/source checkout
696
+ for name in ("LICENSE", "THIRD_PARTY_NOTICES.md"):
697
+ if name not in found and (repo / name).is_file():
698
+ found[name] = (repo / name).read_text(encoding="utf-8")
699
+ return found
700
+
701
+
702
+ def _license_of(dist_name: str) -> str:
703
+ """The declared licence (SPDX expression, License field or classifiers)."""
704
+ from importlib import metadata
705
+
706
+ try:
707
+ meta = metadata.metadata(dist_name)
708
+ except metadata.PackageNotFoundError:
709
+ return "UNKNOWN"
710
+ expression = meta.get_all("License-Expression") or []
711
+ if expression:
712
+ return str(expression[0])
713
+ classifiers = [
714
+ str(c).rsplit(" :: ", 1)[-1]
715
+ for c in meta.get_all("Classifier") or []
716
+ if str(c).startswith("License ::")
717
+ ]
718
+ if classifiers:
719
+ return " AND ".join(classifiers)
720
+ text = str((meta.get_all("License") or [""])[0]).strip().splitlines()
721
+ return text[0][:200] if text else "UNKNOWN"
722
+
723
+
724
+ def _vendor_packages(dest: Path) -> list[str]:
725
+ """Copy the installed packages the app needs (neutralino, websockets) as pure
726
+ Python: compiled speedups are left out (websockets falls back to Python),
727
+ so the build is not tied to this interpreter's ABI."""
728
+ import websockets
729
+
730
+ import neutralino
731
+
732
+ names: list[str] = []
733
+ for mod in (neutralino, websockets):
734
+ src = Path(mod.__file__ or "").parent
735
+ target = dest / src.name
736
+ shutil.copytree(
737
+ src, target, ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "*.so", "*.pyd")
738
+ )
739
+ names.append(src.name)
740
+ return names
741
+
742
+
743
+ # ------------------------------------------------------------- build sources
744
+ @dataclass(frozen=True)
745
+ class _Source:
746
+ rel: PurePosixPath # where it goes (relative to app/ or vendor/)
747
+ path: Path # the file read (an in-project link's target)
748
+ st: os.stat_result # its lstat, compared again when it is copied
749
+
750
+
751
+ _BUILD_SKIP = frozenset({"dist", "build", "venv", "node_modules", "__pycache__"})
752
+ # Inside the frontend directory a compiled bundle usually lives in dist/ or build/.
753
+ _FRONTEND_SKIP = _BUILD_SKIP - {"dist", "build"}
754
+ _SKIP_REASON = {"node_modules": "dependency", "venv": "virtualenv"} # others: "generated"
755
+ _NEVER_COPY = (".pyc", ".pyo")
756
+ # Key material that is never shipped by accident (dotfiles such as .env, .npmrc
757
+ # or .pypirc are already excluded as hidden).
758
+ _SECRET_NAMES = (
759
+ "*.pem",
760
+ "*.key",
761
+ "*.p12",
762
+ "*.pfx",
763
+ "*.jks",
764
+ "*.keystore",
765
+ "id_rsa",
766
+ "id_dsa",
767
+ "id_ecdsa",
768
+ "id_ed25519",
769
+ )
770
+
771
+
772
+ def _under(rel: PurePosixPath, base: PurePosixPath) -> bool:
773
+ return rel.parts[: len(base.parts)] == base.parts
774
+
775
+
776
+ def _exclusion(
777
+ rel: PurePosixPath, frontend: PurePosixPath, *, is_dir: bool, patterns: Sequence[str] = ()
778
+ ) -> str | None:
779
+ """Why ``rel`` (a project path) is left out of a build, or None to ship it.
780
+
781
+ The one place that decides what a build ships: the portable build, the
782
+ managed build (``--mode managed``) and release archives all collect their
783
+ files through it. The same rules apply to a directory build and to the
784
+ files handed to neu for ``--bundle``: hidden files and folders (``.env``,
785
+ ``.git``, ``.venv``), compiled bytecode, key files, dependency/generated
786
+ folders (``node_modules``, ``venv``, ``__pycache__``; ``dist``/``build``
787
+ too, except inside the frontend directory, where a compiled frontend
788
+ lives), and what the project's ``[package].exclude`` patterns name.
789
+ """
790
+ parts = rel.parts
791
+ if any(p.startswith(".") for p in parts):
792
+ return "hidden"
793
+ if is_dir and frontend.parts[: len(parts)] == parts:
794
+ return None # the way to (or the) frontend directory is always walked
795
+ if patterns and exclude_match(rel.as_posix(), patterns):
796
+ return "app.toml exclude"
797
+ inside = _under(rel, frontend)
798
+ names = set(parts[len(frontend.parts) :] if inside else parts)
799
+ hit = names & (_FRONTEND_SKIP if inside else _BUILD_SKIP)
800
+ if hit:
801
+ return _SKIP_REASON.get(min(hit), "generated")
802
+ if not is_dir:
803
+ if rel.suffix in _NEVER_COPY:
804
+ return "bytecode"
805
+ if any(fnmatch.fnmatchcase(rel.name.lower(), pat) for pat in _SECRET_NAMES):
806
+ return "secret"
807
+ return None
808
+
809
+
810
+ def _collect_sources(
811
+ project: Path, frontend: PurePosixPath, skip: Sequence[Path], patterns: Sequence[str] = ()
812
+ ) -> tuple[list[_Source], list[dict[str, str]]]:
813
+ """Walk ``project`` without following links: the files a build ships and
814
+ the paths it leaves out (with the reason, for the manifest).
815
+
816
+ Excluded folders are not walked. Policy for links and junctions: a link
817
+ to a regular file inside the project that the build would ship anyway is
818
+ copied as a file; a link to a directory, a dangling link and a link
819
+ leaving the project are refused, as are FIFOs, sockets and devices.
820
+ """
821
+ sources: list[_Source] = []
822
+ excluded: list[dict[str, str]] = []
823
+ problems: list[str] = []
824
+
825
+ def leave_out(rel: PurePosixPath, reason: str) -> None:
826
+ excluded.append({"path": rel.as_posix(), "reason": reason})
827
+
828
+ def link_source(path: Path, rel: PurePosixPath) -> _Source | None:
829
+ target = Path(os.path.realpath(path))
830
+ st = _lstat(target)
831
+ if st is None:
832
+ problems.append(f"{rel}: dangling symlink")
833
+ return None
834
+ try:
835
+ target_rel = PurePosixPath(target.relative_to(project).as_posix())
836
+ except ValueError:
837
+ problems.append(f"{rel}: links to {target}, outside the project")
838
+ return None
839
+ if stat.S_ISDIR(st.st_mode):
840
+ problems.append(
841
+ f"{rel}: symlinked directory (-> {target_rel}) is not followed; "
842
+ "copy the folder or point the build at it"
843
+ )
844
+ return None
845
+ if _is_link(st, target) or not stat.S_ISREG(st.st_mode):
846
+ problems.append(f"{rel}: links to {target_rel}, which is not a regular file")
847
+ return None
848
+ reason = _exclusion(target_rel, frontend, is_dir=False, patterns=patterns)
849
+ if reason is None and any(target == s or s in target.parents for s in skip):
850
+ reason = "output"
851
+ if reason is not None:
852
+ problems.append(
853
+ f"{rel}: links to {target_rel}, which is excluded from builds ({reason})"
854
+ )
855
+ return None
856
+ return _Source(rel, target, st)
857
+
858
+ def walk(directory: Path, rel_dir: PurePosixPath) -> None:
859
+ with os.scandir(directory) as it:
860
+ names = sorted(e.name for e in it)
861
+ for name in names:
862
+ path, rel = directory / name, rel_dir / name
863
+ if path in skip:
864
+ leave_out(rel, "output")
865
+ continue
866
+ st = _lstat(path)
867
+ if st is None: # vanished during the walk
868
+ continue
869
+ link = _is_link(st, path)
870
+ is_dir = stat.S_ISDIR(st.st_mode) and not link
871
+ reason = _exclusion(rel, frontend, is_dir=is_dir, patterns=patterns)
872
+ if reason is None and is_dir and _lstat(path / "pyvenv.cfg") is not None:
873
+ reason = "virtualenv"
874
+ if reason is not None:
875
+ leave_out(rel, reason)
876
+ elif link:
877
+ found = link_source(path, rel)
878
+ if found is not None:
879
+ sources.append(found)
880
+ elif is_dir:
881
+ walk(path, rel)
882
+ elif stat.S_ISREG(st.st_mode):
883
+ sources.append(_Source(rel, path, st))
884
+ else:
885
+ problems.append(f"{rel}: special file (FIFO, socket or device)")
886
+
887
+ walk(project, PurePosixPath())
888
+ if problems:
889
+ more = f"\n ... and {len(problems) - 20} more" if len(problems) > 20 else ""
890
+ raise ValidationError(
891
+ "refusing to build: unsafe files in the project\n " + "\n ".join(problems[:20]) + more
892
+ )
893
+ return sources, excluded
894
+
895
+
896
+ def _same_file(a: os.stat_result, b: os.stat_result) -> bool:
897
+ if not (a.st_ino and b.st_ino): # no inode numbers on this filesystem
898
+ return True
899
+ return (a.st_dev, a.st_ino) == (b.st_dev, b.st_ino)
900
+
901
+
902
+ def _copy_source(src: _Source, dest: Path) -> None:
903
+ """Copy one checked source to ``dest`` (in the private staging directory):
904
+ opened without following links, and only if it is still the same regular
905
+ file the walk checked."""
906
+ fd = os.open(src.path, os.O_RDONLY | _O_NOFOLLOW | _O_NONBLOCK | _O_BINARY)
907
+ with os.fdopen(fd, "rb") as f_in:
908
+ st = os.fstat(f_in.fileno())
909
+ if not stat.S_ISREG(st.st_mode) or not _same_file(st, src.st):
910
+ raise ValidationError(f"{src.rel} changed while the build was reading it")
911
+ dest.parent.mkdir(parents=True, exist_ok=True)
912
+ with dest.open("xb") as f_out:
913
+ shutil.copyfileobj(f_in, f_out)
914
+ dest.chmod(stat.S_IMODE(st.st_mode))
915
+ os.utime(dest, ns=(st.st_atime_ns, st.st_mtime_ns))
916
+
917
+
918
+ def _check_entry(
919
+ entry: PurePosixPath,
920
+ frontend: PurePosixPath,
921
+ bundle: bool,
922
+ sources: Sequence[_Source],
923
+ excluded: Sequence[dict[str, str]],
924
+ ) -> None:
925
+ if bundle and _under(entry, frontend):
926
+ raise ValidationError(
927
+ f"--app {entry}: inside the frontend folder, packed into resources.neu"
928
+ )
929
+ if any(s.rel == entry for s in sources):
930
+ return
931
+ for e in excluded:
932
+ if _under(entry, PurePosixPath(e["path"])):
933
+ raise ValidationError(
934
+ f"--app {entry} is excluded from builds ({e['reason']}: {e['path']})"
935
+ )
936
+ raise ValidationError(f"--app {entry}: not a regular file in the project")
937
+
938
+
939
+ # ------------------------------------------------------------ import checks
940
+ _PLATFORM_TESTS = frozenset({("sys", "version_info"), ("sys", "platform"), ("os", "name")})
941
+ _IMPORT_GUARDS = frozenset({"ImportError", "ModuleNotFoundError", "Exception", "BaseException"})
942
+
943
+
944
+ def _catches_import_error(handler: ast.ExceptHandler) -> bool:
945
+ kinds = handler.type
946
+ if kinds is None:
947
+ return True
948
+ nodes = kinds.elts if isinstance(kinds, ast.Tuple) else [kinds]
949
+ return any(
950
+ (isinstance(n, ast.Name) and n.id in _IMPORT_GUARDS)
951
+ or (isinstance(n, ast.Attribute) and n.attr in _IMPORT_GUARDS)
952
+ for n in nodes
953
+ )
954
+
955
+
956
+ def _condition_kind(test: ast.expr) -> str | None:
957
+ """ "typing" for ``if TYPE_CHECKING``, "platform" for tests on
958
+ ``sys.version_info``/``sys.platform``/``os.name`` (not evaluated here)."""
959
+ nodes = list(ast.walk(test))
960
+ if any(
961
+ (isinstance(n, ast.Name) and n.id == "TYPE_CHECKING")
962
+ or (isinstance(n, ast.Attribute) and n.attr == "TYPE_CHECKING")
963
+ for n in nodes
964
+ ):
965
+ return "typing"
966
+ if any(
967
+ isinstance(n, ast.Attribute)
968
+ and isinstance(n.value, ast.Name)
969
+ and (n.value.id, n.attr) in _PLATFORM_TESTS
970
+ for n in nodes
971
+ ):
972
+ return "platform"
973
+ return None
974
+
975
+
976
+ def _imports(tree: ast.AST, *, module_level: bool) -> list[tuple[str, int]]:
977
+ """Absolute imports that must succeed: (top-level module, line).
978
+
979
+ Not counted: imports guarded by ``try/except ImportError`` (optional),
980
+ under ``if TYPE_CHECKING`` or under version/platform conditions, relative
981
+ imports, and with ``module_level`` imports inside functions (lazy).
982
+ ``importlib.import_module``/``__import__`` are not seen (dynamic)."""
983
+ found: list[tuple[str, int]] = []
984
+
985
+ def visit(node: ast.AST, guarded: bool) -> None:
986
+ if module_level and isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)):
987
+ return
988
+ if isinstance(node, ast.Import):
989
+ if not guarded:
990
+ found.extend((a.name.partition(".")[0], node.lineno) for a in node.names)
991
+ return
992
+ if isinstance(node, ast.ImportFrom):
993
+ if not guarded and node.level == 0 and node.module:
994
+ found.append((node.module.partition(".")[0], node.lineno))
995
+ return
996
+ if isinstance(node, (ast.Try, ast.TryStar)):
997
+ optional = guarded or any(_catches_import_error(h) for h in node.handlers)
998
+ for stmt in node.body:
999
+ visit(stmt, optional)
1000
+ for part in (*node.handlers, *node.orelse, *node.finalbody):
1001
+ visit(part, guarded)
1002
+ return
1003
+ if isinstance(node, ast.If):
1004
+ kind = _condition_kind(node.test)
1005
+ if kind is not None:
1006
+ for stmt in node.body:
1007
+ visit(stmt, True)
1008
+ for stmt in node.orelse:
1009
+ visit(stmt, guarded or kind == "platform")
1010
+ return
1011
+ for child in ast.iter_child_nodes(node):
1012
+ visit(child, guarded)
1013
+
1014
+ visit(tree, False)
1015
+ return found
1016
+
1017
+
1018
+ def _parse(path: Path, rel: PurePosixPath | str) -> ast.AST:
1019
+ try:
1020
+ return ast.parse(_read_regular(path), filename=str(rel))
1021
+ except (SyntaxError, ValueError) as e:
1022
+ raise ValidationError(f"{rel}: cannot be parsed to check its imports ({e})") from None
1023
+
1024
+
1025
+ def _check_app_imports(
1026
+ entry: PurePosixPath, sources: Sequence[_Source], vendored: Iterable[str]
1027
+ ) -> None:
1028
+ """Fail unless every import reachable from the entry is the standard
1029
+ library, the app's own module (next to the entry: the bootstrap puts that
1030
+ folder on sys.path), neutralino/websockets or a ``--vendor``ed module."""
1031
+ base = entry.parent
1032
+ own: dict[str, list[_Source]] = {}
1033
+ for s in sources:
1034
+ if s.rel.suffix != ".py" or not _under(s.rel, base):
1035
+ continue
1036
+ rest = s.rel.parts[len(base.parts) :]
1037
+ name = rest[0][:-3] if len(rest) == 1 else rest[0]
1038
+ if name.isidentifier():
1039
+ own.setdefault(name, []).append(s)
1040
+ allowed = set(sys.stdlib_module_names) | _SDK_MODULES | set(vendored)
1041
+ by_rel = {s.rel: s for s in sources}
1042
+ queue, seen = [by_rel[entry]], {entry}
1043
+ missing: dict[tuple[str, PurePosixPath], int] = {}
1044
+ while queue:
1045
+ src = queue.pop()
1046
+ for name, line in _imports(_parse(src.path, src.rel), module_level=False):
1047
+ if name in own:
1048
+ for dep in own[name]:
1049
+ if dep.rel not in seen:
1050
+ seen.add(dep.rel)
1051
+ queue.append(dep)
1052
+ elif name not in allowed:
1053
+ missing.setdefault((name, src.rel), line)
1054
+ if missing:
1055
+ found = ", ".join(f"{n} ({rel}:{line})" for (n, rel), line in sorted(missing.items()))
1056
+ raise ValidationError(
1057
+ f"the app imports modules the portable build does not provide: {found}. A build "
1058
+ f"ships the standard library, the app's own modules (next to {entry}), neutralino "
1059
+ "and websockets. Vendor a pure-Python distribution installed here with --vendor "
1060
+ "NAME, guard an optional import with try/except ImportError, or remove it."
1061
+ )
1062
+
1063
+
1064
+ # --------------------------------------------------------------- --vendor
1065
+ @dataclass
1066
+ class _Distribution:
1067
+ name: str
1068
+ version: str
1069
+ license: str
1070
+ modules: list[str]
1071
+ files: list[_Source]
1072
+
1073
+
1074
+ _COMPILED = (".so", ".pyd", ".dylib", ".dll")
1075
+
1076
+
1077
+ def _inspect_distribution(name: str) -> _Distribution:
1078
+ """An installed distribution to vendor: pure Python only, every file a
1079
+ regular file matching its RECORD hash, licence files present. No
1080
+ dependency resolution: its own imports are checked, not installed."""
1081
+ from importlib import metadata
1082
+
1083
+ try:
1084
+ dist = metadata.distribution(name)
1085
+ except metadata.PackageNotFoundError:
1086
+ raise ValidationError(
1087
+ f"--vendor {name}: not installed in this environment ({sys.executable})"
1088
+ ) from None
1089
+ canonical = str(dist.metadata["Name"] or name)
1090
+ if re.sub(r"[-_.]+", "-", canonical).lower() in _SDK_DISTRIBUTIONS:
1091
+ raise ValidationError(f"--vendor {name}: always vendored by the build")
1092
+ files = dist.files
1093
+ if files is None:
1094
+ raise ValidationError(f"--vendor {name}: no RECORD file, its files are unknown")
1095
+ compiled = [str(f) for f in files if f.suffix in _COMPILED or ".so." in f.name]
1096
+ if compiled:
1097
+ raise ValidationError(
1098
+ f"--vendor {name}: {canonical} contains compiled extensions "
1099
+ f"({', '.join(compiled[:5])}); the portable build ships pure Python only"
1100
+ )
1101
+ if any(f.suffix == ".pth" for f in files):
1102
+ raise ValidationError(
1103
+ f"--vendor {name}: {canonical} installs a .pth path hook (an editable or "
1104
+ "path-hook install); install it normally to vendor it"
1105
+ )
1106
+ payload: list[_Source] = []
1107
+ for f in files:
1108
+ rel = PurePosixPath(str(f))
1109
+ if (
1110
+ rel.is_absolute()
1111
+ or ".." in rel.parts
1112
+ or rel.parts[0].endswith((".dist-info", ".egg-info", ".data"))
1113
+ or "__pycache__" in rel.parts
1114
+ or rel.suffix in _NEVER_COPY
1115
+ ):
1116
+ continue
1117
+ if rel.parts[0] in _SDK_MODULES:
1118
+ raise ValidationError(f"--vendor {name}: it ships {rel}, which clashes with the SDK")
1119
+ src = Path(str(dist.locate_file(f)))
1120
+ st = _lstat(src)
1121
+ if st is None or _is_link(st, src) or not stat.S_ISREG(st.st_mode):
1122
+ raise ValidationError(f"--vendor {name}: {rel} is missing or not a regular file")
1123
+ if f.hash is not None and f.hash.mode == "sha256":
1124
+ digest = base64.urlsafe_b64encode(hashlib.sha256(_read_regular(src)).digest())
1125
+ if digest.decode().rstrip("=") != f.hash.value:
1126
+ raise ValidationError(
1127
+ f"--vendor {name}: {rel} differs from the distribution's RECORD hash "
1128
+ "(modified after installation); reinstall it"
1129
+ )
1130
+ payload.append(_Source(rel, src, st))
1131
+ if not _license_files(canonical):
1132
+ raise ValidationError(
1133
+ f"--vendor {name}: no licence file in {canonical}'s installed metadata; "
1134
+ "it cannot be redistributed with its licence"
1135
+ )
1136
+ top = (dist.read_text("top_level.txt") or "").split()
1137
+ modules = sorted(
1138
+ set(top)
1139
+ or {
1140
+ s.rel.parts[0][:-3] if len(s.rel.parts) == 1 else s.rel.parts[0]
1141
+ for s in payload
1142
+ if s.rel.suffix == ".py" or len(s.rel.parts) > 1
1143
+ }
1144
+ )
1145
+ return _Distribution(canonical, dist.version, _license_of(canonical), modules, payload)
1146
+
1147
+
1148
+ def _check_vendored_imports(dists: Sequence[_Distribution]) -> None:
1149
+ """A vendored distribution's module-level imports must be provided too
1150
+ (lazy imports inside functions are not checked: optional features)."""
1151
+ allowed = set(sys.stdlib_module_names) | _SDK_MODULES
1152
+ for d in dists:
1153
+ allowed.update(d.modules)
1154
+ for d in dists:
1155
+ missing = sorted(
1156
+ {
1157
+ f"{n} ({s.rel}:{line})"
1158
+ for s in d.files
1159
+ if s.rel.suffix == ".py"
1160
+ for n, line in _imports(_parse(s.path, s.rel), module_level=True)
1161
+ if n not in allowed
1162
+ }
1163
+ )
1164
+ if missing:
1165
+ raise ValidationError(
1166
+ f"--vendor {d.name}: it imports {', '.join(missing)}, which the build does not "
1167
+ "provide; vendor those distributions too (--vendor NAME)"
1168
+ )
1169
+
1170
+
1171
+ # ------------------------------------------------------------- neu (bundle)
1172
+ @dataclass
1173
+ class _NodeTools:
1174
+ npm: str
1175
+ npx: str
1176
+ node: str | None
1177
+
1178
+
1179
+ @dataclass
1180
+ class _VerifiedNeu:
1181
+ tarball: Path
1182
+ integrity: str
1183
+ npm_version: str
1184
+ node_version: str
1185
+
1186
+
1187
+ def _require_node_tools() -> _NodeTools:
1188
+ npm, npx = shutil.which("npm"), shutil.which("npx")
1189
+ if npm is None or npx is None:
1190
+ raise UnsupportedError(
1191
+ "--bundle needs Node (npm and npx) at build time to run the official neu tool"
1192
+ )
1193
+ return _NodeTools(npm, npx, shutil.which("node"))
1194
+
1195
+
1196
+ def _npm_env() -> dict[str, str]:
1197
+ return dict(
1198
+ os.environ,
1199
+ npm_config_update_notifier="false",
1200
+ npm_config_fund="false",
1201
+ npm_config_audit="false",
1202
+ )
1203
+
1204
+
1205
+ def _tool_version(program: str | None) -> str:
1206
+ if program is None:
1207
+ return "unknown"
1208
+ try:
1209
+ r = subprocess.run(
1210
+ [program, "--version"],
1211
+ capture_output=True,
1212
+ encoding="utf-8",
1213
+ errors="replace",
1214
+ timeout=60,
1215
+ env=_npm_env(),
1216
+ )
1217
+ except (OSError, subprocess.TimeoutExpired):
1218
+ return "unknown"
1219
+ return r.stdout.strip() or "unknown"
1220
+
1221
+
1222
+ def _sri_sha512(path: Path) -> str:
1223
+ h = hashlib.sha512()
1224
+ with path.open("rb") as f:
1225
+ for chunk in iter(lambda: f.read(1 << 20), b""):
1226
+ h.update(chunk)
1227
+ return "sha512-" + base64.b64encode(h.digest()).decode()
1228
+
1229
+
1230
+ def _fetch_verified_neu(tools: _NodeTools, where: Path, offline: bool) -> _VerifiedNeu:
1231
+ """Fetch the pinned neu package tarball with ``npm pack`` (from the npm
1232
+ cache when ``offline``) and check its SHA-512 against the integrity in
1233
+ the lock before anything of it runs. neu then runs from that verified
1234
+ file, so what was checked is what is installed. Its own dependencies are
1235
+ resolved by npm from version ranges (registry integrity, not pinned)."""
1236
+ neu = LOCK["build_tools"]["neu"]
1237
+ spec = f"{neu['npm_package']}@{neu['version']}"
1238
+ cmd = [tools.npm, "pack", spec, "--json", "--pack-destination", str(where)]
1239
+ if offline:
1240
+ cmd.append("--offline")
1241
+ r = subprocess.run(
1242
+ cmd,
1243
+ cwd=where,
1244
+ capture_output=True,
1245
+ encoding="utf-8",
1246
+ errors="replace",
1247
+ env=_npm_env(),
1248
+ timeout=600,
1249
+ )
1250
+ if r.returncode != 0:
1251
+ tail = (r.stdout + r.stderr)[-600:]
1252
+ raise ValidationError(f"npm pack {spec} failed (exit {r.returncode}): {tail}")
1253
+ tarballs = [p for p in where.iterdir() if p.suffix == ".tgz"]
1254
+ if len(tarballs) != 1 or _is_link(os.lstat(tarballs[0]), tarballs[0]):
1255
+ raise ValidationError(f"npm pack {spec} did not produce exactly one package tarball")
1256
+ actual = _sri_sha512(tarballs[0])
1257
+ if not hmac.compare_digest(actual, str(neu["integrity"])):
1258
+ raise RuntimeIntegrityError(
1259
+ f"{spec}: package integrity {actual} does not match the lock "
1260
+ f"({neu['integrity']}, contracts/upstream-lock.json); refusing to run it"
1261
+ )
1262
+ return _VerifiedNeu(tarballs[0], actual, _tool_version(tools.npm), _tool_version(tools.node))
1263
+
1264
+
1265
+ def build(
1266
+ project: Path,
1267
+ *,
1268
+ entry: str = "app.py",
1269
+ out: Path | None = None,
1270
+ frontend_dir: str = "frontend",
1271
+ frontend_cmd: Sequence[str] | None = None,
1272
+ bundle: bool = False,
1273
+ offline: bool = False,
1274
+ runtime_path: Path | None = None,
1275
+ vendor: Sequence[str] = (),
1276
+ extra_modules: Iterable[str] = (),
1277
+ extend: Callable[[Path, dict[str, Any]], None] | None = None,
1278
+ out_name: str | None = None,
1279
+ ) -> BuildResult:
1280
+ """Stage a portable application directory (no installer, not a single file).
1281
+
1282
+ Layout: ``runtime/`` (pinned binary + licence), ``app/`` (entry, Python
1283
+ sources, config, frontend or resources.neu), ``vendor/`` (neutralino,
1284
+ websockets and each ``vendor`` distribution), ``boot.py``, fixed
1285
+ launchers, ``licenses/``, ``manifest.json`` and ``checksums.txt``. Needs
1286
+ the target machine's Python 3.11+; needs no Node and no network at run time.
1287
+
1288
+ The app's imports are checked statically (``_check_app_imports``): an
1289
+ import the build cannot provide fails the build instead of the app on the
1290
+ target machine. ``vendor`` names installed pure-Python distributions to
1291
+ ship (no resolver: their dependencies must be named too).
1292
+
1293
+ UI apps: the vendored ``neutralino`` carries the prebuilt renderer
1294
+ (``_data/renderer``), checked against its manifest digests while staging;
1295
+ the app's own CSS/JS/asset files are project files and ship in ``app/``.
1296
+ A valid ``app.toml`` (if present) is recorded in the manifest.
1297
+
1298
+ ``extra_modules``, ``extend`` and ``out_name`` serve ``--mode managed``:
1299
+ import names its wheelhouse provides, a hook that adds files and manifest
1300
+ keys before the manifest and checksums are written, and the default
1301
+ output folder name.
1302
+
1303
+ Every precondition (pinned runtime, build tools, neu integrity, output
1304
+ location, source safety, imports) is checked before anything is written.
1305
+ The build is staged in a temporary sibling of ``out`` and swapped into
1306
+ place only when complete, so a failed build keeps the previous one and
1307
+ leaves no half-built directory.
1308
+ """
1309
+ project = project.resolve()
1310
+ try:
1311
+ home: Path | None = Path.home().resolve()
1312
+ except RuntimeError: # no home directory known
1313
+ home = None
1314
+ if project == Path(project.anchor) or project == home:
1315
+ raise ValidationError(
1316
+ f"refusing to build {project}: point --project at the application folder, "
1317
+ "not the home directory or filesystem root"
1318
+ )
1319
+ app_cfg = _read_app_toml(project)
1320
+ app_meta = (
1321
+ None
1322
+ if app_cfg is None
1323
+ else {"id": app_cfg.id, "name": app_cfg.name, "version": app_cfg.version,
1324
+ "entry": app_cfg.entry}
1325
+ ) # fmt: skip
1326
+ excludes: list[str] = list(app_cfg.package.get("exclude", ())) if app_cfg else []
1327
+ entry_rel = _relative_inside("--app", entry)
1328
+ fe_rel = _relative_inside("--frontend", frontend_dir)
1329
+ for what, rel in (("--app", entry_rel), ("--frontend", fe_rel)):
1330
+ if pattern := exclude_match(rel.as_posix(), excludes):
1331
+ raise ValidationError(
1332
+ f"{what} {rel} is excluded by the [package].exclude pattern {pattern!r} "
1333
+ "of app.toml; narrow the pattern"
1334
+ )
1335
+ entry_path = project.joinpath(*entry_rel.parts)
1336
+ if not entry_path.is_file():
1337
+ raise ValidationError(f"entry point {entry_path} not found")
1338
+ info = resolve_binary(runtime_path)
1339
+ member, expected = binary_spec(CORE_VERSION)
1340
+ if info.source != "cache" and info.sha256 != expected:
1341
+ raise RuntimeIntegrityError(f"{info.path} is not the pinned {member}")
1342
+ dists = [_inspect_distribution(name) for name in dict.fromkeys(vendor)]
1343
+ _check_vendored_imports(dists)
1344
+ tools = _require_node_tools() if bundle else None
1345
+ if frontend_cmd:
1346
+ _require_executable(frontend_cmd[0], project)
1347
+ slug = slugify(project.name)
1348
+ out = (out or project / "dist" / (out_name or slug)).resolve()
1349
+ fe_root = project.joinpath(*fe_rel.parts)
1350
+ sources_dirs = [fe_root.resolve()]
1351
+ if entry_path.parent != project:
1352
+ sources_dirs.append(entry_path.parent.resolve())
1353
+ if (
1354
+ out == project
1355
+ or out in project.parents
1356
+ or any(out == d or d in out.parents or out in d.parents for d in sources_dirs)
1357
+ ):
1358
+ raise ValidationError(f"refusing to build into {out}: it overlaps the project sources")
1359
+ if out.exists() and not _is_previous_build(out):
1360
+ raise ValidationError(
1361
+ f"{out} exists and is not a previous neutralino build; "
1362
+ "refusing to delete it (choose another --out)"
1363
+ )
1364
+ with tempfile.TemporaryDirectory(prefix="neutralino-neu-") as tmp:
1365
+ neu = _fetch_verified_neu(tools, Path(tmp), offline) if tools is not None else None
1366
+ if frontend_cmd:
1367
+ subprocess.run(list(frontend_cmd), cwd=project, check=True)
1368
+ sources, excluded = _collect_sources(project, fe_rel, skip=(out,), patterns=excludes)
1369
+ _check_entry(entry_rel, fe_rel, bundle, sources, excluded)
1370
+ frontend_files = [s for s in sources if _under(s.rel, fe_rel)] if bundle else []
1371
+ app_files = [s for s in sources if not (bundle and _under(s.rel, fe_rel))]
1372
+ _check_app_imports(
1373
+ entry_rel, app_files, [*(m for d in dists for m in d.modules), *extra_modules]
1374
+ )
1375
+ out.parent.mkdir(parents=True, exist_ok=True)
1376
+ stage = Path(tempfile.mkdtemp(prefix=f".{out.name}.building-", dir=out.parent))
1377
+ try:
1378
+ files, manifest = _stage_build(
1379
+ stage,
1380
+ project,
1381
+ entry=entry_rel,
1382
+ fe_rel=fe_rel,
1383
+ app_files=app_files,
1384
+ frontend_files=frontend_files,
1385
+ excluded=excluded,
1386
+ dists=dists,
1387
+ runtime_bin=info.path,
1388
+ member=member,
1389
+ expected=expected,
1390
+ slug=slug,
1391
+ offline=offline,
1392
+ tools=tools,
1393
+ neu=neu,
1394
+ app_meta=app_meta,
1395
+ extend=extend,
1396
+ )
1397
+ _swap_into_place(stage, out)
1398
+ except BaseException:
1399
+ shutil.rmtree(stage, ignore_errors=True)
1400
+ raise
1401
+ return BuildResult(out, files, manifest)
1402
+
1403
+
1404
+ def _require_executable(program: str, cwd: Path) -> None:
1405
+ """Fail early (environment error) when the frontend build command is missing."""
1406
+ # A relative path with a separator runs relative to ``cwd`` (POSIX Popen).
1407
+ found = shutil.which(str(cwd / program) if os.sep in program else program)
1408
+ if found is None:
1409
+ raise UnsupportedError(f"--frontend-cmd: {program!r} not found or not executable")
1410
+
1411
+
1412
+ def _swap_into_place(stage: Path, out: Path) -> None:
1413
+ """Replace ``out`` (absent or a previous build) by the complete ``stage``."""
1414
+ if not out.exists():
1415
+ stage.rename(out)
1416
+ return
1417
+ old = Path(tempfile.mkdtemp(prefix=f".{out.name}.previous-", dir=out.parent))
1418
+ out.rename(old / out.name)
1419
+ try:
1420
+ stage.rename(out)
1421
+ except BaseException:
1422
+ (old / out.name).rename(out) # put the previous build back
1423
+ old.rmdir()
1424
+ raise
1425
+ shutil.rmtree(old, ignore_errors=True)
1426
+
1427
+
1428
+ def _stage_build(
1429
+ out: Path,
1430
+ project: Path,
1431
+ *,
1432
+ entry: PurePosixPath,
1433
+ fe_rel: PurePosixPath,
1434
+ app_files: Sequence[_Source],
1435
+ frontend_files: Sequence[_Source],
1436
+ excluded: Sequence[dict[str, str]],
1437
+ dists: Sequence[_Distribution],
1438
+ runtime_bin: Path,
1439
+ member: str,
1440
+ expected: str,
1441
+ slug: str,
1442
+ offline: bool,
1443
+ tools: _NodeTools | None,
1444
+ neu: _VerifiedNeu | None,
1445
+ app_meta: dict[str, str] | None = None,
1446
+ extend: Callable[[Path, dict[str, Any]], None] | None = None,
1447
+ ) -> tuple[int, dict[str, Any]]:
1448
+ """Write a complete build into the empty directory ``out``."""
1449
+ (out / "runtime").mkdir(parents=True)
1450
+ shutil.copy2(runtime_bin, out / "runtime" / member)
1451
+ (out / "runtime" / member).chmod(0o755)
1452
+ verify_binary(out / "runtime" / member, expected) # the copy is the pinned binary (A19)
1453
+ out.chmod(0o755) # mkdtemp made it 0700
1454
+ licenses = out / "licenses"
1455
+ licenses.mkdir()
1456
+ for lic in ("LICENSE.neutralinojs", "LICENSE.neutralino-js-client"):
1457
+ (licenses / lic).write_text(
1458
+ _PKG.joinpath(f"_data/{lic}").read_text(encoding="utf-8"), encoding="utf-8"
1459
+ )
1460
+ from importlib import metadata
1461
+
1462
+ inventory: list[dict[str, Any]] = []
1463
+ for dist_name, version, modules in [
1464
+ *((n, metadata.version(n), mods) for n, mods in _SDK_DISTRIBUTIONS.items()),
1465
+ *((d.name, d.version, d.modules) for d in dists),
1466
+ ]:
1467
+ written: list[str] = []
1468
+ for name, text in sorted(_license_files(dist_name).items()):
1469
+ (licenses / f"{dist_name}.{name}").write_text(text, encoding="utf-8")
1470
+ written.append(f"licenses/{dist_name}.{name}")
1471
+ inventory.append(
1472
+ {
1473
+ "name": dist_name,
1474
+ "version": version,
1475
+ "license": _license_of(dist_name),
1476
+ "modules": modules,
1477
+ "license_files": written,
1478
+ }
1479
+ )
1480
+ app_dir = out / "app"
1481
+ app_dir.mkdir()
1482
+ for src in app_files:
1483
+ _copy_source(src, app_dir.joinpath(*src.rel.parts))
1484
+ if tools is not None and neu is not None:
1485
+ _bundle_with_neu(project, frontend_files, app_dir, offline, tools, neu)
1486
+ vendor = out / "vendor"
1487
+ vendor.mkdir()
1488
+ vendored = _vendor_packages(vendor)
1489
+ for d in dists:
1490
+ for src in d.files:
1491
+ _copy_source(src, vendor.joinpath(*src.rel.parts))
1492
+ vendored.extend(d.modules)
1493
+ ui_info = _verify_vendored_renderer(vendor / "neutralino")
1494
+ (out / "boot.py").write_text(_BOOT_PY, encoding="utf-8")
1495
+ (out / "run.sh").write_text(_LAUNCHER_SH, encoding="utf-8")
1496
+ (out / "run.sh").chmod(0o755)
1497
+ (out / "run.bat").write_text(_LAUNCHER_BAT, encoding="utf-8")
1498
+ manifest: dict[str, Any] = {
1499
+ "name": slug,
1500
+ "sdk": _sdk_version(),
1501
+ "runtime": {"version": CORE_VERSION, "binary": member, "sha256": expected},
1502
+ "client": CLIENT_VERSION,
1503
+ "platform": platform_key(),
1504
+ "entry": entry.as_posix(),
1505
+ "bundle": "resources.neu" if neu is not None else "directory",
1506
+ "vendored": vendored,
1507
+ "distributions": inventory,
1508
+ "excluded": list(excluded),
1509
+ "requires": "Python >= 3.11 on the target machine; no Node, no network",
1510
+ "built_at": _built_at(),
1511
+ "mode": "portable",
1512
+ "app": app_meta,
1513
+ "ui": ui_info,
1514
+ }
1515
+ if neu is not None:
1516
+ lock_neu = LOCK["build_tools"]["neu"]
1517
+ manifest["build_tools"] = {
1518
+ "neu": {
1519
+ "package": lock_neu["npm_package"],
1520
+ "version": lock_neu["version"],
1521
+ "integrity": neu.integrity,
1522
+ "verified_against": "contracts/upstream-lock.json",
1523
+ },
1524
+ "npm": neu.npm_version,
1525
+ "node": neu.node_version,
1526
+ }
1527
+ if extend is not None:
1528
+ extend(out, manifest)
1529
+ (out / "manifest.json").write_text(
1530
+ json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
1531
+ )
1532
+ files = sorted(p for p in out.rglob("*") if p.is_file() and p.name != "checksums.txt")
1533
+ checksums = {p.relative_to(out).as_posix(): sha256_file(p) for p in files}
1534
+ (out / "checksums.txt").write_text(
1535
+ "".join(f"{d} {n}\n" for n, d in sorted(checksums.items())), encoding="utf-8"
1536
+ )
1537
+ return len(files) + 1, manifest
1538
+
1539
+
1540
+ def _read_app_toml(project: Path) -> _AppToml | None:
1541
+ """``app.toml`` of the project, validated (a broken one fails the build)."""
1542
+ path = project / "app.toml"
1543
+ st = _lstat(path)
1544
+ if st is None:
1545
+ return None
1546
+ if _is_link(st, path) or not stat.S_ISREG(st.st_mode):
1547
+ raise ValidationError(f"{path} must be a regular file (not a link)")
1548
+ from ._scaffold import load_app_toml
1549
+
1550
+ return load_app_toml(path)
1551
+
1552
+
1553
+ def _verify_vendored_renderer(package: Path) -> dict[str, Any] | None:
1554
+ """Check the vendored UI renderer against its manifest (None if the
1555
+ package has no renderer: a build of a non-UI SDK checkout)."""
1556
+ base = package / "_data" / "renderer"
1557
+ if not (base / "manifest.json").is_file():
1558
+ log.warning("no UI renderer in the vendored neutralino package (%s)", base)
1559
+ return None
1560
+ mf, bad = _renderer_problems(base)
1561
+ if bad:
1562
+ raise RuntimeIntegrityError(
1563
+ f"UI renderer assets missing or modified ({', '.join(bad[:5])}); "
1564
+ "reinstall neutralino-python"
1565
+ )
1566
+ return {
1567
+ "renderer": "vendor/neutralino/_data/renderer",
1568
+ "build": mf.get("build"),
1569
+ "source_digest": mf.get("source_digest"),
1570
+ "protocol": mf.get("protocol"),
1571
+ "files": len(cast("dict[str, Any]", mf.get("files") or {})),
1572
+ "verified": "sha256 of every file matches the renderer manifest.json",
1573
+ }
1574
+
1575
+
1576
+ def _is_previous_build(out: Path) -> bool:
1577
+ """True only for a directory this tool produced (manifest keys + checksums)."""
1578
+ try:
1579
+ manifest: Any = json.loads((out / "manifest.json").read_text(encoding="utf-8"))
1580
+ except (OSError, ValueError):
1581
+ return False
1582
+ keys: set[str] = set(cast("dict[str, Any]", manifest)) if isinstance(manifest, dict) else set()
1583
+ return (
1584
+ {"sdk", "runtime", "entry", "vendored"} <= keys
1585
+ and (out / "checksums.txt").is_file()
1586
+ and (out / "runtime").is_dir()
1587
+ )
1588
+
1589
+
1590
+ def _bundle_with_neu(
1591
+ project: Path,
1592
+ frontend_files: Sequence[_Source],
1593
+ app_dir: Path,
1594
+ offline: bool,
1595
+ tools: _NodeTools,
1596
+ neu: _VerifiedNeu,
1597
+ ) -> None:
1598
+ """Pack resources.neu with the verified official neu (build-time Node only).
1599
+
1600
+ neu sees only a private staging folder holding the frontend files the
1601
+ directory build would ship (same rules) and the SDK-compatible config."""
1602
+ staging = app_dir.parent / ".neu-staging"
1603
+ for src in frontend_files:
1604
+ _copy_source(src, staging.joinpath(*src.rel.parts))
1605
+ # In bundle mode the runtime reads this packed config, not the SDK's
1606
+ # per-instance one: pack an SDK-compatible copy (ADR-015).
1607
+ base = config_mod.load_config(project / config_mod.CONFIG_FILE)
1608
+ if "nativeAllowList" not in base and "nativeBlockList" not in base:
1609
+ log.warning(
1610
+ "the packed config gets the SDK's least-privilege nativeAllowList (ADR-017): add the "
1611
+ "routes your app uses to nativeAllowList in neutralino.config.json"
1612
+ )
1613
+ packed = config_mod.bundle_config(
1614
+ base, default_application_id=config_mod.derive_application_id(project)
1615
+ )
1616
+ staging.mkdir(exist_ok=True)
1617
+ (staging / config_mod.CONFIG_FILE).write_text(
1618
+ json.dumps(packed, indent=2) + "\n", encoding="utf-8"
1619
+ )
1620
+ # --ignore-scripts: no install script of neu's dependency tree runs.
1621
+ cmd = [tools.npx, *(["--offline"] if offline else []), "--yes", "--ignore-scripts"]
1622
+ cmd += ["--package", str(neu.tarball), "--", "neu", "build"]
1623
+ try:
1624
+ subprocess.run(
1625
+ cmd,
1626
+ cwd=staging,
1627
+ check=True,
1628
+ capture_output=True,
1629
+ encoding="utf-8",
1630
+ errors="replace",
1631
+ env=_npm_env(),
1632
+ )
1633
+ except subprocess.CalledProcessError as e:
1634
+ tail = ((e.stdout or "") + (e.stderr or ""))[-600:]
1635
+ raise ValidationError(f"neu build failed (exit {e.returncode}): {tail}") from None
1636
+ produced = list((staging / "dist").rglob("resources.neu"))
1637
+ if not produced:
1638
+ raise ValidationError("neu did not produce resources.neu")
1639
+ # What neu packed is what the runtime will load: check it like a launch does.
1640
+ config_mod.check_bundle_config(read_bundle_config(produced[0]), config_mod.BUNDLE_EXTENSION_ID)
1641
+ shutil.copy2(produced[0], app_dir / "resources.neu")
1642
+ shutil.rmtree(staging)
1643
+
1644
+
1645
+ # ------------------------------------------------------------------ run app
1646
+ def _spawn_app(
1647
+ argv: Sequence[str], cwd: Path, env: Mapping[str, str] | None
1648
+ ) -> subprocess.Popen[bytes]:
1649
+ """Start the app in its own process group, so a terminal Ctrl-C reaches only
1650
+ this tool, which then interrupts the app exactly once."""
1651
+ windows = is_windows()
1652
+ return subprocess.Popen(
1653
+ list(argv),
1654
+ cwd=cwd,
1655
+ env=env,
1656
+ start_new_session=not windows,
1657
+ creationflags=getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0x200) if windows else 0,
1658
+ )
1659
+
1660
+
1661
+ def _interrupt(proc: subprocess.Popen[bytes]) -> None:
1662
+ """Ask the app to shut down as on Ctrl-C (KeyboardInterrupt in Python)."""
1663
+ with contextlib.suppress(OSError):
1664
+ if is_windows():
1665
+ proc.send_signal(signal.CTRL_BREAK_EVENT) # type: ignore[attr-defined]
1666
+ else:
1667
+ proc.send_signal(signal.SIGINT)
1668
+
1669
+
1670
+ def _terminate(proc: subprocess.Popen[bytes]) -> None:
1671
+ with contextlib.suppress(OSError):
1672
+ proc.terminate()
1673
+
1674
+
1675
+ def _kill(proc: subprocess.Popen[bytes]) -> None:
1676
+ with contextlib.suppress(OSError):
1677
+ proc.kill()
1678
+
1679
+
1680
+ @contextlib.contextmanager
1681
+ def _termination_as_interrupt() -> Generator[None]:
1682
+ """While active, SIGTERM/SIGHUP to this tool raise KeyboardInterrupt, so the
1683
+ app child is shut down instead of being left running."""
1684
+ if is_windows() or threading.current_thread() is not threading.main_thread():
1685
+ yield
1686
+ return
1687
+
1688
+ def handler(signum: int, frame: Any) -> None:
1689
+ raise KeyboardInterrupt
1690
+
1691
+ previous: dict[int, Any] = {}
1692
+ for name in ("SIGTERM", "SIGHUP"):
1693
+ signum = getattr(signal, name)
1694
+ previous[signum] = signal.signal(signum, handler)
1695
+ try:
1696
+ yield
1697
+ finally:
1698
+ for signum, prev in previous.items():
1699
+ signal.signal(signum, prev)
1700
+
1701
+
1702
+ def run_app(argv: Sequence[str], cwd: Path, env: dict[str, str] | None = None) -> int:
1703
+ """``neutralino run``: run the app and wait; Ctrl-C (or SIGTERM) interrupts
1704
+ it once and waits for its own clean shutdown, a second one terminates it,
1705
+ a third kills it. Returns the app's exit status (128+N for signal N)."""
1706
+ proc = _spawn_app(argv, cwd, env)
1707
+ interrupts = 0
1708
+ with _termination_as_interrupt():
1709
+ while True:
1710
+ try:
1711
+ code = proc.wait()
1712
+ break
1713
+ except KeyboardInterrupt:
1714
+ interrupts += 1
1715
+ if interrupts == 1:
1716
+ _interrupt(proc)
1717
+ elif interrupts == 2:
1718
+ with contextlib.suppress(OSError):
1719
+ proc.terminate()
1720
+ else:
1721
+ with contextlib.suppress(OSError):
1722
+ proc.kill()
1723
+ return code if code >= 0 else 128 - code
1724
+
1725
+
1726
+ # ---------------------------------------------------------------------- watch
1727
+ def snapshot(
1728
+ roots: Iterable[Path], exclude: set[str], *, keep: Path | None = None
1729
+ ) -> dict[str, tuple[int, int]]:
1730
+ """mtime/size snapshot of watched files (polling, no dependency).
1731
+
1732
+ ``exclude`` names are matched against path parts below each root, never
1733
+ against the root's own location. Below ``keep`` (the frontend directory)
1734
+ ``dist``/``build`` are watched, since that is where a compiled frontend lives.
1735
+ Excluded directories and virtual environments (any directory holding a
1736
+ ``pyvenv.cfg``) are pruned without being walked. Files and directories that
1737
+ vanish or cannot be read during the walk are skipped (next poll sees them).
1738
+ """
1739
+ keep_exclude = exclude - {"dist", "build"}
1740
+ state: dict[str, tuple[int, int]] = {}
1741
+
1742
+ def excluded(p: Path, root: Path) -> bool:
1743
+ if keep is not None and keep in p.parents:
1744
+ return bool(set(p.relative_to(keep).parts) & keep_exclude)
1745
+ return bool(set(p.relative_to(root).parts) & exclude)
1746
+
1747
+ def record(p: Path) -> None:
1748
+ try:
1749
+ st = p.stat()
1750
+ except OSError: # vanished or unreadable since it was listed
1751
+ return
1752
+ if stat.S_ISREG(st.st_mode):
1753
+ state[str(p)] = (st.st_mtime_ns, st.st_size)
1754
+
1755
+ for root in roots:
1756
+ if not root.is_dir():
1757
+ record(root)
1758
+ continue
1759
+ # os.walk skips directories whose scan fails (onerror=None).
1760
+ for dirpath, dirnames, filenames in os.walk(root):
1761
+ here = Path(dirpath)
1762
+ if here != root and "pyvenv.cfg" in filenames:
1763
+ dirnames[:] = [] # a virtualenv: never watched
1764
+ continue
1765
+ dirnames[:] = [
1766
+ d
1767
+ for d in dirnames
1768
+ # keep walking towards ``keep`` even through an excluded name
1769
+ if not excluded(here / d, root)
1770
+ or (keep is not None and (here / d == keep or here / d in keep.parents))
1771
+ ]
1772
+ for name in filenames:
1773
+ p = here / name
1774
+ if not excluded(p, root):
1775
+ record(p)
1776
+ return state
1777
+
1778
+
1779
+ def classify_changes(
1780
+ before: dict[str, tuple[int, int]], after: dict[str, tuple[int, int]], frontend: Path
1781
+ ) -> set[str]:
1782
+ """Return {"backend", "frontend", "config"} for what changed."""
1783
+ kinds: set[str] = set()
1784
+ for path in set(before) ^ set(after) | {p for p in before if before.get(p) != after.get(p)}:
1785
+ p = Path(path)
1786
+ if p.name == config_mod.CONFIG_FILE:
1787
+ kinds.add("config")
1788
+ elif frontend in p.parents:
1789
+ kinds.add("frontend")
1790
+ elif p.suffix == ".py":
1791
+ kinds.add("backend")
1792
+ return kinds
1793
+
1794
+
1795
+ class Watcher:
1796
+ """``neutralino run --watch``: restart the app process on backend/config
1797
+ changes, reload pages on frontend changes (SIGUSR1 -> neuDev_reloadApp on
1798
+ POSIX; restart elsewhere). Debounced; generated/cache dirs excluded."""
1799
+
1800
+ EXCLUDE = {
1801
+ "dist",
1802
+ ".venv",
1803
+ "venv",
1804
+ "node_modules",
1805
+ "__pycache__",
1806
+ ".git",
1807
+ ".pytest_cache",
1808
+ ".mypy_cache",
1809
+ ".ruff_cache",
1810
+ "build",
1811
+ }
1812
+
1813
+ def __init__(
1814
+ self,
1815
+ project: Path,
1816
+ entry: str,
1817
+ *,
1818
+ frontend: str = "frontend",
1819
+ debounce: float = 0.25,
1820
+ interval: float = 0.2,
1821
+ python: str = sys.executable,
1822
+ env: dict[str, str] | None = None,
1823
+ log: Callable[[str], None] = print,
1824
+ ) -> None:
1825
+ self.project = project.resolve()
1826
+ self.entry = entry
1827
+ self.frontend = (self.project / frontend).resolve()
1828
+ self.debounce = debounce
1829
+ self.interval = interval
1830
+ self.python = python
1831
+ self.env = dict(env or os.environ)
1832
+ self.env["NEUTRALINO_DEV_RELOAD"] = "1"
1833
+ self.log = log
1834
+ self.proc: subprocess.Popen[bytes] | None = None
1835
+ self.restarts = 0
1836
+ self.reloads = 0
1837
+ self._ready_dir: Path | None = None
1838
+ self._pending_reload = False
1839
+ self._exit_reported = False
1840
+ self._stop_interrupted = False
1841
+
1842
+ def start_app(self) -> None:
1843
+ if self._ready_dir is None:
1844
+ self._ready_dir = Path(tempfile.mkdtemp(prefix="neutralino-watch-"))
1845
+ ready = self._ready_dir / "reload-ready"
1846
+ with contextlib.suppress(FileNotFoundError):
1847
+ ready.unlink()
1848
+ self.env[DEV_RELOAD_READY_ENV] = str(ready)
1849
+ self._pending_reload = False
1850
+ self._exit_reported = False
1851
+ self.proc = _spawn_app([self.python, self.entry], self.project, self.env)
1852
+
1853
+ def reload_ready(self) -> bool:
1854
+ """True once the running app has installed its SIGUSR1 reload handler.
1855
+
1856
+ Before that, SIGUSR1 would kill it (default action), so reloads wait.
1857
+ """
1858
+ proc = self.proc
1859
+ if proc is None or proc.poll() is not None or self._ready_dir is None:
1860
+ return False
1861
+ try:
1862
+ return (self._ready_dir / "reload-ready").read_text(encoding="utf-8").strip() == str(
1863
+ proc.pid
1864
+ )
1865
+ except OSError:
1866
+ return False
1867
+
1868
+ def stop_app(self, grace: float = 10.0) -> int | None:
1869
+ try:
1870
+ return self._stop_proc(grace)
1871
+ finally:
1872
+ if self._ready_dir is not None:
1873
+ shutil.rmtree(self._ready_dir, ignore_errors=True)
1874
+ self._ready_dir = None
1875
+
1876
+ def _stop_proc(self, grace: float) -> int | None:
1877
+ """Interrupt the app, then terminate, then kill it, each after a bounded
1878
+ wait. A Ctrl-C (or SIGTERM, while translated) during a wait moves on to
1879
+ the next step at once, as in ``run_app``; it is remembered in
1880
+ ``_stop_interrupted`` so the caller can stop too."""
1881
+ proc = self.proc
1882
+ if proc is None:
1883
+ return None
1884
+ for step in (_interrupt, _terminate, _kill):
1885
+ try:
1886
+ if proc.poll() is not None:
1887
+ return proc.returncode
1888
+ step(proc)
1889
+ return proc.wait(grace)
1890
+ except subprocess.TimeoutExpired:
1891
+ continue
1892
+ except KeyboardInterrupt:
1893
+ self._stop_interrupted = True
1894
+ continue
1895
+ return proc.poll()
1896
+
1897
+ def reload_frontend(self) -> None:
1898
+ if self.proc is None or self.proc.poll() is not None:
1899
+ return
1900
+ if is_windows():
1901
+ self.restart()
1902
+ return
1903
+ if not self.reload_ready():
1904
+ if not self._pending_reload:
1905
+ self.log("app not ready for reloads yet; reload deferred")
1906
+ self._pending_reload = True
1907
+ return
1908
+ self._pending_reload = False
1909
+ self.proc.send_signal(signal.SIGUSR1)
1910
+ self.reloads += 1
1911
+
1912
+ def restart(self) -> None:
1913
+ self._stop_interrupted = False
1914
+ self.stop_app()
1915
+ if self._stop_interrupted: # Ctrl-C while the old app was stopping
1916
+ raise KeyboardInterrupt
1917
+ self.start_app()
1918
+ self.restarts += 1
1919
+
1920
+ def _poll(self) -> None:
1921
+ """Per-tick housekeeping: deliver a deferred reload, report an exit once."""
1922
+ if self._pending_reload and self.reload_ready():
1923
+ self.reload_frontend()
1924
+ proc = self.proc
1925
+ if proc is not None and proc.poll() is not None and not self._exit_reported:
1926
+ self._exit_reported = True
1927
+ self.log(f"app exited with {proc.returncode}; waiting for changes")
1928
+
1929
+ def _settle(
1930
+ self, roots: list[Path], current: dict[str, tuple[int, int]]
1931
+ ) -> dict[str, tuple[int, int]]:
1932
+ """Wait for a quiet period of ``debounce`` (bounded to 20 periods)."""
1933
+ for _ in range(20):
1934
+ time.sleep(self.debounce)
1935
+ later = snapshot(roots, self.EXCLUDE, keep=self.frontend)
1936
+ if later == current:
1937
+ return later
1938
+ current = later
1939
+ return current
1940
+
1941
+ def run(self, *, max_seconds: float | None = None) -> int:
1942
+ roots = [self.project]
1943
+ state = snapshot(roots, self.EXCLUDE, keep=self.frontend)
1944
+ started = time.monotonic()
1945
+ # Signals stay translated until the app is gone: a second Ctrl-C or a
1946
+ # SIGTERM during the final stop escalates it instead of killing this tool.
1947
+ with _termination_as_interrupt():
1948
+ try:
1949
+ self.start_app()
1950
+ while max_seconds is None or time.monotonic() - started < max_seconds:
1951
+ time.sleep(self.interval)
1952
+ self._poll()
1953
+ new = snapshot(roots, self.EXCLUDE, keep=self.frontend)
1954
+ if new == state:
1955
+ continue
1956
+ new = self._settle(roots, new) # let editors finish writing
1957
+ kinds = classify_changes(state, new, self.frontend)
1958
+ state = new
1959
+ if kinds & {"backend", "config"}:
1960
+ self.log(f"{', '.join(sorted(kinds))} changed: restarting")
1961
+ self.restart()
1962
+ elif "frontend" in kinds:
1963
+ self.log("frontend changed: reloading")
1964
+ self.reload_frontend()
1965
+ except KeyboardInterrupt:
1966
+ pass
1967
+ finally:
1968
+ self.stop_app()
1969
+ return 0
1970
+
1971
+
1972
+ def file_digest(data: bytes) -> str:
1973
+ return hashlib.sha256(data).hexdigest()