create-expo-updates-server 0.2.1 → 0.3.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 (41) hide show
  1. package/dist/template/docs/expo-app-setup.md +8 -12
  2. package/dist/template/docs/getting-started.md +5 -5
  3. package/dist/template/docs/getting-started.ru.md +5 -5
  4. package/dist/template/docs/ota-client-lifecycle.md +46 -42
  5. package/dist/template/package-lock.json +589 -0
  6. package/dist/template/package.json +1 -0
  7. package/dist/template/scripts/lib/device-identity.test.ts +2 -2
  8. package/dist/template/scripts/lib/doctor.mjs +3 -3
  9. package/dist/template/scripts/lib/doctor.test.mjs +1 -1
  10. package/dist/template/scripts/lib/ota-client-configurator.mjs +116 -34
  11. package/dist/template/scripts/lib/ota-client-configurator.test.ts +210 -61
  12. package/dist/template/scripts/lib/ota-client.test.ts +1 -1
  13. package/dist/template/scripts/lib/ota-root-hook-patcher.mjs +435 -118
  14. package/dist/template/scripts/lib/ota-root-hook-patcher.test.ts +243 -86
  15. package/dist/template/scripts/lib/ota-update-controller.test.ts +10 -9
  16. package/dist/template/scripts/lib/ota-updates-ui.test.tsx +154 -0
  17. package/dist/template/scripts/tests/fixtures/react-native-ui.tsx +34 -0
  18. package/dist/template/scripts/tests/ota-client-types.mjs +69 -0
  19. package/dist/template/templates/expo-app/ota-client/README.md +16 -2
  20. package/dist/template/templates/expo-app/ota-client/controller.ts +107 -0
  21. package/dist/template/templates/expo-app/ota-client/device-identity.ts +48 -0
  22. package/dist/template/templates/expo-app/ota-client/docs/update-lifecycle.md +18 -9
  23. package/dist/template/templates/expo-app/ota-client/index.ts +16 -0
  24. package/dist/template/templates/expo-app/ota-client/model/hooks/useOtaUpdates.ts +97 -0
  25. package/dist/template/templates/expo-app/ota-client/model/update-controller.ts +293 -0
  26. package/dist/template/templates/expo-app/ota-client/runtime.ts +153 -0
  27. package/dist/template/templates/expo-app/ota-client/types.ts +85 -0
  28. package/dist/template/templates/expo-app/ota-client/ui/ota-update-gate.tsx +25 -0
  29. package/dist/template/templates/expo-app/ota-client/ui/ota-updates.tsx +196 -0
  30. package/dist/template/tsconfig.json +3 -1
  31. package/dist/template/vitest.config.mts +3 -0
  32. package/dist/template-manifest.json +85 -65
  33. package/package.json +1 -1
  34. package/dist/template/templates/expo-app/ota-client/controller.js +0 -60
  35. package/dist/template/templates/expo-app/ota-client/device-identity.js +0 -26
  36. package/dist/template/templates/expo-app/ota-client/index.d.ts +0 -47
  37. package/dist/template/templates/expo-app/ota-client/index.js +0 -3
  38. package/dist/template/templates/expo-app/ota-client/model/hooks/useOtaUpdates.js +0 -48
  39. package/dist/template/templates/expo-app/ota-client/model/update-controller.js +0 -182
  40. package/dist/template/templates/expo-app/ota-client/runtime.js +0 -112
  41. package/dist/template/templates/expo-app/ota-client/ui/ota-update-gate.js +0 -56
@@ -1,25 +1,46 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import ts from 'typescript';
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import ts from "typescript";
4
4
 
5
- const extensions = ['tsx', 'jsx', 'ts', 'js'];
6
- const suffixes = ['', '.android', '.ios', '.native', '.web'];
5
+ const extensions = ["tsx", "jsx", "ts", "js"];
6
+ const suffixes = ["", ".android", ".ios", ".native", ".web"];
7
7
 
8
8
  function unwrap(node) {
9
- while (node && (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node))) node = node.expression;
9
+ while (
10
+ node &&
11
+ (ts.isParenthesizedExpression(node) ||
12
+ ts.isAsExpression(node) ||
13
+ ts.isSatisfiesExpression(node))
14
+ )
15
+ node = node.expression;
10
16
  return node;
