wherever-dev 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/drafts.d.ts +7 -0
  2. package/dist/drafts.d.ts.map +1 -1
  3. package/dist/drafts.js +10 -3
  4. package/dist/drafts.js.map +1 -1
  5. package/dist/index.js +691 -46
  6. package/dist/index.js.map +1 -1
  7. package/dist/protocol.d.ts +35 -0
  8. package/dist/protocol.d.ts.map +1 -1
  9. package/dist/protocol.js.map +1 -1
  10. package/dist/remote-candidates.d.ts +52 -0
  11. package/dist/remote-candidates.d.ts.map +1 -0
  12. package/dist/remote-candidates.js +147 -0
  13. package/dist/remote-candidates.js.map +1 -0
  14. package/dist/restore-jobs.d.ts +236 -0
  15. package/dist/restore-jobs.d.ts.map +1 -0
  16. package/dist/restore-jobs.js +716 -0
  17. package/dist/restore-jobs.js.map +1 -0
  18. package/dist/session-pool.d.ts +71 -8
  19. package/dist/session-pool.d.ts.map +1 -1
  20. package/dist/session-pool.js +192 -68
  21. package/dist/session-pool.js.map +1 -1
  22. package/dist/session-types.d.ts +12 -0
  23. package/dist/session-types.d.ts.map +1 -1
  24. package/package.json +1 -1
  25. package/public/_app/immutable/assets/0.CUi0Pn9k.css +1 -0
  26. package/public/_app/immutable/chunks/CJs7WGCY.js +2 -0
  27. package/public/_app/immutable/chunks/{CuGyzHtA.js.map → CJs7WGCY.js.map} +1 -1
  28. package/public/_app/immutable/chunks/{sERBGsNa.js → Cr3SOBcX.js} +2 -2
  29. package/public/_app/immutable/chunks/{sERBGsNa.js.map → Cr3SOBcX.js.map} +1 -1
  30. package/public/_app/immutable/chunks/{55QXfSWV.js → DsMrx0D-.js} +2 -2
  31. package/public/_app/immutable/chunks/{55QXfSWV.js.map → DsMrx0D-.js.map} +1 -1
  32. package/public/_app/immutable/entry/{app.DN0r_HfQ.js → app.q0JTyYdd.js} +3 -3
  33. package/public/_app/immutable/entry/{app.DN0r_HfQ.js.map → app.q0JTyYdd.js.map} +1 -1
  34. package/public/_app/immutable/entry/start.Dn511egP.js +2 -0
  35. package/public/_app/immutable/entry/start.Dn511egP.js.map +1 -0
  36. package/public/_app/immutable/nodes/{0.BhHgt5Z6.js → 0.BhjoTMlz.js} +2 -2
  37. package/public/_app/immutable/nodes/{0.BhHgt5Z6.js.map → 0.BhjoTMlz.js.map} +1 -1
  38. package/public/_app/immutable/nodes/{1.B9mDAaoD.js → 1.CKIQ9-uZ.js} +2 -2
  39. package/public/_app/immutable/nodes/{1.B9mDAaoD.js.map → 1.CKIQ9-uZ.js.map} +1 -1
  40. package/public/_app/immutable/nodes/2.CBHW8874.js +120 -0
  41. package/public/_app/immutable/nodes/2.CBHW8874.js.map +1 -0
  42. package/public/_app/version.json +1 -1
  43. package/public/index.html +11 -11
  44. package/public/service-worker.js +1 -1
  45. package/public/_app/immutable/assets/0.BS_EGmNW.css +0 -1
  46. package/public/_app/immutable/chunks/CuGyzHtA.js +0 -2
  47. package/public/_app/immutable/entry/start.CSyfkZFS.js +0 -2
  48. package/public/_app/immutable/entry/start.CSyfkZFS.js.map +0 -1
  49. package/public/_app/immutable/nodes/2.BjlQDhkN.js +0 -110
  50. package/public/_app/immutable/nodes/2.BjlQDhkN.js.map +0 -1
