Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

feat(mobile-apps): harden deterministic template preparation (#501)

Shubham Agarwal4d386816052b
diff --git a/.github/workflows/mobile-apps-script-tests.yml b/.github/workflows/mobile-apps-script-tests.yml
index 42bb54002..6cfa2314c 100644
--- a/.github/workflows/mobile-apps-script-tests.yml
+++ b/.github/workflows/mobile-apps-script-tests.yml
@@ -40,3 +40,65 @@ jobs:
shell: bash
working-directory: plugins/mobile-apps
run: node --test scripts/tests/*.test.js
+
+ test-mobile-apps-template:
+ name: test-mobile-apps-template (ubuntu, node 22)
+ runs-on: ubuntu-latest
+ env:
+ POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: "1"
+ steps:
+ - name: checkout
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
+
+ - name: setup-node
+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
+ with:
+ node-version: 22
+
+ - name: install-template-dependencies
+ shell: bash
+ working-directory: plugins/mobile-apps/template
+ run: npm install --no-audit --no-fund
+
+ - name: prepare-and-type-check-template
+ shell: bash
+ working-directory: plugins/mobile-apps/template
+ run: |
+ node - <<'NODE'
+ for (const specifier of [
+ '@microsoft/power-apps-native-host/config/expoConfig',
+ '@microsoft/power-apps-native-host/config/babelConfig',
+ '@microsoft/power-apps-native-host/config/metroConfig',
+ '@microsoft/power-apps-native-host/config/tamaguiConfig',
+ '@microsoft/power-apps-native-host/config/tsconfig',
+ ]) {
+ require.resolve(specifier);
+ }
+ NODE
+ node ../scripts/prepare-mobile-template.js \
+ --working-dir . \
+ --display-name "Template Quality Probe" \
+ --slug "template-quality-probe"
+ node - <<'NODE'
+ const fs = require('fs');
+ const files = {
+ 'src/components/AliasProbe.ts': 'export const componentAliasProbe = 1;\n',
+ 'src/native/aliasProbe.ts': 'export const nativeAliasProbe = 2;\n',
+ 'src/generated/services/AliasProbe.ts': 'export const generatedAliasProbe = 3;\n',
+ 'src/alias-resolution-probe.ts': [
+ "import { componentAliasProbe } from '@/components/AliasProbe';",
+ "import { nativeAliasProbe } from '@/native/aliasProbe';",
+ "import { generatedAliasProbe } from '@/generated/services/AliasProbe';",
+ 'export const aliasProbe = componentAliasProbe + nativeAliasProbe + generatedAliasProbe;',
+ '',
+ ].join('\n'),
+ };
+ for (const [file, content] of Object.entries(files)) {
+ fs.mkdirSync(require('path').dirname(file), { recursive: true });
+ fs.writeFileSync(file, content);
+ }
+ NODE
+ npx tsc --noEmit
+ node ../scripts/validate-mobile-files.js \
+ --project-root . \
+ --all-source
diff --git a/plugins/mobile-apps/AGENTS.md b/plugins/mobile-apps/AGENTS.md
index 9ec07a11c..5e21e4922 100644
--- a/plugins/mobile-apps/AGENTS.md
+++ b/plugins/mobile-apps/AGENTS.md
@@ -38,10 +38,10 @@ The Expo template snapshot ships bundled inside this plugin at `template/`. It i
|---|---|
| `app.config.js`: `name`, `slug` | Replace `'Power Apps Dev Player'` / `'powerapps-dev-player'` with wizard answers |
| `package.json`: `name` | Replace `'powerapps-dev-app'` with the app slug |
-| Delete `power.config.json` | `npx power-apps init` regenerates for the user's environment |
-| Reset `src/generated/` + `src/hooks/` | Remove any example stubs — `npx power-apps add-data-source` repopulates |
-| `app/_layout.tsx`: add `tamaguiConfig` + `defaultTheme` props | Screens render under brand tokens, not upstream defaults |
-| `tsconfig.json`: merge `@/` path aliases | `@/components`, `@/hooks`, `@/utils`, `@/tokens`, `@/generated`, `@/native` resolve |
+| Remove an empty placeholder `power.config.json` | Preserve populated environment configuration; `npx power-apps init` creates a missing file |
+| Remove legacy example hooks and query-client files | Preserve every artifact under `src/generated/` |
+| `app/_layout.tsx`: add `tamaguiConfig` + `defaultTheme` | Use host light/dark defaults until generated brand themes are explicitly wired |
+| `tsconfig.json`: verify the host base | Package shims and `@/` aliases remain centralized in the native host |
Do not add preparation rewrites for `scheme`, `package`, `bundleIdentifier`, `src/playerConfig.ts`, `fingerprint.config.js`, or `native-runtime.json` unless those files exist in the synced main template.
diff --git a/plugins/mobile-apps/agents/screen-builder.md b/plugins/mobile-apps/agents/screen-builder.md
index 6bc996f84..684326fa8 100644
--- a/plugins/mobile-apps/agents/screen-builder.md
+++ b/plugins/mobile-apps/agents/screen-builder.md
@@ -715,7 +715,12 @@ Dynamic token values are not always type-checked; unknown aliases can render lit
Read: <working_dir>/tamagui.config.ts
```
-Require Tamagui 2, `@tamagui/config/v5`, both customization markers, and marker-based `customConfig`. Otherwise return `BLOCKED: stale Tamagui template; expected Tamagui 2 with Config v5`.
+Require Tamagui 2, both customization markers,
+`createPowerAppsTamaguiConfig`, and marker-based `customConfig`. The default
+`customConfig` may be empty because the native host supplies Config v5,
+animations, semantic aliases, contrast handling, and the `fonts.mono`
+fallback. Otherwise return `BLOCKED: stale Tamagui template; expected the
+native-host Tamagui config factory`.
Read the effective customizations:
@@ -724,7 +729,12 @@ Read the effective customizations:
- `customConfig.fonts` — added families such as `heading`, `body`, and `mono`.
- `customConfig.themes` — light/dark semantic overrides.
-Config v5 supplies the standard theme values listed below. Use custom token aliases only when `customConfig` defines them; never infer aliases from naming conventions.
+The native-host factory always supplies this semantic contract:
+`$surface0`-`$surface3`, `$mediaSurface`, `$accentDeep`, `$accentBase`,
+`$accentSoft`, `$accentOnAccent`, `$text0`-`$text3`, all documented
+`$status*` foreground/background pairs, and `$mono`. Config v5 supplies the
+standard numbered values. Use other custom aliases only when `customConfig`
+defines them; never infer additional aliases from naming conventions.
**Forbidden — do NOT use any of these in your TSX, ever:**
@@ -733,7 +743,7 @@ Config v5 supplies the standard theme values listed below. Use custom token alia
| `color="$color"` (no number) | Renders as literal string → invisible text | `color="$color12"` (text), `color="$color9"` (muted) |
| `bg="$bg"` (no number) | Same — silently broken | `bg="$background"` or `bg="$color2"` |
| `color="$primary"` | Stock Tamagui has no `$primary`; only brand configs may | `color="$accentBase"` if defined, else `color="$blue10"` |
-| Any `$<name>` you didn't see in `tamagui.config.ts` | Will render as the literal `'$<name>'` string | Read the config and pick a real token |
+| Any `$<name>` outside the native-host contract and not defined in `tamagui.config.ts` | Will render as the literal `'$<name>'` string | Use a host semantic token, a Config v5 standard value, or a visible app-defined token |
| Raw hex (`#1a1a1a`, `#fff`) | Bypasses the design system; breaks dark mode | Always a token |
**Config v5 props:** `onlyAllowShorthands` is enabled. Use v5 shorthands (`bg`, `items`, `justify`, `rounded`, `text`, `self`, `grow`/`shrink`, min/max, spacing, and edge shorthands) whenever defined. Keep unaliased longhands such as `flex`, `width`, `height`, `color`, `position`, `fontSize`, and `fontWeight`. Never use v4 aliases (`ai`, `jc`, `br`, `f`, `w`, `h`, `col`, `pos`, `ta`, `als`, `tt`, `ls`) or a longhand that v5 aliases.
diff --git a/plugins/mobile-apps/docs/base-template-quality-fixes.md b/plugins/mobile-apps/docs/base-template-quality-fixes.md
new file mode 100644
index 000000000..635317b2b
--- /dev/null
+++ b/plugins/mobile-apps/docs/base-template-quality-fixes.md
@@ -0,0 +1,81 @@
+# Mobile Base Template Quality Contracts
+
+The Mobile Apps plug-in ships a deterministic Expo template contract so a new
+application reaches planning and screen generation from a clean,
+production-ready baseline. These rules apply to the bundled template and to
+`/create-mobile-app`.
+
+## Visual and Runtime Baseline
+
+- The native-host Tamagui factory always exposes semantic surfaces, media,
+ accents, text hierarchy, status foreground/background pairs, and a
+ `fonts.mono` role in both light and dark themes.
+- Shared components use literal-safe semantic tokens, minimum touch targets,
+ accessible roles and labels, selected-state semantics, and readable
+ on-accent foregrounds.
+- The starter home, login, and OAuth callback routes use semantic tokens,
+ Ionicons, and route-owned safe-area edges.
+- The root layout owns `SafeAreaProvider`, host light/dark theme selection, the
+ project Tamagui config, generated schema wiring, and the optional offline
+ profile. It does not wrap the router slot in `SafeAreaView`; each rendered
+ route owns its visible edges to prevent double insets.
+- OAuth callback replacement is guarded so React development effects cannot
+ trigger duplicate navigation.
+
+## Deterministic Template Preparation
+
+`scripts/prepare-mobile-template.js` is the sole Step 5 mutation path. It:
+
+1. Updates the display name and slug.
+2. Removes only an empty placeholder `power.config.json`.
+3. Removes recognized legacy example hooks and the obsolete app-owned query
+ client.
+4. Creates shared source directories and copies approved helpers only when a
+ destination is missing.
+5. Verifies that `tsconfig.json` inherits package shims and shared-code aliases
+ from `@microsoft/power-apps-native-host/config/tsconfig`.
+6. Structurally adds missing root provider, theme, Tamagui, and safe-area
+ wiring without replacing custom navigation or unrelated providers.
+7. Verifies postconditions and fails for unsupported layouts or dangling
+ legacy imports.
+
+The script is idempotent. Existing helper bytes, provider props, custom
+nesting, `offlineProfile`, and generation-boundary `@ts-ignore` comments are
+preserved. Failed preparation rolls back every touched file, including deleted
+placeholder or legacy files.
+
+## Generated-File Ownership
+
+Template preparation never creates, resets, or deletes `src/generated/`.
+Models, services, connector schemas, and barrels are owned exclusively by
+Power Apps data-source and schema-generation commands. This keeps generated
+artifacts compatible with protected-path validation and prevents hand-written
+stubs from masking incomplete initialization.
+
+## Lifecycle and Approval Safety
+
+The app instance identity is minted only after `proceed`, so `edit` and `abort`
+leave the fresh template unchanged. If a populated `power.config.json` already
+targets the approved environment, initialization is verified and skipped
+rather than invoking the CLI over an existing config.
+
+Step 3 writes `native-app-plan.md` before Step 5. The preparation gate therefore
+allows that approved plan while still rejecting created-app markers:
+`memory-bank.md`, `.datamodel-manifest.json`, and generated service files.
+
+## Validation Portability
+
+`validate-mobile-files.js --all-source` validates all TypeScript source under
+an application's complete `app/` tree and non-generated `src/` tree, plus root
+TypeScript configuration files. Only CLI-owned `src/generated/` is excluded; a
+route folder named `app/generated/` remains in scope. Mobile CI covers:
+
+- deterministic preparation and rerun idempotency;
+- root-layout import-only, wrapper-only, already-correct, and custom-nesting
+ states;
+- semantic token and font completeness;
+- shared component accessibility and contrast contracts;
+- pristine route safe-area and icon rules;
+- generated-directory ownership;
+- full template dependency installation, TypeScript compilation, and
+ all-source mobile validation.
diff --git a/plugins/mobile-apps/hooks/validate-navigation-idempotency.js b/plugins/mobile-apps/hooks/validate-navigation-idempotency.js
index a9e5a6e65..df5e98855 100644
--- a/plugins/mobile-apps/hooks/validate-navigation-idempotency.js
+++ b/plugins/mobile-apps/hooks/validate-navigation-idempotency.js
@@ -112,12 +112,25 @@ function hasNavigation(content) {
function hasNavigationTapGuard(content) {
const lockMention = /\bisNavigating\b/.test(content);
- if (!lockMention) return false;
+ if (lockMention) {
+ const earlyReturn = /if\s*\(\s*isNavigating\s*\)\s*return/.test(content);
+ const setTrue = /setIsNavigating\s*\(\s*true\s*\)/.test(content);
+ const setFalse = /setIsNavigating\s*\(\s*false\s*\)/.test(content);
+ if (earlyReturn && setTrue && setFalse) return true;
+ }
- const earlyReturn = /if\s*\(\s*isNavigating\s*\)\s*return/.test(content);
- const setTrue = /setIsNavigating\s*\(\s*true\s*\)/.test(content);
- const setFalse = /setIsNavigating\s*\(\s*false\s*\)/.test(content);
- return earlyReturn && setTrue && setFalse;
+ const refDeclarations = [...content.matchAll(
+ /\bconst\s+([A-Za-z_$][\w$]*)\s*=\s*useRef\s*(?:<[^>]+>)?\(\s*false\s*\)/g,
+ )];
+ return refDeclarations.some((match) => {
+ const refName = match[1].replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ const earlyReturn = new RegExp(`if\\s*\\(\\s*${refName}\\.current\\s*\\)\\s*return`).test(content);
+ const setTrue = new RegExp(`${refName}\\.current\\s*=\\s*true`).test(content);
+ const setFalse = new RegExp(`${refName}\\.current\\s*=\\s*false`).test(content);
+ const terminalReplaceOnly = /router\.replace\s*\(/.test(content)
+ && !/router\.(?:push|navigate)\s*\(/.test(content);
+ return earlyReturn && setTrue && (setFalse || terminalReplaceOnly);
+ });
}
function buildBlockMessage(filePath, errors, warnings) {
@@ -140,7 +153,7 @@ function buildBlockMessage(filePath, errors, warnings) {
lines.push('Required fixes:');
lines.push(' - Singleton routes must use `router.navigate(...)`, not `router.push(...)`.');
lines.push(' - Async save flows must use a submit lock (`isSubmitting` or `isPending`) and disabled busy CTA.');
- lines.push(' - Primary navigation actions should use an `isNavigating` lock to prevent iOS duplicate transitions.');
+ lines.push(' - Primary navigation actions should use an `isNavigating` lock or a ref guard that resets on focus/failure; terminal replace-only callbacks may remain one-shot.');
return lines.join('\n');
}
@@ -188,7 +201,7 @@ if (require.main === module) {
}
if (hasNavigation(content) && !hasNavigationTapGuard(content)) {
- warnings.push('Navigation calls found with no clear `isNavigating` duplicate-tap guard.');
+ warnings.push('Navigation calls found with no clear state lock, resettable ref guard, or terminal replace-only guard.');
}
if (errors.length > 0) {
diff --git a/plugins/mobile-apps/scripts/prepare-mobile-template.js b/plugins/mobile-apps/scripts/prepare-mobile-template.js
new file mode 100644
index 000000000..4a2128746
--- /dev/null
+++ b/plugins/mobile-apps/scripts/prepare-mobile-template.js
@@ -0,0 +1,621 @@
+#!/usr/bin/env node
+
+'use strict';
+
+const fs = require('fs');
+const path = require('path');
+
+const REQUIRED_FILES = [
+ 'package.json',
+ 'app.config.js',
+ 'auth.config.json',
+ 'tamagui.config.ts',
+ 'app/_layout.tsx',
+ 'tsconfig.json',
+];
+
+const HOST_TSCONFIG = '@microsoft/power-apps-native-host/config/tsconfig';
+
+const SHARED_FILES = [
+ ['components/index.tsx', 'src/components/index.tsx'],
+ ['hooks/index.ts', 'src/hooks/index.ts'],
+ ['hooks/useCursorListData.ts', 'src/hooks/useCursorListData.ts'],
+ ['hooks/useListData.ts', 'src/hooks/useListData.ts'],
+ ['hooks/useSearchFilter.ts', 'src/hooks/useSearchFilter.ts'],
+ ['utils/index.ts', 'src/utils/index.ts'],
+ ['utils/formatters.ts', 'src/utils/formatters.ts'],
+ ['utils/text.ts', 'src/utils/text.ts'],
+ ['utils/choices.ts', 'src/utils/choices.ts'],
+ ['utils/dataverse.ts', 'src/utils/dataverse.ts'],
+ ['tokens/index.ts', 'src/tokens/index.ts'],
+];
+
+const LEGACY_EXAMPLE_FILES = [
+ 'src/hooks/useContacts.ts',
+ 'src/hooks/useAccounts.ts',
+ 'src/hooks/useUserProfile.ts',
+ 'src/queryClient.ts',
+];
+
+function escapeRegExp(value) {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function singleQuoted(value) {
+ return `'${String(value)
+ .replace(/\\/g, '\\\\')
+ .replace(/\r/g, '\\r')
+ .replace(/\n/g, '\\n')
+ .replace(/\u2028/g, '\\u2028')
+ .replace(/\u2029/g, '\\u2029')
+ .replace(/'/g, "\\'")}'`;
+}
+
+function readJson(filePath) {
+ try {
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
+ } catch (error) {
+ throw new Error(`Could not parse ${filePath}: ${error.message}`);
+ }
+}
+
+function writeJson(filePath, value) {
+ fs.writeFileSync(filePath, `${JSON.stringify(value, null, 2)}\n`);
+}
+
+function assertFreshTemplate(projectRoot) {
+ const missing = REQUIRED_FILES.filter((relativePath) => (
+ !fs.existsSync(path.join(projectRoot, relativePath))
+ ));
+ if (missing.length > 0) {
+ throw new Error(`Not a supported Expo standalone template; missing: ${missing.join(', ')}`);
+ }
+
+ if (!fs.existsSync(path.join(projectRoot, 'node_modules', 'expo'))) {
+ throw new Error('Template dependencies are not installed; node_modules/expo is missing');
+ }
+
+ const createdMarkers = [
+ 'memory-bank.md',
+ '.datamodel-manifest.json',
+ ].filter((relativePath) => fs.existsSync(path.join(projectRoot, relativePath)));
+
+ const generatedServices = path.join(projectRoot, 'src', 'generated', 'services');
+ if (
+ fs.existsSync(generatedServices)
+ && fs.readdirSync(generatedServices).some((name) => name.endsWith('.ts'))
+ ) {
+ createdMarkers.push('src/generated/services/*.ts');
+ }
+
+ if (createdMarkers.length > 0) {
+ throw new Error(`Template already contains created-app markers: ${createdMarkers.join(', ')}`);
+ }
+
+ verifyHostTsconfig(projectRoot);
+}
+
+function updateIdentity(projectRoot, displayName, slug) {
+ const appConfigPath = path.join(projectRoot, 'app.config.js');
+ let appConfig = fs.readFileSync(appConfigPath, 'utf8');
+ const namePattern = /(const APP_NAME\s*=\s*process\.env\.APP_DISPLAY_NAME\s*\|\|\s*)'(?:\\.|[^'\\])*';/;
+ const slugPattern = /(const APP_SLUG\s*=\s*process\.env\.APP_SLUG\s*\|\|\s*)'(?:\\.|[^'\\])*';/;
+
+ if (!namePattern.test(appConfig) || !slugPattern.test(appConfig)) {
+ throw new Error('app.config.js does not contain the supported APP_NAME and APP_SLUG declarations');
+ }
+
+ appConfig = appConfig
+ .replace(namePattern, (_match, prefix) => `${prefix}${singleQuoted(displayName)};`)
+ .replace(slugPattern, (_match, prefix) => `${prefix}${singleQuoted(slug)};`);
+ fs.writeFileSync(appConfigPath, appConfig);
+
+ const packagePath = path.join(projectRoot, 'package.json');
+ const packageJson = readJson(packagePath);
+ packageJson.name = slug;
+ writeJson(packagePath, packageJson);
+}
+
+function removeEmptyPowerConfig(projectRoot) {
+ const powerConfigPath = path.join(projectRoot, 'power.config.json');
+ if (!fs.existsSync(powerConfigPath)) return false;
+
+ const powerConfig = readJson(powerConfigPath);
+ if (typeof powerConfig.environmentId === 'string' && powerConfig.environmentId.trim()) {
+ return false;
+ }
+
+ fs.unlinkSync(powerConfigPath);
+ return true;
+}
+
+function removeLegacyExamples(projectRoot) {
+ const removed = [];
+ for (const relativePath of LEGACY_EXAMPLE_FILES) {
+ const filePath = path.join(projectRoot, relativePath);
+ if (!fs.existsSync(filePath)) continue;
+ fs.unlinkSync(filePath);
+ removed.push(relativePath);
+ }
+ return removed;
+}
+
+function copySharedFiles(projectRoot, samplesRoot) {
+ for (const directory of ['components', 'hooks', 'utils', 'tokens', 'native']) {
+ fs.mkdirSync(path.join(projectRoot, 'src', directory), { recursive: true });
+ }
+
+ const copied = [];
+ const preserved = [];
+ for (const [sampleRelativePath, destinationRelativePath] of SHARED_FILES) {
+ const sourcePath = path.join(samplesRoot, sampleRelativePath);
+ const destinationPath = path.join(projectRoot, destinationRelativePath);
+ if (!fs.existsSync(sourcePath)) {
+ throw new Error(`Shared template helper is missing: ${sourcePath}`);
+ }
+ if (fs.existsSync(destinationPath)) {
+ preserved.push(destinationRelativePath);
+ continue;
+ }
+ fs.copyFileSync(sourcePath, destinationPath);
+ copied.push(destinationRelativePath);
+ }
+
+ return { copied, preserved };
+}
+
+function verifyHostTsconfig(projectRoot) {
+ const tsconfigPath = path.join(projectRoot, 'tsconfig.json');
+ const tsconfig = readJson(tsconfigPath);
+ const inheritedConfigs = Array.isArray(tsconfig.extends)
+ ? tsconfig.extends
+ : [tsconfig.extends];
+ if (!inheritedConfigs.includes(HOST_TSCONFIG)) {
+ throw new Error(`tsconfig.json must extend ${HOST_TSCONFIG}`);
+ }
+}
+
+function ensureNamedImports(source, moduleName, requiredNames) {
+ const modulePattern = escapeRegExp(moduleName);
+ const importPattern = new RegExp(
+ `import\\s+(?!type\\b)(?:([A-Za-z_$][\\w$]*)\\s*,\\s*)?\\{([^}]*)\\}\\s*from\\s*['"]${modulePattern}['"][ \\t]*;?`,
+ );
+ const match = source.match(importPattern);
+
+ if (!match) {
+ return `import { ${requiredNames.join(', ')} } from '${moduleName}';\n${source}`;
+ }
+
+ const existingNames = match[2]
+ .split(',')
+ .map((entry) => entry.trim().split(/\s+as\s+/)[0])
+ .filter(Boolean);
+ const missingNames = requiredNames.filter((name) => !existingNames.includes(name));
+ if (missingNames.length === 0) return source;
+
+ const updatedNames = [...match[2].split(',').map((entry) => entry.trim()).filter(Boolean), ...missingNames];
+ const defaultImport = match[1] ? `${match[1]}, ` : '';
+ const replacement = `import ${defaultImport}{\n ${updatedNames.join(',\n ')},\n} from '${moduleName}';`;
+ return source.replace(importPattern, replacement);
+}
+
+function defaultImportPattern(moduleName, localName) {
+ const modulePattern = escapeRegExp(moduleName);
+ return new RegExp(
+ `import\\s+${escapeRegExp(localName)}\\s*(?:,\\s*(?:\\{[^}]*\\}|\\*\\s+as\\s+[A-Za-z_$][\\w$]*))?\\s+from\\s*['"]${modulePattern}['"][ \\t]*;?`,
+ );
+}
+
+function ensureDefaultImport(source, moduleName, localName) {
+ const importPattern = defaultImportPattern(moduleName, localName);
+ if (importPattern.test(source)) return source;
+ return `import ${localName} from '${moduleName}';\n${source}`;
+}
+
+function ensureColorSchemeHook(source) {
+ if (/\b(?:const|let)\s+colorScheme\s*=\s*useColorScheme\s*\(\s*\)/.test(source)) {
+ return source;
+ }
+
+ const rootPattern = /(export\s+default\s+function\s+RootLayout\s*\([^)]*\)\s*\{)/;
+ if (!rootPattern.test(source)) {
+ throw new Error('app/_layout.tsx must export a supported RootLayout function');
+ }
+ return source.replace(rootPattern, '$1\n const colorScheme = useColorScheme();');
+}
+
+function findJsxOpeningTagEnd(source, startIndex) {
+ let braceDepth = 0;
+ let quote = null;
+
+ for (let index = startIndex; index < source.length; index += 1) {
+ const character = source[index];
+
+ if (quote) {
+ let slashCount = 0;
+ for (let cursor = index - 1; cursor >= 0 && source[cursor] === '\\'; cursor -= 1) {
+ slashCount += 1;
+ }
+ if (character === quote && slashCount % 2 === 0) quote = null;
+ continue;
+ }
+ if (character === '\'' || character === '"' || character === '`') {
+ quote = character;
+ continue;
+ }
+ if (character === '{') {
+ braceDepth += 1;
+ continue;
+ }
+ if (character === '}') {
+ braceDepth -= 1;
+ if (braceDepth < 0) {
+ throw new Error('PowerAppsProvider opening tag contains an unmatched closing brace');
+ }
+ continue;
+ }
+ if (character === '>' && braceDepth === 0) return index;
+ }
+
+ throw new Error('PowerAppsProvider opening tag is not terminated');
+}
+
+function readJsxAttributeValue(source, startIndex) {
+ const opening = source[startIndex];
+ if (opening === '\'' || opening === '"') {
+ for (let index = startIndex + 1; index < source.length; index += 1) {
+ let slashCount = 0;
+ for (let cursor = index - 1; cursor >= 0 && source[cursor] === '\\'; cursor -= 1) {
+ slashCount += 1;
+ }
+ if (source[index] === opening && slashCount % 2 === 0) return index + 1;
+ }
+ throw new Error('PowerAppsProvider opening tag contains an unterminated quoted prop');
+ }
+ if (opening === '{') {
+ let depth = 0;
+ let quote = null;
+ for (let index = startIndex; index < source.length; index += 1) {
+ const character = source[index];
+ if (quote) {
+ let slashCount = 0;
+ for (let cursor = index - 1; cursor >= 0 && source[cursor] === '\\'; cursor -= 1) {
+ slashCount += 1;
+ }
+ if (character === quote && slashCount % 2 === 0) quote = null;
+ continue;
+ }
+ if (character === '\'' || character === '"' || character === '`') {
+ quote = character;
+ } else if (character === '{') {
+ depth += 1;
+ } else if (character === '}') {
+ depth -= 1;
+ if (depth === 0) return index + 1;
+ }
+ }
+ throw new Error('PowerAppsProvider opening tag contains an unterminated expression prop');
+ }
+ let index = startIndex;
+ while (index < source.length && !/\s/.test(source[index])) index += 1;
+ return index;
+}
+
+function getTopLevelJsxAttributes(providerProps) {
+ const attributes = new Map();
+ let index = 0;
+ while (index < providerProps.length) {
+ while (index < providerProps.length && /\s/.test(providerProps[index])) index += 1;
+ if (index >= providerProps.length || providerProps[index] === '/') break;
+ if (providerProps[index] === '{') {
+ index = readJsxAttributeValue(providerProps, index);
+ continue;
+ }
+
+ const nameMatch = providerProps.slice(index).match(/^([A-Za-z_$][\w$:.-]*)/);
+ if (!nameMatch) {
+ index += 1;
+ continue;
+ }
+ const name = nameMatch[1];
+ index += name.length;
+ while (index < providerProps.length && /\s/.test(providerProps[index])) index += 1;
+ if (providerProps[index] !== '=') {
+ attributes.set(name, true);
+ continue;
+ }
+ index += 1;
+ while (index < providerProps.length && /\s/.test(providerProps[index])) index += 1;
+ const valueStart = index;
+ index = readJsxAttributeValue(providerProps, valueStart);
+ attributes.set(name, providerProps.slice(valueStart, index));
+ }
+ return attributes;
+}
+
+function ensureProviderProps(source) {
+ const match = /<PowerAppsProvider\b/.exec(source);
+ if (!match) {
+ throw new Error('app/_layout.tsx does not contain a PowerAppsProvider opening tag');
+ }
+ const tagNameEnd = match.index + match[0].length;
+ const tagEnd = findJsxOpeningTagEnd(source, tagNameEnd);
+ const providerProps = source.slice(tagNameEnd, tagEnd);
+ const providerAttributes = getTopLevelJsxAttributes(providerProps);
+
+ const requiredProps = [
+ ['tamaguiConfig', 'tamaguiConfig={tamaguiConfig}'],
+ ['defaultTheme', "defaultTheme={colorScheme === 'dark' ? 'dark' : 'light'}"],
+ ];
+ const additions = requiredProps
+ .filter(([name]) => !providerAttributes.has(name))
+ .map(([, text]) => text);
+ if (additions.length === 0) return source;
+
+ const indentMatch = source.slice(0, match.index).match(/(^|\n)([ \t]*)[^\n]*$/);
+ const propIndent = `${indentMatch ? indentMatch[2] : ''} `;
+ const existingProps = providerProps.trimEnd();
+ const replacement = `<PowerAppsProvider${existingProps}${existingProps ? '\n' : ' '}${additions
+ .map((prop) => `${propIndent}${prop}`)
+ .join('\n')}\n${indentMatch ? indentMatch[2] : ''}>`;
+ return `${source.slice(0, match.index)}${replacement}${source.slice(tagEnd + 1)}`;
+}
+
+function isWrappedBySafeAreaProvider(source, powerOpenIndex, powerCloseEnd) {
+ const safeOpenIndex = source.lastIndexOf('<SafeAreaProvider', powerOpenIndex);
+ if (safeOpenIndex < 0) return false;
+ const prematureClose = source.indexOf('</SafeAreaProvider>', safeOpenIndex);
+ return prematureClose >= powerCloseEnd;
+}
+
+function ensureSafeAreaProviderWrapper(source) {
+ const powerOpenIndex = source.indexOf('<PowerAppsProvider');
+ const powerClose = '</PowerAppsProvider>';
+ const powerCloseIndex = source.indexOf(powerClose, powerOpenIndex);
+ if (powerOpenIndex < 0 || powerCloseIndex < 0) {
+ throw new Error('app/_layout.tsx must contain a non-self-closing PowerAppsProvider');
+ }
+ const powerCloseEnd = powerCloseIndex + powerClose.length;
+ if (isWrappedBySafeAreaProvider(source, powerOpenIndex, powerCloseEnd)) return source;
+
+ const lineStart = source.lastIndexOf('\n', powerOpenIndex) + 1;
+ const indent = source.slice(lineStart, powerOpenIndex);
+ if (!/^[ \t]*$/.test(indent)) {
+ throw new Error('Could not determine PowerAppsProvider indentation in app/_layout.tsx');
+ }
+
+ const providerBlock = source.slice(powerOpenIndex, powerCloseEnd);
+ // Keep the provider block byte-for-byte intact. Reindenting its inner lines
+ // could change values in multiline template-literal props.
+ const nestedBlock = `${indent}${providerBlock}`;
+ const wrapped = `<SafeAreaProvider>\n${nestedBlock}\n${indent}</SafeAreaProvider>`;
+ return `${source.slice(0, powerOpenIndex)}${wrapped}${source.slice(powerCloseEnd)}`;
+}
+
+function verifyRootLayout(source) {
+ const requiredChecks = [
+ ['SafeAreaProvider import', /import\s+(?!type\b)(?:[A-Za-z_$][\w$]*\s*,\s*)?\{[^}]*\bSafeAreaProvider\b[^}]*\}\s*from\s*['"]react-native-safe-area-context['"]/],
+ ['useColorScheme import', /import\s+(?!type\b)(?:[A-Za-z_$][\w$]*\s*,\s*)?\{[^}]*\buseColorScheme\b[^}]*\}\s*from\s*['"]react-native['"]/],
+ ['colorScheme binding', /\b(?:const|let)\s+colorScheme\s*=\s*useColorScheme\s*\(\s*\)/],
+ ['Tamagui config import', defaultImportPattern('../tamagui.config', 'tamaguiConfig')],
+ ];
+
+ const missing = requiredChecks
+ .filter(([, pattern]) => !pattern.test(source))
+ .map(([label]) => label);
+ const providerMatch = /<PowerAppsProvider\b/.exec(source);
+ if (!providerMatch) {
+ missing.push('PowerAppsProvider opening tag');
+ } else {
+ const tagNameEnd = providerMatch.index + providerMatch[0].length;
+ const tagEnd = findJsxOpeningTagEnd(source, tagNameEnd);
+ const attributes = getTopLevelJsxAttributes(source.slice(tagNameEnd, tagEnd));
+ const providerChecks = [
+ ['Tamagui config provider prop', attributes.get('tamaguiConfig') === '{tamaguiConfig}'],
+ ['default theme provider prop', attributes.has('defaultTheme')],
+ ];
+ missing.push(...providerChecks.filter(([, valid]) => !valid).map(([label]) => label));
+ }
+ if (missing.length > 0) {
+ throw new Error(`Root layout preparation failed postconditions: ${missing.join(', ')}`);
+ }
+
+ const powerOpenIndex = source.indexOf('<PowerAppsProvider');
+ const powerCloseEnd = source.indexOf('</PowerAppsProvider>', powerOpenIndex)
+ + '</PowerAppsProvider>'.length;
+ if (!isWrappedBySafeAreaProvider(source, powerOpenIndex, powerCloseEnd)) {
+ throw new Error('Root layout preparation did not wrap PowerAppsProvider with SafeAreaProvider');
+ }
+
+ if (/<SafeAreaView\b[\s\S]*<Slot\s*\/>/.test(source)) {
+ throw new Error('Root layout must not wrap Slot with SafeAreaView; rendered routes own content edges');
+ }
+}
+
+function prepareRootLayout(projectRoot) {
+ const layoutPath = path.join(projectRoot, 'app', '_layout.tsx');
+ let source = fs.readFileSync(layoutPath, 'utf8');
+
+ source = ensureNamedImports(source, 'react-native', ['useColorScheme']);
+ source = ensureNamedImports(source, 'react-native-safe-area-context', ['SafeAreaProvider']);
+ source = ensureNamedImports(source, '@microsoft/power-apps-native-host', ['PowerAppsProvider']);
+ source = ensureDefaultImport(source, '../tamagui.config', 'tamaguiConfig');
+ source = ensureColorSchemeHook(source);
+ source = ensureProviderProps(source);
+ source = ensureSafeAreaProviderWrapper(source);
+ verifyRootLayout(source);
+
+ fs.writeFileSync(layoutPath, source);
+}
+
+function assertNoDanglingLegacyImports(projectRoot) {
+ const roots = ['app', 'src'];
+ const needles = [
+ 'useContacts',
+ 'useAccounts',
+ 'useUserProfile',
+ 'from "../generated/services',
+ "from '../generated/services",
+ 'from "../generated/models',
+ "from '../generated/models",
+ ];
+ const findings = [];
+
+ function visit(directory) {
+ if (!fs.existsSync(directory)) return;
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
+ const absolutePath = path.join(directory, entry.name);
+ if (entry.isDirectory()) {
+ if (entry.name === 'generated') continue;
+ visit(absolutePath);
+ } else if (entry.name.endsWith('.ts') || entry.name.endsWith('.tsx')) {
+ const source = fs.readFileSync(absolutePath, 'utf8');
+ if (needles.some((needle) => source.includes(needle))) {
+ findings.push(path.relative(projectRoot, absolutePath));
+ }
+ }
+ }
+ }
+
+ roots.forEach((relativePath) => visit(path.join(projectRoot, relativePath)));
+ if (findings.length > 0) {
+ throw new Error(`Legacy example imports remain in: ${findings.join(', ')}`);
+ }
+}
+
+function capturePreparationState(projectRoot) {
+ const relativeFiles = [
+ 'app.config.js',
+ 'package.json',
+ 'power.config.json',
+ 'app/_layout.tsx',
+ ...LEGACY_EXAMPLE_FILES,
+ ...SHARED_FILES.map(([, destinationRelativePath]) => destinationRelativePath),
+ ];
+ const files = new Map();
+
+ for (const relativePath of new Set(relativeFiles)) {
+ const filePath = path.join(projectRoot, relativePath);
+ if (!fs.existsSync(filePath)) {
+ files.set(relativePath, { exists: false });
+ continue;
+ }
+ const stat = fs.lstatSync(filePath);
+ if (!stat.isFile()) {
+ throw new Error(`Template preparation target must be a regular file: ${relativePath}`);
+ }
+ files.set(relativePath, {
+ exists: true,
+ content: fs.readFileSync(filePath),
+ mode: stat.mode,
+ });
+ }
+
+ const directories = ['components', 'hooks', 'utils', 'tokens', 'native']
+ .map((directory) => path.join('src', directory))
+ .map((relativePath) => ({
+ relativePath,
+ existed: fs.existsSync(path.join(projectRoot, relativePath)),
+ }));
+
+ return { directories, files };
+}
+
+function restorePreparationState(projectRoot, state) {
+ for (const [relativePath, snapshot] of state.files) {
+ const filePath = path.join(projectRoot, relativePath);
+ if (snapshot.exists) {
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, snapshot.content);
+ fs.chmodSync(filePath, snapshot.mode);
+ } else if (fs.existsSync(filePath)) {
+ const stat = fs.lstatSync(filePath);
+ if (!stat.isFile()) {
+ throw new Error(`Cannot roll back non-file preparation target: ${relativePath}`);
+ }
+ fs.unlinkSync(filePath);
+ }
+ }
+
+ for (const directory of [...state.directories].reverse()) {
+ if (directory.existed) continue;
+ const directoryPath = path.join(projectRoot, directory.relativePath);
+ if (fs.existsSync(directoryPath) && fs.readdirSync(directoryPath).length === 0) {
+ fs.rmdirSync(directoryPath);
+ }
+ }
+}
+
+function prepareMobileTemplate(options) {
+ const projectRoot = path.resolve(options.workingDir);
+ const samplesRoot = path.resolve(
+ options.samplesRoot || path.join(__dirname, '..', 'shared', 'samples', 'src'),
+ );
+ if (!options.displayName || !options.slug) {
+ throw new Error('displayName and slug are required');
+ }
+
+ assertFreshTemplate(projectRoot);
+ const originalState = capturePreparationState(projectRoot);
+ let removedPowerConfig;
+ let removedLegacyFiles;
+ let sharedFiles;
+ try {
+ updateIdentity(projectRoot, options.displayName, options.slug);
+ removedPowerConfig = removeEmptyPowerConfig(projectRoot);
+ removedLegacyFiles = removeLegacyExamples(projectRoot);
+ sharedFiles = copySharedFiles(projectRoot, samplesRoot);
+ prepareRootLayout(projectRoot);
+ assertNoDanglingLegacyImports(projectRoot);
+ } catch (error) {
+ try {
+ restorePreparationState(projectRoot, originalState);
+ } catch (rollbackError) {
+ throw new Error(`${error.message}; rollback failed: ${rollbackError.message}`);
+ }
+ throw error;
+ }
+
+ return {
+ projectRoot,
+ removedPowerConfig,
+ removedLegacyFiles,
+ copiedSharedFiles: sharedFiles.copied,
+ preservedSharedFiles: sharedFiles.preserved,
+ };
+}
+
+function parseArgs(argv) {
+ const options = {};
+ for (let index = 0; index < argv.length; index += 1) {
+ const argument = argv[index];
+ if (argument === '--working-dir') options.workingDir = argv[++index];
+ else if (argument === '--display-name') options.displayName = argv[++index];
+ else if (argument === '--slug') options.slug = argv[++index];
+ else if (argument === '--samples-root') options.samplesRoot = argv[++index];
+ else throw new Error(`Unknown argument: ${argument}`);
+ }
+ if (!options.workingDir) throw new Error('--working-dir is required');
+ return options;
+}
+
+if (require.main === module) {
+ const result = prepareMobileTemplate(parseArgs(process.argv.slice(2)));
+ process.stdout.write(`${JSON.stringify(result)}\n`);
+}
+
+module.exports = {
+ HOST_TSCONFIG,
+ SHARED_FILES,
+ assertFreshTemplate,
+ copySharedFiles,
+ ensureProviderProps,
+ ensureSafeAreaProviderWrapper,
+ prepareMobileTemplate,
+ prepareRootLayout,
+ removeEmptyPowerConfig,
+ restorePreparationState,
+ updateIdentity,
+ verifyHostTsconfig,
+ verifyRootLayout,
+};
diff --git a/plugins/mobile-apps/scripts/tests/create-mobile-app-quality-contract.test.js b/plugins/mobile-apps/scripts/tests/create-mobile-app-quality-contract.test.js
new file mode 100644
index 000000000..bc32c74dd
--- /dev/null
+++ b/plugins/mobile-apps/scripts/tests/create-mobile-app-quality-contract.test.js
@@ -0,0 +1,47 @@
+'use strict';
+
+const assert = require('assert');
+const fs = require('fs');
+const path = require('path');
+const test = require('node:test');
+
+const skillPath = path.resolve(
+ __dirname,
+ '../../skills/create-mobile-app/SKILL.md',
+);
+const skill = fs.readFileSync(skillPath, 'utf8');
+
+test('template preparation is delegated to the deterministic script', () => {
+ const start = skill.indexOf('### Step 5 — Prepare existing template');
+ const end = skill.indexOf('### Step 6 — Initialize');
+ const step = skill.slice(start, end);
+
+ assert.match(step, /scripts\/prepare-mobile-template\.js/);
+ assert.match(step, /JSON_STRING_OF_WORKING_DIR/);
+ assert.match(step, /JSON_STRING_OF_DISPLAY_NAME/);
+ assert.match(step, /JSON_STRING_OF_SLUG/);
+ assert.doesNotMatch(step, /--display-name "<displayName>"/);
+ assert.match(step, /must not create, reset, delete, or\s+write anything under `src\/generated\/`/);
+ assert.doesNotMatch(step, /rm\s+-rf[\s\S]*src\/generated/);
+ assert.doesNotMatch(step, /src\/generated\/index\.ts[\s\S]*printf/);
+ assert.doesNotMatch(step, /\ncp\s+.*shared\/samples/);
+ assert.doesNotMatch(step, /baseUrl\s*=/);
+ assert.doesNotMatch(step, /Write `app\/_layout\.tsx`/);
+ assert.match(
+ step,
+ /`native-app-plan\.md` is expected here because Step 3 writes the approved plan before template preparation/,
+ );
+});
+
+test('Power Apps initialization directly invokes the CLI with approved values', () => {
+ const initializeStart = skill.indexOf('### Step 6 — Initialize');
+ const initializeEnd = skill.indexOf('### Step 6.5 — Verify dependencies');
+ const initialize = skill.slice(initializeStart, initializeEnd);
+ assert.match(initialize, /npx power-apps init -t MobileApp/);
+ assert.match(initialize, /--display-name "<displayName>"/);
+ assert.match(initialize, /--environment-id "<environment-id>"/);
+ assert.match(initialize, /approved Step 2 display name and Step 4 environment ID/);
+ assert.match(initialize, /shell-safe quoting/);
+ assert.match(initialize, /If a populated file remains, STOP/);
+ assert.doesNotMatch(initialize, /spawnSync|node <<'NODE'/);
+});
diff --git a/plugins/mobile-apps/scripts/tests/prepare-mobile-template.test.js b/plugins/mobile-apps/scripts/tests/prepare-mobile-template.test.js
new file mode 100644
index 000000000..316c34760
--- /dev/null
+++ b/plugins/mobile-apps/scripts/tests/prepare-mobile-template.test.js
@@ -0,0 +1,392 @@
+'use strict';
+
+const assert = require('assert');
+const fs = require('fs');
+const Module = require('module');
+const os = require('os');
+const path = require('path');
+const test = require('node:test');
+
+const {
+ HOST_TSCONFIG,
+ assertFreshTemplate,
+ prepareMobileTemplate,
+ prepareRootLayout,
+} = require('../prepare-mobile-template');
+
+const pluginRoot = path.resolve(__dirname, '../..');
+const templateRoot = path.join(pluginRoot, 'template');
+
+function tempDirectory(name) {
+ return fs.mkdtempSync(path.join(os.tmpdir(), `${name}-`));
+}
+
+function copyTemplate() {
+ const projectRoot = tempDirectory('mobile-template');
+ fs.cpSync(templateRoot, projectRoot, { recursive: true });
+ fs.mkdirSync(path.join(projectRoot, 'node_modules', 'expo'), { recursive: true });
+ return projectRoot;
+}
+
+function loadAppConfig(configPath) {
+ const originalLoad = Module._load;
+ Module._load = function load(request, parent, isMain) {
+ if (request === '@microsoft/power-apps-native-host/config/expoConfig') {
+ return {
+ createPowerAppsExpoConfig(baseConfig, settings, customize) {
+ return customize({
+ ...baseConfig,
+ name: settings.name,
+ slug: settings.slug,
+ });
+ },
+ };
+ }
+ return originalLoad.call(this, request, parent, isMain);
+ };
+ try {
+ delete require.cache[require.resolve(configPath)];
+ return require(configPath);
+ } finally {
+ Module._load = originalLoad;
+ }
+}
+
+function fileSnapshot(projectRoot) {
+ const snapshot = new Map();
+ function visit(directory) {
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
+ if (entry.name === 'node_modules') continue;
+ const absolutePath = path.join(directory, entry.name);
+ if (entry.isDirectory()) visit(absolutePath);
+ else snapshot.set(path.relative(projectRoot, absolutePath), fs.readFileSync(absolutePath));
+ }
+ }
+ visit(projectRoot);
+ return snapshot;
+}
+
+function assertSnapshotsEqual(left, right) {
+ assert.deepStrictEqual([...left.keys()].sort(), [...right.keys()].sort());
+ for (const [relativePath, content] of left) {
+ assert.deepStrictEqual(right.get(relativePath), content, relativePath);
+ }
+}
+
+test('preparation is idempotent and preserves generated and existing helper files', () => {
+ const projectRoot = copyTemplate();
+ const tsconfigPath = path.join(projectRoot, 'tsconfig.json');
+ const originalTsconfig = fs.readFileSync(tsconfigPath);
+ const generatedPath = path.join(projectRoot, 'src', 'generated', 'index.ts');
+ const existingHelperPath = path.join(projectRoot, 'src', 'components', 'index.tsx');
+ fs.mkdirSync(path.dirname(generatedPath), { recursive: true });
+ fs.mkdirSync(path.dirname(existingHelperPath), { recursive: true });
+ fs.writeFileSync(generatedPath, '// generated-owner sentinel\n');
+ fs.writeFileSync(existingHelperPath, '// existing-helper sentinel\n');
+ fs.writeFileSync(path.join(projectRoot, 'power.config.json'), '{"environmentId":""}\n');
+ fs.writeFileSync(path.join(projectRoot, 'native-app-plan.md'), '# Approved plan\n');
+
+ const first = prepareMobileTemplate({
+ workingDir: projectRoot,
+ displayName: "R&D $& Inspector's Workspace",
+ slug: 'inspectors-workspace',
+ });
+
+ assert.strictEqual(first.removedPowerConfig, true);
+ assert.deepStrictEqual(fs.readFileSync(generatedPath, 'utf8'), '// generated-owner sentinel\n');
+ assert.deepStrictEqual(fs.readFileSync(existingHelperPath, 'utf8'), '// existing-helper sentinel\n');
+ assert.deepStrictEqual(
+ fs.readFileSync(path.join(projectRoot, 'native-app-plan.md'), 'utf8'),
+ '# Approved plan\n',
+ );
+ assert.match(
+ fs.readFileSync(path.join(projectRoot, 'app.config.js'), 'utf8'),
+ /R&D \$& Inspector\\'s Workspace/,
+ );
+ assert.strictEqual(require(path.join(projectRoot, 'package.json')).name, 'inspectors-workspace');
+
+ const tsconfig = require(path.join(projectRoot, 'tsconfig.json'));
+ assert.strictEqual(tsconfig.extends, HOST_TSCONFIG);
+ assert.strictEqual(tsconfig.compilerOptions, undefined);
+ assert.deepStrictEqual(fs.readFileSync(tsconfigPath), originalTsconfig);
+
+ const layout = fs.readFileSync(path.join(projectRoot, 'app', '_layout.tsx'), 'utf8');
+ assert.match(layout, /<SafeAreaProvider>/);
+ assert.match(layout, /offlineProfile=\{offlineProfile\}/);
+ assert.match(layout, /tamaguiConfig=\{tamaguiConfig\}/);
+ assert.match(layout, /defaultTheme=/);
+ assert.doesNotMatch(layout, /theme=\{lightTheme\}/);
+ assert.doesNotMatch(layout, /darkTheme=\{darkTheme\}/);
+ assert.doesNotMatch(layout, /<SafeAreaView[\s\S]*<Slot\s*\/>/);
+ assert.match(layout, /@ts-ignore - power\.config\.json/);
+ assert.match(layout, /@ts-ignore - connectorSchemas/);
+
+ const beforeSecondRun = fileSnapshot(projectRoot);
+ const second = prepareMobileTemplate({
+ workingDir: projectRoot,
+ displayName: "R&D $& Inspector's Workspace",
+ slug: 'inspectors-workspace',
+ });
+ const afterSecondRun = fileSnapshot(projectRoot);
+ assert.ok(second.preservedSharedFiles.length > 0);
+ assertSnapshotsEqual(beforeSecondRun, afterSecondRun);
+});
+
+test('preparation round-trips JavaScript line terminators in app display names', () => {
+ const projectRoot = copyTemplate();
+ const displayName = "Line 1\nLine 2\rLine 3\u2028Line 4\u2029Inspector's App";
+ prepareMobileTemplate({
+ workingDir: projectRoot,
+ displayName,
+ slug: 'line-safe-app',
+ });
+
+ const configPath = path.join(projectRoot, 'app.config.js');
+ const source = fs.readFileSync(configPath, 'utf8');
+ assert.match(source, /Line 1\\nLine 2\\rLine 3\\u2028Line 4\\u2029Inspector\\'s App/);
+ const createConfig = loadAppConfig(configPath);
+ assert.strictEqual(createConfig({ config: {} }).name, displayName);
+});
+
+test('preparation rejects a template that does not inherit the host tsconfig', () => {
+ const projectRoot = copyTemplate();
+ const tsconfigPath = path.join(projectRoot, 'tsconfig.json');
+ fs.writeFileSync(tsconfigPath, JSON.stringify({
+ extends: 'expo/tsconfig.base',
+ compilerOptions: { paths: {} },
+ }, null, 2));
+ const before = fileSnapshot(projectRoot);
+
+ assert.throws(() => prepareMobileTemplate({
+ workingDir: projectRoot,
+ displayName: 'Unsupported Template',
+ slug: 'unsupported-template',
+ }), /must extend @microsoft\/power-apps-native-host\/config\/tsconfig/);
+
+ assertSnapshotsEqual(before, fileSnapshot(projectRoot));
+});
+
+test('fresh-template validation allows the approved plan but blocks created-app markers', () => {
+ const projectRoot = copyTemplate();
+ fs.writeFileSync(path.join(projectRoot, 'native-app-plan.md'), '# Approved plan\n');
+ assert.doesNotThrow(() => assertFreshTemplate(projectRoot));
+
+ fs.writeFileSync(path.join(projectRoot, 'memory-bank.md'), '# Created app\n');
+ assert.throws(() => assertFreshTemplate(projectRoot), /memory-bank\.md/);
+ fs.unlinkSync(path.join(projectRoot, 'memory-bank.md'));
+
+ fs.writeFileSync(path.join(projectRoot, '.datamodel-manifest.json'), '{}\n');
+ assert.throws(() => assertFreshTemplate(projectRoot), /\.datamodel-manifest\.json/);
+ fs.unlinkSync(path.join(projectRoot, '.datamodel-manifest.json'));
+
+ const generatedServices = path.join(projectRoot, 'src', 'generated', 'services');
+ fs.mkdirSync(generatedServices, { recursive: true });
+ fs.writeFileSync(path.join(generatedServices, 'CreatedService.ts'), 'export {};\n');
+ assert.throws(() => assertFreshTemplate(projectRoot), /src\/generated\/services\/\*\.ts/);
+});
+
+function writeLayoutFixture(source) {
+ const projectRoot = tempDirectory('root-layout');
+ fs.mkdirSync(path.join(projectRoot, 'app'), { recursive: true });
+ fs.writeFileSync(path.join(projectRoot, 'app', '_layout.tsx'), source);
+ return projectRoot;
+}
+
+const providerBody = `
+ <PowerAppsProvider
+ msalConfig={authConfig.msal}
+ offlineProfile={offlineProfile}
+ customHostProp="preserve-me"
+ >
+ <CustomNavigation>
+ <Slot />
+ </CustomNavigation>
+ </PowerAppsProvider>`;
+
+const fixtureImports = `import { Slot } from 'expo-router';
+import { PowerAppsProvider } from '@microsoft/power-apps-native-host';
+import authConfig from '../auth.config.json';
+import { offlineProfile } from '../offline';
+`;
+
+test('root preparation handles import-only safe-area state', () => {
+ const projectRoot = writeLayoutFixture(`${fixtureImports}
+import { SafeAreaProvider } from 'react-native-safe-area-context';
+export default function RootLayout() {
+ return (${providerBody}
+ );
+}
+`);
+ prepareRootLayout(projectRoot);
+ const result = fs.readFileSync(path.join(projectRoot, 'app', '_layout.tsx'), 'utf8');
+ assert.match(result, /<SafeAreaProvider>[\s\S]*<PowerAppsProvider/);
+ assert.match(result, /customHostProp="preserve-me"/);
+ assert.match(result, /<CustomNavigation>/);
+});
+
+test('root preparation reuses semicolonless combined, named, and default imports', () => {
+ const projectRoot = writeLayoutFixture(`import { Slot } from 'expo-router'
+import ReactNative, { useColorScheme } from 'react-native'
+import { SafeAreaProvider } from 'react-native-safe-area-context'
+import { PowerAppsProvider } from '@microsoft/power-apps-native-host'
+import tamaguiConfig, { appLightTheme } from '../tamagui.config'
+import authConfig from '../auth.config.json'
+import { offlineProfile } from '../offline'
+
+export default function RootLayout() {
+ const colorScheme = useColorScheme()
+ return (${providerBody}
+ )
+}
+`);
+ prepareRootLayout(projectRoot);
+ const result = fs.readFileSync(path.join(projectRoot, 'app', '_layout.tsx'), 'utf8');
+
+ assert.strictEqual((result.match(/from ['"]react-native['"]/g) || []).length, 1);
+ assert.strictEqual(
+ (result.match(/from ['"]react-native-safe-area-context['"]/g) || []).length,
+ 1,
+ );
+ assert.strictEqual(
+ (result.match(/from ['"]@microsoft\/power-apps-native-host['"]/g) || []).length,
+ 1,
+ );
+ assert.strictEqual((result.match(/from ['"]\.\.\/tamagui\.config['"]/g) || []).length, 1);
+ assert.match(result, /import tamaguiConfig,\s*\{\s*appLightTheme\s*\}\s*from\s*'\.\.\/tamagui\.config'/s);
+ assert.match(result, /import ReactNative,\s*\{[^}]*\buseColorScheme\b[^}]*\}\s*from\s*'react-native'/s);
+ assert.doesNotMatch(result, /\blightTheme\b|\bdarkTheme\b/);
+ assert.match(result, /<SafeAreaProvider>[\s\S]*<PowerAppsProvider/);
+});
+
+test('root preparation creates the required colorScheme binding when the hook uses another name', () => {
+ const projectRoot = writeLayoutFixture(`${fixtureImports}
+import { useColorScheme } from 'react-native';
+export default function RootLayout() {
+ const scheme = useColorScheme();
+ return (${providerBody}
+ );
+}
+`);
+ prepareRootLayout(projectRoot);
+ const result = fs.readFileSync(path.join(projectRoot, 'app', '_layout.tsx'), 'utf8');
+ assert.match(result, /const scheme = useColorScheme\(\);/);
+ assert.match(result, /const colorScheme = useColorScheme\(\);/);
+ assert.match(result, /defaultTheme=\{colorScheme === 'dark' \? 'dark' : 'light'\}/);
+});
+
+test('root preparation handles wrapper-only and already-correct states idempotently', () => {
+ const projectRoot = writeLayoutFixture(`${fixtureImports}
+export default function RootLayout() {
+ return (
+ <SafeAreaProvider>${providerBody}
+ </SafeAreaProvider>
+ );
+}
+`);
+ prepareRootLayout(projectRoot);
+ const first = fs.readFileSync(path.join(projectRoot, 'app', '_layout.tsx'), 'utf8');
+ prepareRootLayout(projectRoot);
+ const second = fs.readFileSync(path.join(projectRoot, 'app', '_layout.tsx'), 'utf8');
+ assert.strictEqual(second, first);
+ assert.strictEqual((second.match(/<SafeAreaProvider>/g) || []).length, 1);
+ assert.match(second, /offlineProfile=\{offlineProfile\}/);
+});
+
+test('root preparation preserves custom outer provider nesting', () => {
+ const projectRoot = writeLayoutFixture(`${fixtureImports}
+export default function RootLayout() {
+ return (
+ <TelemetryBoundary>
+${providerBody}
+ </TelemetryBoundary>
+ );
+}
+`);
+ prepareRootLayout(projectRoot);
+ const result = fs.readFileSync(path.join(projectRoot, 'app', '_layout.tsx'), 'utf8');
+ assert.match(result, /<TelemetryBoundary>[\s\S]*<SafeAreaProvider>[\s\S]*<PowerAppsProvider/);
+ assert.match(result, /<\/PowerAppsProvider>[\s\S]*<\/SafeAreaProvider>[\s\S]*<\/TelemetryBoundary>/);
+});
+
+test('safe-area wrapping preserves multiline provider prop values byte-for-byte', () => {
+ const multilineValue = `customMessage={\`first line
+ intentionally indented second line\`}`;
+ const multilineProvider = `<PowerAppsProvider
+ ${multilineValue}
+ >
+ <Slot />
+ </PowerAppsProvider>`;
+ const projectRoot = writeLayoutFixture(`${fixtureImports}
+export default function RootLayout() {
+ return (
+ ${multilineProvider}
+ );
+}
+`);
+ prepareRootLayout(projectRoot);
+ const result = fs.readFileSync(path.join(projectRoot, 'app', '_layout.tsx'), 'utf8');
+ assert.ok(result.includes(multilineValue));
+});
+
+test('provider preparation preserves JSX and callback prop values byte-for-byte', () => {
+ const jsxValue = 'customHeader={<Header title="A > B" tamaguiConfig={nestedConfig} theme={nestedLight} darkTheme={nestedDark} />}';
+ const callbackValue = 'renderHeader={() => <Header compact />}';
+ const projectRoot = writeLayoutFixture(`${fixtureImports}
+export default function RootLayout() {
+ return (
+ <PowerAppsProvider
+ ${jsxValue}
+ ${callbackValue}
+ >
+ <Slot />
+ </PowerAppsProvider>
+ );
+}
+`);
+ prepareRootLayout(projectRoot);
+ const first = fs.readFileSync(path.join(projectRoot, 'app', '_layout.tsx'), 'utf8');
+ assert.ok(first.includes(jsxValue));
+ assert.ok(first.includes(callbackValue));
+ assert.match(first, /\n\s+tamaguiConfig=\{tamaguiConfig\}\n/);
+ assert.doesNotMatch(first, /\n\s+theme=\{lightTheme\}\n/);
+ assert.doesNotMatch(first, /\n\s+darkTheme=\{darkTheme\}\n/);
+ prepareRootLayout(projectRoot);
+ assert.strictEqual(
+ fs.readFileSync(path.join(projectRoot, 'app', '_layout.tsx'), 'utf8'),
+ first,
+ );
+});
+
+test('root preparation rejects a root-owned SafeAreaView around Slot', () => {
+ const projectRoot = writeLayoutFixture(`${fixtureImports}
+import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';
+export default function RootLayout() {
+ return (
+ <SafeAreaProvider>
+ <PowerAppsProvider tamaguiConfig={tamaguiConfig} defaultTheme="light">
+ <SafeAreaView><Slot /></SafeAreaView>
+ </PowerAppsProvider>
+ </SafeAreaProvider>
+ );
+}
+`);
+ assert.throws(() => prepareRootLayout(projectRoot), /must not wrap Slot with SafeAreaView/);
+});
+
+test('failed full preparation restores every mutated file', () => {
+ const projectRoot = copyTemplate();
+ const layoutPath = path.join(projectRoot, 'app', '_layout.tsx');
+ const invalidLayout = fs.readFileSync(layoutPath, 'utf8')
+ .replace('<Slot />', '<SafeAreaView><Slot /></SafeAreaView>');
+ fs.writeFileSync(layoutPath, invalidLayout);
+ fs.writeFileSync(path.join(projectRoot, 'power.config.json'), '{"environmentId":""}\n');
+ const before = fileSnapshot(projectRoot);
+
+ assert.throws(() => prepareMobileTemplate({
+ workingDir: projectRoot,
+ displayName: 'Rollback Probe',
+ slug: 'rollback-probe',
+ }), /must not wrap Slot with SafeAreaView/);
+
+ assertSnapshotsEqual(before, fileSnapshot(projectRoot));
+});
diff --git a/plugins/mobile-apps/scripts/tests/template-quality-contract.test.js b/plugins/mobile-apps/scripts/tests/template-quality-contract.test.js
new file mode 100644
index 000000000..2ea190eea
--- /dev/null
+++ b/plugins/mobile-apps/scripts/tests/template-quality-contract.test.js
@@ -0,0 +1,130 @@
+'use strict';
+
+const assert = require('assert');
+const fs = require('fs');
+const path = require('path');
+const test = require('node:test');
+const {
+ hasNavigationTapGuard,
+} = require('../../hooks/validate-navigation-idempotency');
+
+const pluginRoot = path.resolve(__dirname, '../..');
+
+function read(relativePath) {
+ return fs.readFileSync(path.join(pluginRoot, relativePath), 'utf8');
+}
+
+test('base Tamagui config inherits the generated-screen semantic contract from the host', () => {
+ const config = read('template/tamagui.config.ts');
+ assert.match(config, /createPowerAppsTamaguiConfig/);
+ assert.match(config, /const customConfig = \{\}/);
+ assert.match(config, /declare module 'tamagui'/);
+ assert.doesNotMatch(config, /createTamagui|withSemanticAliases|parseColorChannels/);
+});
+
+test('shipped routes own safe-area edges and avoid forbidden icons and raw hex colors', () => {
+ for (const relativePath of [
+ 'template/app/(app)/home.tsx',
+ 'template/app/login.tsx',
+ 'template/app/oauth-callback.tsx',
+ ]) {
+ const source = read(relativePath);
+ assert.match(source, /SafeAreaView/);
+ assert.match(source, /backgroundColor:\s*theme\.surface0\.val/);
+ assert.doesNotMatch(source, /MaterialCommunityIcons/);
+ assert.doesNotMatch(source, /#[0-9a-fA-F]{3,8}\b/);
+ }
+ const callback = read('template/app/oauth-callback.tsx');
+ assert.match(callback, /didNavigate\.current/);
+ assert.strictEqual(hasNavigationTapGuard(callback), true);
+});
+
+test('navigation ref guards must reset unless the route performs a terminal replace', () => {
+ const reusableNavigation = `
+ const didNavigate = useRef(false);
+ if (didNavigate.current) return;
+ didNavigate.current = true;
+ router.navigate('/details');
+ `;
+ const resettableNavigation = `
+ const didNavigate = useRef(false);
+ if (didNavigate.current) return;
+ didNavigate.current = true;
+ try {
+ router.navigate('/details');
+ } catch {
+ didNavigate.current = false;
+ }
+ `;
+
+ assert.strictEqual(hasNavigationTapGuard(reusableNavigation), false);
+ assert.strictEqual(hasNavigationTapGuard(resettableNavigation), true);
+});
+
+test('root runtime owns context but not route content edges', () => {
+ const layout = read('template/app/_layout.tsx');
+ assert.match(layout, /<SafeAreaProvider>/);
+ assert.match(layout, /appConfig=\{appConfig\}/);
+ assert.match(layout, /offlineProfile=\{offlineProfile\}/);
+ assert.match(layout, /defaultTheme=/);
+ assert.doesNotMatch(layout, /theme=\{lightTheme\}/);
+ assert.doesNotMatch(layout, /darkTheme=\{darkTheme\}/);
+ assert.doesNotMatch(layout, /SafeAreaView/);
+});
+
+test('native configuration follows the system light or dark appearance', () => {
+ const config = read('template/app.config.js');
+ assert.match(config, /createPowerAppsExpoConfig/);
+ assert.doesNotMatch(config, /userInterfaceStyle:\s*'automatic'/);
+});
+
+test('Babel and Metro configuration are delegated to native-host factories', () => {
+ assert.match(read('template/babel.config.js'), /createPowerAppsBabelConfig/);
+ assert.match(read('template/metro.config.js'), /createPowerAppsMetroConfig/);
+ assert.doesNotMatch(read('template/metro.config.js'), /power-apps-native-host\/metro-logger/);
+});
+
+test('bundled dependencies match the current host-factory template boundary', () => {
+ const packageJson = JSON.parse(read('template/package.json'));
+ assert.strictEqual(packageJson.dependencies['@microsoft/power-apps-native-host'], '^0.3.3');
+ assert.strictEqual(packageJson.dependencies['expo-media-library'], undefined);
+ assert.strictEqual(packageJson.dependencies['expo-modules-core'], undefined);
+ assert.strictEqual(packageJson.devDependencies['@microsoft/power-apps-cli'], '0.15.3');
+ assert.strictEqual(packageJson.overrides.metro, '0.83.8');
+ assert.strictEqual(packageJson.scripts['bundle:android'], 'build-codegen-package android');
+ assert.strictEqual(packageJson.scripts['bundle:ios'], 'build-codegen-package ios');
+});
+
+test('create flow keeps host theme foregrounds aligned with Tamagui brand accents', () => {
+ const skill = read('skills/create-mobile-app/SKILL.md');
+ const integration = read('skills/design-system/references/tamagui-integration.md');
+ assert.match(skill, /appLightTheme/);
+ assert.match(skill, /appDarkTheme/);
+ assert.match(skill, /accentOnAccent:\s*appLightTheme\.accentOnAccent/);
+ assert.match(skill, /accentOnAccent:\s*appDarkTheme\.accentOnAccent/);
+ assert.match(skill, /surface4:\s*appLightTheme\.color6/);
+ assert.match(skill, /surface4:\s*appDarkTheme\.color6/);
+ assert.doesNotMatch(skill, /function parseColorChannels/);
+ assert.match(integration, /createPowerAppsTamaguiConfig/);
+ assert.match(integration, /withPowerAppsSemanticAliases/);
+ assert.match(integration, /export const appLightTheme/);
+ assert.match(integration, /export const appDarkTheme/);
+ assert.doesNotMatch(integration, /function parseColorChannels/);
+});
+
+test('shared components preserve token literals and accessible row selection semantics', () => {
+ const components = read('shared/samples/src/components/index.tsx');
+ assert.match(components, /as const satisfies Record<StatusVariant/);
+ assert.match(components, /aria-pressed=\{selected\}/);
+ assert.match(components, /role="button"/);
+ assert.match(components, /minH=\{48\}/);
+ assert.match(components, /\$accentOnAccent/);
+ assert.doesNotMatch(components, /Button\.Text color="\$color1"/);
+ assert.doesNotMatch(components, /<Ionicons[^>]*color="\$[A-Za-z]/);
+});
+
+test('template path aliases are inherited from the host tsconfig', () => {
+ const tsconfig = JSON.parse(read('template/tsconfig.json'));
+ assert.strictEqual(tsconfig.extends, '@microsoft/power-apps-native-host/config/tsconfig');
+ assert.strictEqual(tsconfig.compilerOptions, undefined);
+});
diff --git a/plugins/mobile-apps/scripts/tests/validate-mobile-files-all-source.test.js b/plugins/mobile-apps/scripts/tests/validate-mobile-files-all-source.test.js
new file mode 100644
index 000000000..d339017af
--- /dev/null
+++ b/plugins/mobile-apps/scripts/tests/validate-mobile-files-all-source.test.js
@@ -0,0 +1,73 @@
+'use strict';
+
+const assert = require('assert');
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+const test = require('node:test');
+
+const {
+ collectSourceTargets,
+ main,
+ parseArgs,
+} = require('../validate-mobile-files');
+
+test('all-source flag is explicit and does not require individual files', () => {
+ const parsed = parseArgs(['--project-root', '/tmp/project', '--all-source']);
+ assert.strictEqual(parsed.allSource, true);
+ assert.deepStrictEqual(parsed.targets, []);
+});
+
+test('all-source rejects explicit validation targets', () => {
+ let stderr = '';
+ const originalWrite = process.stderr.write;
+ process.stderr.write = (chunk) => {
+ stderr += String(chunk);
+ return true;
+ };
+
+ try {
+ assert.strictEqual(main([
+ '--project-root',
+ '/tmp/project',
+ '--all-source',
+ '--file',
+ 'app/home.tsx',
+ ]), 1);
+ } finally {
+ process.stderr.write = originalWrite;
+ }
+
+ assert.match(stderr, /Usage: node validate-mobile-files\.js/);
+});
+
+test('all-source discovery includes app and source TypeScript but excludes generated files', () => {
+ const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-all-source-'));
+ const files = [
+ 'app/home.tsx',
+ 'app/(app)/detail.tsx',
+ 'app/generated/report.tsx',
+ 'src/components/index.tsx',
+ 'src/hooks/useItems.ts',
+ 'src/generated/services/Generated.ts',
+ 'tamagui.config.ts',
+ 'app.config.js',
+ ];
+ for (const relativePath of files) {
+ const absolutePath = path.join(projectRoot, relativePath);
+ fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
+ fs.writeFileSync(absolutePath, 'export {};\n');
+ }
+
+ const targets = collectSourceTargets(projectRoot);
+ assert.deepStrictEqual(targets, [
+ path.join('app', '(app)', 'detail.tsx'),
+ path.join('app', 'generated', 'report.tsx'),
+ path.join('app', 'home.tsx'),
+ path.join('src', 'components', 'index.tsx'),
+ path.join('src', 'hooks', 'useItems.ts'),
+ 'tamagui.config.ts',
+ ].sort());
+ assert.ok(!targets.some((target) => target.startsWith(path.join('src', 'generated'))));
+ assert.ok(!targets.includes('app.config.js'));
+});
diff --git a/plugins/mobile-apps/scripts/validate-mobile-files.js b/plugins/mobile-apps/scripts/validate-mobile-files.js
index 8ecd6e2a7..145081b61 100644
--- a/plugins/mobile-apps/scripts/validate-mobile-files.js
+++ b/plugins/mobile-apps/scripts/validate-mobile-files.js
@@ -15,9 +15,10 @@ const PLUGIN_ROOT = path.resolve(__dirname, '..');
function usage() {
return [
- 'Usage: node validate-mobile-files.js --project-root <path> --file <path> [--file <path> ...] [--approved-js-dependency <name>@<exact-version> ...]',
+ 'Usage: node validate-mobile-files.js --project-root <path> (--all-source | --file <path> [--file <path> ...]) [--approved-js-dependency <name>@<exact-version> ...]',
'',
'Paths must be regular files. Relative paths resolve from --project-root.',
+ '--all-source validates every .ts/.tsx file under app/ and src/, plus root .ts/.tsx files.',
'Approved JavaScript dependencies must use exact semver versions from the reviewed app plan.',
].join('\n');
}
@@ -34,7 +35,13 @@ function parseApprovedJsDependency(value) {
}
function parseArgs(argv) {
- const parsed = { approvedJsDependencies: [], errors: [], projectRoot: null, targets: [] };
+ const parsed = {
+ allSource: false,
+ approvedJsDependencies: [],
+ errors: [],
+ projectRoot: null,
+ targets: [],
+ };
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
@@ -44,6 +51,8 @@ function parseArgs(argv) {
} else if (arg === '--file') {
parsed.targets.push(argv[index + 1]);
index += 1;
+ } else if (arg === '--all-source') {
+ parsed.allSource = true;
} else if (arg === '--approved-js-dependency') {
const approvedDependency = parseApprovedJsDependency(argv[index + 1]);
if (approvedDependency) {
@@ -67,6 +76,34 @@ function isWithinRoot(filePath, projectRoot) {
return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
}
+function collectSourceTargets(projectRoot) {
+ const targets = [];
+
+ function visit(relativeDirectory) {
+ const absoluteDirectory = path.join(projectRoot, relativeDirectory);
+ if (!fs.existsSync(absoluteDirectory)) return;
+ for (const entry of fs.readdirSync(absoluteDirectory, { withFileTypes: true })) {
+ const relativePath = path.join(relativeDirectory, entry.name);
+ if (entry.isSymbolicLink()) continue;
+ if (entry.isDirectory()) {
+ if (relativePath === path.join('src', 'generated')) continue;
+ visit(relativePath);
+ } else if (entry.isFile() && /\.(?:ts|tsx)$/.test(entry.name)) {
+ targets.push(relativePath);
+ }
+ }
+ }
+
+ visit('app');
+ visit('src');
+ for (const entry of fs.readdirSync(projectRoot, { withFileTypes: true })) {
+ if (entry.isFile() && /\.(?:ts|tsx)$/.test(entry.name)) {
+ targets.push(entry.name);
+ }
+ }
+ return targets.sort();
+}
+
function runValidator(validatorName, filePath, content, projectRoot, approvedJsDependencies) {
const validatorPath = path.join(PLUGIN_ROOT, 'hooks', validatorName);
const payload = JSON.stringify({
@@ -94,7 +131,14 @@ function runValidator(validatorName, filePath, content, projectRoot, approvedJsD
}
function main(argv) {
- const { approvedJsDependencies, errors, help, projectRoot: projectRootArg, targets } = parseArgs(argv);
+ const {
+ allSource,
+ approvedJsDependencies,
+ errors,
+ help,
+ projectRoot: projectRootArg,
+ targets,
+ } = parseArgs(argv);
if (help) {
process.stdout.write(`${usage()}\n`);
return 0;
@@ -103,7 +147,11 @@ function main(argv) {
process.stderr.write(`${errors.join('\n')}\n\n${usage()}\n`);
return 1;
}
- if (!projectRootArg || targets.length === 0 || targets.some((target) => !target)) {
+ if (
+ !projectRootArg
+ || (allSource ? targets.length > 0 : targets.length === 0)
+ || targets.some((target) => !target)
+ ) {
process.stderr.write(`${usage()}\n`);
return 1;
}
@@ -114,11 +162,12 @@ function main(argv) {
return 1;
}
const projectRoot = fs.realpathSync(requestedProjectRoot);
+ const validationTargets = allSource ? collectSourceTargets(projectRoot) : targets;
const files = new Set();
let blocked = false;
- for (const target of targets) {
+ for (const target of validationTargets) {
const requestedTargetPath = path.resolve(projectRoot, target);
if (!isWithinRoot(requestedTargetPath, projectRoot)) {
process.stderr.write(`BLOCKED: validation target is outside the mobile project root: ${requestedTargetPath}\n`);
@@ -187,6 +236,7 @@ if (require.main === module) {
}
module.exports = {
+ collectSourceTargets,
isWithinRoot,
main,
parseArgs,
diff --git a/plugins/mobile-apps/shared/references/color-palette-architecture.md b/plugins/mobile-apps/shared/references/color-palette-architecture.md
index 74502b6db..97016a701 100644
--- a/plugins/mobile-apps/shared/references/color-palette-architecture.md
+++ b/plugins/mobile-apps/shared/references/color-palette-architecture.md
@@ -266,13 +266,12 @@ Dark mode is not a raw theme swap. It is a designed inversion.
```tsx
// Inside the tamagui.config.ts customization markers
+// Import withPowerAppsSemanticAliases from the native-host Tamagui config.
const customConfig = {
- ...defaultConfig,
- animations,
themes: {
...defaultConfig.themes,
dark: {
- ...defaultConfig.themes.dark,
+ ...withPowerAppsSemanticAliases(defaultConfig.themes.dark),
surface0: '#0E0D0B', // base background
surface1: '#14130F', // lightly differentiated surface
surface2: '#1E1C18', // card fill
diff --git a/plugins/mobile-apps/shared/references/design-planning.md b/plugins/mobile-apps/shared/references/design-planning.md
index f1d4acc11..8ef66a81e 100644
--- a/plugins/mobile-apps/shared/references/design-planning.md
+++ b/plugins/mobile-apps/shared/references/design-planning.md
@@ -188,7 +188,11 @@ Default stack — no customization needed.
- tamagui-design-system: add-aliases
```
-> **`add-aliases` mode** — even on the default path, Step 9b applies `skills/design-system/references/tamagui-integration.md` in alias-only mode to add `$surface0`–`$surface3`, `$accentBase`, `$accentSoft`, `$accentDeep`, and `$accentOnAccent` as named theme values over `defaultConfig`. This keeps `tamagui.config.ts` on `defaultConfig` for everything else, but gives the screen-builder a stable semantic contract regardless of whether a custom design system was configured.
+> **`add-aliases` mode** — on the default path, Step 9b verifies that
+> `tamagui.config.ts` uses the native host's
+> `createPowerAppsTamaguiConfig`. The host factory already provides
+> `$surface0`–`$surface3`, `$accentBase`, `$accentSoft`, `$accentDeep`, and
+> `$accentOnAccent`, so the app does not copy a second alias implementation.
### If deviating:
@@ -268,8 +272,10 @@ per-screen specs so the builder knows which sections to apply.
| `## Design` says | Step 9b action |
|---|---|
-| `tamagui-design-system: add-aliases` | **Always run** — apply `skills/design-system/references/tamagui-integration.md` in alias-only mode. This is the default path. Adds `$surface0`–`$surface3` and `$accent*` aliases over `defaultConfig`. No brand tokens, no theme overrides. |
+| `tamagui-design-system: add-aliases` | Verify that `tamagui.config.ts` calls `createPowerAppsTamaguiConfig`. The host already supplies the semantic aliases. |
| `tamagui-design-system: required` | Apply `skills/design-system/references/tamagui-integration.md` with brand tokens + theme from the `## Design` section. |
-| Custom font only (no design-system line) | `npx expo install expo-font` + `useFonts()` in `app/_layout.tsx`. Also apply alias-only mode so semantic tokens exist for the screen-builder. |
+| Custom font only (no design-system line) | `npx expo install expo-font` + `useFonts()` in `app/_layout.tsx`, preserving the host Tamagui factory. |
-**There is no "skip Step 9b" path.** Every plan now includes a `tamagui-design-system` line. `add-aliases` is the minimum — it always runs. `required` runs when there is a custom brand color, custom theme, or non-default font pairing.
+**There is no unchecked Step 9b path.** Every plan includes a
+`tamagui-design-system` line. `add-aliases` verifies host ownership; `required`
+applies generated brand tokens.
diff --git a/plugins/mobile-apps/shared/references/tamagui-component-recipes.md b/plugins/mobile-apps/shared/references/tamagui-component-recipes.md
index 2cde5da22..5fd9b4db3 100644
--- a/plugins/mobile-apps/shared/references/tamagui-component-recipes.md
+++ b/plugins/mobile-apps/shared/references/tamagui-component-recipes.md
@@ -664,9 +664,12 @@ const bodyFont = createFont({
})
const customConfig = {
- ...defaultConfig,
- animations,
- fonts: { ...defaultConfig.fonts, heading: headingFont, body: bodyFont },
+ fonts: {
+ ...defaultConfig.fonts,
+ heading: headingFont,
+ body: bodyFont,
+ mono: defaultConfig.fonts.body,
+ },
}
```
@@ -727,13 +730,12 @@ When the plan specifies a custom palette, override Tamagui's default tokens. Ful
```tsx
// Inside the tamagui.config.ts customization markers — warm ochre brand
+// Import withPowerAppsSemanticAliases from the native-host Tamagui config.
const customConfig = {
- ...defaultConfig,
- animations,
themes: {
...defaultConfig.themes,
light: {
- ...defaultConfig.themes.light,
+ ...withPowerAppsSemanticAliases(defaultConfig.themes.light),
background: '#F7F3EC', // default page background
surface0: '#F7F3EC', // semantic page background
surface1: '#FBF8F2', // lightly elevated
@@ -747,7 +749,7 @@ const customConfig = {
blue10: '#A8763E', // repurpose as brand accent
},
dark: {
- ...defaultConfig.themes.dark,
+ ...withPowerAppsSemanticAliases(defaultConfig.themes.dark),
background: '#0E0D0B', // default page background
surface0: '#0E0D0B', // semantic page background
surface1: '#14130F', // lightly elevated
diff --git a/plugins/mobile-apps/shared/references/tamagui-custom-tokens.md b/plugins/mobile-apps/shared/references/tamagui-custom-tokens.md
index b65125c85..4ed0aa1c8 100644
--- a/plugins/mobile-apps/shared/references/tamagui-custom-tokens.md
+++ b/plugins/mobile-apps/shared/references/tamagui-custom-tokens.md
@@ -6,24 +6,34 @@ These examples target Tamagui 2 with Config v5 and the standalone template's cus
## Rule #1 — Extend, don't replace
-Always spread `defaultConfig` first:
+Pass only the overrides to the native-host factory. It preserves the complete
+Config v5 baseline:
```ts
-import { createTamagui } from '@tamagui/core'
+import {
+ createPowerAppsTamaguiConfig,
+ withPowerAppsSemanticAliases,
+} from '@microsoft/power-apps-native-host/config/tamaguiConfig'
import { defaultConfig } from '@tamagui/config/v5'
// CUSTOMIZATION START - DO NOT REMOVE OR RENAME
-import { animations } from '@tamagui/config/v5-rn'
-
const customConfig = {
- ...defaultConfig,
- animations,
tokens: { ...defaultConfig.tokens, /* non-color overrides */ },
- themes: { ...defaultConfig.themes, /* overrides */ },
+ themes: {
+ ...defaultConfig.themes,
+ light: {
+ ...withPowerAppsSemanticAliases(defaultConfig.themes.light),
+ /* light overrides */
+ },
+ dark: {
+ ...withPowerAppsSemanticAliases(defaultConfig.themes.dark),
+ /* dark overrides */
+ },
+ },
}
// CUSTOMIZATION END - DO NOT REMOVE OR RENAME
-export const tamaguiConfig = createTamagui(customConfig)
+export const tamaguiConfig = createPowerAppsTamaguiConfig(customConfig)
```
Replacing the whole config means you lose all the built-in themes (light, dark, red, blue, etc.) and have to rebuild them. Don't.
@@ -33,12 +43,13 @@ Replacing the whole config means you lose all the built-in themes (light, dark,
Config v5 color values live in themes. Define each custom name in both root themes so `$brand500` follows the active light/dark theme.
```ts
-import { createTamagui } from '@tamagui/core'
+import {
+ createPowerAppsTamaguiConfig,
+ withPowerAppsSemanticAliases,
+} from '@microsoft/power-apps-native-host/config/tamaguiConfig'
import { defaultConfig } from '@tamagui/config/v5'
// CUSTOMIZATION START - DO NOT REMOVE OR RENAME
-import { animations } from '@tamagui/config/v5-rn'
-
const lightBrandColors = {
brand50: '#FFF4E6',
brand100: '#FFD9B3',
@@ -58,23 +69,21 @@ const darkBrandColors = {
const themes = {
...defaultConfig.themes,
light: {
- ...defaultConfig.themes.light,
+ ...withPowerAppsSemanticAliases(defaultConfig.themes.light),
...lightBrandColors,
},
dark: {
- ...defaultConfig.themes.dark,
+ ...withPowerAppsSemanticAliases(defaultConfig.themes.dark),
...darkBrandColors,
},
}
const customConfig = {
- ...defaultConfig,
- animations,
themes,
}
// CUSTOMIZATION END - DO NOT REMOVE OR RENAME
-export const tamaguiConfig = createTamagui(customConfig)
+export const tamaguiConfig = createPowerAppsTamaguiConfig(customConfig)
```
Use it as `<Button bg="$brand500" />`.
@@ -85,14 +94,14 @@ A "theme" in Tamagui is a set of colors keyed to semantic slots. To add a brand
```ts
const customConfig = {
- ...defaultConfig,
- animations,
themes: {
...defaultConfig.themes,
+ light: withPowerAppsSemanticAliases(defaultConfig.themes.light),
+ dark: withPowerAppsSemanticAliases(defaultConfig.themes.dark),
// Light brand
light_brand: {
- ...defaultConfig.themes.light,
+ ...withPowerAppsSemanticAliases(defaultConfig.themes.light),
background: lightBrandColors.brand500,
color: '#fff',
borderColor: lightBrandColors.brand700,
@@ -100,7 +109,7 @@ const customConfig = {
// Dark brand
dark_brand: {
- ...defaultConfig.themes.dark,
+ ...withPowerAppsSemanticAliases(defaultConfig.themes.dark),
background: darkBrandColors.brand700,
color: '#fff',
borderColor: darkBrandColors.brand900,
@@ -172,11 +181,10 @@ const headingFont = createFont({
})
const customConfig = {
- ...defaultConfig,
- animations,
fonts: {
...defaultConfig.fonts,
heading: headingFont,
+ mono: defaultConfig.fonts.body,
},
}
```
@@ -239,11 +247,11 @@ const darkStatusColors = {
const themes = {
...defaultConfig.themes,
light: {
- ...defaultConfig.themes.light,
+ ...withPowerAppsSemanticAliases(defaultConfig.themes.light),
...statusColors,
},
dark: {
- ...defaultConfig.themes.dark,
+ ...withPowerAppsSemanticAliases(defaultConfig.themes.dark),
...darkStatusColors,
},
}
@@ -275,4 +283,9 @@ You probably need at most: 4–6 brand color tokens, named status tokens (above)
## Config version
-The standalone template uses Tamagui 2 with `@tamagui/config/v5`. Keep `createTamagui`, `createTokens`, and `createFont` imports on `@tamagui/core`, preserve the template's `declare module '@tamagui/core'` augmentation, and keep customization code between the marker lines. Use `createTokens` for non-color token groups; put color values in `light` and `dark` themes.
+The standalone template uses Tamagui 2 with `@tamagui/config/v5`. Keep
+`createPowerAppsTamaguiConfig` imported from the native host, keep
+`createTokens` and `createFont` on `@tamagui/core`, preserve the template's
+`declare module 'tamagui'` augmentation, and keep customization code between
+the marker lines. Use `createTokens` for non-color token groups; put color
+values in `light` and `dark` themes.
diff --git a/plugins/mobile-apps/shared/references/typography-and-tone.md b/plugins/mobile-apps/shared/references/typography-and-tone.md
index e8bcd52ca..a00f1c392 100644
--- a/plugins/mobile-apps/shared/references/typography-and-tone.md
+++ b/plugins/mobile-apps/shared/references/typography-and-tone.md
@@ -122,13 +122,18 @@ Complete copy-paste block for `expo-font` + Tamagui wiring:
```tsx
// app/_layout.tsx
+import { PowerAppsProvider } from '@microsoft/power-apps-native-host'
import { useFonts } from 'expo-font'
import * as SplashScreen from 'expo-splash-screen'
import { useEffect } from 'react'
+import { useColorScheme } from 'react-native'
+
+import tamaguiConfig from '../tamagui.config'
SplashScreen.preventAutoHideAsync()
export default function RootLayout() {
+ const colorScheme = useColorScheme()
const [fontsLoaded] = useFonts({
// Replace with your chosen pairing
Lora: require('../assets/fonts/Lora-Regular.ttf'),
@@ -143,31 +148,39 @@ export default function RootLayout() {
if (!fontsLoaded) return null
return (
- <TamaguiProvider config={tamaguiConfig} defaultTheme={colorScheme}>
+ <PowerAppsProvider
+ // Keep the existing msalConfig, powerConfig, and schemaMap props.
+ tamaguiConfig={tamaguiConfig}
+ defaultTheme={colorScheme === 'dark' ? 'dark' : 'light'}
+ >
{/* ... */}
- </TamaguiProvider>
+ </PowerAppsProvider>
)
}
```
```tsx
// tamagui.config.ts
-// Inside the Tamagui 2 + Config v5 customization markers.
+// Keep the existing imports, factory call, exports, and module augmentation.
+// Replace only customConfig inside the customization markers.
+import { createPowerAppsTamaguiConfig } from '@microsoft/power-apps-native-host/config/tamaguiConfig'
+import { defaultConfig } from '@tamagui/config/v5'
import { createFont } from '@tamagui/core'
-import { animations } from '@tamagui/config/v5-rn'
const headingFont = createFont({ /* from pairing above */ })
const bodyFont = createFont({ /* from pairing above */ })
const customConfig = {
- ...defaultConfig,
- animations,
fonts: {
...defaultConfig.fonts,
heading: headingFont,
body: bodyFont,
+ mono: defaultConfig.fonts.body,
},
}
+
+export const tamaguiConfig = createPowerAppsTamaguiConfig(customConfig)
+export default tamaguiConfig
```
Usage in components:
diff --git a/plugins/mobile-apps/shared/samples/src/components/index.tsx b/plugins/mobile-apps/shared/samples/src/components/index.tsx
index 5875816ea..68862b37c 100644
--- a/plugins/mobile-apps/shared/samples/src/components/index.tsx
+++ b/plugins/mobile-apps/shared/samples/src/components/index.tsx
@@ -47,14 +47,14 @@ export type StatusVariant =
| 'draft'
| 'cancelled';
-const STATUS_STYLES: Record<StatusVariant, { bg: string; text: string; label: string }> = {
+const STATUS_STYLES = {
overdue: { bg: '$statusOverdueBg', text: '$statusOverdue', label: 'Overdue' },
complete: { bg: '$statusCompleteBg', text: '$statusComplete', label: 'Complete' },
'in-progress': { bg: '$statusInProgressBg', text: '$statusInProgress', label: 'In Progress' },
pending: { bg: '$statusPendingBg', text: '$statusPending', label: 'Pending' },
draft: { bg: '$statusDraftBg', text: '$statusDraft', label: 'Draft' },
cancelled: { bg: '$statusCancelledBg', text: '$statusCancelled', label: 'Cancelled' },
-};
+} as const satisfies Record<StatusVariant, { bg: string; text: string; label: string }>;
export function StatusPill({
status,
@@ -167,8 +167,8 @@ export function SectionHeader({
<XStack items="center" justify="space-between" mb="$2">
<Text fontSize="$5" fontWeight="600" color="$color11">{title}</Text>
{action && (
- <Button size="$2" chromeless onPress={action.onPress}>
- <Text fontSize="$3" color="$blue10">{action.label}</Text>
+ <Button size="$3" hitSlop={8} chromeless onPress={action.onPress}>
+ <Text fontSize="$3" color="$accentDeep">{action.label}</Text>
</Button>
)}
</XStack>
@@ -358,8 +358,8 @@ export function EmptyState({
<Text fontSize="$5" fontWeight="600" color="$color12">{title}</Text>
<Text color="$color10" text="center" fontSize="$4">{message}</Text>
{actionLabel && onAction && (
- <Button bg="$blue10" onPress={onAction}>
- <Button.Text color="$color1">{actionLabel}</Button.Text>
+ <Button bg="$accentBase" onPress={onAction}>
+ <Button.Text color="$accentOnAccent">{actionLabel}</Button.Text>
</Button>
)}
</YStack>
@@ -399,6 +399,7 @@ export function FloatingActionButton({
extended?: boolean;
}) {
const insets = useSafeAreaInsets();
+ const theme = useTheme();
return (
<Button
position="absolute"
@@ -408,15 +409,15 @@ export function FloatingActionButton({
height={56}
px={extended ? '$4' : 0}
rounded="$10"
- bg="$blue10"
+ bg="$accentBase"
boxShadow="0 4px 16px rgba(0, 0, 0, 0.12)"
onPress={onPress}
role="button"
aria-label={label}
- icon={<Ionicons name={iconName} size={22} color="white" />}
+ icon={<Ionicons name={iconName} size={22} color={theme.accentOnAccent.val} />}
pressStyle={{ scale: 0.96 }}
>
- {extended ? <Button.Text color="$color1">{label}</Button.Text> : null}
+ {extended ? <Button.Text color="$accentOnAccent">{label}</Button.Text> : null}
</Button>
);
}
@@ -454,7 +455,7 @@ export function FilterChipRow({
rounded="$10"
px="$3"
minH={36}
- bg={selected ? '$blue10' : '$surface2'}
+ bg={selected ? '$accentBase' : '$surface2'}
borderWidth={selected ? 0 : 1}
borderColor="$borderColor"
onPress={() => onChange(option.key)}
@@ -463,7 +464,7 @@ export function FilterChipRow({
aria-label={label}
pressStyle={{ scale: 0.98 }}
>
- <Button.Text color={selected ? '$color1' : '$color11'}>{label}</Button.Text>
+ <Button.Text color={selected ? '$accentOnAccent' : '$color11'}>{label}</Button.Text>
</Button>
);
})}
@@ -570,24 +571,30 @@ export function RowPick({
selected: boolean;
onPress: () => void;
}) {
+ const theme = useTheme();
return (
<XStack
- px="$3" py="$3" items="center" justify="space-between" rounded="$3"
+ px="$3" py="$3" minH={48} items="center" justify="space-between" rounded="$3"
borderWidth={1}
- borderColor={selected ? '$color12' : '$borderColor'}
- bg={selected ? '$color12' : '$background'}
+ borderColor={selected ? '$accentBase' : '$borderColor'}
+ bg={selected ? '$accentBase' : '$background'}
onPress={onPress}
+ role="button"
+ aria-label={label}
+ aria-pressed={selected}
pressStyle={{ opacity: 0.7 }}
>
<YStack>
- <Text fontSize={15} fontWeight="600" color={selected ? 'white' : '$color12'}>{label}</Text>
+ <Text fontSize={15} fontWeight="600" color={selected ? '$accentOnAccent' : '$color12'}>{label}</Text>
{subtitle ? (
- <Text fontSize={12} color={selected ? 'white' : '$color10'} mt="$1">
+ <Text fontSize={12} color={selected ? '$accentOnAccent' : '$color10'} mt="$1">
{subtitle}
</Text>
) : null}
</YStack>
- {selected && <Ionicons name="checkmark-circle" size={20} color="white" />}
+ {selected && (
+ <Ionicons name="checkmark-circle" size={20} color={theme.accentOnAccent.val} />
+ )}
</XStack>
);
}
diff --git a/plugins/mobile-apps/shared/samples/tamagui.config.ts b/plugins/mobile-apps/shared/samples/tamagui.config.ts
index a09f7ad8c..a73ba0786 100644
--- a/plugins/mobile-apps/shared/samples/tamagui.config.ts
+++ b/plugins/mobile-apps/shared/samples/tamagui.config.ts
@@ -1,22 +1,16 @@
-import { createTamagui } from '@tamagui/core'
-import { defaultConfig } from '@tamagui/config/v5'
+import { createPowerAppsTamaguiConfig } from '@microsoft/power-apps-native-host/config/tamaguiConfig'
// CUSTOMIZATION START - DO NOT REMOVE OR RENAME
-// Replace or extend this Tamagui config value only.
-import { animations } from '@tamagui/config/v5-rn'
-
-const customConfig = {
- ...defaultConfig,
- animations,
-}
+// Add or replace Tamagui configuration values here.
+const customConfig = {}
// CUSTOMIZATION END - DO NOT REMOVE OR RENAME
-export const tamaguiConfig = createTamagui(customConfig)
+export const tamaguiConfig = createPowerAppsTamaguiConfig(customConfig)
export default tamaguiConfig
export type Conf = typeof tamaguiConfig
-declare module '@tamagui/core' {
+declare module 'tamagui' {
interface TamaguiCustomConfig extends Conf {}
}
diff --git a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md b/plugins/mobile-apps/skills/create-mobile-app/SKILL.md
index 13cba068f..6e3688fb5 100644
--- a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md
+++ b/plugins/mobile-apps/skills/create-mobile-app/SKILL.md
@@ -902,22 +902,42 @@ If any required template file is missing, STOP:
If `node_modules/expo` is missing, STOP:
> "Dependencies are not installed. Run `npm install` in the template folder, then rerun `/create-mobile-app --working-dir <fresh-template-dir>`."
-If already-created markers appear (`memory-bank.md`, `native-app-plan.md`, `.datamodel-manifest.json`, or `src/generated/services/*.ts`) and Step 0 did not enter the resume path, STOP:
+If already-created markers appear (`memory-bank.md`, `.datamodel-manifest.json`, or `src/generated/services/*.ts`) and Step 0 did not enter the resume path, STOP. `native-app-plan.md` is expected here because Step 3 writes the approved plan before template preparation:
> "This folder already looks like a created app. For a new app, materialize a fresh `expo-app-standalone` template with `degit` into a new folder and rerun this skill there."
-Then apply these **safe idempotent** prep steps:
+Run the deterministic preparation script once:
-1. Update app identity in `app.config.js` and `package.json` from Step 2 answers (`displayName`, `slug`) using targeted string replacements only.
-2. Ensure `src/generated/index.ts` exists with the empty generated barrel if no generated services exist.
-3. Ensure `src/components/`, `src/hooks/`, `src/utils/`, `src/tokens/`, and `src/native/` directories exist.
-4. Copy shared helper files from plugin samples only when the destination file is missing. Do not overwrite user-edited files.
-5. Merge the six path aliases into `tsconfig.json` (`@/components`, `@/hooks`, `@/utils`, `@/tokens`, `@/generated`, `@/native`) without deleting existing aliases.
-6. Verify `app/_layout.tsx` imports `PowerAppsProvider` from `@microsoft/power-apps-native-host` and imports `tamaguiConfig`. If either is missing, patch `_layout.tsx` conservatively; do not rewrite custom navigation or unrelated provider code.
-7. Remove placeholder `power.config.json` if its `environmentId` is empty or missing. `npx power-apps init` in Step 6 writes the real file for the selected environment.
-
-Do **not** preserve placeholder `power.config.json` from the template. Keeping it would let downstream steps read an empty or stale environment.
-
-After preparation, continue to Step 6.
+```bash
+PREPARE_SCRIPT="${PLUGIN_ROOT}/scripts/prepare-mobile-template.js"
+node - "$PREPARE_SCRIPT" <<'NODE'
+const { prepareMobileTemplate } = require(process.argv[2]);
+
+// Replace these placeholders with JSON.stringify(...) output so user-provided
+// quotes and dollar signs remain data rather than becoming shell syntax.
+const result = prepareMobileTemplate({
+ workingDir: <JSON_STRING_OF_WORKING_DIR>,
+ displayName: <JSON_STRING_OF_DISPLAY_NAME>,
+ slug: <JSON_STRING_OF_SLUG>,
+});
+process.stdout.write(`${JSON.stringify(result)}\n`);
+NODE
+```
+
+The script is the only owner of Step 5 mutations. It updates identity, removes
+only recognized legacy example hooks/query-client files, copies shared helpers
+only when missing, verifies that TypeScript inherits the host configuration,
+and structurally verifies the root provider/theme/safe-area contract. It
+preserves custom navigation, existing helper bytes, `offlineProfile`, provider
+props, and the template's `@ts-ignore` generation boundaries.
+
+**Generated ownership boundary:** Step 5 must not create, reset, delete, or
+write anything under `src/generated/`. Only Power Apps schema/data-source
+generation commands own that directory. A generated file required later is
+created by its owning command, never by a placeholder barrel.
+
+The script fails visibly for unsupported root-layout shapes or dangling legacy
+imports. Do not fall back to a full-file rewrite or regex patch. After it
+returns successfully, continue to Step 6.
**Fix 1 — App identity in `app.config.js` and `package.json`**
@@ -931,63 +951,33 @@ Substitute the hardcoded template values with wizard answers from Step 2:
Bundle ID and scheme are left as template defaults — they are fixed across all dev builds and patched by the wrap pipeline at release time.
-**Fix 2 — Delete `power.config.json`**
+**Fix 2 — Remove only an empty placeholder `power.config.json`**
-`npx power-apps init` in Step 6 creates the correct one for the user's environment. Remove the template copy:
+The preparation script parses `power.config.json` and removes it only when
+`environmentId` is empty or missing. A populated file is preserved and later
+validated against the approved environment. Do not use an unconditional
+delete.
-```bash
-rm -f "<working_dir>/power.config.json"
-```
-
-**Fix 3 — Clean `src/generated/` and `src/hooks/` (idempotent)**
+**Fix 3 — Remove recognized legacy examples without touching generated code**
-Newer template snapshots **no longer ship** the example models / services / hooks (Contacts / Accounts / UserProfile / Office365Users) — `src/` only contains app infrastructure files such as `global.d.ts` and `playerConfig.ts`. Older snapshots still do. If a copied template includes `src/queryClient.ts`, remove it: `PowerAppsProvider` already owns the React Query `QueryClientProvider` and screen code should use `useQueryClient()`, not an app-owned singleton. The block below is **idempotent** — a no-op on the new template, a real cleanup on the old one. Always run it; never assume one snapshot.
+Newer snapshots do not ship the Contacts / Accounts / UserProfile example
+hooks or the old app-owned query client. The preparation script removes only
+those recognized files when present. It never traverses or mutates
+`src/generated/`; generated models, services, schemas, and barrels remain
+owned by Power Apps generation commands.
-```bash
-# Remove example generated artefacts if present (no error if missing)
-rm -rf "<working_dir>/src/generated/models" \
- "<working_dir>/src/generated/services" \
- "<working_dir>/src/generated/index.ts"
-
-# Wipe example React Query hooks and stale app-owned query client if present
-rm -f "<working_dir>/src/hooks/useContacts.ts" \
- "<working_dir>/src/hooks/useAccounts.ts" \
- "<working_dir>/src/hooks/useUserProfile.ts" \
- "<working_dir>/src/queryClient.ts"
-
-# Reset the generated barrel so `import … from '../generated'` resolves to nothing
-mkdir -p "<working_dir>/src/generated"
-printf '// Populated by npx power-apps add-data-source. Do not edit.\nexport {};\n' \
- > "<working_dir>/src/generated/index.ts"
-```
-
-**Do NOT overwrite `app/(app)/home.tsx` here.** The current template ships a minimal RN stub (`View` + `Text` from `react-native`) that compiles cleanly. Our screen-builder replaces it at Step 11. Replacing it with a Tamagui stub before Fix 8 (which threads brand `tamaguiConfig` into `PowerAppsProvider`) would render under the upstream default Tamagui config instead of the project's brand tokens.
+**Do NOT overwrite `app/(app)/home.tsx` here.** The current template ships a
+safe-area-aware, semantic-token starter route. The screen-builder replaces it
+only when the approved Screen Map assigns that route.
Keep `src/hooks/` itself — screen-builders write new hooks into it.
**Fix 3b — Scan for dangling imports referencing deleted files (back-compat only)**
-Only meaningful on older template snapshots that shipped the example hooks. On the current template the scan returns zero matches and you can skip it. Run it unconditionally — it is fast and self-skipping.
-
-```bash
-# Scan for any remaining imports of the deleted modules
-grep -rn \
- -e "useContacts" \
- -e "useAccounts" \
- -e "useUserProfile" \
- -e "from.*generated/services" \
- -e "from.*generated/models" \
- --include="*.ts" --include="*.tsx" \
- "<working_dir>/app/" "<working_dir>/src/" \
- || true
-```
-
-**If matches found:**
-- For screen files (`app/(app)/*.tsx`): replace the entire file with the same minimal stub used for `home.tsx` (screen-builder will overwrite at Step 11).
-- For layout files (`_layout.tsx`): remove only the import lines and any code referencing the deleted symbols. Do NOT replace the whole file — layouts have navigation structure that must be preserved.
-- For barrel/index files: remove the re-export lines.
-
-**If no matches:** Continue — template is clean.
+The preparation script scans `app/` and non-generated `src/` files after
+cleanup. Any remaining legacy example import is an explicit failure. Do not
+replace whole screens or layouts to make the scan pass; use a supported fresh
+template or repair the precise stale import before continuing.
**Fix 6 — Schema generation boundary**
@@ -997,116 +987,46 @@ Do NOT hand-write a stub `connectorSchemas.ts` — the generated output has a sp
**Why `tsc` already passes post-clone (current template, PR #30):** the template's `app/_layout.tsx` and `src/playerConfig.ts` carry `// @ts-ignore` comments above the `power.config.json` and `connectorSchemas` imports specifically so the project type-checks before `power.config.json` and `connectorSchemas.ts` exist. **Never strip these `@ts-ignore` lines** — Fix 8 below preserves them when patching `app/_layout.tsx` to thread the project's `tamaguiConfig` into `PowerAppsProvider`, and any future `Edit` to either file MUST keep them. Removing them resurfaces a `tsc` failure against missing generated files.
-**Fix 7 — Create `src/components/`, `src/hooks/`, `src/utils/`, `src/tokens/`**
-
-Copy the shared code structure into the project. This gives screen-builders a production-grade layout with path aliases:
-
-```bash
-mkdir -p "<working_dir>/src/components"
-mkdir -p "<working_dir>/src/hooks"
-mkdir -p "<working_dir>/src/utils"
-mkdir -p "<working_dir>/src/tokens"
-
-cp "${PLUGIN_ROOT}/shared/samples/src/components/index.tsx" "<working_dir>/src/components/index.tsx"
-cp "${PLUGIN_ROOT}/shared/samples/src/hooks/index.ts" "<working_dir>/src/hooks/index.ts"
-cp "${PLUGIN_ROOT}/shared/samples/src/hooks/useCursorListData.ts" "<working_dir>/src/hooks/useCursorListData.ts"
-cp "${PLUGIN_ROOT}/shared/samples/src/hooks/useListData.ts" "<working_dir>/src/hooks/useListData.ts"
-cp "${PLUGIN_ROOT}/shared/samples/src/hooks/useSearchFilter.ts" "<working_dir>/src/hooks/useSearchFilter.ts"
-cp "${PLUGIN_ROOT}/shared/samples/src/utils/index.ts" "<working_dir>/src/utils/index.ts"
-cp "${PLUGIN_ROOT}/shared/samples/src/utils/formatters.ts" "<working_dir>/src/utils/formatters.ts"
-cp "${PLUGIN_ROOT}/shared/samples/src/utils/text.ts" "<working_dir>/src/utils/text.ts"
-cp "${PLUGIN_ROOT}/shared/samples/src/utils/choices.ts" "<working_dir>/src/utils/choices.ts"
-cp "${PLUGIN_ROOT}/shared/samples/src/utils/dataverse.ts" "<working_dir>/src/utils/dataverse.ts"
-cp "${PLUGIN_ROOT}/shared/samples/src/tokens/index.ts" "<working_dir>/src/tokens/index.ts"
-```
-
-**Fix 8 — Thread the project's `tamaguiConfig` into the host provider** (required so screens render under brand tokens, not upstream defaults)
+**Fix 7 — Seed shared code only when missing**
-The template ships `PowerAppsProvider` (composed-tree API, v0.2.0+). Fix 8 adds `tamaguiConfig`, `defaultTheme`, `theme`, and `darkTheme` props so screens render under brand tokens. Do NOT add an outer `<TamaguiProvider>` — `PowerAppsProvider` composes it internally and duplicating triggers "useTheme must be used within a TamaguiProvider" warnings on hot reload.
+The preparation script creates the shared source directories and copies each
+approved sample helper only when its destination does not exist. Existing
+helpers are byte-for-byte preserved, so reruns cannot overwrite user or
+builder changes.
-Write `app/_layout.tsx` (run AFTER `npm install`):
-
-```tsx
-import { Slot } from 'expo-router';
-import { StatusBar } from 'expo-status-bar';
-import { useColorScheme } from 'react-native';
-import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';
-import { PowerAppsProvider, lightTheme, darkTheme } from '@microsoft/power-apps-native-host';
-import type { ThemeTokens } from '@microsoft/power-apps-native-host';
+**Fix 8 — Thread the project's `tamaguiConfig` and active theme into the host provider**
-import authConfig from '../auth.config.json';
-// @ts-ignore - power.config.json is auto-generated at build time
-import powerConfig from '../power.config.json';
-// @ts-ignore - connectorSchemas is auto-generated at build time
-import { schemaMap } from '../src/generated/connectorSchemas';
-import tamaguiConfig from '../tamagui.config';
+The template ships `PowerAppsProvider` with host-owned light and dark theme
+defaults. Fix 8 ensures the project `tamaguiConfig` and color-scheme-driven
+`defaultTheme` are present. It preserves explicit `theme` and `darkTheme`
+overrides when an app already has them, but does not add redundant overrides
+to a fresh template. Step 9b adds explicit themes only when applying generated
+brand tokens. Do NOT add an outer `<TamaguiProvider>` — `PowerAppsProvider`
+composes it internally and duplicating triggers "useTheme must be used within
+a TamaguiProvider" warnings on hot reload.
-// lightTheme / darkTheme are the built-in defaults from @microsoft/power-apps-native-host.
-// When brand/tokens.ts exists, the Brand-token wiring block (Step 9b) replaces
-// these props with brand-derived ThemeTokens objects instead.
-
-export default function RootLayout() {
- const colorScheme = useColorScheme();
- return (
- <SafeAreaProvider>
- <PowerAppsProvider
- msalConfig={authConfig.msal}
- powerConfig={powerConfig}
- schemaMap={schemaMap}
- tamaguiConfig={tamaguiConfig}
- defaultTheme={colorScheme === 'dark' ? 'dark' : 'light'}
- theme={lightTheme}
- darkTheme={darkTheme}
- >
- <StatusBar style="auto" />
- <SafeAreaView edges={['top', 'bottom']} style={{ flex: 1 }}>
- <Slot />
- </SafeAreaView>
- </PowerAppsProvider>
- </SafeAreaProvider>
- );
-}
-```
+The preparation script edits the existing root layout structurally. It adds
+missing imports and provider props, then wraps `PowerAppsProvider` with
+`SafeAreaProvider` only when needed. It does not replace the file and it does
+not wrap `<Slot />` with `SafeAreaView`; each rendered route owns its content
+edges to avoid double insets.
Key points:
- **Do NOT remove the two `// @ts-ignore` lines.** They keep `tsc` green pre-`npx power-apps init`.
- **Do NOT add an outer `<TamaguiProvider>`** — `PowerAppsProvider` composes it internally.
-- **`SafeAreaProvider` wraps the tree** so child screens can call `useSafeAreaInsets()` without a context error. `SafeAreaView` around `<Slot />` keeps content out of the status-bar / home-indicator areas — required by `validate-screen-quality.js`.
+- **`SafeAreaProvider` wraps the tree** so child screens can call `useSafeAreaInsets()` without a context error. Each route must use `SafeAreaView` or explicit insets for its own visible edges.
- `tamaguiConfig` is imported from `'../tamagui.config'` (the `default export` of `tamagui.config.ts` at project root).
- `defaultTheme` flips between light/dark via `useColorScheme()`. `/design-system --add-dark-mode` later wires per-token dark variants.
-Write the file directly when applying this fix.
-
-**Fix 4 — Path aliases in `tsconfig.json` (idempotent JSON merge)**
-
-The upstream template's `tsconfig.json` only ships `paths` polyfills for `react-native`, `expo-auth-session`, `expo-secure-store`, `expo-web-browser` — it does NOT define the `@/components`, `@/hooks`, `@/utils`, `@/tokens` aliases that screens (and the helpers Fix 7 just copied) import from. Without this fix, every `import { lookupName, formattedValue, newId } from '@/utils'` at screen-build time fails to resolve at both `tsc --noEmit` and Metro bundle time. Run this merge script in `<working_dir>`:
-
-```bash
-node -e '
- const fs = require("fs");
- const file = "tsconfig.json";
- const json = JSON.parse(fs.readFileSync(file, "utf8"));
- json.compilerOptions = json.compilerOptions || {};
- json.compilerOptions.baseUrl = json.compilerOptions.baseUrl || ".";
- json.compilerOptions.paths = json.compilerOptions.paths || {};
- const aliases = {
- "@/components": ["src/components"],
- "@/hooks": ["src/hooks"],
- "@/utils": ["src/utils"],
- "@/tokens": ["src/tokens"],
- "@/generated": ["src/generated"],
- "@/native": ["src/native"],
- };
- for (const [k, v] of Object.entries(aliases)) json.compilerOptions.paths[k] = v;
- fs.writeFileSync(file, JSON.stringify(json, null, 2) + "\n");
-'
-```
+**Fix 4 — Shared TypeScript configuration**
-Key points:
-- **Idempotent.** Re-running the script (e.g. on `/create-mobile-app` resume) overwrites the six alias keys with the same values — it does NOT touch `react-native`, `expo-auth-session`, `expo-secure-store`, `expo-web-browser`, or any other existing `paths` entries.
-- **Six aliases, not four.** `@/generated` and `@/native` are pre-wired so `npx power-apps add-data-source` output (`src/generated/services/...`) and `/add-native` output (`src/native/camera.ts`, etc.) can be imported via the alias too. Costs nothing now and avoids a second tsconfig patch later.
-- **`baseUrl: "."`** is preserved if already set (the template ships it). The merge script defaults it to `"."` only if missing.
-- Metro auto-resolves `paths` defined in `tsconfig.json` for any project running `expo`-based bundling, so this single edit covers both the type checker AND the bundler. No `babel.config.js` plugin needed.
+The current template extends
+`@microsoft/power-apps-native-host/config/tsconfig`. That host configuration
+owns the runtime package paths and the six shared-code aliases:
+`@/components`, `@/hooks`, `@/utils`, `@/tokens`, `@/generated`, and
+`@/native`. The preparation script verifies this inheritance and does not
+create a second template-local alias map. Expo Metro consumes the resulting
+effective TypeScript paths, so no Babel alias plug-in is required.
`<Gradient>` (used by `components/index.tsx`) requires `expo-linear-gradient`. **Assume the upstream template ships it** — do NOT edit `package.json` to add it. If `npm install` (Step 6.5) later reveals the dep is missing, STOP and ask the user to wait for the next template release; do not work around by adding the dep here (same lockdown rule as `/add-native`).
@@ -1121,10 +1041,17 @@ Do not run `npm install` inside Step 5 — in template-only mode dependencies mu
```bash
cd <working_dir>
-npx power-apps init -t MobileApp --display-name '<displayName>' --environment-id <environment-id> --non-interactive
+npx power-apps init -t MobileApp --display-name "<displayName>" --environment-id "<environment-id>" --non-interactive
```
-Verify `power.config.json` was created and `environmentId` matches Step 4. If `npx power-apps init` fails, report the exact error and STOP — do not proceed.
+Substitute the approved Step 2 display name and Step 4 environment ID using
+shell-safe quoting; do not ask for either value again. Step 5 must leave
+`power.config.json` absent. If a populated file remains, STOP and report its
+environment instead of overwriting it or running `init` again.
+
+Verify `power.config.json` exists and both its `environmentId` and
+`appDisplayName` match the approved Step 2/Step 4 values. If initialization
+fails, report the exact error and STOP.
### Step 6.5 — Verify dependencies
@@ -1136,57 +1063,15 @@ This step verifies dependencies only. The user must have run `npm install` befor
If `node_modules/expo` is missing, STOP. Tell the user to run `npm install` in the template folder. Do not provision ADO tokens or run `npm install` from this skill.
-### Step 6.5b — Ensure SafeAreaProvider wraps the root layout (always runs, idempotent)
-
-> **Why this step exists.** This step idempotently ensures safe-area context is present in the root layout so screens do not render under system bars.
-
-**Print before starting:**
-> "→ [Step 6.5b/13] Verifying SafeAreaProvider wraps the root layout (idempotent — usually a no-op)…"
-
-```bash
-cd <working_dir>
-
-if [ -f app/_layout.tsx ] && ! grep -q 'SafeAreaProvider' app/_layout.tsx; then
- echo "→ [6.5b] Patching app/_layout.tsx to add SafeAreaProvider + SafeAreaView"
- node -e '
- const fs = require("fs");
- const FILE = "app/_layout.tsx";
- let src = fs.readFileSync(FILE, "utf8");
- // 1. Add the import if missing — splice in right after the react-native
- // import; fallback is prepend after the first import line.
- if (!/from\s*["\047]react-native-safe-area-context["\047]/.test(src)) {
- const importLine = "import { SafeAreaProvider, SafeAreaView } from \"react-native-safe-area-context\";\n";
- if (/^import\s*\{[^}]*\}\s*from\s*["\047]react-native["\047];?/m.test(src)) {
- src = src.replace(/(^import\s*\{[^}]*\}\s*from\s*["\047]react-native["\047];?\n)/m, "$1" + importLine);
- } else {
- src = src.replace(/(^import[^\n]*\n)/m, "$1" + importLine);
- }
- }
- // 2. Wrap the outermost <PowerAppsProvider> ... </PowerAppsProvider> with
- // <SafeAreaProvider> AND wrap the inner <Slot /> with <SafeAreaView>.
- src = src.replace(
- /<PowerAppsProvider([\s\S]*?)>([\s\S]*?)<\/PowerAppsProvider>/,
- "<SafeAreaProvider>\n <PowerAppsProvider$1>$2</PowerAppsProvider>\n </SafeAreaProvider>"
- );
- if (!/<SafeAreaView/.test(src)) {
- src = src.replace(
- /<Slot\s*\/>/,
- "<SafeAreaView edges={[\"top\", \"bottom\"]} style={{ flex: 1 }}>\n <Slot />\n </SafeAreaView>"
- );
- }
- fs.writeFileSync(FILE, src);
- console.log(" ✓ app/_layout.tsx wrapped with SafeAreaProvider + SafeAreaView");
- ' || { echo "SafeArea patch of app/_layout.tsx failed — see error above"; exit 19; }
-elif [ ! -f app/_layout.tsx ]; then
- echo " ↷ app/_layout.tsx does not exist yet, skipping patch"
-else
- echo " ↷ SafeAreaProvider already present, skipping"
-fi
-
-echo "✓ [Step 6.5b] SafeAreaProvider verified"
-```
+### Step 6.5b — Root runtime contract verification
-**If the patch fails:** the node script exits with an error. The most common cause is an unusual `_layout.tsx` shape (custom rewrite). Fix manually by importing `SafeAreaProvider` + `SafeAreaView` from `react-native-safe-area-context`, wrapping the outermost provider with `<SafeAreaProvider>`, and wrapping the inner `<Slot />` with `<SafeAreaView edges={['top', 'bottom']} style={{ flex: 1 }}>`.
+Step 5 already performs the idempotent structural update and postcondition
+checks. Do not mutate `_layout.tsx` again here. Verify only that the prepared
+layout still contains `SafeAreaProvider`, `tamaguiConfig`, `offlineProfile`,
+and the color-scheme-driven `defaultTheme`. If brand-token wiring has already
+run, also verify its explicit `theme` and `darkTheme` props. If any applicable
+contract element is missing, rerun the Step 5 preparation script and stop if
+it reports an unsupported layout.
### Step 6.6 — Scaffold TypeScript gate
@@ -1615,50 +1500,82 @@ Gate 4b approval is consent for exactly the packages and versions in the table.
### Step 9b — Apply design system
-`/design-system` owns user-facing brand/design choices. This step owns the internal Tamagui integration that makes those choices usable by generated screens. Even if the user accepts the default design path, run the alias-only integration so screens can rely on the semantic token contract.
+`/design-system` owns user-facing brand/design choices. The native-host
+`createPowerAppsTamaguiConfig` factory owns the baseline semantic aliases,
+contrast handling, animations, and font fallback. This step applies generated
+brand tokens without copying that host logic into the app.
Read the `## Design` section from `native-app-plan.md` and follow the execution mapping in [`shared/references/design-planning.md`](${PLUGIN_ROOT}/shared/references/design-planning.md):
| Condition | Action |
|---|---|
-| `brand/tokens.ts` exists | **Highest priority.** Apply [`../design-system/references/tamagui-integration.md`](../design-system/references/tamagui-integration.md) in brand-import mode, then wire brand `ThemeTokens` into `app/_layout.tsx` (see below). |
+| `brand/tokens.ts` exists | **Highest priority.** Apply [`../design-system/references/tamagui-integration.md`](../design-system/references/tamagui-integration.md) in brand-import mode, export the resolved app light/dark themes, then wire matching `ThemeTokens` into `app/_layout.tsx`. |
| `## Design` says `required` | Apply the same reference using the approved `## Design` section. Builds custom token system + aliases. |
-| `## Design` says `add-aliases` | Apply the same reference in alias-only mode. Adds semantic surface/accent aliases over `defaultConfig`. |
-| Custom font only | `npx expo install expo-font` + `useFonts()` in `_layout.tsx` + `add-aliases` mode. |
+| `## Design` says `add-aliases` | Verify `tamagui.config.ts` uses `createPowerAppsTamaguiConfig`; the host already provides the semantic aliases. |
+| Custom font only | `npx expo install expo-font` + `useFonts()` in `_layout.tsx`; preserve the host config factory. |
-**No skip path.** Screen-builders require `$surface0`–`$surface3` and `$accent*` aliases. Minimum action is always `add-aliases`. Pass the complete `## Design` section verbatim — not a summary. Re-run `npx tsc --noEmit` after Tamagui config changes.
+**No unchecked path.** Screen-builders require `$surface0`–`$surface3` and
+`$accent*` aliases. On the default path, verify the host factory rather than
+rewriting the config. Pass the complete `## Design` section verbatim — not a
+summary. Re-run `npx tsc --noEmit` after Tamagui config changes.
-**Brand-token wiring** — when `brand/tokens.ts` exists, update `app/_layout.tsx` to spread brand values over the built-in `lightTheme`/`darkTheme` with nullish fallback:
+**Brand-token wiring** — when `brand/tokens.ts` exists, the Tamagui integration
+exports `appLightTheme` and `appDarkTheme`. Map those resolved semantic values
+into the host themes so `useTheme()` and `useThemeTokens()` cannot drift:
```tsx
-import { tokens as brandTokens } from '../brand/tokens';
-import { PowerAppsProvider, lightTheme as hostLightTheme, darkTheme as hostDarkTheme } from '@microsoft/power-apps-native-host';
+import {
+ PowerAppsProvider,
+ lightTheme as hostLightTheme,
+ darkTheme as hostDarkTheme,
+} from '@microsoft/power-apps-native-host';
import type { ThemeTokens } from '@microsoft/power-apps-native-host';
+import tamaguiConfig, {
+ appDarkTheme,
+ appLightTheme,
+} from '../tamagui.config';
const brandedLightTheme: ThemeTokens = {
...hostLightTheme,
- accentDeep: brandTokens.color.primary,
- accentBase: brandTokens.color.primary,
- accentSoft: brandTokens.color.accent,
- surface0: brandTokens.color.bg,
- surface1: brandTokens.color.surface,
- surface2: brandTokens.color.surface,
- surface3: brandTokens.color.border,
- text0: brandTokens.color.text,
- text1: brandTokens.color.textMuted,
+ surface0: appLightTheme.surface0,
+ surface1: appLightTheme.surface1,
+ surface2: appLightTheme.surface2,
+ surface3: appLightTheme.surface3,
+ surface4: appLightTheme.color6,
+ text0: appLightTheme.text0,
+ text1: appLightTheme.text1,
+ text2: appLightTheme.text2,
+ text3: appLightTheme.text3,
+ accentDeep: appLightTheme.accentDeep,
+ accentBase: appLightTheme.accentBase,
+ accentSoft: appLightTheme.accentSoft,
+ accentOnAccent: appLightTheme.accentOnAccent,
};
const brandedDarkTheme: ThemeTokens = {
...hostDarkTheme,
- accentDeep: brandTokens.color.primary,
- accentBase: brandTokens.color.primary,
- accentSoft: brandTokens.color.accent,
+ surface0: appDarkTheme.surface0,
+ surface1: appDarkTheme.surface1,
+ surface2: appDarkTheme.surface2,
+ surface3: appDarkTheme.surface3,
+ surface4: appDarkTheme.color6,
+ text0: appDarkTheme.text0,
+ text1: appDarkTheme.text1,
+ text2: appDarkTheme.text2,
+ text3: appDarkTheme.text3,
+ accentDeep: appDarkTheme.accentDeep,
+ accentBase: appDarkTheme.accentBase,
+ accentSoft: appDarkTheme.accentSoft,
+ accentOnAccent: appDarkTheme.accentOnAccent,
};
// In RootLayout:
<PowerAppsProvider ... theme={brandedLightTheme} darkTheme={brandedDarkTheme}>
```
-The generated schema has one brand palette, so dark surfaces and text retain the host defaults while brand accents carry across modes. For runtime theme switching (in-app theme pickers, per-tenant branding), use `useThemeControl()` from `@microsoft/power-apps-native-host`: `setTheme({ ...hostLightTheme, accentBase: color })` / `resetTheme()`.
+The generated schema has one brand palette, so the exported dark app theme
+retains Config v5 dark surfaces and text while carrying brand accents and
+statuses. For runtime theme switching, use `useThemeControl()` from
+`@microsoft/power-apps-native-host`.
### Step 10 — Add connectors
diff --git a/plugins/mobile-apps/skills/design-system/SKILL.md b/plugins/mobile-apps/skills/design-system/SKILL.md
index 0b381b95c..7360410d4 100644
--- a/plugins/mobile-apps/skills/design-system/SKILL.md
+++ b/plugins/mobile-apps/skills/design-system/SKILL.md
@@ -598,7 +598,7 @@ History stored in `brand/.history/`, capped at 50 entries (oldest auto-pruned).
| Consumer | Reads from brand/ | Behavior |
|---|---|---|
| `screen-builder` | `brand/design-system.md` (MANDATORY) | Negatives = HARD RULES. Token references required. |
-| Tamagui integration reference | `brand/tokens.ts` | Imported into `tamagui.config.ts` by `/create-mobile-app` Step 9b |
+| Tamagui integration reference | `brand/tokens.ts` | Applied through native-host theme helpers by `/create-mobile-app` Step 9b |
| `preview-screens` | `visual_companion` flag | Renders previews with brand tokens |
| `/edit-app` | Routes visual changes here | Non-visual schema and screen-plan changes stay in `/edit-app` |
| `/deploy` | `brand/` shipped in bundle | No special handling |
diff --git a/plugins/mobile-apps/skills/design-system/references/design-system-schema.md b/plugins/mobile-apps/skills/design-system/references/design-system-schema.md
index 0e6fb565b..e0351dd32 100644
--- a/plugins/mobile-apps/skills/design-system/references/design-system-schema.md
+++ b/plugins/mobile-apps/skills/design-system/references/design-system-schema.md
@@ -238,12 +238,18 @@ Missing sections → skill surfaces error, asks user to re-run.
## How Tamagui Integration Uses tokens.ts
-`brand/tokens.ts` is a plain TypeScript export. `/create-mobile-app` Step 9b imports it into `tamagui.config.ts` using [`tamagui-integration.md`](./tamagui-integration.md) and its `withSemanticAliases` helper:
+`brand/tokens.ts` is a plain TypeScript export. `/create-mobile-app` Step 9b
+imports it into `tamagui.config.ts` using
+[`tamagui-integration.md`](./tamagui-integration.md) and the native host's
+`withPowerAppsSemanticAliases` helper:
```ts
-// CUSTOMIZATION START - DO NOT REMOVE OR RENAME
import { createTokens } from '@tamagui/core';
-import { animations } from '@tamagui/config/v5-rn';
+import { defaultConfig } from '@tamagui/config/v5';
+import {
+ createPowerAppsTamaguiConfig,
+ withPowerAppsSemanticAliases,
+} from '@microsoft/power-apps-native-host/config/tamaguiConfig';
import { tokens as brandTokens } from './brand/tokens';
const tokens = createTokens({
@@ -253,20 +259,31 @@ const tokens = createTokens({
radius: { ...defaultConfig.tokens.radius, ...brandTokens.radius },
});
-const themes = {
- ...defaultConfig.themes,
- light: withSemanticAliases(defaultConfig.themes.light, brandTokens.color),
- dark: withSemanticAliases(defaultConfig.themes.dark, {
+export const appLightTheme = withPowerAppsSemanticAliases(
+ defaultConfig.themes.light,
+ brandTokens.color,
+);
+
+export const appDarkTheme = withPowerAppsSemanticAliases(
+ defaultConfig.themes.dark,
+ {
primary: brandTokens.color.primary,
accent: brandTokens.color.accent,
- }),
-};
+ statusSuccess: brandTokens.color.statusSuccess,
+ statusWarning: brandTokens.color.statusWarning,
+ statusDanger: brandTokens.color.statusDanger,
+ statusInfo: brandTokens.color.statusInfo,
+ },
+);
const customConfig = {
- ...defaultConfig,
- animations,
tokens,
- themes,
+ themes: {
+ ...defaultConfig.themes,
+ light: appLightTheme,
+ dark: appDarkTheme,
+ },
};
-// CUSTOMIZATION END - DO NOT REMOVE OR RENAME
+
+export const tamaguiConfig = createPowerAppsTamaguiConfig(customConfig);
```
diff --git a/plugins/mobile-apps/skills/design-system/references/tamagui-integration.md b/plugins/mobile-apps/skills/design-system/references/tamagui-integration.md
index e983775c6..689bd9040 100644
--- a/plugins/mobile-apps/skills/design-system/references/tamagui-integration.md
+++ b/plugins/mobile-apps/skills/design-system/references/tamagui-integration.md
@@ -1,116 +1,72 @@
# Tamagui Integration
-Internal reference used by `/create-mobile-app` Step 9b after `/design-system` writes `brand/tokens.ts`. This is not a user-invocable skill.
+Internal reference used by `/create-mobile-app` Step 9b after `/design-system`
+writes `brand/tokens.ts`. This is not a user-invocable skill.
-`/design-system` and this reference deliberately complement each other: `/design-system` captures the user's brand/design intent and writes artifacts; this reference translates those artifacts into Tamagui config/provider wiring. A default app still runs this reference in alias-only mode so generated screens have the same `$surface*` and `$accent*` token contract as a branded app.
+The native host owns the baseline Tamagui contract. Generated applications
+must extend that contract rather than copying its semantic aliases, color
+parsing, contrast selection, animations, or font fallback into each app.
## Goal
-Keep generated screens on one stable token contract:
-
-- Always provide `$surface0`-`$surface3` and `$accentBase` / `$accentSoft` / `$accentDeep` / `$accentOnAccent`.
-- Import `brand/tokens.ts` when it exists; it is the source of truth from `/design-system`.
-- Do not add an outer `TamaguiProvider`, `PortalProvider`, app-owned `Toaster`, `GestureHandlerRootView`, or `QueryClientProvider`; current `PowerAppsProvider` owns the provider and portal infrastructure. In Tamagui 2, `Toaster` is a sibling component rather than a provider wrapper.
+- Keep `$surface0`-`$surface3`, `$mediaSurface`, `$accent*`, `$text*`, status
+ foreground/background pairs, and `fonts.mono` available in every app.
+- Use `createPowerAppsTamaguiConfig` as the only Tamagui config factory.
+- Use `withPowerAppsSemanticAliases` when applying `brand/tokens.ts`.
+- Export the resolved light and dark app themes so `PowerAppsProvider` and
+ Tamagui consume the same semantic values.
+- Do not add an outer `TamaguiProvider`, `PortalProvider`, app-owned `Toaster`,
+ `GestureHandlerRootView`, or `QueryClientProvider`.
## Mode Selection
| Condition | Action |
|---|---|
-| `brand/tokens.ts` exists | Import brand tokens into `tamagui.config.ts`, then add aliases. |
-| `## Design` says `tamagui-design-system: required` but no brand tokens exist | Create brand/custom tokens from the approved `## Design`, then add aliases. |
-| `## Design` says `tamagui-design-system: add-aliases` or no custom design tokens exist | Add aliases over `defaultConfig` only. |
-
-Run `npx tsc --noEmit` after changing Tamagui config or root provider wiring.
-
-## Alias Layer
-
-Extend the Config v5 `light` and `dark` themes; do not replace `defaultConfig`.
-
-This integration targets Tamagui 2 with Config v5, matching the current standalone template. Tamagui components generated from this config must use v2 APIs (`transition`, ARIA props, web-standard input props, and `boxShadow`).
+| `brand/tokens.ts` exists | Apply the brand-import implementation below. |
+| `## Design` requires custom tokens but `brand/tokens.ts` is missing | Materialize the approved tokens first, then use brand-import mode. |
+| No custom design tokens exist | Verify the template calls `createPowerAppsTamaguiConfig({})`; make no config edit. |
-The template owns the file shell and marks the safe edit region with:
+The alias-only path is now a verification step. The host factory already
+provides the complete semantic alias and font contract.
-```ts
-// CUSTOMIZATION START - DO NOT REMOVE OR RENAME
-// CUSTOMIZATION END - DO NOT REMOVE OR RENAME
-```
+## Base Template
-Keep all added imports, token construction, and the `customConfig` replacement between those markers. Do not remove or rename either marker. Preserve the template's existing `createTamagui` and `defaultConfig` imports, exports, and `declare module '@tamagui/core'` block outside them.
+The current template starts with:
```ts
-import { createTamagui } from '@tamagui/core';
-import { defaultConfig } from '@tamagui/config/v5';
-
-// CUSTOMIZATION START - DO NOT REMOVE OR RENAME
-import { animations } from '@tamagui/config/v5-rn';
-
-type BrandColors = Partial<{
- bg: string;
- surface: string;
- primary: string;
- accent: string;
- border: string;
- statusSuccess: string;
- statusWarning: string;
- statusDanger: string;
- statusInfo: string;
-}>;
-
-function withSemanticAliases(
- theme: typeof defaultConfig.themes.light,
- brand: BrandColors = {},
-) {
- return {
- ...theme,
- surface0: brand.bg ?? theme.background,
- surface1: brand.surface ?? theme.color2,
- surface2: theme.color3,
- surface3: brand.border ?? theme.color4,
- accentDeep: brand.primary ?? theme.blue8,
- accentBase: brand.primary ?? theme.blue10,
- accentSoft: brand.accent ?? theme.blue3,
- accentOnAccent: theme.color1,
- statusComplete: brand.statusSuccess ?? theme.green10,
- statusCompleteBg: theme.green3,
- statusPending: brand.statusWarning ?? theme.yellow10,
- statusPendingBg: theme.yellow3,
- statusOverdue: brand.statusDanger ?? theme.red10,
- statusOverdueBg: theme.red3,
- statusInProgress: brand.statusInfo ?? theme.blue10,
- statusInProgressBg: theme.blue3,
- };
-}
+import { createPowerAppsTamaguiConfig } from '@microsoft/power-apps-native-host/config/tamaguiConfig';
-const themes = {
- ...defaultConfig.themes,
- light: withSemanticAliases(defaultConfig.themes.light),
- dark: withSemanticAliases(defaultConfig.themes.dark),
-};
+// CUSTOMIZATION START - DO NOT REMOVE OR RENAME THE COMMENT
+// Add or replace Tamagui configuration values here.
+const customConfig = {};
+// CUSTOMIZATION END - DO NOT REMOVE OR RENAME THE COMMENT
-const customConfig = {
- ...defaultConfig,
- animations,
- themes,
-};
-// CUSTOMIZATION END - DO NOT REMOVE OR RENAME
-
-export const tamaguiConfig = createTamagui(customConfig);
+export const tamaguiConfig = createPowerAppsTamaguiConfig(customConfig);
export default tamaguiConfig;
-export type Conf = typeof tamaguiConfig;
-declare module '@tamagui/core' {
+export type Conf = typeof tamaguiConfig;
+declare module 'tamagui' {
interface TamaguiCustomConfig extends Conf {}
}
```
+Keep `createPowerAppsTamaguiConfig`, the exports, and the `declare module
+'tamagui'` block. Replace only the customization region and add the required
+imports.
+
## Brand Import
-When `brand/tokens.ts` exists, reuse `withSemanticAliases`, map its colors into the root themes, and merge only its non-color token groups. Keep added imports inside the customization markers:
+When `brand/tokens.ts` exists, update `tamagui.config.ts` to this shape:
```ts
-// CUSTOMIZATION START - DO NOT REMOVE OR RENAME
import { createTokens } from '@tamagui/core';
-import { animations } from '@tamagui/config/v5-rn';
+import { defaultConfig } from '@tamagui/config/v5';
+import {
+ createPowerAppsTamaguiConfig,
+ withPowerAppsSemanticAliases,
+} from '@microsoft/power-apps-native-host/config/tamaguiConfig';
+
+// CUSTOMIZATION START - DO NOT REMOVE OR RENAME THE COMMENT
import { tokens as brandTokens } from './brand/tokens';
const tokens = createTokens({
@@ -120,58 +76,130 @@ const tokens = createTokens({
radius: { ...defaultConfig.tokens.radius, ...brandTokens.radius },
});
-const darkBrandColors = {
- primary: brandTokens.color.primary,
- accent: brandTokens.color.accent,
- statusSuccess: brandTokens.color.statusSuccess,
- statusWarning: brandTokens.color.statusWarning,
- statusDanger: brandTokens.color.statusDanger,
- statusInfo: brandTokens.color.statusInfo,
-};
-
-const themes = {
- ...defaultConfig.themes,
- light: withSemanticAliases(defaultConfig.themes.light, brandTokens.color),
- // The generated schema has one palette: carry accents/status into dark mode,
- // but retain Config v5's dark surfaces and readable status backgrounds.
- dark: withSemanticAliases(defaultConfig.themes.dark, darkBrandColors),
-};
+export const appLightTheme = withPowerAppsSemanticAliases(
+ defaultConfig.themes.light,
+ brandTokens.color,
+);
+
+export const appDarkTheme = withPowerAppsSemanticAliases(
+ defaultConfig.themes.dark,
+ {
+ primary: brandTokens.color.primary,
+ accent: brandTokens.color.accent,
+ statusSuccess: brandTokens.color.statusSuccess,
+ statusWarning: brandTokens.color.statusWarning,
+ statusDanger: brandTokens.color.statusDanger,
+ statusInfo: brandTokens.color.statusInfo,
+ },
+);
const customConfig = {
- ...defaultConfig,
- animations,
tokens,
- themes,
+ themes: {
+ ...defaultConfig.themes,
+ light: appLightTheme,
+ dark: appDarkTheme,
+ },
};
-// CUSTOMIZATION END - DO NOT REMOVE OR RENAME
+// CUSTOMIZATION END - DO NOT REMOVE OR RENAME THE COMMENT
+
+export const tamaguiConfig = createPowerAppsTamaguiConfig(customConfig);
+export default tamaguiConfig;
+
+export type Conf = typeof tamaguiConfig;
+declare module 'tamagui' {
+ interface TamaguiCustomConfig extends Conf {}
+}
```
-Hard rule: never remap brand space keys (`xs`, `sm`, `md`, `lg`, `xl`, `2xl`, `3xl`, `4xl`) onto Tamagui numeric keys (`1`, `2`, `3`, `4`, `0.25`, etc.). Screen-builder and Tamagui components rely on the default numeric scale. If a comment says `Map brand space names to Tamagui numeric token keys`, delete that override block.
+The generated schema has one palette. Light mode receives its approved
+surfaces, text, accents, and statuses. Dark mode keeps Config v5 dark surfaces
+and text while carrying the approved accent and status colors.
+
+Never copy `parseColorChannels`, `readableForeground`, or
+`withSemanticAliases` into the app. The host helper owns those rules.
+
+Never remap brand space keys (`xs`, `sm`, `md`, `lg`, `xl`, `2xl`, `3xl`,
+`4xl`) onto Tamagui numeric keys. Preserve the default numeric scale.
## Root Provider Wiring
-Current templates pass design values through `PowerAppsProvider`:
+Tamagui components read the themes above through `useTheme()`. Shared host
+components and navigation read `ThemeTokens` through `useThemeTokens()`.
+Build the provider themes from the exported app themes so both channels use
+the same semantic colors:
```tsx
+import {
+ PowerAppsProvider,
+ lightTheme as hostLightTheme,
+ darkTheme as hostDarkTheme,
+} from '@microsoft/power-apps-native-host';
+import type { ThemeTokens } from '@microsoft/power-apps-native-host';
+
+import tamaguiConfig, {
+ appDarkTheme,
+ appLightTheme,
+} from '../tamagui.config';
+
+const brandedLightTheme: ThemeTokens = {
+ ...hostLightTheme,
+ surface0: appLightTheme.surface0,
+ surface1: appLightTheme.surface1,
+ surface2: appLightTheme.surface2,
+ surface3: appLightTheme.surface3,
+ surface4: appLightTheme.color6,
+ text0: appLightTheme.text0,
+ text1: appLightTheme.text1,
+ text2: appLightTheme.text2,
+ text3: appLightTheme.text3,
+ accentDeep: appLightTheme.accentDeep,
+ accentBase: appLightTheme.accentBase,
+ accentSoft: appLightTheme.accentSoft,
+ accentOnAccent: appLightTheme.accentOnAccent,
+};
+
+const brandedDarkTheme: ThemeTokens = {
+ ...hostDarkTheme,
+ surface0: appDarkTheme.surface0,
+ surface1: appDarkTheme.surface1,
+ surface2: appDarkTheme.surface2,
+ surface3: appDarkTheme.surface3,
+ surface4: appDarkTheme.color6,
+ text0: appDarkTheme.text0,
+ text1: appDarkTheme.text1,
+ text2: appDarkTheme.text2,
+ text3: appDarkTheme.text3,
+ accentDeep: appDarkTheme.accentDeep,
+ accentBase: appDarkTheme.accentBase,
+ accentSoft: appDarkTheme.accentSoft,
+ accentOnAccent: appDarkTheme.accentOnAccent,
+};
+
<PowerAppsProvider
- authConfig={authConfig}
- powerConfig={powerConfig}
tamaguiConfig={tamaguiConfig}
defaultTheme={colorScheme === 'dark' ? 'dark' : 'light'}
- theme={lightTheme}
- darkTheme={darkTheme}
+ theme={brandedLightTheme}
+ darkTheme={brandedDarkTheme}
>
<Slot />
</PowerAppsProvider>
```
-If `brand/tokens.ts` exists, spread brand values over `lightTheme` / `darkTheme` with nullish fallback; do not rename imported `lightTheme`/`darkTheme` into local constants with the same names.
+Preserve the existing auth, app config, schema map, offline profile, telemetry,
+and custom provider props when applying this change.
-## Common Fixes
+`SafeAreaProvider` owns context only. Do not wrap `<Slot />` in a root
+`SafeAreaView`; rendered routes own their visible safe-area edges.
-| Symptom | Fix |
-|---|---|
-| `PortalDispatchContext cannot be null` | Pass config/theme props to `PowerAppsProvider`; do not add an outer `PortalProvider` unless on a verified legacy host. |
-| Reanimated error | Ensure `react-native-reanimated/plugin` is last in `babel.config.js`. |
-| Brand spacing blows up layouts | Remove numeric remapping of brand space keys; spread brand spaces verbatim. |
-| Template upgrade creates a `tamagui.config.ts.rej` file | Move every custom import and config expression back between the customization markers; leave the v5 file shell unchanged. |
\ No newline at end of file
+## Validation
+
+After Tamagui or provider changes:
+
+```bash
+npx tsc --noEmit
+```
+
+Also verify that `tamagui.config.ts` contains no local color parser or semantic
+alias implementation and that both provider themes map every
+surface/text/accent value from `appLightTheme` / `appDarkTheme`.