11
17
  }
12
18
 
13
19
  function componentFor(source) {
14
- const exported = source.statements.find((node) => node.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword));
20
+ const exported = source.statements.find((node) =>
21
+ node.modifiers?.some(
22
+ (modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword,
23
+ ),
24
+ );
15
25
  if (exported) return exported;
16
- const assignment = source.statements.find((node) => ts.isExportAssignment(node) && !node.isExportEquals);
26
+ const assignment = source.statements.find(
27
+ (node) => ts.isExportAssignment(node) && !node.isExportEquals,
28
+ );
17
29
  let component = unwrap(assignment?.expression);
18
30
  if (component && ts.isIdentifier(component)) {
19
31
  const name = component.text;
20
- component = source.statements.find((node) => ts.isFunctionDeclaration(node) && node.name?.text === name)
21
- || source.statements.flatMap((node) => ts.isVariableStatement(node) ? [...node.declarationList.declarations] : [])
22
- .find((node) => ts.isIdentifier(node.name) && node.name.text === name)?.initializer;
32
+ component =
33
+ source.statements.find(
34
+ (node) => ts.isFunctionDeclaration(node) && node.name?.text === name,
35
+ ) ||
36
+ source.statements
37
+ .flatMap((node) =>
38
+ ts.isVariableStatement(node)
39
+ ? [...node.declarationList.declarations]
40
+ : [],
41
+ )
42
+ .find((node) => ts.isIdentifier(node.name) && node.name.text === name)
43
+ ?.initializer;
23
44
  }
24
45
  return unwrap(component);
25
46
  }
@@ -28,145 +49,441 @@ function isDirective(node) {
28
49
  return ts.isExpressionStatement(node) && ts.isStringLiteral(node.expression);
29
50
  }
30
51
 
31
- /** Parse for insertion locations only: never reprint or reformat application code. */
52
+ /** Parse insertion locations without reprinting the application's existing code. */
32
53
  export function patchOtaRootHook(text, filename, appRoot) {
33
- const source = ts.createSourceFile(filename, text, ts.ScriptTarget.Latest, true);
34
- const fail = (reason) => { throw new Error(`Cannot automatically connect useOtaUpdates in ${filename}: ${reason}. Export a synchronous function component directly or through a local identifier, then rerun configure-app.`); };
35
- if (source.parseDiagnostics.length) fail('the root file has syntax errors');
54
+ const source = ts.createSourceFile(
55
+ filename,
56
+ text,
57
+ ts.ScriptTarget.Latest,
58
+ true,
59
+ );
60
+ const fail = (reason) => {
61
+ throw new Error(
62
+ `Cannot automatically connect OtaUpdates in ${filename}: ${reason}. Render <OtaUpdates /> once beside navigation in a synchronous JSX root component, then rerun configure-app.`,
63
+ );
64
+ };
65
+ if (source.parseDiagnostics.length) fail("the root file has syntax errors");
66
+ if (filename.endsWith(".ts"))
67
+ fail("rename the root to .tsx before inserting JSX");
36
68
  const component = componentFor(source);
37
- if (!component || !(ts.isFunctionDeclaration(component) || ts.isFunctionExpression(component) || ts.isArrowFunction(component)) || !component.body) fail('unsupported default root component');
38
- if (component.asteriskToken || component.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword)) fail('async/generator components cannot call React hooks');
39
-
40
- const clientPath = path.join(appRoot, 'ota-client');
69
+ if (
70
+ !component ||
71
+ !(
72
+ ts.isFunctionDeclaration(component) ||
73
+ ts.isFunctionExpression(component) ||
74
+ ts.isArrowFunction(component)
75
+ ) ||
76
+ !component.body
77
+ )
78
+ fail("unsupported default root component");
79
+ if (
80
+ component.asteriskToken ||
81
+ component.modifiers?.some((m) => m.kind === ts.SyntaxKind.AsyncKeyword)
82
+ )
83
+ fail("async/generator root components are unsupported");
84
+ const newline = text.includes("\r\n") ? "\r\n" : "\n";
85
+ const clientPath = path.join(appRoot, "ota-client");
41
86
  const imports = source.statements.filter(ts.isImportDeclaration);
