codecin 7.22.10__py3-none-win_amd64.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 (202) hide show
  1. codecin/__init__.py +27 -0
  2. codecin/aot.py +1057 -0
  3. codecin/assembler.py +619 -0
  4. codecin/cbackend.py +3024 -0
  5. codecin/cin.py +4265 -0
  6. codecin/cli.py +670 -0
  7. codecin/codecin_native.dll +0 -0
  8. codecin/config.py +50 -0
  9. codecin/console.py +183 -0
  10. codecin/cpu.py +312 -0
  11. codecin/crom.py +449 -0
  12. codecin/cvm.py +708 -0
  13. codecin/disasm.py +149 -0
  14. codecin/environment.py +176 -0
  15. codecin/errors.py +54 -0
  16. codecin/isa.py +560 -0
  17. codecin/lib/array/pic.toml +10 -0
  18. codecin/lib/array/src/array.cin +103 -0
  19. codecin/lib/bigint/pic.toml +10 -0
  20. codecin/lib/bigint/src/bigint.cin +589 -0
  21. codecin/lib/bits/pic.toml +10 -0
  22. codecin/lib/bits/src/bits.cin +143 -0
  23. codecin/lib/bitset/pic.toml +10 -0
  24. codecin/lib/bitset/src/bitset.cin +374 -0
  25. codecin/lib/codec/pic.toml +10 -0
  26. codecin/lib/codec/src/codec.cin +563 -0
  27. codecin/lib/combin/pic.toml +10 -0
  28. codecin/lib/combin/src/combin.cin +414 -0
  29. codecin/lib/conv/pic.toml +10 -0
  30. codecin/lib/conv/src/conv.cin +151 -0
  31. codecin/lib/cppstd/pic.toml +10 -0
  32. codecin/lib/cppstd/src/cppstd.cin +418 -0
  33. codecin/lib/cstd/pic.toml +10 -0
  34. codecin/lib/cstd/src/cstd.cin +424 -0
  35. codecin/lib/csv/pic.toml +10 -0
  36. codecin/lib/csv/src/csv.cin +405 -0
  37. codecin/lib/dp/pic.toml +10 -0
  38. codecin/lib/dp/src/dp.cin +325 -0
  39. codecin/lib/ffi/pic.toml +10 -0
  40. codecin/lib/ffi/src/ffi.cin +163 -0
  41. codecin/lib/fmt/pic.toml +10 -0
  42. codecin/lib/fmt/src/fmt.cin +325 -0
  43. codecin/lib/frac/pic.toml +10 -0
  44. codecin/lib/frac/src/frac.cin +252 -0
  45. codecin/lib/gostd/pic.toml +10 -0
  46. codecin/lib/gostd/src/gostd.cin +415 -0
  47. codecin/lib/graph/pic.toml +10 -0
  48. codecin/lib/graph/src/graph.cin +367 -0
  49. codecin/lib/gui/pic.toml +10 -0
  50. codecin/lib/gui/src/gui.cin +218 -0
  51. codecin/lib/hash/pic.toml +10 -0
  52. codecin/lib/hash/src/hash.cin +67 -0
  53. codecin/lib/heap/pic.toml +10 -0
  54. codecin/lib/heap/src/heap.cin +199 -0
  55. codecin/lib/io/pic.toml +10 -0
  56. codecin/lib/io/src/io.cin +141 -0
  57. codecin/lib/json/pic.toml +10 -0
  58. codecin/lib/json/src/json.cin +84 -0
  59. codecin/lib/key/pic.toml +10 -0
  60. codecin/lib/key/src/key.cin +78 -0
  61. codecin/lib/math/pic.toml +10 -0
  62. codecin/lib/math/src/math.cin +50 -0
  63. codecin/lib/matrix/pic.toml +10 -0
  64. codecin/lib/matrix/src/matrix.cin +155 -0
  65. codecin/lib/net/pic.toml +10 -0
  66. codecin/lib/net/src/net.cin +171 -0
  67. codecin/lib/path/pic.toml +10 -0
  68. codecin/lib/path/src/path.cin +372 -0
  69. codecin/lib/queue/pic.toml +10 -0
  70. codecin/lib/queue/src/queue.cin +112 -0
  71. codecin/lib/rand/pic.toml +10 -0
  72. codecin/lib/rand/src/rand.cin +46 -0
  73. codecin/lib/set/pic.toml +10 -0
  74. codecin/lib/set/src/set.cin +269 -0
  75. codecin/lib/sort/pic.toml +10 -0
  76. codecin/lib/sort/src/sort.cin +93 -0
  77. codecin/lib/stat/pic.toml +10 -0
  78. codecin/lib/stat/src/stat.cin +138 -0
  79. codecin/lib/str/pic.toml +10 -0
  80. codecin/lib/str/src/str.cin +54 -0
  81. codecin/lib/termux/pic.toml +10 -0
  82. codecin/lib/termux/src/termux.cin +118 -0
  83. codecin/lib/test/pic.toml +10 -0
  84. codecin/lib/test/src/test.cin +74 -0
  85. codecin/lib/text/pic.toml +10 -0
  86. codecin/lib/text/src/text.cin +323 -0
  87. codecin/lib/time/pic.toml +10 -0
  88. codecin/lib/time/src/time.cin +54 -0
  89. codecin/lib/token/pic.toml +10 -0
  90. codecin/lib/token/src/token.cin +183 -0
  91. codecin/lib/tree/pic.toml +10 -0
  92. codecin/lib/tree/src/tree.cin +256 -0
  93. codecin/lib/unionfind/pic.toml +10 -0
  94. codecin/lib/unionfind/src/unionfind.cin +115 -0
  95. codecin/lib/validate/pic.toml +10 -0
  96. codecin/lib/validate/src/validate.cin +148 -0
  97. codecin/lib/vec/pic.toml +10 -0
  98. codecin/lib/vec/src/vec.cin +88 -0
  99. codecin/logger.py +145 -0
  100. codecin/memory.py +306 -0
  101. codecin/mkn.py +916 -0
  102. codecin/native/aot/aot.go +114 -0
  103. codecin/native/aot/stub_main.go.txt +23 -0
  104. codecin/native/build.ps1 +33 -0
  105. codecin/native/build.sh +48 -0
  106. codecin/native/cmd/cincc/main.go +66 -0
  107. codecin/native/compiler/codegen.go +2238 -0
  108. codecin/native/compiler/compile_test.go +1069 -0
  109. codecin/native/compiler/parser.go +1331 -0
  110. codecin/native/compiler/syscalls.go +166 -0
  111. codecin/native/compiler/tokenizer.go +394 -0
  112. codecin/native/compiler/types.go +217 -0
  113. codecin/native/engine/args.go +37 -0
  114. codecin/native/engine/audio.go +402 -0
  115. codecin/native/engine/audio_other.go +105 -0
  116. codecin/native/engine/audio_test.go +279 -0
  117. codecin/native/engine/audio_windows.go +190 -0
  118. codecin/native/engine/canvas.go +271 -0
  119. codecin/native/engine/console_other.go +9 -0
  120. codecin/native/engine/console_windows.go +43 -0
  121. codecin/native/engine/crom.go +86 -0
  122. codecin/native/engine/encode.go +93 -0
  123. codecin/native/engine/engine_test.go +198 -0
  124. codecin/native/engine/ffi_nocgo.go +20 -0
  125. codecin/native/engine/ffi_registry.go +69 -0
  126. codecin/native/engine/ffi_unix.go +109 -0
  127. codecin/native/engine/ffi_windows.go +117 -0
  128. codecin/native/engine/gui.go +209 -0
  129. codecin/native/engine/gui_stub.go +13 -0
  130. codecin/native/engine/gui_test.go +148 -0
  131. codecin/native/engine/gui_windows.go +604 -0
  132. codecin/native/engine/gui_x11.go +723 -0
  133. codecin/native/engine/host_test.go +139 -0
  134. codecin/native/engine/hostcrypto.go +30 -0
  135. codecin/native/engine/hostdesktop.go +173 -0
  136. codecin/native/engine/hostnet.go +127 -0
  137. codecin/native/engine/isa_gen.go +689 -0
  138. codecin/native/engine/keyboard.go +432 -0
  139. codecin/native/engine/keyboard_other.go +94 -0
  140. codecin/native/engine/keyboard_stub.go +17 -0
  141. codecin/native/engine/keyboard_termios_darwin.go +9 -0
  142. codecin/native/engine/keyboard_termios_linux.go +9 -0
  143. codecin/native/engine/keyboard_test.go +246 -0
  144. codecin/native/engine/keyboard_windows.go +208 -0
  145. codecin/native/engine/keyboard_windows_test.go +123 -0
  146. codecin/native/engine/lineedit.go +262 -0
  147. codecin/native/engine/lineedit_test.go +105 -0
  148. codecin/native/engine/lineint_unix.go +17 -0
  149. codecin/native/engine/lineint_windows.go +19 -0
  150. codecin/native/engine/mem_other.go +37 -0
  151. codecin/native/engine/mem_windows.go +33 -0
  152. codecin/native/engine/native.go +640 -0
  153. codecin/native/engine/netsock.go +321 -0
  154. codecin/native/engine/ops_ext.go +515 -0
  155. codecin/native/engine/stdin.go +72 -0
  156. codecin/native/engine/stdin_other.go +9 -0
  157. codecin/native/engine/stdin_windows.go +60 -0
  158. codecin/native/engine/system.go +313 -0
  159. codecin/native/engine/termux.go +180 -0
  160. codecin/native/engine/version_gen.go +7 -0
  161. codecin/native/engine/vkb_darwin.go +62 -0
  162. codecin/native/engine/vkb_linux.go +95 -0
  163. codecin/native/engine/vkb_stub.go +11 -0
  164. codecin/native/engine/vm.go +1677 -0
  165. codecin/native/go.mod +3 -0
  166. codecin/native/ir/ir.go +48 -0
  167. codecin/native/main.go +448 -0
  168. codecin/native/mc/aarch64.go +165 -0
  169. codecin/native/mc/aarch64_test.go +30 -0
  170. codecin/native/mc/elf.go +88 -0
  171. codecin/native/mc/print_test.go +52 -0
  172. codecin/native/mc/x86_64.go +1262 -0
  173. codecin/native/mc/x86_64_test.go +102 -0
  174. codecin/native.py +432 -0
  175. codecin/native_codegen.py +987 -0
  176. codecin/nativegen.py +786 -0
  177. codecin/object.py +539 -0
  178. codecin/optimizer.py +236 -0
  179. codecin/packaging/__init__.py +46 -0
  180. codecin/packaging/archive.py +177 -0
  181. codecin/packaging/model.py +519 -0
  182. codecin/packaging/spec.py +193 -0
  183. codecin/packaging/store.py +372 -0
  184. codecin/packaging/toml.py +541 -0
  185. codecin/packaging/vcs.py +215 -0
  186. codecin/pic.py +1917 -0
  187. codecin/pic_api.py +374 -0
  188. codecin/pic_login.py +519 -0
  189. codecin/pic_registry.py +515 -0
  190. codecin/registers.py +130 -0
  191. codecin/sdgcc.py +493 -0
  192. codecin/stats.py +230 -0
  193. codecin/stdlib.py +138 -0
  194. codecin/toolchain.py +396 -0
  195. codecin/toolkit.py +26 -0
  196. codecin/version.py +260 -0
  197. codecin-7.22.10.dist-info/METADATA +1077 -0
  198. codecin-7.22.10.dist-info/RECORD +202 -0
  199. codecin-7.22.10.dist-info/WHEEL +5 -0
  200. codecin-7.22.10.dist-info/entry_points.txt +5 -0
  201. codecin-7.22.10.dist-info/licenses/LICENSE +7 -0
  202. codecin-7.22.10.dist-info/top_level.txt +1 -0