@@ -0,0 +1,147 @@
1
+ // Remote CANDIDATES: which repository does a MISSING working folder correspond to?
2
+ //
3
+ // A synced transcript routinely names a clone that does not exist on this
4
+ // machine (`folder missing`, see CONTEXT.md). Curing that is a RESTORE, and the
5
+ // restore panel wants a URL pre-filled rather than typed on a phone. This module
6
+ // answers with an ORDERED list of candidates, in decreasing confidence:
7
+ //
8
+ // 1. PROBE. The folder matches a configured remote-repo rule, so the provider
9
+ // CLI the create-session path already uses is asked whether that repository
10
+ // exists, and its SSH URL is taken. This covers what the configured account
11
+ // OWNS.
12
+ // 2. PATH CONVENTION. The `<...>/<host-token>/<owner>/<repo>` layout is read
13
+ // back into an scp-style SSH URL. This is what covers repositories owned by
14
+ // SOMEONE ELSE, which the probe structurally cannot find, and it is the case
15
+ // that DOMINATES the migration this feature exists for: one rule covering
16
+ // one personal namespace, and a folder tree full of other people's repos.
17
+ // 3. Nothing. An empty list is an honest answer; the user pastes a URL.
18
+ //
19
+ // A candidate is ADVISORY, never an authority: the server clones what it is
20
+ // finally GIVEN (after `restore-jobs.ts` validates it), not what it guessed here.
21
+ // Every candidate is an SSH remote and an HTTPS URL is never synthesised
22
+ // (`docs/adr/0010`), including one handed back by a provider CLI.
23
+ //
24
+ // The probe is an INJECTED function rather than an import. That keeps this
25
+ // module free of the session pool (and so of the pi agent dependency it drags
26
+ // in), keeps the resolver a fast pure function over a path plus a rules list,
27
+ // and makes "the tests need no provider CLI installed or authenticated"
28
+ // structural rather than a discipline.
29
+ import os from 'node:os';
30
+ import path from 'node:path';
31
+ /**
32
+ * Folder tokens that NAME a forge. Deliberately short: a token that is not one
33
+ * of these and is not already a hostname yields NO candidate, because a
34
+ * confidently wrong pre-filled URL is worse than an empty field the user pastes
35
+ * into. `gitea`/`forgejo` are absent on purpose -- they are software, not a
36
+ * host, so the self-hosted instance is written as its own dotted hostname.
37
+ */
38
+ const HOST_TOKENS = {
39
+ github: 'github.com',
40
+ codeberg: 'codeberg.org',
41
+ gitlab: 'gitlab.com',
42
+ };
43
+ /** A token that is already a hostname (`git.example.com`) stands for itself. */
44
+ const DOTTED_HOST = /^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)+$/;
45
+ /** Owner / repo segments, restricted to what the clone URL allowlist accepts. */
46
+ const PATH_SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
47
+ /** Candidates are SSH-only (`docs/adr/0010`), whatever their source claims. */
48
+ const SSH_CANDIDATE = /^(?:[A-Za-z0-9._-]+@[A-Za-z0-9.-]+:[A-Za-z0-9._~/-]+|ssh:\/\/[^\s]+)$/;
49
+ function expandTilde(p) {
50
+ if (p.startsWith('~'))
51
+ return path.join(os.homedir(), p.slice(1));
52
+ return p;
53
+ }
54
+ /**
55
+ * The first rule whose `pattern` matches `resolvedPath`, or undefined.
56
+ *
57
+ * `resolvedPath` is absolute and tilde-EXPANDED (`/home/u/dev/...`), so a
58
+ * pattern written with a leading `~` (as users naturally write it, mirroring
59
+ * `commonFolders`) would never match; expand it before building the RegExp. An
60
+ * invalid pattern is a non-match rather than a throw: one malformed rule in the
61
+ * config must not take out every caller of this.
62
+ *
63
+ * This is the ONE implementation of remote-repo rule matching -- `/check-path`,
64
+ * `/check-remote-repo` and the candidate resolver all come here, so a fix to the
65
+ * matching semantics lands once.
66
+ */
67
+ export function matchRemoteRepoRule(rules, resolvedPath) {
68
+ if (!rules || !Array.isArray(rules))
69
+ return undefined;
70
+ return rules.find((rule) => {
71
+ try {
72
+ return new RegExp(expandTilde(rule.pattern)).test(resolvedPath);
73
+ }
74
+ catch {
75
+ return false;
76
+ }
77
+ });
78
+ }
79
+ /**
80
+ * Read `<...>/<host-token>/<owner>/<repo>` back into an SSH URL, or null when
81
+ * the layout does not carry one: an unknown host token, a path too shallow for
82
+ * an owner and a repo, or segments that are not plausible owner/repo names.
83
+ *
84
+ * Only the LAST THREE segments are consulted, so the convention holds wherever
85
+ * the tree is rooted (`~/dev/github/o/r`, `~/src/work/github/o/r`).
86
+ */
87
+ export function deriveCandidateFromPath(resolvedPath) {
88
+ const segments = path.resolve(resolvedPath).split(path.sep).filter(Boolean);
89
+ if (segments.length < 3)
90
+ return null;
91
+ const [hostToken, owner, repoSegment] = segments.slice(-3);
92
+ const host = resolveHostToken(hostToken);
93
+ if (!host)
94
+ return null;
95
+ if (!PATH_SEGMENT.test(owner) || !PATH_SEGMENT.test(repoSegment))
96
+ return null;
97
+ // A folder named `repo.git` (a bare-style checkout) must not become `repo.git.git`.
98
+ const repo = repoSegment.endsWith('.git') ? repoSegment.slice(0, -'.git'.length) : repoSegment;
99
+ if (!repo)
100
+ return null;
101
+ return { url: `git@${host}:${owner}/${repo}.git`, source: 'path-convention' };
102
+ }
103
+ function resolveHostToken(token) {
104
+ const lowered = token.toLowerCase();
105
+ if (HOST_TOKENS[lowered])
106
+ return HOST_TOKENS[lowered];
107
+ if (DOTTED_HOST.test(lowered))
108
+ return lowered;
109
+ return null;
110
+ }
111
+ /**
112
+ * The ordered candidate list for `resolvedPath`: the probe candidate first (when
113
+ * a rule covers the folder AND the provider says the repository exists), then
114
+ * the path-convention one, de-duplicated by URL.
115
+ *
116
+ * `probe` is optional; omitting it resolves the path convention alone. A probe
117
+ * failure of ANY kind -- CLI missing, not authenticated, repository absent, a
118
+ * throw -- degrades to the derived candidate rather than erroring, because a
119
+ * candidate list is advisory and an unprovisioned box must still get the answer
120
+ * it can have.
121
+ */
122
+ export function resolveRemoteCandidates(resolvedPath, rules, probe) {
123
+ const candidates = [];
124
+ const rule = matchRemoteRepoRule(rules, resolvedPath);
125
+ if (rule && probe) {
126
+ try {
127
+ const result = probe(rule, path.basename(path.resolve(resolvedPath)));
128
+ if (result?.exists && result.sshUrl && isSshCandidate(result.sshUrl)) {
129
+ candidates.push({ url: result.sshUrl, source: 'probe' });
130
+ }
131
+ }
132
+ catch {
133
+ // CLI missing, not logged in, network down: fall through to the derivation.
134
+ }
135
+ }
136
+ const derived = deriveCandidateFromPath(resolvedPath);
137
+ // The probe and the convention routinely agree (the owner's own namespace laid
138
+ // out by convention). Report the URL once, keeping the more confident source.
139
+ if (derived && !candidates.some((c) => c.url === derived.url))
140
+ candidates.push(derived);
141
+ return candidates;
142
+ }
143
+ /** An HTTPS URL is never a candidate, even when a provider CLI hands one over. */
144
+ function isSshCandidate(url) {
145
+ return SSH_CANDIDATE.test(url) && !url.startsWith('-');
146
+ }
147
+ //# sourceMappingURL=remote-candidates.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remote-candidates.js","sourceRoot":"","sources":["../src/remote-candidates.ts"],"names":[],"mappings":"AAAA,mFAAmF;AACnF,EAAE;AACF,0EAA0E;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a,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;AACzD,CAAC"}
@@ -0,0 +1,236 @@
1
+ import { type ChildProcess, type SpawnOptions } from 'node:child_process';
2
+ /** Materialise by cloning a remote, or by creating an empty folder. */
3
+ export type RestoreJobKind = 'clone' | 'create';
4
+ /** `running` is the only non-terminal state. */
5
+ export type RestoreJobState = 'running' | 'done' | 'failed' | 'cancelled';
6
+ /**
7
+ * The phase a job is in. `starting` covers "git has begun on this scope but has
8
+ * reported nothing measurable yet"; every other value is one of git's own
9
+ * progress lines (or, for the create kind, the mkdir/init steps).
10
+ */
11
+ export type RestorePhase = 'starting' | 'enumerating' | 'counting' | 'compressing' | 'receiving' | 'resolving' | 'checking-out' | 'filtering' | 'creating' | 'initialising';
12
+ /**
13
+ * The scope of the top-level repository. Submodules report under their own path
14
+ * (relative to the target) instead, because folding them into one number would
15
+ * be a fake global percentage: git restarts counting per submodule and nothing
16
+ * knows how many objects the remaining ones hold.
17
+ */
18
+ export declare const REPOSITORY_SCOPE = "repository";
19
+ export interface RestoreProgress {
20
+ phase: RestorePhase;
21
+ /** `REPOSITORY_SCOPE`, or a submodule path relative to the target. */
22
+ scope: string;
23
+ /** 0..100, or null when git reports no percentage for this phase. */
24
+ percent: number | null;
25
+ /** Explicitly true exactly when `percent` is null. Honesty, not a fallback. */
26
+ indeterminate: boolean;
27
+ /** The git line this was parsed from, for a detail line in the UI. */
28
+ text: string;
29
+ /** Epoch ms. */
30
+ at: number;
31
+ }
32
+ /**
33
+ * The named causes. Every one of them is a DIFFERENT one-line fix on the box, so
34
+ * they are reported separately; `unknown` is surfaced verbatim rather than
35
+ * reworded into a guess.
36
+ */
37
+ export type RestoreFailureCause = 'no-key' | 'unknown-host' | 'not-found' | 'network' | 'unknown';
38
+ export interface RestoreFailure {
39
+ cause: RestoreFailureCause;
40
+ /** Actionable, human-readable. Names the missing credential, never fixes it. */
41
+ message: string;
42
+ /** git's raw stderr, kept underneath the mapping and never replaced by it. */
43
+ stderr: string;
44
+ }
45
+ /** A plain-data view of a job. Safe to serialise straight onto the wire. */
46
+ export interface RestoreJobSnapshot {
47
+ /** Monotonic within a registry, so a client can tell a retry from the job it replaced. */
48
+ id: number;
49
+ kind: RestoreJobKind;
50
+ /** Resolved absolute path. This is also the registry key. */
51
+ targetPath: string;
52
+ /** The URL this job is ACTUALLY cloning (clone kind only). */
53
+ url?: string;
54
+ gitInit?: boolean;
55
+ state: RestoreJobState;
56
+ /** Latest parsed progress, or null before the first one. */
57
+ progress: RestoreProgress | null;
58
+ failure?: RestoreFailure;
59
+ startedAt: number;
60
+ endedAt?: number;
61
+ }
62
+ export type RestoreRejectionReason = 'outside-home' | 'invalid-target' | 'target-not-empty' | 'invalid-url';
63
+ export type RestoreRequestResult = {
64
+ ok: true;
65
+ /**
66
+ * `joined` means a job for this path was ALREADY running and this request
67
+ * coalesced onto it. The caller must compare `job.url` with what it asked
68
+ * for: a joiner whose edited URL differs has to be told a clone of the
69
+ * OTHER url is in flight, never silently answered as though its own was
70
+ * accepted.
71
+ */
72
+ outcome: 'started' | 'joined';
73
+ job: RestoreJobSnapshot;
74
+ } | {
75
+ ok: false;
76
+ reason: RestoreRejectionReason;
77
+ message: string;
78
+ };
79
+ export interface RestoreJobObserver {
80
+ onProgress?(progress: RestoreProgress, job: RestoreJobSnapshot): void;
81
+ onSettled?(job: RestoreJobSnapshot): void;
82
+ }
83
+ export interface RestoreCloneRequest {
84
+ kind: 'clone';
85
+ targetPath: string;
86
+ url: string;
87
+ }
88
+ export interface RestoreCreateRequest {
89
+ kind: 'create';
90
+ targetPath: string;
91
+ gitInit?: boolean;
92
+ }
93
+ export type RestoreRequest = RestoreCloneRequest | RestoreCreateRequest;
94
+ /** The spawn seam, so a test can count processes without a test-only API. */
95
+ export type SpawnGit = (command: string, args: string[], options: SpawnOptions) => ChildProcess;
96
+ export interface RestoreJobRegistryOptions {
97
+ /**
98
+ * How long a TERMINAL job is retained before being reaped. A phone that
99
+ * reconnects after the clone finished still has to learn the outcome, so a job
100
+ * cannot vanish the instant it ends.
101
+ */
102
+ retainMs?: number;
103
+ /** Minimum ms between emitted progress frames (a phase or scope change always emits). */
104
+ progressIntervalMs?: number;
105
+ spawn?: SpawnGit;
106
+ }
107
+ /**
108
+ * True iff `p` resolves to the home directory or somewhere beneath it.
109
+ *
110
+ * This mirrors `isWithinHome()` in `index.ts` (the HTTP layer's guard on
111
+ * /check-path and /autocomplete-path) rather than importing it, because
112
+ * `index.ts` is the CLI entry point and DISPATCHES on import: importing it from
113
+ * a library module would run the server. The later wiring task should collapse
114
+ * the two onto this one, since this module is the importable side.
115
+ *
116
+ * `os.homedir()` is read on every call, not captured at module load, so the home
117
+ * a test points `HOME` at is the home the guard enforces.
118
+ */
119
+ export declare function isWithinHome(p: string): boolean;
120
+ export declare function isAllowedCloneUrl(url: string): boolean;
121
+ /**
122
+ * The clone argv. An ARRAY, never a shell string, and `--` before the operands
123
+ * so neither the URL nor the path can be read as an option.
124
+ *
125
+ * It carries NO `-c protocol.file.allow=...`: file-transport submodules are
126
+ * blocked by git since 2.38 (CVE-2022-39253) and that protection must never be
127
+ * relaxed for a real clone. The test fixtures need the relaxation, and they get
128
+ * it from their own process ENVIRONMENT (`GIT_CONFIG_COUNT` / `GIT_CONFIG_KEY_0`),
129
+ * which is why it must not live here.
130
+ */
131
+ export declare function buildCloneArgs(url: string, targetPath: string): string[];
132
+ /**
133
+ * The clone environment: every interactive prompt disabled, so a box missing a
134
+ * key, a known-hosts entry or a network route FAILS instead of hanging at zero
135
+ * percent behind an invisible prompt (ADR 0010). `ConnectTimeout` bounds the one
136
+ * case batch mode cannot: a host that accepts the TCP connection and then says
137
+ * nothing.
138
+ *
139
+ * The surrounding environment is INHERITED (a user's ssh config, agent socket
140
+ * and `GIT_SSH_COMMAND` are all legitimate and load-bearing on a real box); only
141
+ * the interactive levers are overridden.
142
+ */
143
+ export declare function buildCloneEnv(base?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
144
+ /**
145
+ * Map git's well-known failure signatures onto a named, actionable cause while
146
+ * keeping the raw stderr underneath.
147
+ *
148
+ * On an SSH-only, no-credential-setup design this IS the remedy: the product's
149
+ * job is to say precisely which one-line fix the box needs, not to perform it.
150
+ * An unrecognised failure is passed through verbatim rather than reworded, since
151
+ * a wrong guess costs more than raw git output.
152
+ */
153
+ export declare function mapCloneFailure(stderr: string, url: string): RestoreFailure;
154
+ /** The host part of an SSH URL, for naming it in a failure message. */
155
+ export declare function extractHost(url: string): string | undefined;
156
+ /**
157
+ * Turns raw `git clone --progress` output into progress frames.
158
+ *
159
+ * The load-bearing detail: git REWRITES one line in place, emitting frames
160
+ * separated by CARRIAGE RETURNS inside a single newline-terminated chunk. A
161
+ * newline-only parser therefore sees almost nothing during the receiving phase,
162
+ * which is exactly the phase a long clone spends its time in. So `\r` is a frame
163
+ * separator here, on equal footing with `\n`.
164
+ *
165
+ * The parser is also what keeps submodules honestly scoped: git announces each
166
+ * one with its own `Cloning into '<abs path>'...`, so the scope switches to that
167
+ * submodule's path and its percentages are never mixed into the parent's.
168
+ */
169
+ export declare class GitProgressParser {
170
+ private buffer;
171
+ private scope;
172
+ private readonly target;
173
+ constructor(targetPath: string);
174
+ /**
175
+ * Feed a chunk; get back the frames it completed. A trailing partial frame is
176
+ * BUFFERED rather than reported, so a half-read line can never be published as
177
+ * a wrong percentage.
178
+ */
179
+ push(chunk: string): RestoreProgress[];
180
+ private parseLine;
181
+ private scopeFor;
182
+ private frame;
183
+ }
184
+ /**
185
+ * The path-keyed registry. One job per target path at a time; a second request
186
+ * for a running path coalesces onto it.
187
+ */
188
+ export declare class RestoreJobRegistry {
189
+ private readonly jobs;
190
+ private readonly observers;
191
+ private readonly retainMs;
192
+ private readonly progressIntervalMs;
193
+ private readonly spawnFn;
194
+ private nextId;
195
+ constructor(options?: RestoreJobRegistryOptions);
196
+ /**
197
+ * Start a restore job for a path, or JOIN the one already running there.
198
+ *
199
+ * Every refusal happens here, before anything is spawned or created, so an
200
+ * unsafe request never has a partial effect.
201
+ */
202
+ request(request: RestoreRequest): RestoreRequestResult;
203
+ /** The job at `targetPath`, running or briefly-retained terminal, if any. */
204
+ get(targetPath: string): RestoreJobSnapshot | undefined;
205
+ list(): RestoreJobSnapshot[];
206
+ /**
207
+ * Observe a path: progress frames plus the terminal outcome.
208
+ *
209
+ * Subscription is keyed by PATH and independent of any particular job, so a
210
+ * consumer may attach before a job starts and stays attached across a retry.
211
+ * Returns the unsubscribe function.
212
+ */
213
+ subscribe(targetPath: string, observer: RestoreJobObserver): () => void;
214
+ /** Resolves with the terminal snapshot of the job at `targetPath`. */
215
+ settled(targetPath: string): Promise<RestoreJobSnapshot>;
216
+ /**
217
+ * Cancel the job at `targetPath`. Returns false when there is nothing running.
218
+ *
219
+ * Cancellation is AUTHORITATIVE: the job settles as `cancelled` even if the
220
+ * child happened to finish in the same breath, because the user asked for the
221
+ * folder not to be there. A directory this job CREATED is removed; one that
222
+ * already existed is never touched.
223
+ */
224
+ cancel(targetPath: string): boolean;
225
+ /** Drop every timer and kill anything running. For shutdown and for tests. */
226
+ dispose(): void;
227
+ private createJob;
228
+ private runClone;
229
+ private runCreate;
230
+ /** Store the latest frame always; publish it at a few frames per second. */
231
+ private record;
232
+ private cleanupCancelled;
233
+ private finish;
234
+ private observersFor;
235
+ }
236
+ //# sourceMappingURL=restore-jobs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"restore-jobs.d.ts","sourceRoot":"","sources":["../src/restore-jobs.ts"],"names":[],"mappings":"AA8BA,OAAO,EAAoC,KAAK,YAAY,EAAE,KAAK,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAE5G,uEAAuE;AACvE,MAAM,MAAM,cAAc,GAAG,OAAO,GAAG,QAAQ,CAAC;AAEhD,gDAAgD;AAChD,MAAM,MAAM,eAAe,GAAG,SAAS,GAAG,MAAM,GAAG,QAAQ,GAAG,WAAW,CAAC;AAE1E;;;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