87
+ const clientImports = imports.filter(
88
+ (node) =>
89
+ ts.isStringLiteral(node.moduleSpecifier) &&
90
+ node.moduleSpecifier.text.startsWith(".") &&
91
+ ["", "/index", "/index.js", "/index.ts"].some(
92
+ (suffix) =>
93
+ path.resolve(path.dirname(filename), node.moduleSpecifier.text) ===
94
+ clientPath + suffix,
95
+ ),
96
+ );
97
+ const binding = (nodes, name) =>
98
+ nodes
99
+ .flatMap((node) =>
100
+ !node.importClause?.isTypeOnly &&
101
+ node.importClause?.namedBindings &&
102
+ ts.isNamedImports(node.importClause.namedBindings)
103
+ ? [...node.importClause.namedBindings.elements]
104
+ : [],
105
+ )
106
+ .find(
107
+ (element) =>
108
+ !element.isTypeOnly &&
109
+ (element.propertyName || element.name).text === name,
110
+ )?.name.text;
111
+ if (
112
+ imports.some(
113
+ (node) =>
114
+ !clientImports.includes(node) &&
115
+ (binding([node], "useOtaUpdates") || binding([node], "OtaUpdates")),
116
+ )
117
+ )
118
+ fail(
119
+ "use a relative import to ota-client so existing configuration can be preserved",
120
+ );
121
+ const hookName = binding(clientImports, "useOtaUpdates");
122
+ const gateName = binding(clientImports, "OtaUpdateGate");
123
+ const createName = binding(
124
+ imports.filter((node) => node.moduleSpecifier.text === "react"),
125
+ "createElement",
126
+ );
127
+ const existingName = binding(clientImports, "OtaUpdates");
42
128
  const identifiers = new Set();