codecin/pic_api.py ADDED
@@ -0,0 +1,374 @@
1
+ """Cdifit 身份服务 API 客户端 (pic v6.2.0+)。
2
+
3
+ Cdifit (``https://www.cdifit.cn``) **只用于登录/Token 校验**; 包记录与
4
+ ``.cinpkg`` 制品由 ``package.codecin.org.cn`` 中央注册/分发服务器负责
5
+ (见 :mod:`codecin.pic_registry`)。本模块只负责:
6
+
7
+ * ``POST /api/v4/session/token`` 密码登录 (含 2FA);
8
+ * ``PUT /api/v4/session/token/refresh`` 刷新令牌;
9
+ * ``DELETE /api/v4/session/token`` 退出;
10
+ * ``GET /api/v4/session/oauth/userinfo`` 用户信息。
11
+
12
+ API 文档: https://docs.cdifit.com/zh/api/session
13
+ """
14
+
15
+ import contextlib
16
+ import json
17
+ import os
18
+ import tempfile
19
+ import time
20
+ import urllib.error
21
+ import urllib.request
22
+ from dataclasses import dataclass, field
23
+ from datetime import datetime, timezone
24
+ from typing import Any, Dict, Optional
25
+
26
+ DEFAULT_API_BASE = 'https://www.cdifit.cn'
27
+ API_PREFIX = '/api/v4'
28
+ __all__ = [
29
+ 'ApiError', 'AuthState', 'AuthStore', 'CdifitClient', 'TwoFactorRequired',
30
+ 'DEFAULT_API_BASE', 'auth_path',
31
+ ]
32
+
33
+
34
+ class ApiError(RuntimeError):
35
+ """Cdifit API 返回非 0 code 或 HTTP 错误。"""
36
+
37
+ def __init__(self, message: str, *, status: int = 0, code: int = 0,
38
+ data: Any = None):
39
+ super().__init__(message)
40
+ self.status = status
41
+ self.code = code
42
+ self.data = data
43
+
44
+
45
+ class TwoFactorRequired(ApiError):
46
+ """密码登录返回 code=203, 需要 2FA。"""
47
+
48
+ def __init__(self, session: str):
49
+ super().__init__('需要两步验证', code=203, data=session)
50
+ self.session = session
51
+
52
+
53
+ @dataclass
54
+ class AuthState:
55
+ api_base: str = DEFAULT_API_BASE
56
+ access_token: str = ''
57
+ refresh_token: str = ''
58
+ access_expires: Optional[str] = None
59
+ refresh_expires: Optional[str] = None
60
+ user: Dict[str, Any] = field(default_factory=dict)
61
+
62
+ @property
63
+ def email(self) -> str:
64
+ return str(self.user.get('email') or '')
65
+
66
+ @property
67
+ def display_name(self) -> str:
68
+ return str(self.user.get('nickname') or self.user.get('name')
69
+ or self.email or self.user.get('id') or 'unknown')
70
+
71
+ def to_dict(self) -> Dict[str, Any]:
72
+ return {
73
+ 'api_base': self.api_base,
74
+ 'access_token': self.access_token,
75
+ 'refresh_token': self.refresh_token,
76
+ 'access_expires': self.access_expires,
77
+ 'refresh_expires': self.refresh_expires,
78
+ 'user': self.user,
79
+ }
80
+
81
+ @classmethod
82
+ def from_dict(cls, data: Dict[str, Any]) -> 'AuthState':
83
+ return cls(
84
+ api_base=str(data.get('api_base') or DEFAULT_API_BASE),
85
+ access_token=str(data.get('access_token') or ''),
86
+ refresh_token=str(data.get('refresh_token') or ''),
87
+ access_expires=data.get('access_expires'),
88
+ refresh_expires=data.get('refresh_expires'),
89
+ user=dict(data.get('user') or {}),
90
+ )
91
+
92
+
93
+ def _parse_time(value: Any) -> Optional[datetime]:
94
+ if not value:
95
+ return None
96
+ text = str(value).strip()
97
+ try:
98
+ parsed = datetime.fromisoformat(text.replace('Z', '+00:00'))
99
+ except ValueError:
100
+ return None
101
+ if parsed.tzinfo is None:
102
+ parsed = parsed.replace(tzinfo=timezone.utc)
103
+ return parsed
104
+
105
+
106
+ def _expiring(value: Any, skew: int = 60) -> bool:
107
+ parsed = _parse_time(value)
108
+ if parsed is None:
109
+ return False
110
+ return parsed.timestamp() - skew <= time.time()
111
+
112
+
113
+ def _pic_home() -> str:
114
+ return os.path.abspath(os.environ.get('PIC_HOME')
115
+ or os.path.join(os.path.expanduser('~'), '.pic'))
116
+
117
+
118
+ def auth_path() -> str:
119
+ return os.path.join(_pic_home(), 'auth.json')
120
+
121
+
122
+ class AuthStore:
123
+ """``$PIC_HOME/auth.json`` 的读写 (权限尽量设为 0600)。"""
124
+
125
+ def __init__(self, path: Optional[str] = None):
126
+ self.path = path or auth_path()
127
+
128
+ def load(self) -> Optional[AuthState]:
129
+ if not os.path.isfile(self.path):
130
+ return None
131
+ try:
132
+ with open(self.path, encoding='utf-8') as f:
133
+ data = json.load(f)
134
+ if not isinstance(data, dict):
135
+ return None
136
+ state = AuthState.from_dict(data)
137
+ return state if state.access_token else None
138
+ except (OSError, ValueError, TypeError):
139
+ return None
140
+
141
+ def save(self, state: AuthState) -> None:
142
+ os.makedirs(os.path.dirname(self.path), exist_ok=True)
143
+ payload = json.dumps(state.to_dict(), ensure_ascii=False,
144
+ indent=2) + '\n'
145
+ fd, tmp = tempfile.mkstemp(prefix='.auth-', suffix='.json',
146
+ dir=os.path.dirname(self.path))
147
+ try:
148
+ with os.fdopen(fd, 'w', encoding='utf-8', newline='\n') as f:
149
+ f.write(payload)
150
+ with contextlib.suppress(OSError):
151
+ os.chmod(tmp, 0o600)
152
+ os.replace(tmp, self.path)
153
+ finally:
154
+ if os.path.exists(tmp):
155
+ with contextlib.suppress(OSError):
156
+ os.remove(tmp)
157
+
158
+ def clear(self) -> None:
159
+ with contextlib.suppress(OSError):
160
+ os.remove(self.path)
161
+
162
+
163
+ class CdifitClient:
164
+ """轻量 HTTP 客户端 (标准库, 无第三方依赖)。"""
165
+
166
+ def __init__(self, api_base: str = DEFAULT_API_BASE,
167
+ auth: Optional[AuthState] = None,
168
+ store: Optional[AuthStore] = None,
169
+ timeout: int = 25):
170
+ self.api_base = (api_base or DEFAULT_API_BASE).rstrip('/')
171
+ self.auth = auth
172
+ self.store = store
173
+ self.timeout = timeout
174
+
175
+ # ---------------- 底层请求 ----------------
176
+
177
+ def _url(self, path: str) -> str:
178
+ if path.startswith('http://') or path.startswith('https://'):
179
+ return path
180
+ return self.api_base + (path if path.startswith('/') else '/' + path)
181
+
182
+ def _send(self, method: str, path: str, body: Optional[Dict[str, Any]] = None,
183
+ token: Optional[str] = None) -> Any:
184
+ headers = {'Accept': 'application/json',
185
+ 'User-Agent': f'pic/{_version()}'}
186
+ data = None
187
+ if body is not None:
188
+ data = json.dumps(body, ensure_ascii=False).encode('utf-8')
189
+ headers['Content-Type'] = 'application/json'
190
+ if token:
191
+ headers['Authorization'] = 'Bearer ' + token
192
+ request = urllib.request.Request(self._url(path), data=data,
193
+ headers=headers, method=method)
194
+ status = 0
195
+ try:
196
+ with urllib.request.urlopen(request, timeout=self.timeout) as resp:
197
+ status = resp.status
198
+ raw = resp.read()
199
+ except urllib.error.HTTPError as e:
200
+ status = e.code
201
+ raw = e.read()
202
+ except urllib.error.URLError as e:
203
+ raise ApiError(f'无法连接 Cdifit API: {e.reason}') from e
204
+ except OSError as e:
205
+ raise ApiError(f'无法连接 Cdifit API: {e}') from e
206
+
207
+ try:
208
+ payload = json.loads(raw.decode('utf-8')) if raw else {}
209
+ except (ValueError, UnicodeDecodeError):
210
+ text = raw.decode('utf-8', 'replace')[:300]
211
+ raise ApiError(
212
+ f'Cdifit API 返回非 JSON (HTTP {status}): {text}',
213
+ status=status) from None
214
+
215
+ if not isinstance(payload, dict):
216
+ return payload
217
+ code = payload.get('code', 0)
218
+ if code == 203:
219
+ raise TwoFactorRequired(str(payload.get('data') or ''))
220
+ if code not in (0, None):
221
+ # Cdifit 对无效 Token 返回 HTTP 200 + code=401/403,
222
+ # 这里归一为 status, 让 _request 的刷新逻辑生效。
223
+ raise ApiError(str(payload.get('msg') or 'Cdifit API 请求失败'),
224
+ status=int(code) if code in (401, 403) else status,
225
+ code=int(code or 0),
226
+ data=payload.get('data'))
227
+ return payload.get('data', payload)
228
+
229
+ def _token(self) -> Optional[str]:
230
+ return self.auth.access_token if self.auth else None
231
+
232
+ def _refresh_if_needed(self) -> None:
233
+ if not self.auth:
234
+ return
235
+ if self.auth.access_expires and _expiring(self.auth.access_expires):
236
+ self.refresh()
237
+
238
+ def ensure_token(self) -> None:
239
+ """确保 access token 存在且未过期 (必要时刷新)。"""
240
+ if not self.auth or not self.auth.access_token:
241
+ raise ApiError('未登录: 请先运行 `pic login`', status=401)
242
+ self._refresh_if_needed()
243
+
244
+ def _request(self, method: str, path: str,
245
+ body: Optional[Dict[str, Any]] = None,
246
+ auth: bool = True, retry: bool = True) -> Any:
247
+ if auth:
248
+ if not self.auth or not self.auth.access_token:
249
+ raise ApiError('未登录: 请先运行 `pic login`', status=401)
250
+ self._refresh_if_needed()
251
+ try:
252
+ return self._send(method, path, body, self._token() if auth else None)
253
+ except ApiError as e:
254
+ if auth and e.status in (401, 403) and retry and self.auth \
255
+ and self.auth.refresh_token:
256
+ self.refresh()
257
+ return self._send(method, path, body, self._token())
258
+ raise
259
+
260
+ # ---------------- 会话 ----------------
261
+
262
+ def login(self, email: str, password: str,
263
+ captcha: Optional[str] = None,
264
+ ticket: Optional[str] = None) -> AuthState:
265
+ body: Dict[str, Any] = {'email': email, 'password': password}
266
+ if captcha:
267
+ body['captcha'] = captcha
268
+ if ticket:
269
+ body['ticket'] = ticket
270
+ payload = self._send('POST', API_PREFIX + '/session/token', body)
271
+ data = payload if isinstance(payload, dict) else {}
272
+ token = data.get('token') or {}
273
+ user = data.get('user') or {}
274
+ if not token.get('access_token'):
275
+ raise ApiError('登录响应缺少 access_token', data=data)
276
+ self.auth = AuthState(
277
+ api_base=self.api_base,
278
+ access_token=str(token.get('access_token')),
279
+ refresh_token=str(token.get('refresh_token') or ''),
280
+ access_expires=token.get('access_expires'),
281
+ refresh_expires=token.get('refresh_expires'),
282
+ user=dict(user),
283
+ )
284
+ if self.store:
285
+ self.store.save(self.auth)
286
+ return self.auth
287
+
288
+ def finish_2fa(self, session: str, code: str) -> AuthState:
289
+ payload = self._send('POST', API_PREFIX + '/session/token/2fa',
290
+ {'session': session, 'code': code})
291
+ data = payload if isinstance(payload, dict) else {}
292
+ token = data.get('token') or {}
293
+ user = data.get('user') or {}
294
+ if not token.get('access_token'):
295
+ raise ApiError('2FA 响应缺少 access_token', data=data)
296
+ self.auth = AuthState(
297
+ api_base=self.api_base,
298
+ access_token=str(token.get('access_token')),
299
+ refresh_token=str(token.get('refresh_token') or ''),
300
+ access_expires=token.get('access_expires'),
301
+ refresh_expires=token.get('refresh_expires'),
302
+ user=dict(user) or (self.auth.user if self.auth else {}),
303
+ )
304
+ if self.store:
305
+ self.store.save(self.auth)
306
+ return self.auth
307
+
308
+ def refresh(self) -> AuthState:
309
+ if not self.auth or not self.auth.refresh_token:
310
+ raise ApiError('没有可用的 refresh_token, 请重新登录', status=401)
311
+ payload = self._send(
312
+ 'PUT', API_PREFIX + '/session/token/refresh',
313
+ {'refresh_token': self.auth.refresh_token},
314
+ token=self.auth.refresh_token)
315
+ data = payload if isinstance(payload, dict) else {}
316
+ if not data.get('access_token'):
317
+ raise ApiError('刷新令牌响应缺少 access_token', data=data)
318
+ self.auth.access_token = str(data['access_token'])
319
+ if data.get('refresh_token'):
320
+ self.auth.refresh_token = str(data['refresh_token'])
321
+ self.auth.access_expires = data.get('access_expires') \
322
+ or self.auth.access_expires
323
+ self.auth.refresh_expires = data.get('refresh_expires') \
324
+ or self.auth.refresh_expires
325
+ if self.store:
326
+ self.store.save(self.auth)
327
+ return self.auth
328
+
329
+ def logout(self) -> None:
330
+ if self.auth and self.auth.access_token:
331
+ with contextlib.suppress(ApiError):
332
+ self._request('DELETE', API_PREFIX + '/session/token')
333
+ self.auth = None
334
+ if self.store:
335
+ self.store.clear()
336
+
337
+ def userinfo(self) -> Dict[str, Any]:
338
+ payload = self._request('GET',
339
+ API_PREFIX + '/session/oauth/userinfo')
340
+ if isinstance(payload, dict) and payload.get('sub'):
341
+ if self.auth:
342
+ self.auth.user.update(payload)
343
+ if self.store:
344
+ self.store.save(self.auth)
345
+ return payload
346
+ return self.auth.user if self.auth else {}
347
+
348
+
349
+ def _version() -> str:
350
+ try:
351
+ from . import __version__
352
+ return __version__
353
+ except Exception: # pragma: no cover
354
+ return '0'
355
+
356
+
357
+ def load_auth(api_base: Optional[str] = None) -> Optional[AuthState]:
358
+ state = AuthStore().load()
359
+ if state is None:
360
+ return None
361
+ if api_base and state.api_base.rstrip('/') != api_base.rstrip('/'):
362
+ return None
363
+ return state
364
+
365
+
366
+ def client_from_store(api_base: Optional[str] = None,
367
+ store: Optional[AuthStore] = None) -> Optional[CdifitClient]:
368
+ store = store or AuthStore()
369
+ state = store.load()
370
+ if state is None:
371
+ return None
372
+ if api_base and state.api_base.rstrip('/') != api_base.rstrip('/'):
373
+ return None
374
+ return CdifitClient(api_base or state.api_base, auth=state, store=store)