@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 395 lines 12.8 KB
Raw
1 import * as androiddeviceprovisioning from "@distilled.cloud/gcp/androiddeviceprovisioning_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 DEFAULT_IS_DEFAULT,
12 encodeOwnershipLine,
13 findConfigurationByName,
14 findOwnedConfiguration,
15 getConfiguration,
16 hasOwnershipMarker,
17 lastSegment,
18 listOwnedConfigurations,
19 MAX_CONFIGURATION_NAME_LENGTH,
20 ownedByAlchemy,
21 ownershipLabels,
22 parentOf,
23 parseOwnership,
24 pickDpcName,
25 replaceOnIdentity,
26 sameBoolean,
27 sameText,
28 toConfigurationName,
29 toCustomerName,
30 toDisplayName,
31 toDpcName,
32 updateMaskOf,
33 } from "./internal.ts";
34
35 export type CustomersConfigurationProps = {
36 /**
37 * Parent customer (`customers/{customer}` or `{customer}`). Immutable
38 * — changing it replaces the configuration.
39 */
40 parent: string;
41 /**
42 * Server-assigned configuration id (last path segment). Immutable —
43 * changing it replaces the configuration.
44 */
45 configurationId?: string;
46 /**
47 * DPC resource (`customers/{customer}/dpcs/{dpc}` or `{dpc}`). When
48 * omitted, Alchemy lists the customer's DPCs and prefers Android
49 * Device Policy.
50 */
51 dpcResourcePath?: string;
52 /**
53 * Email shown to device users for help. Validated by the API.
54 */
55 contactEmail: string;
56 /**
57 * Phone number shown to device users for help. Accepts numerals,
58 * spaces, `+`, hyphens, and parentheses.
59 */
60 contactPhone: string;
61 /**
62 * Organization name shown during zero-touch setup.
63 */
64 companyName: string;
65 /**
66 * Short admin-facing name. Configurations have no labels field, so
67 * Alchemy stores ownership in a `[alchemy …]` prefix and strips it
68 * from attributes.
69 */
70 configurationName?: string;
71 /**
72 * JSON extras passed to the DPC at provisioning time.
73 */
74 dpcExtras?: string;
75 /**
76 * Whether newly purchased devices receive this configuration.
77 * @default false
78 */
79 isDefault?: boolean;
80 /**
81 * Help text shown to the device user before provisioning.
82 */
83 customMessage?: string;
84 /**
85 * Factory-reset timeout when setup does not complete (for example
86 * `"7200s"`). The API default is two hours when unset.
87 */
88 forcedResetTime?: string;
89 };
90
91 export type CustomersConfiguration = Resource<
92 "GCP.AndroidDeviceProvisioning.CustomersConfiguration",
93 CustomersConfigurationProps,
94 {
95 /** Resource name `customers/{customer}/configurations/{configuration}`. */
96 name: string;
97 /** Configuration id (last path segment). */
98 configurationId: string;
99 /** Parent customer name `customers/{customer}`. */
100 parent: string;
101 /** Project id used when the configuration was reconciled. */
102 project: string;
103 /** Admin-facing name with the Alchemy ownership prefix stripped. */
104 configurationName: string | undefined;
105 /** DPC resource path applied to devices. */
106 dpcResourcePath: string | undefined;
107 /** JSON extras passed to the DPC. */
108 dpcExtras: string | undefined;
109 /** Organization name shown during setup. */
110 companyName: string | undefined;
111 /** Help email shown to device users. */
112 contactEmail: string | undefined;
113 /** Help phone shown to device users. */
114 contactPhone: string | undefined;
115 /** Help message shown before provisioning. */
116 customMessage: string | undefined;
117 /** Whether this is the customer's default configuration. */
118 isDefault: boolean | undefined;
119 /** Factory-reset timeout duration. */
120 forcedResetTime: string | undefined;
121 },
122 never,
123 Providers
124 >;
125
126 /**
127 * A zero-touch enrollment configuration
128 * (`customers/{customer}/configurations/{configuration}`).
129 *
130 * Configurations have no labels field, so Alchemy stamps ownership into
131 * `configurationName` for `list` / nuke. Parent customer and
132 * configuration id are identity — changing either replaces the
133 * configuration. Contact fields, DPC, extras, default flag, custom
134 * message, and reset timeout update in place. Create requires a
135 * zero-touch customer the caller can administer.
136 *
137 * ### Creating a Configuration
138 * **Example:** Named sales profile
139 * ```typescript
140 * const config = yield* GCP.AndroidDeviceProvisioning.CustomersConfiguration(
141 * "Sales",
142 * {
143 * parent: "customers/123456789",
144 * dpcResourcePath: "customers/123456789/dpcs/abc",
145 * companyName: "Acme",
146 * contactEmail: "it@example.com",
147 * contactPhone: "+1 555 0100",
148 * configurationName: "Sales team",
149 * },
150 * );
151 * ```
152 *
153 * **Example:** Default configuration for new devices
154 * ```typescript
155 * const config = yield* GCP.AndroidDeviceProvisioning.CustomersConfiguration(
156 * "Default",
157 * {
158 * parent: customer,
159 * dpcResourcePath: dpc,
160 * companyName: "Acme",
161 * contactEmail: "it@example.com",
162 * contactPhone: "+1 555 0100",
163 * isDefault: true,
164 * },
165 * );
166 * ```
167 *
168 * ### Updating a Configuration
169 * Re-declare the same logical id with changed props; the engine keeps the
170 * physical resource and updates it in place.
171 *
172 * **Example:** Rename and change the help email
173 * ```typescript
174 * const config = yield* GCP.AndroidDeviceProvisioning.CustomersConfiguration(
175 * "Sales",
176 * {
177 * parent: customer,
178 * dpcResourcePath: dpc,
179 * contactEmail: "help@example.com",
180 * contactPhone: "+1 555 0100",
181 * configurationName: "Field sales",
182 * },
183 * );
184 * ```
185 *
186 * @resource
187 * @category AndroidDeviceProvisioning
188 */
189 export const CustomersConfiguration = Resource<CustomersConfiguration>(
190 "GCP.AndroidDeviceProvisioning.CustomersConfiguration",
191 );
192
193 export class CustomersConfigurationNotResolved extends Data.TaggedError(
194 "GCP.AndroidDeviceProvisioning.CustomersConfigurationNotResolved",
195 )<{
196 parent: string;
197 resourceName: string;
198 }> {}
199
200 const lookupName = (
201 parent: string,
202 configurationId: string | undefined,
203 existingName: string | undefined,
204 ) => {
205 if (existingName && existingName.length > 0) return existingName;
206 return toConfigurationName(parent, configurationId);
207 };
208
209 const toAttrs = (row: androiddeviceprovisioning.Configuration, project: string) => {
210 const name = row.name ?? "";
211 return {
212 name,
213 configurationId: row.configurationId ?? lastSegment(name),
214 parent: parentOf(name) || toCustomerName(name),
215 project,
216 configurationName: parseOwnership(row.configurationName).text,
217 dpcResourcePath: row.dpcResourcePath,
218 dpcExtras: row.dpcExtras,
219 companyName: row.companyName,
220 contactEmail: row.contactEmail,
221 contactPhone: row.contactPhone,
222 customMessage: row.customMessage,
223 isDefault: row.isDefault,
224 forcedResetTime: row.forcedResetTime,
225 };
226 };
227
228 const desiredBody = (input: {
229 news: CustomersConfigurationProps;
230 configurationName: string;
231 dpcResourcePath: string;
232 current?: androiddeviceprovisioning.Configuration;
233 }): androiddeviceprovisioning.Configuration => ({
234 configurationName: input.configurationName,
235 dpcResourcePath: input.dpcResourcePath,
236 contactEmail: input.news.contactEmail,
237 contactPhone: input.news.contactPhone,
238 companyName: input.news.companyName,
239 dpcExtras: input.news.dpcExtras ?? input.current?.dpcExtras,
240 isDefault: input.news.isDefault ?? input.current?.isDefault ?? DEFAULT_IS_DEFAULT,
241 customMessage: input.news.customMessage ?? input.current?.customMessage,
242 forcedResetTime: input.news.forcedResetTime ?? input.current?.forcedResetTime,
243 });
244
245 export const CustomersConfigurationProvider = () =>
246 Provider.succeed(CustomersConfiguration, {
247 stables: ["name", "configurationId", "parent", "project"],
248
249 diff: Effect.fn(function* ({ news, olds, output }) {
250 if (!isResolved(news)) return undefined;
251 return replaceOnIdentity({
252 previousParent: olds?.parent ?? output?.parent,
253 nextParent: news.parent,
254 previousId: olds?.configurationId ?? output?.configurationId,
255 nextId: news.configurationId,
256 });
257 }),
258
259 read: Effect.fn(function* ({ id, olds, output }) {
260 const env = yield* GcpEnvironment.current;
261 const parent = toCustomerName(olds?.parent ?? output?.parent ?? "");
262 const name = lookupName(
263 parent,
264 olds?.configurationId ?? output?.configurationId,
265 output?.name,
266 );
267 let existing = yield* getConfiguration(name);
268 if (existing === undefined) {
269 existing = yield* findOwnedConfiguration(id, parent);
270 }
271 if (existing === undefined) return undefined;
272 const attrs = toAttrs(existing, env.project);
273 return (yield* ownedByAlchemy(id, existing.configurationName)) ? attrs : Unowned(attrs);
274 }),
275
276 list: () =>
277 Effect.gen(function* () {
278 const env = yield* GcpEnvironment.current;
279 const rows = yield* listOwnedConfigurations();
280 return rows
281 .filter((row) => hasOwnershipMarker(row.configurationName))
282 .map((row) => toAttrs(row, env.project));
283 }),
284
285 reconcile: Effect.fn(function* ({ id, news, output }) {
286 const env = yield* GcpEnvironment.current;
287 const parent = toCustomerName(news.parent);
288 const ownership = yield* ownershipLabels(id);
289 const rawName = yield* toDisplayName(id, news.configurationName, output?.configurationName);
290 const configurationName = encodeOwnershipLine(
291 ownership,
292 rawName,
293 MAX_CONFIGURATION_NAME_LENGTH,
294 );
295 const dpcResourcePath = news.dpcResourcePath
296 ? toDpcName(parent, news.dpcResourcePath)
297 : (output?.dpcResourcePath ?? (yield* pickDpcName(parent)) ?? "");
298 const name = lookupName(
299 parent,
300 news.configurationId ?? output?.configurationId,
301 output?.name,
302 );
303
304 let current = yield* getConfiguration(name);
305 if (current === undefined) {
306 current = yield* findOwnedConfiguration(id, parent);
307 }
308 if (current === undefined) {
309 current = yield* findConfigurationByName(configurationName, parent);
310 }
311
312 if (current === undefined) {
313 const created = yield* androiddeviceprovisioning
314 .createCustomersConfigurations({
315 parent,
316 body: desiredBody({
317 news,
318 configurationName,
319 dpcResourcePath,
320 }),
321 })
322 .pipe(
323 Effect.catchTag("Conflict", () => findConfigurationByName(configurationName, parent)),
324 );
325 current = created ?? undefined;
326 }
327
328 if (current === undefined) {
329 return yield* new CustomersConfigurationNotResolved({
330 parent,
331 resourceName: name || configurationName,
332 });
333 }
334
335 const desiredDpcResourcePath =
336 dpcResourcePath.length > 0 ? dpcResourcePath : (current.dpcResourcePath ?? "");
337 const desired = desiredBody({
338 news,
339 configurationName,
340 dpcResourcePath: desiredDpcResourcePath,
341 current,
342 });
343 const currentName = current.name ?? name;
344 const updateMask = updateMaskOf(
345 !sameText(current.configurationName, desired.configurationName)
346 ? "configurationName"
347 : undefined,
348 desiredDpcResourcePath.length > 0 &&
349 !sameText(current.dpcResourcePath, desiredDpcResourcePath)
350 ? "dpcResourcePath"
351 : undefined,
352 news.dpcExtras !== undefined && !sameText(current.dpcExtras, desired.dpcExtras)
353 ? "dpcExtras"
354 : undefined,
355 !sameText(current.companyName, desired.companyName) ? "companyName" : undefined,
356 !sameText(current.contactEmail, desired.contactEmail) ? "contactEmail" : undefined,
357 !sameText(current.contactPhone, desired.contactPhone) ? "contactPhone" : undefined,
358 news.customMessage !== undefined && !sameText(current.customMessage, desired.customMessage)
359 ? "customMessage"
360 : undefined,
361 news.isDefault !== undefined && !sameBoolean(current.isDefault, desired.isDefault)
362 ? "isDefault"
363 : undefined,
364 news.forcedResetTime !== undefined &&
365 !sameText(current.forcedResetTime, desired.forcedResetTime)
366 ? "forcedResetTime"
367 : undefined,
368 );
369
370 if (updateMask.length > 0 && currentName.length > 0) {
371 current = yield* androiddeviceprovisioning.patchCustomersConfigurations({
372 name: currentName,
373 updateMask,
374 body: desired,
375 });
376 }
377
378 const fresh = (yield* getConfiguration(current.name ?? currentName)) ?? current;
379 return toAttrs(fresh, env.project);
380 }),
381
382 delete: Effect.fn(function* ({ output }) {
383 if (!output.name) return;
384 yield* androiddeviceprovisioning
385 .deleteCustomersConfigurations({
386 name: output.name,
387 })
388 .pipe(
389 Effect.catchTags({
390 NotFound: () => Effect.void,
391 BadRequest: () => Effect.void,
392 }),
393 );
394 }),
395 });