43
- const gather = (node) => { if (ts.isIdentifier(node)) identifiers.add(node.text); ts.forEachChild(node, gather); };
44
- gather(source);
45
- const unique = (name) => {
46
- let candidate = name;
47
- for (let index = 2; identifiers.has(candidate); index += 1) candidate = `${name}${index}`;
48
- identifiers.add(candidate);
49
- return candidate;
129
+ const gather = (node) => {
130
+ if (ts.isIdentifier(node)) identifiers.add(node.text);
131
+ ts.forEachChild(node, gather);
50
132
  };
51
- const clientImports = imports.filter((node) => ts.isStringLiteral(node.moduleSpecifier)
52
- && node.moduleSpecifier.text.startsWith('.')
53
- && [clientPath, `${clientPath}/index`, `${clientPath}/index.js`].includes(path.resolve(path.dirname(filename), node.moduleSpecifier.text)));
54
- const binding = (nodes, name) => nodes.flatMap((node) => !node.importClause?.isTypeOnly && node.importClause?.namedBindings && ts.isNamedImports(node.importClause.namedBindings)
55
- ? [...node.importClause.namedBindings.elements] : [])
56
- .find((element) => !element.isTypeOnly && (element.propertyName || element.name).text === name)?.name.text;
57
- if (imports.some((node) => !clientImports.includes(node) && binding([node], 'useOtaUpdates'))) {
58
- fail('an existing useOtaUpdates import cannot be resolved to the generated ota-client; use a relative import to ota-client so its options can be preserved');
59
- }
60
- const importedHook = binding(clientImports, 'useOtaUpdates');
61
- const importedGate = binding(clientImports, 'OtaUpdateGate');
62
- const importedCreate = binding(imports.filter((node) => node.moduleSpecifier.text === 'react'), 'createElement');
63
- const importedNames = new Set([importedHook, importedGate, importedCreate].filter(Boolean));
64
- const checkBinding = (name) => {
65
- if (!name) return;
66
- if (ts.isIdentifier(name) && importedNames.has(name.text)) fail(`the imported OTA/React binding ${name.text} is shadowed in the component`);
67
- if (ts.isObjectBindingPattern(name) || ts.isArrayBindingPattern(name)) for (const element of name.elements) {
68
- if (ts.isBindingElement(element)) checkBinding(element.name);
69
- }
133
+ gather(source);
134
+ let name = existingName || "OtaUpdates";
135
+ if (!existingName)
136
+ for (let i = 2; identifiers.has(name); i++) name = `OtaUpdates${i}`;
137
+ const watched = new Set(
138
+ [hookName, gateName, createName, existingName].filter(Boolean),
139
+ );
140
+ const checkBinding = (node) => {
141
+ if (!node) return;
142
+ if (ts.isIdentifier(node) && watched.has(node.text))
143
+ fail(`imported OTA/React binding ${node.text} is shadowed`);
144
+ if (ts.isObjectBindingPattern(node) || ts.isArrayBindingPattern(node))
145
+ for (const element of node.elements)
146
+ if (ts.isBindingElement(element)) checkBinding(element.name);
70
147
  };
71
148
  for (const parameter of component.parameters) checkBinding(parameter.name);
72
- const hookName = importedHook || unique('useOtaUpdates');
73
- const gateName = importedGate || unique('OtaUpdateGate');
74
- const createName = importedCreate || unique('createElement');
75
- const newline = text.includes('\r\n') ? '\r\n' : '\n';
76
- const edits = [];
77
- let controllerName;
78
- let existingHookCall;
79
149
  const returns = [];
150
+ let hook;
80
151
  const inspect = (node) => {
81
- if (ts.isVariableDeclaration(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) checkBinding(node.name);
152
+ if (
153
+ ts.isVariableDeclaration(node) ||
154
+ ts.isFunctionDeclaration(node) ||
155
+ ts.isClassDeclaration(node)
156
+ )
157
+ checkBinding(node.name);
82
158
  if (ts.isFunctionLike(node)) return;
83
- if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === importedHook) {
84
- if (existingHookCall) fail('multiple update hooks in the root component');
85
- existingHookCall = node;
86
- }
87
159
  if (ts.isReturnStatement(node)) returns.push(node);
160
+ if (
161
+ ts.isCallExpression(node) &&
162
+ ts.isIdentifier(node.expression) &&
163
+ node.expression.text === hookName
164
+ ) {
165
+ if (hook) fail("multiple update hooks in the root");
166
+ hook = node;
167
+ }
88
168
  ts.forEachChild(node, inspect);
89
169
  };
90
170
  inspect(component.body);
91
- if (existingHookCall) {
92
- if (returns.some((statement) => statement.pos < existingHookCall.pos)) fail('the existing hook appears after an early return');
93
- const owner = existingHookCall.parent;
94
- if (ts.isVariableDeclaration(owner) && ts.isIdentifier(owner.name) && owner.parent.parent.parent === component.body) {
95
- controllerName = owner.name.text;
96
- } else if (ts.isExpressionStatement(owner) && owner.parent === component.body) {
97
- controllerName = unique('otaUpdates');
98
- edits.push({ start: owner.getStart(source), end: owner.getStart(source), content: `const ${controllerName} = ` });
99
- } else fail('the existing update hook must be called unconditionally at the top of the root component');
100
- } else {
101
- controllerName = unique('otaUpdates');
171
+ const edits = [];
172
+ let props = "autoCheck autoUpdate={false} autoReload={false}";
173
+ let controller;
174
+ let hookStatement;
175
+ if (hook) {
176
+ if (returns.some((node) => node.pos < hook.pos))
177
+ fail("the existing hook appears after an early return");
178
+ const parent = hook.parent;
179
+ if (
180
+ ts.isVariableDeclaration(parent) &&
181
+ ts.isIdentifier(parent.name) &&
182
+ parent.parent.parent.parent === component.body &&
183
+ parent.parent.declarations.length === 1
184
+ ) {
185
+ controller = parent.name.text;
186
+ hookStatement = parent.parent.parent;
187
+ } else if (
188
+ ts.isExpressionStatement(parent) &&
189
+ parent.parent === component.body
190
+ )
191
+ hookStatement = parent;
192
+ else fail("the existing hook must be unconditional at the top level");
193
+ if (hook.arguments.length > 1 || hook.arguments.some(ts.isSpreadElement)) {
194
+ fail("unsupported hook arguments");
195
+ }
196
+ props = "autoCheck={false}";
197
+ let replacement = "";
198
+ if (hook.arguments[0]) {
199
+ let optionsName = "otaOptions";
200
+ for (let i = 2; identifiers.has(optionsName); i++)
201
+ optionsName = `otaOptions${i}`;
202
+ let inputName = "providedOtaOptions";
203
+ for (
204
+ let i = 2;
205
+ identifiers.has(inputName) || inputName === optionsName;
206
+ i++
207
+ )
208
+ inputName = `providedOtaOptions${i}`;
209
+ let autoCheckName = "otaAutoCheck";
210
+ for (let i = 2; identifiers.has(autoCheckName); i++)
211
+ autoCheckName = `otaAutoCheck${i}`;
212
+ replacement = `const ${inputName} = ${hook.arguments[0].getText(source)};${newline}const { autoCheck: ${autoCheckName} = false, ...${optionsName} } = ${inputName} ?? {};${newline}`;
213
+ props = `{...${optionsName}} autoCheck={${autoCheckName}}`;
214
+ }
215
+ edits.push({
216
+ start: hookStatement.getStart(source),
217
+ end: hookStatement.end,
218
+ content: replacement,
219
+ });
102
220
  }
103
- const hook = `const ${controllerName} = ${hookName}({ autoCheck: true, autoUpdate: false, autoReload: false });`;
104
- const wrap = (expression) => {
105
- const unwrapped = unwrap(expression);
106
- if (unwrapped && ts.isCallExpression(unwrapped) && ts.isIdentifier(unwrapped.expression) && unwrapped.expression.text === createName
107
- && unwrapped.arguments[0] && ts.isIdentifier(unwrapped.arguments[0]) && unwrapped.arguments[0].text === gateName) return;
108
- if (unwrapped && (ts.isJsxElement(unwrapped) || ts.isJsxSelfClosingElement(unwrapped))
109
- && (unwrapped.openingElement?.tagName || unwrapped.tagName)?.getText(source) === gateName) return;
110
- if (!expression) return;
111
- edits.push({ start: expression.getStart(source), end: expression.getStart(source), content: `${createName}(${gateName}, { controller: ${controllerName} }, ` });
112
- edits.push({ start: expression.end, end: expression.end, content: ')' });
221
+ const tagName = (node) =>
222
+ (node.openingElement?.tagName || node.tagName)?.getText(source);
223
+ const hasComponent = (node) => {
224
+ node = unwrap(node);
225
+ if (!node) return false;
226
+ if (
227
+ (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node)) &&
228
+ tagName(node) === existingName
229
+ )
230
+ return true;
231
+ if (ts.isJsxElement(node) || ts.isJsxFragment(node))
232
+ return node.children.some((child) => hasComponent(child));
233
+ if (ts.isJsxExpression(node)) return hasComponent(node.expression);
234
+ return false;
235
+ };
236
+ const containsComponent = (node) => {
237
+ if (!node) return false;
238
+ if (
239
+ (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node)) &&
240
+ tagName(node) === existingName
241
+ )
242
+ return true;
243
+ return ts.forEachChild(node, containsComponent) || false;
113
244
  };
114
- if (ts.isBlock(component.body)) {
115
- if (!existingHookCall) {
116
- let at = component.body.getStart(source) + 1;
117
- for (const statement of component.body.statements) {
245
+ const obsolete = new Set([hookName, gateName, createName].filter(Boolean));
246
+ const expressions = ts.isBlock(component.body)
247
+ ? returns.map((node) => ({ node, expression: node.expression }))
248
+ : [{ expression: component.body }];
249
+ if (!expressions.length) fail("the root has no return statement");
250
+ const legacyReferences = new Set();
251
+ for (const { node, expression } of expressions) {
252
+ if (hasComponent(expression)) {
253
+ if (hook)
254
+ fail(
255
+ "both a root hook and OtaUpdates are present; consolidate their options manually",
256
+ );
257
+ continue;
258
+ }
259
+ if (containsComponent(expression))
260
+ fail(
261
+ "an existing OtaUpdates is conditional or nested in a render callback; keep its placement and integrate manually",
262
+ );
263
+ let child = unwrap(expression);
264
+ if (
265
+ child &&
266
+ ts.isCallExpression(child) &&
267
+ ts.isIdentifier(child.expression) &&
268
+ child.expression.text === createName &&
269
+ child.arguments[0]?.getText(source) === gateName
270
+ ) {
271
+ const settings = child.arguments[1];
272
+ if (
273
+ !hook ||
274
+ !settings ||
275
+ !ts.isObjectLiteralExpression(settings) ||
276
+ settings.properties.length !== 1 ||
277
+ !ts.isPropertyAssignment(settings.properties[0]) ||
278
+ settings.properties[0].name.getText(source) !== "controller" ||
279
+ settings.properties[0].initializer.getText(source) !== controller ||
280
+ child.arguments.length > 3
281
+ )
282
+ fail("custom legacy gate needs manual migration");
283
+ legacyReferences.add(settings.properties[0].initializer);
284
+ child = unwrap(child.arguments[2]);
285
+ } else if (
286
+ child &&
287
+ (ts.isJsxElement(child) || ts.isJsxSelfClosingElement(child)) &&
288
+ tagName(child) === gateName
289
+ ) {
290
+ const opening = child.openingElement || child;
291
+ const attrs = opening.attributes.properties;
292
+ if (
293
+ !hook ||
294
+ attrs.length !== 1 ||
295
+ !ts.isJsxAttribute(attrs[0]) ||
296
+ attrs[0].name.text !== "controller" ||
297
+ !attrs[0].initializer ||
298
+ !ts.isJsxExpression(attrs[0].initializer) ||
299
+ attrs[0].initializer.expression?.getText(source) !== controller
300
+ )
301
+ fail("custom legacy gate needs manual migration");
302
+ legacyReferences.add(attrs[0].initializer.expression);
303
+ // A fragment preserves all original gate children without retaining the wrapper.
304
+ const children = ts.isJsxElement(child)
305
+ ? text.slice(
306
+ child.openingElement.end,
307
+ child.closingElement.getStart(source),
308
+ )
309
+ : "";
310
+ child = { getText: () => `<>${children}</>` };
311
+ }
312
+ const start = expression?.getStart(source) ?? node.getStart(source);
313
+ const lineStart = text.lastIndexOf("\n", start - 1) + 1;
314
+ const indent = text.slice(lineStart, start).match(/^\s*/)[0];
315
+ let original = child?.getText(source) ?? "null";
316
+ const rendered =
317
+ original === "null" || original === "undefined"
318
+ ? ""
319
+ : `${newline}${indent} ${original.startsWith("<") ? original : `{${original}}`}`;
320
+ const content = `(${newline}${indent} <>${newline}${indent} <${name} ${props} />${rendered}${newline}${indent} </>${newline}${indent})`;
321
+ edits.push(
322
+ expression
323
+ ? { start, end: expression.end, content }
324
+ : { start, end: node.end, content: `return ${content};` },
325
+ );
326
+ }
327
+ if (controller) {
328
+ const inspectReferences = (node) => {
329
+ if (node === hookStatement || legacyReferences.has(node)) return;
330
+ if (ts.isIdentifier(node) && node.text === controller)
331
+ fail(
332
+ "the old controller is used by custom root code; migrate those references manually",
333
+ );
334
+ ts.forEachChild(node, inspectReferences);
335
+ };
336
+ inspectReferences(component.body);
337
+ }
338
+ for (const node of clientImports) {
339
+ if (node.moduleSpecifier.text.endsWith("/index.js")) {
340
+ const specifier = node.moduleSpecifier;
341
+ const quote = text[specifier.getStart(source)];
342
+ edits.push({
343
+ start: specifier.getStart(source),
344
+ end: specifier.end,
345
+ content: `${quote}${specifier.text.slice(0, -"/index.js".length)}${quote}`,
346
+ });
347
+ }
348
+ }
349
+ if (!edits.length) return text;
350
+ if (!existingName) {
351
+ let relative = path
352
+ .relative(path.dirname(filename), clientPath)
353
+ .split(path.sep)
354
+ .join("/");
355
+ if (!relative.startsWith(".")) relative = `./${relative}`;
356
+ let at =
357
+ imports.at(-1)?.end ??
358
+ source.statements[0]?.getStart(source) ??
359
+ text.length;
360
+ if (!imports.length)
361
+ for (const statement of source.statements) {
118
362
  if (!isDirective(statement)) break;
119
363
  at = statement.end;
120
364
  }
121
- edits.push({ start: at, end: at, content: `${newline} ${hook}${newline}` });
122
- }
123
- for (const statement of returns) {
124
- if (statement.expression) wrap(statement.expression);
125
- else edits.push({ start: statement.getStart(source), end: statement.end, content: `return ${createName}(${gateName}, { controller: ${controllerName} }, null);` });
126
- }
127
- if (!returns.length) fail('the root component has no return statement');
128
- } else {
129
- edits.push({ start: component.body.getStart(source), end: component.body.end, content: `{${newline} ${hook}${newline} return ${createName}(${gateName}, { controller: ${controllerName} }, (${component.body.getText(source)}));${newline}}` });
365
+ const specifier = name === "OtaUpdates" ? name : `OtaUpdates as ${name}`;
366
+ edits.push({
367
+ start: at,
368
+ end: at,
369
+ content: `${newline}import { ${specifier} } from '${relative}';${newline}`,
370
+ });
130
371
  }
131
- const newImports = [];
132
- let relative = path.relative(path.dirname(filename), clientPath).split(path.sep).join('/');
133
- if (!relative.startsWith('.')) relative = `./${relative}`;
134
- const specifier = (name, alias) => name === alias ? name : `${name} as ${alias}`;
135
- const missingClientBindings = [];
136
- if (!importedHook) missingClientBindings.push(specifier('useOtaUpdates', hookName));
137
- if (!importedGate) missingClientBindings.push(specifier('OtaUpdateGate', gateName));
138
- if (missingClientBindings.length) newImports.push(`import { ${missingClientBindings.join(', ')} } from '${relative}';`);
139
- if (!importedCreate) newImports.push(`import { ${specifier('createElement', createName)} } from 'react';`);
140
- if (newImports.length) {
141
- let at = imports.at(-1)?.end ?? source.statements[0]?.getStart(source) ?? text.length;
142
- if (!imports.length) for (const statement of source.statements) {
143
- if (!isDirective(statement)) break;
144
- at = statement.end;
372
+ for (const edit of edits.sort((a, b) => b.start - a.start))
373
+ text = text.slice(0, edit.start) + edit.content + text.slice(edit.end);
374
+ // Drop only obsolete imports which no longer have references after migration.
375
+ const updated = ts.createSourceFile(
376
+ filename,
377
+ text,
378
+ ts.ScriptTarget.Latest,
379
+ true,
380
+ );
381
+ const counts = new Map();
382
+ const count = (node) => {
383
+ if (ts.isIdentifier(node))
384
+ counts.set(node.text, (counts.get(node.text) || 0) + 1);
385
+ ts.forEachChild(node, count);
386
+ };
387
+ count(updated);
388
+ const removals = [];
389
+ for (const node of updated.statements.filter(ts.isImportDeclaration)) {
390
+ const clause = node.importClause;
391
+ if (!clause?.namedBindings || !ts.isNamedImports(clause.namedBindings))
392
+ continue;
393
+ const kept = clause.namedBindings.elements.filter(
394
+ (element) =>
395
+ !obsolete.has(element.name.text) ||
396
+ (counts.get(element.name.text) || 0) >
397
+ (element.propertyName?.text === element.name.text ? 2 : 1),
398
+ );
399
+ if (kept.length === clause.namedBindings.elements.length) continue;
400
+ let content = "";
401
+ if (kept.length || clause.name) {
402
+ const bindings = kept.length
403
+ ? `{ ${kept.map((element) => element.getText(updated)).join(", ")} }`
404
+ : "";
405
+ content = `import ${clause.name?.text || ""}${clause.name && bindings ? ", " : ""}${bindings} from ${node.moduleSpecifier.getText(updated)};`;
145
406
  }
146
- edits.push({ start: at, end: at, content: `${newline}${newImports.join(newline)}${newline}` });
407
+ removals.push({ start: node.getStart(updated), end: node.end, content });
408
+ }
409
+ for (const edit of removals.sort((a, b) => b.start - a.start))
410
+ text = text.slice(0, edit.start) + edit.content + text.slice(edit.end);
411
+ return formatRoot(text, filename, newline);
412
+ }
413
+
414
+ function formatRoot(text, filename, newline) {
415
+ const service = ts.createLanguageService({
416
+ getScriptFileNames: () => [filename],
417
+ getScriptVersion: () => "0",
418
+ getScriptSnapshot: (name) =>
419
+ name === filename ? ts.ScriptSnapshot.fromString(text) : undefined,
420
+ getCurrentDirectory: () => path.dirname(filename),
421
+ getCompilationSettings: () => ({ jsx: ts.JsxEmit.ReactJSX }),
422
+ getDefaultLibFileName: () => "lib.d.ts",
423
+ fileExists: (name) => name === filename,
424
+ readFile: (name) => (name === filename ? text : undefined),
425
+ });
426
+ try {
427
+ const edits = service.getFormattingEditsForDocument(filename, {
428
+ ...ts.getDefaultFormatCodeSettings(newline),
429
+ indentSize: 2,
430
+ tabSize: 2,
431
+ convertTabsToSpaces: true,
432
+ newLineCharacter: newline,
433
+ indentStyle: ts.IndentStyle.Smart,
434
+ });
435
+ for (const edit of edits.sort((a, b) => b.span.start - a.span.start))
436
+ text =
437
+ text.slice(0, edit.span.start) +
438
+ edit.newText +
439
+ text.slice(edit.span.start + edit.span.length);
440
+ return text;
441
+ } finally {
442
+ service.dispose();
147
443
  }
148
- for (const edit of edits.sort((a, b) => b.start - a.start)) text = text.slice(0, edit.start) + edit.content + text.slice(edit.end);
149
- return text;
150
444
  }
151
445
 
152
446
  export function planOtaRootHook({ appRoot, originalEntry }) {
153
- const candidates = (base) => suffixes.flatMap((suffix) => extensions.map((extension) => `${base}${suffix}.${extension}`)).filter((name) => fs.existsSync(path.join(appRoot, name)));
154
- const router = originalEntry === 'expo-router/entry';
447
+ const candidates = (base) =>
448
+ suffixes
449
+ .flatMap((suffix) =>
450
+ extensions.map((extension) => `${base}${suffix}.${extension}`),
451
+ )
452
+ .filter((name) => fs.existsSync(path.join(appRoot, name)));
453
+ const router = originalEntry === "expo-router/entry";
155
454
  let roots = [];
156
455
  if (router) {
157
- roots = candidates(fs.existsSync(path.join(appRoot, 'src/app')) ? 'src/app/_layout' : 'app/_layout');
158
- } else if (['__platform_default__', '__app_fallback__', 'node_modules/expo/AppEntry.js', 'expo/AppEntry', 'expo/AppEntry.js'].includes(originalEntry.replace(/^\.\//, ''))) {
456
+ roots = candidates(
457
+ fs.existsSync(path.join(appRoot, "src/app"))
458
+ ? "src/app/_layout"
459
+ : "app/_layout",
460
+ );
461
+ } else if (
462
+ [
463
+ "__platform_default__",
464
+ "__app_fallback__",
465
+ "node_modules/expo/AppEntry.js",
466
+ "expo/AppEntry",
467
+ "expo/AppEntry.js",
468
+ ].includes(originalEntry.replace(/^\.\//, ""))
469
+ ) {
159
470
  // A custom index may register another root; never guess in that case.
160
- if (!candidates('index').length) roots = candidates('App');
471
+ if (!candidates("index").length) roots = candidates("App");
161
472
  }
162
- if (!roots.length) return {
163
- files: [],
164
- warnings: ['The OTA identity/telemetry bootstrap is configured, but no safely identifiable root component was found. Call useOtaUpdates from ota-client in your main layout to enable update orchestration.'],
165
- };
473
+ if (!roots.length)
474
+ return {
475
+ files: [],
476
+ warnings: [
477
+ "The OTA identity/telemetry bootstrap is configured, but no safely identifiable root component was found. Render <OtaUpdates /> from ota-client beside navigation in your main layout to enable update orchestration.",
478
+ ],
479
+ };
166
480
  return {
167
481
  files: roots.map((name) => {
168
482
  const filename = path.join(appRoot, name);
169
- return [name, patchOtaRootHook(fs.readFileSync(filename, 'utf8'), filename, appRoot)];
483
+ return [
484
+ name,
485
+ patchOtaRootHook(fs.readFileSync(filename, "utf8"), filename, appRoot),
486
+ ];
170
487
  }),
171
488
  warnings: [],
172
489
  };