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.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
Fix model-apps language code handling (#450)
jibin jose87b905f10e81
diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.mdindex d52c43aee..4ed54dc47 100644--- a/plugins/model-apps/AGENTS.md+++ b/plugins/model-apps/AGENTS.md@@ -132,6 +132,27 @@ the pipeline and delegates each script's **behavioral spec** to the entries belodefault; `--apply` writes, `--sample-data` / `--publish` opt-in (`--publish` gates the final *bulk*publish; edit/finalize paths — reconciling an existing form/view, form events, quick-views,existing-app sitemap, page finalize — still publish their one artifact so the change takes effect).+ **DATA-MODEL Dataverse labels are stamped with the ORGANIZATION's base language, not a hardcoded+ 1033.** `resolveLanguageCode` (`scripts/lib/entity-provision.js`) reads `organization.languagecode`+ once per build and threads it into every label-emitting SDK call in that phase (tables, columns,+ customer columns, global choices, status reasons, alternate keys, relationships); precedence is+ `--language-code` → App Spec `languageCode` → the org's base language → 1033. Without this, an org+ that has not provisioned 1033 fails the data-model phase with `The language code 1033 is not a valid+ language for this organization`+ ([#447](https://github.com/microsoft/power-platform-skills/issues/447)) — and confusingly only on+ *some* column types, because (observed 2026-08) Dataverse tolerates an unprovisioned LCID on+ `EntityMetadata` and `PicklistAttributeMetadata` but rejects it on `DateTime`/`Memo`. Every fallback+ to 1033 warns, as does an explicitly supplied LCID that had to be discarded. Note+ `updateTable(logical, { quickCreateEnabled })` deliberately passes no language: it only builds a+ Label when a `displayName`/`pluralName`/`description` is supplied, and otherwise round-trips+ Dataverse's own labels under `MSCRM.MergeLabels`.+ **Scope — this does NOT extend to the `forms`, `dashboards` or `app-shell` phases.** Those go+ through the vendored SDK's artifact serializers, which hardcode `1033` into FormXML+ (`<label languagecode="1033">`), SiteMap XML (`<Title LCID="1033">`) and dashboard XML with **no+ caller override**, so the plugin cannot pass a language even though it has one. That is an SDK-side+ gap tracked in [#455](https://github.com/microsoft/power-platform-skills/issues/455). It is not+ known to fail a build — the #447 reporter's full build completed once the data-model phase was+ fixed — but in a non-1033 org those labels are stored tagged with a language the org lacks.`--verify` (opt-in) auto-runs the read-only reconcile after a successful apply and exits non-zero on a silent partial build (the samecheck `verify-model-app.js` runs standalone). Recovery from a halted build is a full rerun (idempotent).**`--changed-only`** (Preview, off by default) is a fail-closed SAFE partial apply: after a FRESH@@ -398,11 +419,11 @@ scripts/create-connection-reference.js ← Creates Dataverse connectionreference rows for connector bindingslist-custom-apis.js ← Discovers bindable Custom APIs (Global + entity-bound) + parameter kinds (custom-api gated)add-page-to-solution.js ← Adds GenPages and optional connection references to a solution- provision-entities.js ← CLI wrapper for entity provisioning (solution + data-model + sample-data)+ provision-entities.js ← CLI wrapper for entity provisioning (solution + data-model + sample-data; --language-code)provision-solution.js ← Creates a Dataverse solution via the SDKwrite-page-plan.js ← app-builder Phase 1.5: projects an App Spec into the genpage-plan.md read by page-builder workerspromote-intent-pages.js ← app-builder Phase 1.5: validates every generated page, then atomically flips source: intent → tsx- build-model-app.js ← app-builder: narrated, idempotent SDK build (dry-run default; --stage data|ui|app|publish; --changed-only)+ build-model-app.js ← app-builder: narrated, idempotent SDK build (dry-run default; --stage data|ui|app|publish; --changed-only; --language-code)download-model-app.js ← app-builder: pull a deployed app into an editable spec (edit flow)teardown-model-app.js ← app-builder: classifier-safe reverse-of-build teardownverify-model-app.js ← app-builder: reconcile the spec against the deployed appdiff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.mdindex 4092f6cb2..0946544a8 100644--- a/plugins/model-apps/CHANGELOG.md+++ b/plugins/model-apps/CHANGELOG.md@@ -9,6 +9,27 @@ jobs-to-be-done surfaces checkable, fixes four crash paths, and corrects asmoke-eval assertion that could never pass live.### Added+- **Dataverse labels now use the organization's own language instead of a hardcoded+ `1033`** ([#447](https://github.com/microsoft/power-platform-skills/issues/447)).+ In an organization that has not provisioned 1033, `data-model` halted with+ `The language code 1033 is not a valid language for this organization`. The build+ resolves `organization.languagecode` once per run and threads it into every+ label-emitting call (tables, columns, customer columns, global choices, status+ reasons, alternate keys, relationships), and warns whenever it has to fall back.++ Precedence: `--language-code` / `--languageCode` → App Spec `languageCode` (or+ `languageCode` in the `provision-entities.js` input JSON) → the organization's+ base language → 1033. Both CLIs accept the flag.++ Two things worth knowing if you hit this. The failure is **not** all-or-nothing:+ Dataverse accepts an unprovisioned LCID on `EntityMetadata` and+ `PicklistAttributeMetadata` but rejects it on `DateTime` and `Memo`, so the table+ and its Choice columns are created and the build fails a few steps later — which+ reads like an environment problem rather than a defect. And this covers the+ **data-model phase only**; form, dashboard and sitemap labels still come from SDK+ serializers that hardcode 1033 with no caller override+ ([#455](https://github.com/microsoft/power-platform-skills/issues/455)).+- **`verify` now proves what a persona security role GRANTS, not just that itexists.** The `role` check only asserted a role row carrying the SDK ownershipmarker, so a role built with the wrong access — or one whose privilege writediff --git a/plugins/model-apps/agents/genpage-entity-builder.md b/plugins/model-apps/agents/genpage-entity-builder.mdindex 211b9d875..74bf50d4e 100644--- a/plugins/model-apps/agents/genpage-entity-builder.md+++ b/plugins/model-apps/agents/genpage-entity-builder.md@@ -160,6 +160,20 @@ PREFIX="<Publisher Prefix>" # e.g. new### JSON Structure+Optional top-level field: **`languageCode`** — the LCID for the Dataverse labels this step creates.+**Normally omit it.** `provision-entities.js` reads the organization's base language+(`organization.languagecode`) and uses that, which is always a language the org has provisioned. Set+it only to deliberately author labels in a *different* provisioned language. It must be a positive+integer LCID up to 65535 (`1031`, not `"de-DE"`); an invalid value is rejected before any Dataverse+write. `--language-code` / `--languageCode <lcid>` overrides it for one run.++**If provisioning fails with `The language code N is not a valid language for this organization`,**+that is this setting — the organization does not have LCID N. Re-run with `--language-code <an LCID+the org actually has>`. Note the failure is *not* all-or-nothing: the table and any Choice columns+are created first and it fails on the first `DateTime`/`Memo` column, so it can look like an+environment fault. A `⚠ could not determine the organization's base language …` warning on stderr+means discovery failed and 1033 was assumed — pass the flag explicitly.+The input JSON follows the App Spec format. Build it with:```jsondiff --git a/plugins/model-apps/references/app-spec-schema.md b/plugins/model-apps/references/app-spec-schema.mdindex 04875d7ea..b054129ba 100644--- a/plugins/model-apps/references/app-spec-schema.md+++ b/plugins/model-apps/references/app-spec-schema.md@@ -58,7 +58,8 @@ sample data (incl. multi-parent junction links + status reasons), and publish."appShell": { "areas": [ /* sitemap */ ] },"sampleData": { /* optional, keyed by entity schemaName */ },"ai": { /* optional — AI feature flags + row-summary config */ },- "personas": [ /* optional — one security role per persona (see below) */ ]+ "personas": [ /* optional — one security role per persona (see below) */ ],+ "languageCode": 1031 /* optional — LCID for Dataverse labels; defaults to the org's base language */}```@@ -72,6 +73,22 @@ sample data (incl. multi-parent junction links + status reasons), and publish.**existing** app by identity — even after you **rename** the display `app.name` — instead of creating a**duplicate** app. You normally never hand-author this: an authored create-fresh spec omits it, and thebuild derives the uniquename deterministically from `solution.publisherPrefix` + `app.name`.+- **`languageCode`** *(optional)* — the [LCID](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-lcid/)+ stamped on the Dataverse labels the **data-model phase** creates (table, column, choice, status+ reason, relationship and alternate-key display names). It does **not** reach form, dashboard or+ sitemap labels — those go through SDK serializers that hardcode 1033 with no caller override+ ([#455](https://github.com/microsoft/power-platform-skills/issues/455)).+ **Normally omit it**: the build reads the organization's base language+ (`organization.languagecode`) and uses that, which is always a language the org has provisioned.+ Set it only to deliberately author labels in a *different* provisioned language than the org+ default; `--language-code <lcid>` overrides it for a single run.+ Must be a positive integer LCID up to 65535 — `1031`, not `"de-DE"` and not `true`. An invalid+ value is rejected by validation, and a caller that bypasses validation gets a warning naming the+ discarded value rather than a silent fall-through.+ **Not emitted by `download-model-app.js`**, and that is deliberate: an LCID copied out of the+ source org would be re-applied verbatim when the spec is rebuilt somewhere else, which is exactly+ how a spec starts failing in an org that lacks that language. Leaving it absent lets every target+ org resolve its own base language. If you pinned one by hand, re-add it after a download.## entities[]```jsoncdiff --git a/plugins/model-apps/scripts/build-model-app.js b/plugins/model-apps/scripts/build-model-app.jsindex 50014fedf..aa4824d73 100644--- a/plugins/model-apps/scripts/build-model-app.js+++ b/plugins/model-apps/scripts/build-model-app.js@@ -13,7 +13,7 @@const os = require('node:os');const fs = require('node:fs');const path = require('node:path');-const { validateAppSpec, migrateAppSpec, normalizePageSource } = require('./lib/app-spec.js');+const { validateAppSpec, migrateAppSpec, normalizePageSource, normalizeLanguageCode } = require('./lib/app-spec.js');const { runSdkBuild, planFor, appUniqueName, compileFormIntent, resolveExistingFormId } = require('./lib/sdk-build.js');const { stagePhasesOrResolve, PHASES, STAGES } = require('./lib/stages.js');const { createAzHttpClient } = require('./lib/sdk-http-client.js');@@ -264,6 +264,8 @@ async function buildModelApp(spec, opts, deps) {phases: opts.phases,appDir: opts.appDir, // resolves web-resource `contentPath` relative to the app folderenv: opts.env, // for the pages phase (pac model genpage upload --environment)+ languageCode: opts.languageCode,+ warn: deps.warn,genpageCli: deps.genpageCli, // injectable seam for tests; else constructed from envworkspaceDir: opts.workspaceDir, // lease/staging live under the real workspace dirallowDestructive: opts.allowDestructive, // pages phase gates destructive page removals (Imp6)@@ -386,6 +388,17 @@ function list(v) {return typeof v === 'string' ? v.split(',').map((s) => s.trim()).filter(Boolean) : undefined;}+function parseLanguageCode(value) {+ if (value === undefined) return undefined;+ // Shares app-spec's normalizer so the CLI flag, the App Spec field and the resolver can never+ // disagree about which LCIDs are valid.+ const lc = normalizeLanguageCode(value);+ if (lc === null) {+ throw new Error(`--language-code / --languageCode must be digits only, a positive integer LCID up to 65535 (got '${value}')`);+ }+ return lc;+}+async function main() {const { positional, flags } = parseArgs(process.argv.slice(2));// parseArgs sets a value-less flag to boolean `true`. Coerce required-VALUE flags to missing so a@@ -397,14 +410,14 @@ async function main() {const specArg = typeof flags.spec === 'string' ? flags.spec : positional[0];if (!env || !specArg) {process.stderr.write(- 'Usage: node scripts/build-model-app.js --env <url> --spec @<app-folder>/app-spec.json [--apply] [--sample-data] [--publish] [--verify] [--changed-only] [--stage <data|ui|app|publish>] [--only|--skip <phases>] [--from|--to <phase>] [--non-interactive] [--allow-destructive] [--workspace <dir>]\n'+ 'Usage: node scripts/build-model-app.js --env <url> --spec @<app-folder>/app-spec.json [--apply] [--sample-data] [--publish] [--verify] [--changed-only] [--stage <data|ui|app|publish>] [--only|--skip <phases>] [--from|--to <phase>] [--language-code|--languageCode <lcid>] [--non-interactive] [--allow-destructive] [--workspace <dir>]\n');process.exit(1);}// A value-less phase selector (or --workspace) is a USAGE ERROR — never a silent all-phases select// or default workspace. `--only`/`--skip`/`--from`/`--to`/`--stage` with no value would otherwise be// dropped by list()/stagePhasesOrResolve and resolve to the full phase set.- const valuelessFlag = ['stage', 'only', 'skip', 'from', 'to', 'workspace'].find((k) => flags[k] === true);+ const valuelessFlag = ['stage', 'only', 'skip', 'from', 'to', 'workspace', 'language-code', 'languageCode'].find((k) => flags[k] === true);if (valuelessFlag) {process.stderr.write(`✗ --${valuelessFlag} requires a value.\n`);process.exit(1);@@ -420,6 +433,7 @@ async function main() {const specPath = path.resolve(specArg.startsWith('@') ? specArg.slice(1) : specArg);const spec = migrateAppSpec(readJsonArg('@' + specPath));const workspaceDir = flags.workspace || path.join(path.dirname(specPath), '.maker-workspace');+ const languageCode = parseLanguageCode(flags['language-code'] ?? flags.languageCode);const opts = {apply: flags.apply === true,sampleData: flags['sample-data'] === true,@@ -429,6 +443,7 @@ async function main() {profile: (flags.apply === true && flags.stage !== 'data') ? 'deploy' : 'plan',allowDestructive: flags['allow-destructive'] === true,nonInteractive: flags['non-interactive'] === true || envTruthy(process.env.POWER_PLATFORM_SKILLS_NONINTERACTIVE),+ languageCode,appDir: path.dirname(specPath),env,workspaceDir,@@ -487,6 +502,7 @@ async function main() {// core stays free of SDK-reader wiring and fully injectable for tests.const deps = {log: (m) => process.stderr.write(m + '\n'),+ warn: (m) => process.stderr.write(`⚠ ${m}\n`),sdk, provisionSdk, journal,// `httpClient` + `envUrl` are threaded through so the role-privileges check actually RUNS// here. verify-spec skips it unless BOTH `rolePrivileges` and `entityPrivileges` readers are@@ -555,4 +571,4 @@ async function main() {if (require.main === module) {main().catch((err) => emitResult(false, err));}-module.exports = { buildModelApp, planFor, isTransientHalt, checkCollisions, discoverOpDiffState, envTruthy };+module.exports = { buildModelApp, planFor, isTransientHalt, checkCollisions, discoverOpDiffState, envTruthy, parseLanguageCode };diff --git a/plugins/model-apps/scripts/lib/app-spec.js b/plugins/model-apps/scripts/lib/app-spec.jsindex 7703fa94e..2a524fd5c 100644--- a/plugins/model-apps/scripts/lib/app-spec.js+++ b/plugins/model-apps/scripts/lib/app-spec.js@@ -358,6 +358,32 @@ function resolveChoiceValue(byLabel, v, isMulti) {// See docs/app-builder-design.md §7.1.const VALIDATION_PROFILES = ['design', 'plan', 'deploy', 'structural'];+// Normalize a Dataverse language identifier (LCID) to a positive integer, or null if it is not one.+//+// This is the SINGLE definition used by all three entry points an LCID can arrive from, so they can+// never disagree about what is valid: the `--language-code` CLI flag (always a string), the App Spec+// `languageCode` field (JSON, so nominally a number but in practice anything), and a programmatic+// caller of resolveLanguageCode().+//+// It deliberately does NOT use a bare `Number(value)` cast, which is far too lenient for a value that+// is sent straight to Dataverse as a label LanguageCode:+// Number(true) === 1 -> `"languageCode": true` would build every label with LCID 1+// Number([1033]) === 1033 -> a one-element array would silently "work"+// Number('1e3') === 1000 -> exponent notation is never a real LCID+// Each of those passes a naive positive-integer check and then fails deep inside the data-model phase+// with an opaque Dataverse 400, instead of a clear spec/CLI error up front. Accept only a real number+// or an all-digits string, and bound it: an LCID is a 16-bit value, so anything above 0xFFFF cannot be+// one and would fail the same opaque way (65536, 1e20 and MAX_SAFE_INTEGER all cleared an unbounded+// positive-integer check).+// LCID reference: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-lcid/+const MAX_LCID = 0xFFFF;+function normalizeLanguageCode(value) {+ const ok = (n) => (n > 0 && n <= MAX_LCID ? n : null);+ if (typeof value === 'number') return Number.isInteger(value) ? ok(value) : null;+ if (typeof value === 'string' && /^\d+$/.test(value.trim())) return ok(Number(value.trim()));+ return null;+}+// Normalize a page's implementation source into a discriminated shape:// { kind: 'tsx', codeFile } | { kind: 'intent' } | null// A legacy top-level `codeFile` (schemaVersion < 2) is treated as an implemented tsx page. `null`@@ -427,6 +453,9 @@ function validateAppSpec(spec, opts = {}) {if (!spec.app || !spec.app.name) {errors.push('app.name is required');}+ if (spec.languageCode !== undefined && normalizeLanguageCode(spec.languageCode) === null) {+ errors.push('languageCode must be a positive integer LCID');+ }const entityNames = new Set();const entityByLower = new Map(); // logical (lowercased schemaName) -> entityfor (const e of spec.entities || []) {@@ -1253,6 +1282,7 @@ function migrateAppSpec(spec) {module.exports = {validateAppSpec,normalizePageSource,+ normalizeLanguageCode,quickCreateEnabledFor,isPlatformIconRef,webResourceNameFromRef,diff --git a/plugins/model-apps/scripts/lib/entity-provision.js b/plugins/model-apps/scripts/lib/entity-provision.jsindex ec8056e08..689de1a08 100644--- a/plugins/model-apps/scripts/lib/entity-provision.js+++ b/plugins/model-apps/scripts/lib/entity-provision.js@@ -12,6 +12,7 @@ const {relationshipSchemaName,manyToManySchemaName,quickCreateEnabledFor,+ normalizeLanguageCode,} = require('./app-spec.js');const { topoOrderEntities, entityByLogical } = require('./_graph.js');// OData string-literal escaping for spec-controlled values interpolated into $filter (a solution@@ -27,11 +28,65 @@ const SDK_COLUMN_TYPE = {File: 'file', Image: 'image', AutoNumber: 'autonumber',};const REQUIRED = (c) => (c.required === true ? 'ApplicationRequired' : c.required === 'recommended' ? 'Recommended' : 'None');+const DEFAULT_LANGUAGE_CODE = 1033;++// Dataverse label payloads must use an LCID the org actually has provisioned. Resolve an explicit+// CLI override first, then an App Spec override, then the org's base `organization.languagecode`,+// and only fall back to 1033 if discovery itself fails so an unrelated read error does not block+// the whole build.+async function resolveLanguageCode({ provision, spec, languageCode, warn }) {+ // A supplied-but-invalid value is DISCARDED, not honoured — but it must not be discarded in+ // silence. "You gave me nothing" and "you gave me something I could not use" are different facts,+ // and only the second means the caller believes they pinned a language and is wrong. The CLI flags+ // hard-error before reaching here; this covers the programmatic seam and any caller that skips the+ // validation gate. Nobody's build breaks by being told their explicit input was rejected.+ const rejected = (label, value) => {+ if (typeof warn === 'function') {+ warn(`ignoring ${label} '${value}' — not a valid LCID (expected a positive integer up to 65535); `+ + 'falling back to the next source.');+ }+ };++ const explicit = normalizeLanguageCode(languageCode);+ if (explicit) return explicit;+ if (languageCode !== undefined && languageCode !== null) rejected('--language-code', languageCode);++ const specLanguage = normalizeLanguageCode(spec?.languageCode);+ if (specLanguage) return specLanguage;+ if (spec && spec.languageCode !== undefined && spec.languageCode !== null) rejected('languageCode', spec.languageCode);++ // EVERY fallback to the default is announced, not just the read-threw case. 1033 is precisely the+ // value that breaks a non-English organization (#447), so a build that silently lands here fails+ // later in the data-model phase with an opaque "The language code 1033 is not a valid language for+ // this organization" and nothing connecting it back to language resolution — which is exactly the+ // confusing failure this change exists to remove.+ const fallback = (reason) => {+ if (typeof warn === 'function') {+ warn(`could not determine the organization's base language (${reason}); using ${DEFAULT_LANGUAGE_CODE}. `+ + `If this organization does not have ${DEFAULT_LANGUAGE_CODE} provisioned, pass `+ + '--language-code (or --languageCode) <lcid>, or set "languageCode" in the App Spec.');+ }+ return DEFAULT_LANGUAGE_CODE;+ };++ if (!provision || typeof provision.queryRecords !== 'function') {+ return fallback('no Dataverse reader was supplied');+ }++ try {+ const rows = await provision.queryRecords('organization', { select: ['languagecode'], top: 1 });+ const orgLanguage = normalizeLanguageCode(rows && rows[0] && rows[0].languagecode);+ if (orgLanguage) return orgLanguage;+ return fallback('organization.languagecode was missing or not a valid LCID');+ } catch (err) {+ return fallback(`the organization read failed: ${(err && err.message) || err}`);+ }+}// Map an App Spec column to SDK CreateColumnOptions. `globalChoiceIds` maps a global-choice// name -> its metadataId (so a column can bind to a shared option set).-function columnOptions(c, globalChoiceIds, globalChoices) {- const o = { schemaName: c.schemaName, displayName: c.displayName || c.schemaName, type: SDK_COLUMN_TYPE[c.type || 'Text'], required: REQUIRED(c) };+function columnOptions(c, globalChoiceIds, globalChoices, languageCode) {+ const o = { schemaName: c.schemaName, displayName: c.displayName || c.schemaName, type: SDK_COLUMN_TYPE[c.type || 'Text'], required: REQUIRED(c), languageCode };switch (c.type) {case 'Text': if (c.maxLength) o.maxLength = c.maxLength; if (c.format) o.stringFormat = c.format; break;case 'Memo': if (c.maxLength) o.maxLength = c.maxLength; break;@@ -162,8 +217,9 @@ async function provisionSolution({ sdk, provision, runner, solution }) {// Discover-then-create global choices, tables, columns, status reasons, alternate keys,// and relationships (idempotent). Returns captured maps used by sample data + later phases.-async function provisionDataModel({ sdk, provision, runner, spec, apply }) {+async function provisionDataModel({ sdk, provision, runner, spec, apply, languageCode, warn }) {const result = { entities: {}, globalChoiceIds: {}, statusReasonValues: {}, columns: {}, relationships: [] };+ const resolvedLanguageCode = await resolveLanguageCode({ provision, spec, languageCode, warn });const globalChoiceIds = result.globalChoiceIds;const statusReasonValues = result.statusReasonValues;@@ -177,7 +233,7 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply }) {// runner.run instead of being silently swallowed.for (const gc of spec.globalChoices || []) {await runner.run('data-model', `global choice ${gc.name}`, async () => {- const r = await sdk.createGlobalOptionSet({ name: gc.name, displayName: gc.displayName || gc.name, options: (gc.options || []).map((label, i) => ({ value: 100000000 + i, label })) });+ const r = await sdk.createGlobalOptionSet({ name: gc.name, displayName: gc.displayName || gc.name, languageCode: resolvedLanguageCode, options: (gc.options || []).map((label, i) => ({ value: 100000000 + i, label })) });globalChoiceIds[gc.name] = r.metadataId;});}@@ -195,7 +251,7 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply }) {} else {await runner.run('data-model', `table ${e.schemaName}`, async () => {const createOpts = { schemaName: e.schemaName, displayName: e.displayName, pluralName: e.pluralName || `${e.displayName}s`,- primaryColumnSchemaName: e.primaryAttribute.schemaName, primaryColumnDisplayName: e.primaryAttribute.displayName || 'Name', hasNotes: e.hasNotes === true };+ primaryColumnSchemaName: e.primaryAttribute.schemaName, primaryColumnDisplayName: e.primaryAttribute.displayName || 'Name', hasNotes: e.hasNotes === true, languageCode: resolvedLanguageCode };// AutoNumber the primary/title column when requested (the order number IS the identity).if (e.primaryAttribute.autoNumberFormat) createOpts.primaryColumnAutoNumberFormat = e.primaryAttribute.autoNumberFormat;try {@@ -234,8 +290,8 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply }) {const toCreate = buildable.filter((c) => !existingCols.has(c.schemaName.toLowerCase()));const colResults = await runner.mapLimit(toCreate, 1, (c) => runner.run('data-model', `column ${e.schemaName}.${c.schemaName} (${c.type || 'Text'})`,() => c.type === 'Customer'- ? sdk.createCustomerColumn(logical, { schemaName: c.schemaName, displayName: c.displayName || c.schemaName, required: REQUIRED(c) })- : sdk.createColumn(logical, columnOptions(c, globalChoiceIds, spec.globalChoices)),+ ? sdk.createCustomerColumn(logical, { schemaName: c.schemaName, displayName: c.displayName || c.schemaName, required: REQUIRED(c), languageCode: resolvedLanguageCode })+ : sdk.createColumn(logical, columnOptions(c, globalChoiceIds, spec.globalChoices, resolvedLanguageCode)),{ skipIf: isAlreadyExists }));// Capture real column results (logicalName + metadataId)toCreate.forEach((c, i) => {@@ -262,7 +318,7 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply }) {srIdx += 1;(statusReasonValues[logical] = statusReasonValues[logical] || {})[sr.label] = { value: pinned, stateCode };await runner.run('data-model', `status reason ${e.schemaName}: ${sr.label}`, async () => {- const v = await sdk.insertStatusValue(logical, { label: sr.label, stateCode, color: sr.color, value: pinned });+ const v = await sdk.insertStatusValue(logical, { label: sr.label, stateCode, color: sr.color, value: pinned, languageCode: resolvedLanguageCode });statusReasonValues[logical][sr.label] = { value: typeof v === 'number' ? v : pinned, stateCode };}, { recoverable: true, skipIf: isAlreadyExists });}@@ -270,7 +326,7 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply }) {// already-exists error is treated as a skip (not a halt) via skipIf.for (const k of e.alternateKeys || []) {await runner.run('data-model', `alt key ${e.schemaName}.${k.schemaName}`,- () => sdk.createAlternateKey(logical, { schemaName: k.schemaName, displayName: k.displayName || k.schemaName, keyAttributes: (k.columns || []).map((x) => x.toLowerCase()) }),+ () => sdk.createAlternateKey(logical, { schemaName: k.schemaName, displayName: k.displayName || k.schemaName, keyAttributes: (k.columns || []).map((x) => x.toLowerCase()), languageCode: resolvedLanguageCode }),{ recoverable: true, skipIf: isAlreadyExists });}}@@ -286,7 +342,7 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply }) {try { exists = ((await provision.fetchEntityMetadata(rel.referenced.toLowerCase())).relationships || []).some((r) => r.schemaName.toLowerCase() === schema.toLowerCase()); } catch { /* just created */ }if (exists) { runner.skip('data-model', `relationship ${schema} (exists)`); continue; }await runner.run('data-model', `relationship 1:N ${rel.referenced}->${rel.referencing}`, async () => {- const res = await sdk.createRelationship({ type: 'OneToMany', schemaName: schema, referencedEntity: rel.referenced.toLowerCase(), referencingEntity: rel.referencing.toLowerCase(), lookupSchemaName: rel.lookup.schemaName, lookupDisplayName: rel.lookup.displayName });+ const res = await sdk.createRelationship({ type: 'OneToMany', schemaName: schema, referencedEntity: rel.referenced.toLowerCase(), referencingEntity: rel.referencing.toLowerCase(), lookupSchemaName: rel.lookup.schemaName, lookupDisplayName: rel.lookup.displayName, languageCode: resolvedLanguageCode });result.relationships.push({schemaName: res.schemaName || schema,metadataId: res.metadataId,@@ -300,7 +356,7 @@ async function provisionDataModel({ sdk, provision, runner, spec, apply }) {try { exists = ((await provision.fetchEntityMetadata(rel.entity1.toLowerCase())).relationships || []).some((r) => r.schemaName.toLowerCase() === schema.toLowerCase()); } catch { /* just created */ }if (exists) { runner.skip('data-model', `relationship ${schema} (exists)`); continue; }await runner.run('data-model', `relationship N:N ${rel.entity1}<->${rel.entity2}`, async () => {- const res = await sdk.createRelationship({ type: 'ManyToMany', schemaName: schema, entity1: rel.entity1.toLowerCase(), entity2: rel.entity2.toLowerCase(), intersectEntityName: rel.intersectEntityName });+ const res = await sdk.createRelationship({ type: 'ManyToMany', schemaName: schema, entity1: rel.entity1.toLowerCase(), entity2: rel.entity2.toLowerCase(), intersectEntityName: rel.intersectEntityName, languageCode: resolvedLanguageCode });result.relationships.push({schemaName: res.schemaName || schema,metadataId: res.metadataId,@@ -445,4 +501,4 @@ async function provisionSampleData({ sdk, provision, runner, spec, dataModel })return { records: result.records, entitySetFor };}-module.exports = { makeRunner, requireSuccessfulPush, makeEntitySetResolver, provisionSolution, provisionDataModel, provisionSampleData, buildSeedGroup, BuildHalt, SDK_COLUMN_TYPE };+module.exports = { makeRunner, requireSuccessfulPush, makeEntitySetResolver, resolveLanguageCode, provisionSolution, provisionDataModel, provisionSampleData, buildSeedGroup, BuildHalt, SDK_COLUMN_TYPE };diff --git a/plugins/model-apps/scripts/lib/provision-input.js b/plugins/model-apps/scripts/lib/provision-input.jsindex 2b1abd0c7..7bb1a7525 100644--- a/plugins/model-apps/scripts/lib/provision-input.js+++ b/plugins/model-apps/scripts/lib/provision-input.js@@ -5,7 +5,7 @@// App-Spec subset: { solution, entities, relationships, globalChoices?, sampleData? }.// Entities carry FULL schema names (e.g. cr_candidate), not bare suffixes.-const { TYPE_MAP } = require('./app-spec.js');+const { TYPE_MAP, normalizeLanguageCode } = require('./app-spec.js');// Validates provision-entities input. Returns { ok, errors }.function validateProvisionInput(input) {@@ -28,6 +28,16 @@ function validateProvisionInput(input) {}}+ // An LCID supplied here must be validated at the SAME strictness as the `--language-code` flag and+ // the App Spec `languageCode` field. Without this the input-file path fails OPEN: resolveLanguageCode+ // maps anything non-conforming to null and silently falls through to the org default, so a typo like+ // "1O33" (capital O) produces `ok: true` with every label in the wrong language and nothing on stderr.+ // The other two entry points hard-error on the identical string; this gate keeps all three consistent+ // and runs before any SDK write.+ if (input.languageCode !== undefined && normalizeLanguageCode(input.languageCode) === null) {+ errors.push('languageCode must be a positive integer LCID');+ }+// Entities validationif (!Array.isArray(input.entities)) {errors.push('entities must be an array');diff --git a/plugins/model-apps/scripts/lib/sdk-build.js b/plugins/model-apps/scripts/lib/sdk-build.jsindex 45d6f8311..1e2cd65b6 100644--- a/plugins/model-apps/scripts/lib/sdk-build.js+++ b/plugins/model-apps/scripts/lib/sdk-build.js@@ -896,7 +896,7 @@ async function runSdkBuild(spec, opts = {}) {// entity (fresh -> createTable result, existing -> findTables hit).let dataModel = { entities: {}, globalChoiceIds: {}, statusReasonValues: {}, columns: {}, relationships: [] };if (has('data-model')) {- dataModel = await provisionDataModel({ sdk, provision, runner, spec, apply });+ dataModel = await provisionDataModel({ sdk, provision, runner, spec, apply, languageCode: opts.languageCode, warn: opts.warn });Object.assign(result.created.entities, dataModel.entities);}diff --git a/plugins/model-apps/scripts/provision-entities.js b/plugins/model-apps/scripts/provision-entities.jsindex 3078db1eb..9b42871a3 100644--- a/plugins/model-apps/scripts/provision-entities.js+++ b/plugins/model-apps/scripts/provision-entities.js@@ -4,13 +4,13 @@// a structured JSON result. Dry-run by default; --apply writes. --sample-data opt-in.//// Usage:-// node provision-entities.js --env <orgUrl> --input @<path> [--apply] [--sample-data]+// node provision-entities.js --env <orgUrl> --input @<path> [--apply] [--sample-data] [--language-code|--languageCode <lcid>]const os = require('node:os');const fs = require('node:fs');const path = require('node:path');const { validateProvisionInput } = require('./lib/provision-input.js');const { makeRunner, provisionSolution, provisionDataModel, provisionSampleData } = require('./lib/entity-provision.js');-const { quickCreateEnabledFor } = require('./lib/app-spec.js');+const { quickCreateEnabledFor, normalizeLanguageCode } = require('./lib/app-spec.js');const { createAzHttpClient } = require('./lib/sdk-http-client.js');const { parseArgs, readJsonArg, emitResult } = require('./lib/dataverse-auth.js');@@ -116,7 +116,7 @@ function buildPlan(input, opts) {}// The testable core: validates, computes plan, runs the shared provision functions.-// `deps` injects { sdk, provision, emit, log } so tests never touch the network.+// `deps` injects { sdk, provision, emit, log, warn } so tests never touch the network.async function provisionEntities(input, opts = {}, deps = {}) {// 1. Validation gate first — if invalid, return errors with ZERO SDK writes.const v = validateProvisionInput(input);@@ -133,6 +133,7 @@ async function provisionEntities(input, opts = {}, deps = {}) {// 3. Apply: run the shared core (solution → data-model → sample-data-if-requested).const log = deps.log || (() => undefined);const emit = deps.emit || (() => undefined);+ const warn = deps.warn || (() => undefined);const sdk = deps.sdk;const provision = deps.provision;@@ -146,18 +147,27 @@ async function provisionEntities(input, opts = {}, deps = {}) {relationships: input.relationships || [],globalChoices: input.globalChoices || [],sampleData: input.sampleData,+ // Carried through so a caller can pin the label LCID here exactly as an App Spec can. Without+ // it the field would be silently dropped on this path while working on the build path.+ ...(input.languageCode !== undefined ? { languageCode: input.languageCode } : {}),};// Provision solutionawait provisionSolution({ sdk, provision, runner, solution: spec.solution });// Provision data model (entities, columns, relationships)+ // `warn` is threaded so a fallback to the default label LCID is REPORTED here too. This CLI is the+ // genpage create flow's data-model path, so without it a non-English org would hit the same opaque+ // "language code 1033 is not a valid language for this organization" that #447 describes, with no+ // diagnostic — the build path would explain itself and this one would not.const dataModel = await provisionDataModel({sdk,provision,runner,spec,apply: true,+ languageCode: opts.languageCode,+ warn,});// Provision sample data (if requested)@@ -270,17 +280,34 @@ async function main() {if (!env || !inputArg || flags.input === true) {process.stderr.write(- 'Usage: node provision-entities.js --env <url> --input @<path> [--apply] [--sample-data]\n'+ 'Usage: node provision-entities.js --env <url> --input @<path> [--apply] [--sample-data] [--language-code|--languageCode <lcid>]\n');process.exit(1);}+ // A value-less `--language-code` is a usage error, never a silent fall-through to the org default.+ const valuelessLang = ['language-code', 'languageCode'].find((k) => flags[k] === true);+ if (valuelessLang) {+ process.stderr.write(`✗ --${valuelessLang} requires a value.\n`);+ process.exit(1);+ }const inputPath = path.resolve(typeof inputArg === 'string' && inputArg.startsWith('@') ? inputArg.slice(1) : inputArg);const input = readJsonArg('@' + inputPath);+ const rawLang = flags['language-code'] ?? flags.languageCode;+ let languageCode;+ if (rawLang !== undefined) {+ languageCode = normalizeLanguageCode(rawLang);+ if (languageCode === null) {+ process.stderr.write(`✗ --language-code / --languageCode must be digits only, a positive integer LCID up to 65535 (got '${rawLang}')\n`);+ process.exit(1);+ }+ }+const opts = {apply: flags.apply === true,sampleData: flags['sample-data'] === true,+ languageCode,};// Construct SDK clients (offline until first call)@@ -290,6 +317,7 @@ async function main() {try {const deps = {log: (m) => process.stderr.write(m + '\n'),+ warn: (m) => process.stderr.write(`⚠ ${m}\n`),sdk,provision,};diff --git a/plugins/model-apps/scripts/tests/build-model-app.test.js b/plugins/model-apps/scripts/tests/build-model-app.test.jsindex e88b8f697..802c47ba0 100644--- a/plugins/model-apps/scripts/tests/build-model-app.test.js+++ b/plugins/model-apps/scripts/tests/build-model-app.test.js@@ -6,7 +6,9 @@ const { test } = require('node:test');const assert = require('node:assert');const path = require('node:path');const fs = require('node:fs');-const { buildModelApp, isTransientHalt, discoverOpDiffState } = require(path.join(__dirname, '..', 'build-model-app.js'));+const { buildModelApp, isTransientHalt, discoverOpDiffState, parseLanguageCode } = require(path.join(__dirname, '..', 'build-model-app.js'));+const { resolveLanguageCode } = require(path.join(__dirname, '..', 'lib', 'entity-provision.js'));+const { validateAppSpec, normalizeLanguageCode } = require(path.join(__dirname, '..', 'lib', 'app-spec.js'));const desk = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'samples', 'app-spec.support-desk.json'), 'utf8')@@ -111,6 +113,54 @@ test('apply threads through to the SDK engine (solution + tables created)', asyn});// R3 — auto-verify after a successful --apply (opt-in; deps.verify injected)+test('data-model languageCode defaults to the org base language and reaches table/column labels', async () => {+ const { sdk, calls } = mockSdk();+ sdk.queryRecords = async (set) => {+ if (set === 'organization') return [{ languagecode: 1031 }];+ if (set === 'solution') return [];+ return [{ publisherid: 'pub-1' }];+ };+ const r = await buildModelApp(desk, { apply: true, env: 'https://x' }, { sdk });+ assert.strictEqual(r.ok, true);+ assert.ok(calls.some((c) => c[0] === 'createTable' && c[1] && c[1].languageCode === 1031), 'table create carries the org language');+ assert.ok(calls.some((c) => c[0] === 'createColumn' && c[2] && c[2].languageCode === 1031), 'column create carries the org language');+});++test('languageCode option overrides the org base language', async () => {+ const { sdk, calls } = mockSdk();+ sdk.queryRecords = async (set) => {+ if (set === 'organization') return [{ languagecode: 1031 }];+ if (set === 'solution') return [];+ return [{ publisherid: 'pub-1' }];+ };+ const r = await buildModelApp(desk, { apply: true, env: 'https://x', languageCode: 3082 }, { sdk });+ assert.strictEqual(r.ok, true);+ assert.ok(calls.some((c) => c[0] === 'createTable' && c[1] && c[1].languageCode === 3082), 'table create uses the override');+ assert.ok(calls.some((c) => c[0] === 'createColumn' && c[2] && c[2].languageCode === 3082), 'column create uses the override');+});++test('language resolution falls back cleanly when the provision stub has no queryRecords', async () => {+ const lc = await resolveLanguageCode({ provision: {}, spec: {} });+ assert.strictEqual(lc, 1033);+});++test('language resolution ignores an invalid override and still honors a valid spec languageCode', async () => {+ const lc = await resolveLanguageCode({ provision: {}, spec: { languageCode: 1031 }, languageCode: 0 });+ assert.strictEqual(lc, 1031);+});++test('language resolution warns when org-language discovery fails but still falls back', async () => {+ const warnings = [];+ const lc = await resolveLanguageCode({+ provision: { queryRecords: async () => { throw new Error('boom'); } },+ spec: {},+ warn: (msg) => warnings.push(msg),+ });+ assert.strictEqual(lc, 1033);+ // The warning must carry the underlying cause, not just announce that a fallback happened.+ assert.ok(warnings.some((w) => /base language/i.test(w) && /boom/.test(w)));+});+test('auto-verify (opts.verify) runs the injected reconcile and attaches r.verify on pass', async () => {const { sdk } = mockSdk();let received = null;@@ -511,3 +561,151 @@ test('makeSdk returns the httpClient so the caller can wire verify', () => {assert.match(src, /return \{ sdk, provisionSdk, httpClient, cleanup \}/, 'makeSdk must expose httpClient');assert.match(src, /const \{ sdk, provisionSdk, httpClient, cleanup \} = makeSdk\(/, 'main must destructure it');});++// #447 follow-up: an LCID reaches Dataverse as a label LanguageCode, so a value that merely SURVIVES+// a `Number()` cast is not good enough. `Number(true) === 1` and `Number([1033]) === 1033` both pass+// a naive positive-integer check, so a spec containing `"languageCode": true` would have built every+// label with the invalid LCID 1 and failed deep in the data-model phase with an opaque Dataverse 400.+test('languageCode rejects non-numeric JSON types instead of coercing them to a bogus LCID', () => {+ const base = { app: { name: 'A' }, entities: [], solution: { uniqueName: 'x', publisherPrefix: 'new' } };+ const bad = [true, [1033], '1e3', '12.5', {}, 1033.5, -1, 0];+ for (const v of bad) {+ const r = validateAppSpec({ ...base, languageCode: v });+ assert.ok(+ (r.errors || []).some((e) => /languageCode must be a positive integer LCID/.test(e)),+ `languageCode=${JSON.stringify(v)} must be REJECTED (Number() would coerce it to ${Number(v)})`+ );+ }+ // A real number and the string form the CLI always produces must still be accepted.+ for (const v of [1033, 1031, '1031', ' 1033 ']) {+ const r = validateAppSpec({ ...base, languageCode: v });+ assert.ok(!(r.errors || []).some((e) => /languageCode/.test(e)), `languageCode=${JSON.stringify(v)} must be accepted`);+ }+});++test('resolveLanguageCode does not accept a coerced non-numeric override', async () => {+ // `true` must NOT win over a valid spec value; it is not a language.+ const lc = await resolveLanguageCode({ provision: {}, spec: { languageCode: 1031 }, languageCode: true });+ assert.strictEqual(lc, 1031, 'a boolean override must be ignored, not coerced to LCID 1');+ const lc2 = await resolveLanguageCode({ provision: {}, spec: { languageCode: true } });+ assert.strictEqual(lc2, 1033, 'a boolean spec value must fall through to the default, not become LCID 1');+});++test('parseLanguageCode (CLI) rejects the same coercible values', () => {+ for (const v of ['abc', '0', '-1', '1e3', '12.5']) {+ assert.throws(() => parseLanguageCode(v), /positive integer LCID/, `--language-code ${v} must throw`);+ }+ assert.strictEqual(parseLanguageCode('1031'), 1031);+ assert.strictEqual(parseLanguageCode(undefined), undefined);+});++// #447 follow-up: 1033 is the exact value that breaks a non-English org, so EVERY path that falls+// back to it must say so. Previously only the read-threw path warned; an empty result set or a null+// languagecode returned 1033 silently and the build then died on a DateTime/Memo column with an+// opaque Dataverse 400 that pointed nowhere near language resolution.+test('every fallback to the default LCID warns, not just the read-threw path', async () => {+ const cases = [+ ['no reader supplied', {}],+ ['empty result set', { queryRecords: async () => [] }],+ ['null languagecode', { queryRecords: async () => [{ languagecode: null }] }],+ ['non-LCID languagecode', { queryRecords: async () => [{ languagecode: 'de-DE' }] }],+ ['read threw', { queryRecords: async () => { throw new Error('boom'); } }],+ ];+ for (const [name, provision] of cases) {+ const warnings = [];+ const lc = await resolveLanguageCode({ provision, spec: {}, warn: (m) => warnings.push(m) });+ assert.strictEqual(lc, 1033, name + ': falls back to the default');+ assert.strictEqual(warnings.length, 1, name + ': must emit exactly one warning');+ assert.match(warnings[0], /base language/i, name + ': warning explains what could not be determined');+ assert.match(warnings[0], /--language-code/, name + ': warning names the escape hatch');+ }+});++test('a successful org read does NOT warn', async () => {+ const warnings = [];+ const lc = await resolveLanguageCode({+ provision: { queryRecords: async () => [{ languagecode: 1031 }] },+ spec: {},+ warn: (m) => warnings.push(m),+ });+ assert.strictEqual(lc, 1031);+ assert.deepStrictEqual(warnings, [], 'the happy path must be silent');+});++test('the org language read asks for the right column and a single row', async () => {+ // Pins the query itself, not just its result. The read is wrapped in try/catch and degrades to+ // 1033, so a wrong $select would surface live as an HTTP 400 swallowed into a warning -- a+ // regression a result-only assertion cannot see.+ let seen = null;+ await resolveLanguageCode({+ provision: { queryRecords: async (set, opts) => { seen = { set, opts }; return [{ languagecode: 1031 }]; } },+ spec: {},+ });+ assert.strictEqual(seen.set, 'organization', 'logical name (the SDK resolves the entity set itself)');+ assert.deepStrictEqual(seen.opts.select, ['languagecode']);+ assert.strictEqual(seen.opts.top, 1);+});++// #447 follow-up: the unit tests above call resolveLanguageCode() directly with a `warn`, which+// proves the FUNCTION warns but says nothing about whether the CLI is wired to it. The chain is+// build-model-app `deps.warn` -> runBuild `opts.warn` -> provisionDataModel -> resolveLanguageCode,+// and a break anywhere in it silently costs the user the only diagnostic they get before an opaque+// Dataverse 400. This asserts the whole chain end to end through the public buildModelApp entry.+test('deps.warn reaches language resolution — the CLI warning wiring, not just the function', async () => {+ const { sdk } = mockSdk();+ sdk.queryRecords = async (set) => {+ if (set === 'organization') throw new Error('org read blocked');+ if (set === 'solution') return [];+ return [{ publisherid: 'pub-1' }];+ };+ const warnings = [];+ const r = await buildModelApp(desk, { apply: true, env: 'https://x' }, { sdk, warn: (m) => warnings.push(m) });+ assert.strictEqual(r.ok, true, 'a failed language read must not fail the build');+ assert.ok(+ warnings.some((w) => /base language/i.test(w) && /--language-code/.test(w)),+ 'the fallback warning must actually reach deps.warn; got: ' + JSON.stringify(warnings)+ );+});++test('a healthy org language read produces no warning through the CLI path', async () => {+ const { sdk, calls } = mockSdk();+ sdk.queryRecords = async (set) => {+ if (set === 'organization') return [{ languagecode: 1031 }];+ if (set === 'solution') return [];+ return [{ publisherid: 'pub-1' }];+ };+ const warnings = [];+ const r = await buildModelApp(desk, { apply: true, env: 'https://x' }, { sdk, warn: (m) => warnings.push(m) });+ assert.strictEqual(r.ok, true);+ assert.deepStrictEqual(warnings, [], 'the happy path must not warn');+ assert.ok(calls.some((c) => c[0] === 'createColumn' && c[2] && c[2].languageCode === 1031));+});++// An LCID is a 16-bit value, so anything above 0xFFFF cannot be one. Without an upper bound these+// cleared the positive-integer check and reached the wire, failing in exactly the opaque way the+// normalizer's own comment claims it prevents.+test('normalizeLanguageCode bounds the LCID to 16 bits', () => {+ for (const bad of [65536, 1e20, Number.MAX_SAFE_INTEGER, '65536', '99999']) {+ assert.strictEqual(normalizeLanguageCode(bad), null, `${bad} is above 0xFFFF and must be rejected`);+ }+ assert.strictEqual(normalizeLanguageCode(65535), 65535, 'the boundary itself is valid');+ assert.strictEqual(normalizeLanguageCode(1033), 1033);+});++// "You gave me nothing" and "you gave me something I could not use" are different facts. Only the+// second means the caller believes they pinned a language and is wrong, so it must not be silent.+test('a supplied-but-invalid language override is reported, not silently discarded', async () => {+ const warnings = [];+ const lc = await resolveLanguageCode({ provision: {}, spec: {}, languageCode: 'de-DE', warn: (m) => warnings.push(m) });+ assert.strictEqual(lc, 1033, 'still falls through rather than failing the build');+ assert.ok(warnings.some((w) => /ignoring --language-code 'de-DE'/.test(w)), 'the discarded value is named: ' + JSON.stringify(warnings));++ const w2 = [];+ await resolveLanguageCode({ provision: {}, spec: { languageCode: '1O33' }, warn: (m) => w2.push(m) });+ assert.ok(w2.some((w) => /ignoring languageCode '1O33'/.test(w)), 'a bad spec value is named too: ' + JSON.stringify(w2));++ // Absent must stay silent — only the org-discovery fallback warning applies there.+ const w3 = [];+ await resolveLanguageCode({ provision: { queryRecords: async () => [{ languagecode: 1031 }] }, spec: {}, warn: (m) => w3.push(m) });+ assert.deepStrictEqual(w3, [], 'omitting the override is not a problem and must not warn');+});diff --git a/plugins/model-apps/scripts/tests/entity-provision.test.js b/plugins/model-apps/scripts/tests/entity-provision.test.jsindex 11e74eeee..5ebb1f688 100644--- a/plugins/model-apps/scripts/tests/entity-provision.test.js+++ b/plugins/model-apps/scripts/tests/entity-provision.test.js@@ -438,3 +438,84 @@ test('requireSuccessfulPush halts (BuildHalt) on a 412 version-conflict result',(err) => err.name === 'BuildHalt' && /re-download the app and rebuild/.test(err.message) && err.code === 'version-conflict');});++// #447 regression net. The bug this fixes was a SINGLE label-emitting call that forgot to pass a+// language, and it stayed invisible until a user in a German org filed a bug — CI runs offline mocks+// and nobody's CI runs against a non-1033 org. So pinning only the two call sites that happened to be+// mutation-tested leaves the same detection gap for the other six.+//+// This asserts GENERICALLY: every recorded SDK call that carries a label must carry the resolved LCID.+// A new label-emitting call added later is therefore covered by construction rather than by someone+// remembering to extend a list.+test('EVERY label-emitting SDK call carries the resolved language code (#447)', async () => {+ const seen = [];+ const rec = (name) => (...args) => {+ // The options object is the last argument for every one of these SDK signatures.+ seen.push({ name, opts: args[args.length - 1] });+ return {};+ };++ const sdk = {+ createGlobalOptionSet: async (...a) => { seen.push({ name: 'createGlobalOptionSet', opts: a[0] }); return { metadataId: 'g1' }; },+ createTable: async (...a) => { seen.push({ name: 'createTable', opts: a[0] }); return { logicalName: a[0].schemaName.toLowerCase(), entitySetName: a[0].schemaName.toLowerCase() + 's', metadataId: 't1' }; },+ createColumn: async (...a) => { seen.push({ name: 'createColumn', opts: a[1] }); return { logicalName: a[1].schemaName.toLowerCase(), metadataId: 'c1' }; },+ createCustomerColumn: async (...a) => { seen.push({ name: 'createCustomerColumn', opts: a[1] }); return { logicalName: a[1].schemaName.toLowerCase(), metadataId: 'c2' }; },+ insertStatusValue: async (...a) => { seen.push({ name: 'insertStatusValue', opts: a[1] }); return 100000000; },+ createAlternateKey: async (...a) => { seen.push({ name: 'createAlternateKey', opts: a[1] }); return {}; },+ createRelationship: async (...a) => { seen.push({ name: 'createRelationship', opts: a[0] }); return { schemaName: a[0].schemaName, metadataId: 'r1' }; },+ updateTable: rec('updateTable'),+ };+ const provision = {+ findTables: async () => [],+ findColumns: async () => [],+ fetchEntityMetadata: async (l) => ({ logicalName: l, entitySetName: l + 's', relationships: [] }),+ queryRecords: async (set) => (set === 'organization' ? [{ languagecode: 1031 }] : [{ solutionid: 's' }]),+ };++ // A spec that reaches all seven call sites in one pass.+ const spec = {+ solution: { uniqueName: 'Cover', publisherPrefix: 'cr' },+ globalChoices: [{ name: 'cr_pri', displayName: 'Priority', options: ['Low', 'High'] }],+ entities: [+ { schemaName: 'cr_parent', displayName: 'Parent', pluralName: 'Parents',+ primaryAttribute: { schemaName: 'cr_name', displayName: 'Name' },+ columns: [+ { schemaName: 'cr_when', displayName: 'When', type: 'DateTime' },+ { schemaName: 'cr_cust', displayName: 'Cust', type: 'Customer' },+ ],+ statusReasons: [{ label: 'Open', state: 'Active' }],+ alternateKeys: [{ schemaName: 'cr_key', displayName: 'Key', columns: ['cr_name'] }] },+ { schemaName: 'cr_child', displayName: 'Child', pluralName: 'Children',+ primaryAttribute: { schemaName: 'cr_cname', displayName: 'CName' }, columns: [] },+ { schemaName: 'cr_tag', displayName: 'Tag', pluralName: 'Tags',+ primaryAttribute: { schemaName: 'cr_tname', displayName: 'TName' }, columns: [] },+ ],+ relationships: [+ { type: 'OneToMany', referenced: 'cr_parent', referencing: 'cr_child', lookup: { schemaName: 'cr_ParentId', displayName: 'Parent' } },+ { type: 'ManyToMany', entity1: 'cr_parent', entity2: 'cr_tag' },+ ],+ };++ const runner = makeRunner({ emit: () => {}, total: 99 });+ await provisionDataModel({ sdk, provision, runner, spec, apply: true });++ // `updateTable` is deliberately excluded: with only `quickCreateEnabled` the SDK builds no Label at+ // all, it round-trips Dataverse's own labels under MSCRM.MergeLabels. Passing a language there would+ // be noise, not safety.+ const LABEL_EMITTING = new Set([+ 'createGlobalOptionSet', 'createTable', 'createColumn', 'createCustomerColumn',+ 'insertStatusValue', 'createAlternateKey', 'createRelationship',+ ]);++ const emitted = seen.filter((c) => LABEL_EMITTING.has(c.name));+ const names = new Set(emitted.map((c) => c.name));+ for (const expected of LABEL_EMITTING) {+ assert.ok(names.has(expected), `${expected} was never exercised — this test no longer covers it`);+ }++ const missing = emitted.filter((c) => !c.opts || c.opts.languageCode !== 1031);+ assert.deepStrictEqual(+ missing.map((c) => c.name), [],+ 'these label-emitting calls did not carry the resolved LCID: ' + JSON.stringify(missing.map((c) => c.name))+ );+});diff --git a/plugins/model-apps/scripts/tests/provision-entities.test.js b/plugins/model-apps/scripts/tests/provision-entities.test.jsindex e4d44287f..791030880 100644--- a/plugins/model-apps/scripts/tests/provision-entities.test.js+++ b/plugins/model-apps/scripts/tests/provision-entities.test.js@@ -179,3 +179,51 @@ test('apply seeds requested sample data and returns created record ids', async (assert.strictEqual(seedGroup.matchOn, 'cr_name', 'a single-column alternate key makes sample seeding idempotent');assert.deepStrictEqual(r.records, { cr_parent: ['id-a', 'id-b'] });});++// #447: this CLI is the genpage create flow's data-model path, so it must resolve the organization's+// base language exactly as build-model-app.js does. It builds its own `spec` object from `input`,+// which is easy to leave a field out of -- and because resolveLanguageCode degrades to 1033 rather+// than throwing, a dropped field is invisible until a non-English org fails on a DateTime column.+test('provision-entities resolves the org base language for labels (#447)', async () => {+ const d = mockDeps();+ d.provision.queryRecords = async (set) => (set === 'organization' ? [{ languagecode: 1031 }] : [{ solutionid: 's' }]);+ const seen = [];+ d.sdk.createColumn = async (l, o) => { seen.push(o); return { logicalName: o.schemaName.toLowerCase(), metadataId: 'c' }; };+ const r = await provisionEntities(input, { apply: true }, { sdk: d.sdk, provision: d.provision });+ assert.strictEqual(r.ok, true);+ assert.ok(seen.length > 0, 'a column was created');+ assert.strictEqual(seen[0].languageCode, 1031, 'the org language reached the column create');+});++test('provision-entities honors an explicit language override and an input languageCode', async () => {+ const d = mockDeps();+ d.provision.queryRecords = async (set) => (set === 'organization' ? [{ languagecode: 1031 }] : [{ solutionid: 's' }]);+ const seen = [];+ d.sdk.createColumn = async (l, o) => { seen.push(o); return { logicalName: o.schemaName.toLowerCase(), metadataId: 'c' }; };+ await provisionEntities(input, { apply: true, languageCode: 3082 }, { sdk: d.sdk, provision: d.provision });+ assert.strictEqual(seen[0].languageCode, 3082, 'opts.languageCode wins over the org base language');++ const seen2 = [];+ const d2 = mockDeps();+ d2.provision.queryRecords = async (set) => (set === 'organization' ? [{ languagecode: 1031 }] : [{ solutionid: 's' }]);+ d2.sdk.createColumn = async (l, o) => { seen2.push(o); return { logicalName: o.schemaName.toLowerCase(), metadataId: 'c' }; };+ await provisionEntities({ ...input, languageCode: 1036 }, { apply: true }, { sdk: d2.sdk, provision: d2.provision });+ assert.strictEqual(seen2[0].languageCode, 1036, 'input.languageCode is carried into the spec, not dropped');+});++test('provision-entities surfaces a language fallback through deps.warn', async () => {+ // Without this the genpage path would fall back to 1033 in silence and the user would see only an+ // opaque Dataverse 400 later -- the build path would explain itself and this one would not.+ const d = mockDeps();+ d.provision.queryRecords = async (set) => {+ if (set === 'organization') throw new Error('org read blocked');+ return [{ solutionid: 's' }];+ };+ const warnings = [];+ const r = await provisionEntities(input, { apply: true }, { sdk: d.sdk, provision: d.provision, warn: (m) => warnings.push(m) });+ assert.strictEqual(r.ok, true, 'a failed language read must not fail provisioning');+ assert.ok(+ warnings.some((w) => /base language/i.test(w) && /--language-code/.test(w)),+ 'the fallback must reach deps.warn; got: ' + JSON.stringify(warnings)+ );+});diff --git a/plugins/model-apps/scripts/tests/provision-input.test.js b/plugins/model-apps/scripts/tests/provision-input.test.jsindex 884571d92..6d0949122 100644--- a/plugins/model-apps/scripts/tests/provision-input.test.js+++ b/plugins/model-apps/scripts/tests/provision-input.test.js@@ -84,3 +84,27 @@ test('accepts a valid OneToMany relationship', () => {});assert.strictEqual(r.ok, true, JSON.stringify(r.errors));});++// #447: an LCID supplied in the input JSON must be rejected at the SAME strictness as the+// `--language-code` flag and the App Spec field. Before this gate the input-file path failed OPEN --+// resolveLanguageCode maps garbage to null and falls through to the org default -- so a typo like+// "1O33" (capital O for zero) produced ok:true with every label in the wrong language, no error and+// no warning, while the identical string was fatal on the flag path one line away.+test('languageCode in the provision input is validated, not silently discarded (#447)', () => {+ const base = { solution: { uniqueName: 'S', publisherPrefix: 'cr' },+ entities: [{ schemaName: 'cr_a', displayName: 'A', pluralName: 'As', primaryAttribute: { schemaName: 'cr_name' }, columns: [] }],+ relationships: [] };+ for (const bad of ['1O33', 'de-DE', true, 0, -1, '1e3', 65536, 1033.5, [1033], {}]) {+ const r = validateProvisionInput({ ...base, languageCode: bad });+ assert.ok(+ (r.errors || []).some((e) => /languageCode must be a positive integer LCID/.test(e)),+ `languageCode=${JSON.stringify(bad)} must be REJECTED before any SDK write`+ );+ }+ for (const good of [1033, 1031, '1036', 1, 65535]) {+ const r = validateProvisionInput({ ...base, languageCode: good });+ assert.ok(!(r.errors || []).some((e) => /languageCode/.test(e)), `languageCode=${JSON.stringify(good)} must be accepted`);+ }+ // Absent stays valid — the field is optional and the org default is the normal case.+ assert.ok(!(validateProvisionInput(base).errors || []).some((e) => /languageCode/.test(e)));+});diff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.mdindex d220f34ef..c8a5972b6 100644--- a/plugins/model-apps/skills/app-builder/SKILL.md+++ b/plugins/model-apps/skills/app-builder/SKILL.md@@ -284,6 +284,17 @@ before applying.)other stages and the legacy `--from/--to/--only/--skip` selectors are dry-run inspection only —their phase ranges are not dependency-closed and are rejected on `--apply`.+**Language (`--language-code` / `--languageCode <lcid>`)** — you normally do **not** pass this.+Data-model labels are+stamped with the organization's own base language, read once per build. Pass it only to author+labels in a different **provisioned** language, or if the build warns that it could not determine+the base language and fell back to 1033. If a build fails with *"The language code N is not a valid+language for this organization"*, that is this setting — re-run with `--language-code <an LCID the+org actually has>`, listing them with+`node "${PLUGIN_ROOT}/scripts/dataverse-request.js" <envUrl> GET RetrieveProvisionedLanguages`.+The App Spec field `languageCode` pins the same value across runs. Note this covers the data-model+phase only; form and sitemap labels still carry 1033 (SDK limitation, issue #455).+Narrate progress as it runs. Transient env errors (429 customization-lock, 503 SQL-timeout,concurrent-op guards) are **auto-retried** with backoff on `--apply` (the build is idempotent, so aretry reuses what's already created). If the build still **halts** (`BuildHalt`) on an